﻿
//Adjustments made to menus if needed
$(document).ready(function() {
    //Center the feature nav, if found
    centerFeatureNav();
    //Select the appropriate top nav if needed
    selectMenu("#topNav > li > a", "current");
    //Select the appropriate sub nav if needed
    selectMenu("#secondNav > li > a", "current");
    //Select the appropriate tertiary nav if needed
    selectMenu("#tertiary > li > a", "current");

    //include alphanumeric check for certain textboxes
    if ($('.alphacheck').alphanumeric)
        $('.alphacheck').alphanumeric({ allow: " " });
    
});

function reloadAd(adContainerId) {
    var adContainer = $("#" + adContainerId);
    var reloadCount = adContainer.attr("reloadCount");
    
    if(reloadCount == null)
    {
        reloadCount = 0;
    }
    
    if(reloadCount < 2)
    {
        if (adContainer.attr("loading") == "YES") return;
        
        var oldAdFrame = $("#" + adContainerId + " > iframe:eq(0)");
        var newAdFrame = oldAdFrame.clone();

        adContainer.attr("loading", "YES");
        
        //Temporarily set the new iframe's id to something different
        newAdFrame.attr({ id: oldAdFrame.attr("id") + "_temp" });

        newAdFrame.hide();
        adContainer.append(newAdFrame);

        newAdFrame.load(function() {
            oldAdFrame.hide();
            newAdFrame.show();
            var adContainerElement = document.getElementById(adContainerId);
            var adFrameElement = document.getElementById(oldAdFrame.attr("id"));
            adContainerElement.removeChild(adFrameElement);
            //Remove the old frame
            oldAdFrame.replaceWith("");
            //Set the new iframe's id to the old one
            newAdFrame.attr({ id: oldAdFrame.attr("id") });
            adContainer.attr("loading", "no");
            var count = ++reloadCount;
            adContainer.attr("reloadCount", count);
        });
    }
    

}

function adPopupInit(src, duration) {
    if (!duration) duration = 20;
    tb_show_overlay("", src + "{0}&KeepThis=true&TB_iframe=true&height=650&width=900", false, "50");
    $('#TB_iframeContent').hide();
    $('#TB_iframeContent').load(function() { $(this).show(); });

    //auto close option with message
    //$("#TB_closeWindowButton").attr({ timeRemaining: duration });
    //$("#TB_closeWindowButton").attr({ intervalId: window.setInterval(adPopupCallback, 1000) });
}

function adPopupCallback() {
    var closeWindowButton = $("#TB_closeWindowButton");
    var timeLeft = closeWindowButton.attr("timeRemaining");
    var intervalId = closeWindowButton.attr("intervalId");

    var buttonText = "Window will automatically close in " + timeLeft + " seconds or click here to continue";
    closeWindowButton.text(buttonText);
    if (timeLeft <= 0) {
        tb_remove();
        window.clearInterval(intervalId);
    }
    else {
        $("#TB_closeWindowButton").attr({ timeRemaining: timeLeft - 1 });
    }
}

//Fix for validation summary controls (this will disable window.scrollTo(0,0) only)
var builtInScrollTo = window.scrollTo;
window.scrollTo = function(x, y) {
if (y != 0) 
    builtInScrollTo(x, y);
};

function selectMenu(findExpression, selectedClassName) {
    var parts = document.location.href.split("?");
    if (parts.length == 1) return;
    var baseHref = parts[0].toLowerCase();
    var selectedMenu = $(findExpression + "." + selectedClassName).get(0);

    if (!selectedMenu) {
        var menus = $(findExpression).get();
        for (var i = 0; i < menus.length; i++) {
            var href = menus[i].href.toLowerCase();
            //Possibly checking for an exact match would be better
            if (baseHref == href) {
                menus[i].className = selectedClassName;
                //alert(baseHref == href);
                return;//Found one
            }
        }
    }
}

function centerFeatureNav() {
    var ul = document.getElementById('featureNav');
    if (!ul) return; //Not found
    var i = 0, c = 0;
    while (ul.getElementsByTagName('li')[i++]) c++;
    var menuWidth = document.getElementById('featureNav').offsetWidth;
    var navWidth = 0;
    var doc = document.getElementsByTagName('li');
    for (var i = 0; i < c; i++) {
        itemNumber = ('navItem' + eval(i + 1));
        navWidth = navWidth + document.getElementById(itemNumber).offsetWidth;
    }
    var margLeft = (menuWidth - navWidth) / 2;
    document.getElementById('navItem1').style.marginLeft = document.getElementById('navItem1').style.marginLeft = margLeft + 'px';
}

function disableLink(linkId, cursor) {
    var linkElement = document.getElementById(linkId);
    linkElement.onclick = null;
    linkElement.removeAttribute("href");
    linkElement.style.cursor = cursor ? cursor : "default";
}

function hasOptions(obj) {
    if (obj != null && obj.options != null) { return true; }
    return false;
}

function setActiveTab(tabControlClientId, tabNumber) {
    var ctrl = $find(tabControlClientId);
    ctrl.set_activeTab(ctrl.get_tabs()[tabNumber]);
}

function parseTime(timeString) {
    if (timeString == '') return null;
    var d = new Date();
    var time = timeString.match(/(\d+)(:(\d\d))?\s*(p?)/);
    d.setHours(parseInt(time[1]) + ((parseInt(time[1]) < 12 && time[4]) ? 12 : 0));
    d.setMinutes(parseInt(time[3]) || 0);
    d.setSeconds(0, 0);
    if (timeString.toLowerCase().indexOf("pm") >= 0)
        d.setHours(d.getHours() + 12);
    return d;
}

function AddItem(from, to, hiddenField, errorDiv) {
    hiddenField.value = "";
    elem = document.getElementById(errorDiv);

    if (to.options.length <= 4) {
        elem.style.display = "none";
        if (!hasOptions(to)) { var index = 0; } else { var index = to.options.length; }
        var id = document.getElementById("ctl00_ctl00_cphBodyContent_cphMainContent_hidResultId");
        if (id.value.length) {
            to.options[index] = new Option(from.value, id.value, false, false);
            from.value = "";
            id.value = "";
        }
    }
    else {
        elem.style.display = "inline";
    }

    for (var i = 0; i < to.options.length; i++) {
        var o = to.options[i];
        hiddenField.value += o.text + "~" + o.value + "|";
    }
}

function RemoveItem(from, hiddenField, errorDiv) {
    hiddenField.value = "";
    elem = document.getElementById(errorDiv);
    elem.style.display = "none";
    
    for (var i = (from.options.length - 1); i >= 0; i--) {
        var o = from.options[i];
        if (o.selected) {
            from.options[i] = null;
        }
    }
    for (var i = 0; i < from.options.length; i++) {
        var o = from.options[i];
        hiddenField.value += o.text + "~" + o.value + "|";
    }
}

function selectItem(li) {
    if (li == null) return "";

    if (!!li.extra)
    var id = document.getElementById("ctl00_ctl00_cphBodyContent_cphMainContent_hidResultId");
    id.value = li.extra[0];
}

function AddItemToList(from, to, hiddenField, errorDiv) {
    hiddenField.value = "";
    elem = document.getElementById(errorDiv);

    if (to.options.length <= 4) {
        for (var i = 0; i < from.options.length; i++) {
            var o = from.options[i];
            if (o.selected) {
                elem.style.display = "none";
                if (!hasOptions(to)) { var index = 0; } else { var index = to.options.length; }
                to.options[index] = new Option(o.text, o.value, false, false);
            }
        }
        
        for (var i = (from.options.length - 1); i >= 0; i--) {
            var o = from.options[i];
            if (o.selected) {
                from.options[i] = null;
            }
        }
    }
    else {
        elem.style.display = "inline";
    }

    for (var i = 0; i < to.options.length; i++) {
        var o = to.options[i];
        hiddenField.value += o.text + "~" + o.value + "|";
    }
}

function RemoveItemFromList(from, to, hiddenField, errorDiv) {
    hiddenField.value = "";
    elem = document.getElementById(errorDiv);
    elem.style.display = "none";
    
    for (var i = 0; i < from.options.length; i++) {
        var o = from.options[i];
        if (o.selected) {
            if (!hasOptions(to)) { var index = 0; } else { var index = to.options.length; }
            to.options[index] = new Option(o.text, o.value, false, false);
        }
    }
    for (var i = (from.options.length - 1); i >= 0; i--) {
        var o = from.options[i];
        if (o.selected) {
            from.options[i] = null;
        }
    }
    for (var i = 0; i < from.options.length; i++) {
        var o = from.options[i];
        hiddenField.value += o.text + "~" + o.value + "|";
    }
}

function setQueryStringValues(location, nameValueArray) {
    for (name in nameValueArray) {
        location = setQueryStringValue(location, name, nameValueArray[name]);
    }
    return location;
}

function setQueryStringValue(location, name, value) {
    value = escape(value);
    var baseHref = location;
    var queryString = "?";
    var questionIndex = location.indexOf("?");
    if (questionIndex > 0) {
        baseHref = location.substr(0, questionIndex);
        queryString = location.substr(questionIndex);
    }

    if (queryString.length > 0) {
        var re =  new RegExp("([\?&])" + name + "=([^&]*)");
        var results = re.exec(queryString);
        var nameValue = name + "=" + value;
        if (value == "") nameValue = "";//Remove this item from the query string, since it is blank
        if (results) {
            queryString = queryString.replace(re, "$1" + nameValue);
        }
        else if (nameValue) {
            if (queryString.length > 1) {
                queryString += "&";
            }
            queryString += nameValue;
        }
    }

    return baseHref + queryString;
}
function jumpPage(element) {

    var destination = element.value;
    window.location = destination;

}

//functions for jquerytabs called from XSLT
function tabTop() {
    $ektron(function() {
    $ektron("#sub_onecolumn_feature > ul").tabs({ fx: { opacity: 'toggle'} }).tabs('rotate', 6000);
    });
}

function tabTopImax() {
    $ektron(function() {
    $ektron("#sub_onecolumn_feature > ul").tabs({ fx: { opacity: 'toggle'} }).tabs('rotate', 30000);
    });
}

function offersFeature() {
    $ektron(function() {
    $ektron("#offersFeature > ul").tabs({fx:{opacity: 'toggle'}}).tabs('rotate', 6000);
    });
}

function featuredPosts() {
    $ektron(function() {
    $ektron("#blog_imgPod > ul").tabs({fx:{opacity: 'toggle'}}).tabs('rotate', 8000);
    });
}

function blogRoll() {
    $ektron(document).ready(function() {
    $ektron("#BlogRoll > ul").tabs();
    });
}

//All searches
var instructionalText;

function clearInstructionText(textBoxId, performMatch, maxLength) {
    var textBox = document.getElementById(textBoxId);
    if (!performMatch || textBox.value == instructionalText) {
        textBox.value = "";
    }
    if (maxLength) {
        textBox.maxLength = maxLength;
    }
}

function clearText(textBoxId, instructionalText, maxLength) {
    var textBox = document.getElementById(textBoxId);
    if (textBox.value == instructionalText) {
        textBox.value = "";
        if (maxLength) {
            textBox.maxLength = maxLength;
        }
    }
}

function replaceInstructionText(textBoxId, text, maxLength) {
    var textBox = document.getElementById(textBoxId);
    if(textBox.value == "")
    {
        textBox.value = text;
        if (maxLength) {
            textBox.maxLength = maxLength;
        }
    }
}

function enterClickHandler(e, buttonId) {
    //alert("HERE");
    var keynum = 0;
    if (window.event) // IE
    {
        keynum = window.event.keyCode;
    }
    else if (e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    if (keynum == 13) {
        var button = document.getElementById(buttonId);
        var result = true;
        if (button.onclick) {
            result = button.onclick();
        }
        if (result) {
            document.location.href = button.href;
        }
        return false;
    }
    return true;
}

//Showtime Search
var zipCodeBoxId;
var zipCodeUrlKey;

var radiusBoxId;
var radiusUrlKey;

var dateDropdownId;
var dateUrlKey;

var attributeDropdownId;
var attributeUrlKey;

var goButtonId;
var destinationUrl;
var autoPostBack = false;

function showtimeSearch() {
    clearInstructionText(zipCodeBoxId, true);
   
    var values = Array();
    values[zipCodeUrlKey] = document.getElementById(zipCodeBoxId) ? document.getElementById(zipCodeBoxId).value : "";
    values[radiusUrlKey] = document.getElementById(radiusBoxId) ? document.getElementById(radiusBoxId).value : "";
    var dateDropdown = document.getElementById(dateDropdownId);
    values[dateUrlKey] = (dateDropdown) ? dateDropdown.options[dateDropdown.selectedIndex].value : "";
    var attributeDropdown = document.getElementById(attributeDropdownId);
    values[attributeUrlKey] = (attributeDropdown) ? attributeDropdown.options[attributeDropdown.selectedIndex].value : "";

    //Put a space in for canadian values
    if (values[zipCodeUrlKey].length == 6) {
        values[zipCodeUrlKey] = values[zipCodeUrlKey].substr(0, 3) + " " + values[zipCodeUrlKey].substr(3);
    }

    if (values[zipCodeUrlKey].length != 5 && values[zipCodeUrlKey].length != 7) {
        alert("Please enter a valid postal code to continue");
        return false;
    }

    var goButton = document.getElementById(goButtonId);
    goButton.style.cursor = "default";
    
    if (!autoPostBack) //Navigate, do not post back
    {
        if (document.location.href.indexOf(destinationUrl) > 0) {
            destinationUrl = document.location.href;
        }
        var anchorTag = '#results';
        var location = destinationUrl ? destinationUrl : document.location.href;
        var destination = setQueryStringValues(location, values) + anchorTag;

        document.location.href = destination;
        
        if(location.replace(anchorTag,'') != destination.replace(anchorTag,''))
        {
            disableLink(goButtonId, "wait");
        }
        else
        {
            goButton.style.cursor = "pointer";
        }

        return false;
    }
    return true;
}

//Site Search
var searchTypeKey;
var searchTypeDropdownId;
var searchQueryKey;
var searchQueryId = "searchText";
var searchGoButtonId = "searchGoButton";
var searchDestinationUrl = "/Search.aspx";

function siteSearch() {
    clearInstructionText(searchQueryId, true);
    var values = Array();
    var searchTypeDropdown = document.getElementById(searchTypeDropdownId);
    if (searchTypeDropdown.options) {
        //Optionally present, do not override existing
        values[searchTypeKey] = searchTypeDropdown.options[searchTypeDropdown.selectedIndex].value;
    }
    else {
        values[searchTypeKey] = searchTypeDropdown.value;
    }
    values[searchQueryKey] = document.getElementById(searchQueryId).value;

//    if (!values[searchQueryKey]) {
//        //alert?
//        return;
//    }

    if (document.location.href.indexOf(searchDestinationUrl) > 0) {
        searchDestinationUrl = document.location.href;
    }
    document.location.href = setQueryStringValues(searchDestinationUrl, values);
    disableLink(searchGoButtonId, "wait");
    return false;
}

//AMC Images Prompt
function AcceptTerms() {
    $(document).ready(function() {
        var html = 'Your use of the assets within this area of site are subject to the <a href="/AMC_Info/Media_Center/Terms_of_Use">Terms of Use</a>.';
        var acceptedTerms = readCookie("amcImages");
        if (!acceptedTerms) {
            $.prompt(html, {
                buttons: { Accept: true },
                top: '50%',
                submit: function(v, m, f) {
                    if (v) {
                        //add cookie
                        createCookie("amcImages", "true", 1);
                        AcceptedTerms(true);
                    }
                }
            });
        }
        AcceptedTerms(acceptedTerms);
    });
}

function AcceptedTerms(yesNo) {
    if (yesNo) {
        $(".acceptedTermsButton").css("display", "inline");
    }
    else {
        $(".acceptedTermsButton").css("display", "none");
    }
}

//Message Prompt
function MessagePrompt(html) {
    $(document).ready(function() {
        $.prompt(html, {
            buttons: { OK: true },
            top: '25%'
        });
    });
}

//Load HomepageFlash
function LoadEscapePod()
{
	var flashvars = {};
	var params = {};
	params.wmode = "transparent";
	var attributes = {};
	attributes.id = "EscapePod";
	swfobject.embedSWF("/flash/EscapePod/EscapePodLoader.swf", "flashAlternativeContent", "891", "428", "9.0.0", "/flash/expressInstall.swf", flashvars, params, attributes);
}


//Font Size toggle
var min=12;
var max=20;
function increaseFontSize() {
   var p = document.getElementsByTagName('body');
   var smallLink = document.getElementById('textSmall');
   var largeLink = document.getElementById('textLarge');
   for(i=0;i<p.length;i++) {
      if(p[i].style.fontSize) {
         var s = parseInt(p[i].style.fontSize.replace("px",""));
      } else {
         var s = 14;
      }
      if(s!=max) {
         s += 2;
         largeLink.style.color = "#0e867d";
      }
      if(s==max){
        largeLink.style.color = "#ccdfdb";
        }
        if(s > min)
        {
            smallLink.style.color = "#0e867d";
        }
      p[i].style.fontSize = s+"px"
   }
}
function decreaseFontSize() {
   var p = document.getElementsByTagName('body');
   var smallLink = document.getElementById('textSmall');
   var largeLink = document.getElementById('textLarge');
   for(i=0;i<p.length;i++) {
      if(p[i].style.fontSize) {
         var s = parseInt(p[i].style.fontSize.replace("px",""));
      } else {
         var s = 14;
      }
      if(s!=min) {
         s -= 2;
         smallLink.style.color = "#0e867d";
      }
      if(s==min)
      {
        smallLink.style.color = "#ccdfdb";
      }
       if(s < max)
        {
            largeLink.style.color = "#0e867d";
        }
      p[i].style.fontSize = s+"px"
   }   
}

//cookie functions
function createCookie(name, value, days){
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
