﻿//Menu, Side down panel, Sitemap, TV Schedule, What On Right Now, Login Popup, Search

// Will prevent the modal from opening. Set to "true" if the user is logged in,
//  or if a video is being loaded on the page.
var ModalDisabled = false;

//Menu
var SelectionAllowed = true;
var SelectionAllowOff = false;
var currentMenuDiv = null;

$(document).ready(function() {

    var config = {
        sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
        interval: 10, // number = milliseconds for onMouseOver polling interval    
        over: //makeTall, // function = onMouseOver callback (REQUIRED)    
                function(event) {
                    HoverMenu(this);
                },
        timeout: 1, // number = milliseconds delay before onMouseOut    
        out: //makeShort // function = onMouseOut callback (REQUIRED)
                function(event) {
                    MenuOff(this);
                }
    };
    try {
        $('div.MenuItem').hoverIntent(config);
    }
    catch (er) {
    }
});

function ReInitializeUgcApi() {
    var url = Agility.ResolveUrl("~/Scripts/UGCAPIInit.ashx/api.js?dt=" + (new Date()).getTime());
    var html = "<scr" + "ipt type='text/javascript' src='" + url + "'></scri" + "pt>";
    //$(html).appendTo($(document.body));
    $(html).insertAfter($("#initUgcApi"));
};

function HoverMenu(divName) {
    if (SelectionAllowed == true || currentMenuDiv != divName) {
        currentMenuDiv = divName;
        SelectionAllowed = false;
        var MenuItem = $(divName);
        var MainMenuItem = MenuItem.find("div.MainMenuItem");
        $("div:eq(0)", MainMenuItem).addClass('MenuLeft');
        $("div:eq(1)", MainMenuItem).addClass('MenuFill');
        $("div:eq(2)", MainMenuItem).addClass('MenuRight');

        var DropDownMenu = MenuItem.find("div.DropDownMenu");
        if (DropDownMenu.html() != null) {
            if ($.browser.msie && $.browser.version.indexOf("7") == 0) { //IE7
                MenuItem.css('marginTop', 3);
            }
            var MenuItemWidth = MenuItem.width();
            if (MenuItemWidth < 100 && !MenuItem.is(".RightMenuItem")) {
                MenuItemWidth = 100;
            }
            $('.List', DropDownMenu).css("width", MenuItemWidth);
            $('.tc, .bc', DropDownMenu).css("width", MenuItemWidth + 20);

            if ($.browser.msie && $.browser.version.indexOf("6") == 0) { //IE6
                var ie6width = -MenuItemWidth - 15;
                DropDownMenu.css("marginLeft", ie6width);
            }
            else {
                DropDownMenu.css("marginLeft", "-15px");
            }
            DropDownMenu.toggle();
        }
    }
}

function MenuOff(divName) {
    var MenuItem = $(divName);
    var MainMenuItem = MenuItem.find("div.MainMenuItem");
    $("div:eq(0)", MainMenuItem).removeClass('MenuLeft');
    $("div:eq(1)", MainMenuItem).removeClass('MenuFill');
    $("div:eq(2)", MainMenuItem).removeClass('MenuRight');
    var DropDownMenu = MenuItem.find("div.DropDownMenu");
    if (DropDownMenu.html() != null) {
        if ($.browser.msie && $.browser.version.indexOf("7") == 0) {
            MenuItem.css('marginTop', 0);
        }
        DropDownMenu.hide();
    }
    SelectionAllowed = true;
}

//Side down schedule
var onTVOpen = false;
var animationTime = 200; //ms
$(document).ready(function() {
    var config = {
        sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
        interval: 100, // number = milliseconds for onMouseOver polling interval    
        over: //makeTall, // function = onMouseOver callback (REQUIRED)    
                function(event) {
                    if (!onTVOpen) {
                        toggleOnTV(this, event);
                    }
                },
        timeout: 500, // number = milliseconds delay before onMouseOut    
        out: //makeShort // function = onMouseOut callback (REQUIRED)
                function(event) { }
    };

    try {
        $(btnOpenID).hoverIntent(config);

        $(".ShowsLink").hover(linkHoverOn, linkHoverOff);
        $(".VideoLink").hover(linkHoverOn, linkHoverOff);
        $(".MoviesLink").hover(linkHoverOn, linkHoverOff);
        $(".BeOnTVLink").hover(linkHoverOn, linkHoverOff);
        $(".FullScheduleLink").hover(linkHoverOn, linkHoverOff);
    }
    catch (er) {
    }
});

function linkHoverOn() {
    $(this).addClass("hover");
}

function linkHoverOff() {
    $(this).removeClass("hover");
}

function toggleOnTV(sender, theevent) {
    if (onTVOpen) {
        $(sender).parent().prev().animate({ marginTop: "-180" },
                animationTime, null,
                function() {
                    $(sender).parent().prev().removeClass("OnTVOpen");
                    $(btnCloseID).hide();
                    $(btnOpenID).show();
                }
            );
    }
    else {
        $(sender).parent().prev().addClass("OnTVOpen");
        $(sender).parent().prev().animate({ marginTop: "0" },
                animationTime, null,
                function() {
                    $(btnOpenID).hide();
                    $(btnCloseID).show();

                    // Handle clicks outside the Schedule to close it
                    $(sender).parent().prev().click(function(event) {
                        event.stopPropagation();
                    });
                    $(sender).parent().next().next().click(function(event) {
                        event.stopPropagation();
                    });
                    $(document).one("click", function(event) {
                        toggleOnTV(sender, event);
                    });
                }
            );
    }
    onTVOpen = !onTVOpen;
    return false;
}

//Sitemap
var expandedText = "Click to Shrink";
var shrinkedText = "Click to Expand";
var sitemapClosed = true;

function ToggleSitemap() {
    if (sitemapClosed) {
        $('.Sitemap .Head a:eq(0)').text(expandedText);
        divSiteMapContainer.slideDown();
        sitemapClosed = false;
    }
    else {
        $('.Sitemap .Head a:eq(0)').text(shrinkedText);
        divSiteMapContainer.slideUp();
        sitemapClosed = true;
    }
}

//TV Schedule

var cachedSchedules = [];
var firstIndex = 0;
var lastIndex = -1;
var fromLastGlobal = null;

function alertSched() {
    alert(firstIndex + ', ' + lastIndex + ', ' + cachedSchedules.length);
}

$(document).ready(function() {
    try{
        Get5Schedules(true); // I will make the first call
    }
    catch (er) {
    }
});

function GetNext5Schedules() {
    if (cachedSchedules.length - 1 == lastIndex) {
        Get5Schedules(true);
    }
    else {
        RenderSchedule(lastIndex + 1);
    }
}

function GetPrev5Schedules() {
    if (firstIndex == 0) {
        Get5Schedules(false);
    }
    else {
        RenderSchedule(firstIndex - 5);
    }
}

function Get5Schedules_Callback(result) {
    var strdate = 'x';

    if (result.GetScheduleResult == null) {
        return;
    }

    // Convert all the dates to date format
    for (var idx = 0; idx < result.GetScheduleResult.length; idx++) {
        result.GetScheduleResult[idx].SIM.Gmt_datetime = RenderDateFromJSON(result.GetScheduleResult[idx].SIM.Gmt_datetime);
        result.GetScheduleResult[idx].SIM.Airing_datetime = RenderDateFromJSON(result.GetScheduleResult[idx].SIM.Airing_datetime);
    }

    if (lastIndex > 0) { // Not first call
        if (fromLastGlobal) {
            strdate = FormatDate(cachedSchedules[lastIndex].SIM.Gmt_datetime);
        }
        else {
            strdate = FormatDate(cachedSchedules[firstIndex].SIM.Gmt_datetime);
        }
    }

    if (result.GetScheduleResult != undefined && result.GetScheduleResult != null) {
        if (fromLastGlobal) {

            cachedSchedules = cachedSchedules.concat(result.GetScheduleResult);
            RenderSchedule(lastIndex + 1);
        }
        else {
            cachedSchedules = result.GetScheduleResult.concat(cachedSchedules);
            RenderSchedule(0);
        }
    }
}

function Get5Schedules(fromLast) {
    fromLastGlobal = fromLast;
    var strdate = 'x';

    if (lastIndex > 0) { // Not first call
        if (fromLastGlobal) {
            strdate = FormatDate(cachedSchedules[lastIndex].SIM.Gmt_datetime);  //FormatDate(RenderDateFromJSON(cachedSchedules[lastIndex].Gmt_datetime));
        }
        else {
            strdate = FormatDate(cachedSchedules[firstIndex].SIM.Gmt_datetime); //FormatDate(RenderDateFromJSON(cachedSchedules[firstIndex].Gmt_datetime));
        }
    }

    var wsurl = wcfHostHeader + '/WebServices/TVSchedule.svc/TVSchedule/' + strdate + '/' + (fromLastGlobal ? '' : '-') + '5?method=Get5Schedules_Callback'; // Request 5 shows
    $.ajax({
        type: "GET",
        url: wsurl,
        contentType: "application/json; charset=utf-8",
        dataType: "jsonp"
    });
}

var Days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];

function RenderSchedule(index) {
    firstIndex = lastIndex = index;
    if (index < cachedSchedules.length) {
        $(".TVSchedule .Show").each(function(i) {

            var sched = cachedSchedules[index + i];
            //sched.Airing_datetime = RenderDateFromJSON(sched.Airing_datetime);

            var day = adjustedDay(sched.SIM.Airing_datetime);
            var html = "";
            html += "<div class='Time'>" + dateFormat(sched.SIM.Airing_datetime, "hh:MM TT") + " E/P " + Days[day] + "</div>";

            html += "<div class='LeftText'><b>"
            if (sched.AgilityShow != null) {
                html += "<a href='" + sched.AgilityShow.ShowURL + "' target='_top'>" + sched.SIM.Program_name.replace("<30>", "") + "</a>";
            }
            else {
                html += sched.SIM.Program_name.replace("<30>", "");
            }
            html += "</b>";

            if (sched.SIM.Title_name != null) {
                html += "<br/><span class='Title'>" + sched.SIM.Title_name + "</span>";
            }
            html += "</div>";
            $(this).html(html);
            lastIndex++;
        });
        lastIndex--;
    }
}

function adjustedDay(date) {
    var baseDay = date.getDay();
    if (date.getHours() >= 0 && date.getHours() < 6) {
        return (baseDay == 6) ? 0 : baseDay + 1;
    }
    return baseDay;
}

function FormatDate(varDate) {

    var strDate = "";
    strDate = adjust0(varDate.getDate().toString());
    strDate += adjust0((varDate.getMonth() + 1).toString());
    strDate += varDate.getFullYear().toString();
    strDate += adjust0(varDate.getHours().toString());
    strDate += adjust0(varDate.getMinutes().toString());
    return strDate;
}

function adjust0(str) {
    if (str.length == 1) {
        str = '0' + str;
    }
    return str;
}

function SummarizeText(text) {
    if (text == null) {
        return '';
    }
    if (text.length > 40) {
        return text.substring(0, 40) + ' ..';
    }
    else {
        return text;
    }
}
//Login Popup
var callbackOnClose = null;

function ShowLoginPopup(callbackFunction) {
    callbackOnClose = callbackFunction;
    var d = new Date();
    $('.LoginPopupBody iframe', loginPopup).attr('src',
            loginURL + d.getTime());

    $.blockUI.defaults.fadeOut = 0;
    $.blockUI.defaults.fadeIn = 0;
    $.blockUI({
        message: loginPopup,
        css: {
            border: 'none',
            backgroundColor: 'transparent'
        },
        overlayCSS: {
            backgroundColor: '#fff'
        }
    });
}

function CloseLoginPopup(userID) {
    if (userID != undefined) {
        try {
            LoadLoginPanel();
        }
        catch (er) { }
    }
    
    $.unblockUI();
    if (callbackOnClose != null) {
        callbackOnClose(userID);
    }
    
    return false;
}

//Search

function submitOnEnter(oEvent) {
    if ((oEvent.keyCode && oEvent.keyCode == 13) || (oEvent.which && oEvent.which == 13)) {
        $(btnSearchID).trigger('click');
        return false;
    }
    return true;
}
function submitSearch() {
    if ($(txtSearchForID).val() != '') {
        window.location = searchURL + $(txtSearchForID).val();
    }
}
function SearchClick() {
    var txtBox = $(txtSearchForID);
    if (txtBox.val() == "type your search here") {
        txtBox.val("")
        return false;
    }
}
function FillSearchBox() {
    var txtBox = $(txtSearchForID);
    if (txtBox.val() == "") {
        txtBox.val("type your search here")
    }
}

//SWF upload

function SetUpAttachment(fieldName, inputID, panelID, progressPanelID, uploadButtonImageUrl, mimeErrorID, callback) {

    var imageMimeTypes = ["image/jpeg", "image/gif", "image/png"];

    var fieldTypes = $.grep(imageMimeTypes, function(elem, index) {
        return elem.Name == fieldName;
    });

    //fieldName, inputID, fieldType  fieldPanel, swfUploadUrl, beforeUpload, uploadComplete, uploadError, uploadProgress, uploadButtonImageUrl, uploadButtonImageHeight, uploadButtonImageWidth, </param>        
    Agility.UGC.API.GetAmazonS3Form({
        fieldname: fieldName,
        inputID: inputID,
        fieldType: fieldTypes[0],
        fieldPanel: $("#" + panelID),
        swfUploadUrl: Agility.ResolveUrl("~/Scripts/SwfUpload/swfupload.swf"),
        uploadButtonImageUrl: Agility.ResolveUrl(uploadButtonImageUrl),
        uploadButtonImageHeight: 27,
        uploadButtonImageWidth: 103,
        beforeUpload: function(fileName, mime, filesize, uploader) {

            if (jQuery.inArray(mime, imageMimeTypes) < 0) {

                if ((mimeErrorID != undefined) && (mimeErrorID != null) && (mimeErrorID.length > 0)) {

                    $("#" + mimeErrorID).show();
                }

                if (uploader != undefined && uploader != null) {

                    uploader.cancelUpload(null, false);
                }

                $("#" + inputID).val("");

                return false;
            } 
            else if ((mimeErrorID != undefined) && (mimeErrorID != null) && (mimeErrorID.length > 0)) {

                $("#" + mimeErrorID).hide();
            }

            var percent = "50%";
            if (uploader != undefined && uploader != null) {
                percent = "0%";
            }
            $("#" + progressPanelID).html("&nbsp;&nbsp;" + percent);

        },
        uploadComplete: function(key, filesize) {
            //upload complete

            //hide the progress...
            var index = key.lastIndexOf("\\");
            if (index == -1) index = key.lastIndexOf("/");
            var fileName = key.substring(index + 1);

            $("#" + inputID).val(key);
            $("#" + progressPanelID).html("&nbsp;&nbsp;" + fileName);

            if ((callback != undefined) && (callback != null)) {
                callback(key);
            }
        },
        uploadError: function(file, errorCode, message) {
            //upload error...

            //hide the progress

            var html = "An error occurred.";

            //determine the message...
            switch (errorCode) {
                case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                    html = "Please choose a file less than or equal to " + fieldType.MaxLength + "kb";
                    break;
                case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                    html = "Please choose a file greater than zero bytes.";
                    break;
                case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
                    html = fieldType.ValidationMessage;
                    break;

                case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
                case SWFUpload.UPLOAD_ERROR.IO_ERROR:
                case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
                case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
                case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
                case SWFUpload.UPLOAD_ERROR.IO_ERROR:
                    html = "An error occurred while uploading the file.  Please check your connection and try again."
                    break;
                case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
                    html = "An error occurred while uploading the file.  You may need to add the crossdomain.xml file to your Amazon S3 bucket.";
                    break;
                case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
                case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
                    //ignore these errors...
                    break;
                default:
                    html = message;
                    break;
            }

            $("#" + progressPanelID).html(html);

        },
        uploadProgress: function(file, bytesLoaded) {

            //progress...
            var percent = Math.ceil((bytesLoaded / file.size) * 100);
            $("#" + progressPanelID).html("&nbsp;&nbsp;" + percent + "%");
        }
    });
};


