// global variable
var CONTENTOFFSET = 0; /* fix for dynamic content area calculations */

//  jQuery FUNCTIONS

$(document).ready(function() {
    // Country select box replacement
    if ($('.countrySelectBoxData').length) {
        $('.countrySelectBoxData').sSelect();
    }

    // find current href
    var thisHref = location.href;
    thisHref = thisHref.split('/');
    currHref = thisHref[thisHref.length - 1];
    // top navigation on consumer and professional pages
    $('.topNavMain').find('.topNavItem').mouseover(function() {
        navHref = $(this).parent().attr('href');
        if (navHref != currHref) {
            $(this).addClass('hover');
        }
    });
    $('.topNavMain').find('.topNavItem').mouseout(function() {
        $(this).removeClass('hover');
    });
    // tabs on detail pages
    if ($('#tabs').length) {
        $('#tabs').tabs();
    }

    // class change on promo buckets
    if ($('.promoBucket').length) {
        $('.promoBucket').each(function() {
            $(this).mouseover(function() {
                $(this).find('.promoTitle').css('cursor', 'pointer');
                $(this).find('.promoTitle').addClass('hoverState');
                $(this).find('.promoTitle span').addClass('hoverState');
            });
            $(this).mouseout(function() {
                $(this).find('.promoTitle').removeClass('hoverState');
                $(this).find('.promoTitle span').removeClass('hoverState');
            });
        });
    }
    // class change on section nav
    if ($('.sectionNavContainer').length) {
        $('.navButtonContainer').each(function() {
            $(this).mouseover(function() {
                $(this).addClass('hoverState');
            });
            $(this).mouseout(function() {
                $(this).removeClass('hoverState');
            });
        });
    }

    //Blue bullets formatting.
    $('.blueBullets').each(function() {
        var bulletText = $(this).html();
        var span = $(this);
        var pTag = $(this).parent();
        pTag.each(function() {
            var current = $(this);
            var next = current.next();
            if (next.children().is('.blueBullets')) {
                // $(this).attr('style', "margin-bottom:0px;");
            }
            else {
                if (next.is('blockquote')) {
                    //$(this).attr('style', "margin-bottom:0px;");
                }
                else if ($(this).parent().is('blockquote')) {
                    //$(this).attr('style', "margin-bottom:0px;");
                    $(this).parent().attr('style', "margin-bottom:0px;");
                }
                else {
                    //  $(this).attr('style', "margin-bottom:20px;");
                }
            }
        });
    });
    
     //Code to add spacing if Bluebullets is below Header tag
        $('H1').each(function(){
       
            var current = $(this);
            var next = current.next();
            if (next.children().is('.blueBullets')) 
            {
                next.css("margin-top", "30px");
            }
               
         });
         $('H2').each(function(){
       
            var current = $(this);
            var next = current.next();
            if (next.children().is('.blueBullets')) 
            {
                next.css("margin-top", "30px");
            }
               
         });
         $('H3').each(function(){
       
            var current = $(this);
            var next = current.next();
            if (next.children().is('.blueBullets')) 
            {
                next.css("margin-top", "30px");
            }
               
         });
         $('H4').each(function(){
       
            var current = $(this);
            var next = current.next();
            if (next.children().is('.blueBullets')) 
            {
                next.css("margin-top", "28px");
            }
               
         });
    
    //      $('.blueBullets:last').parent().attr("style","margin-bottom:20px");
    $('div').each(function() {
        if ($(this).hasClass(".ui-tabs-panel")) {
            $(this).find('p:first').find('.blueBullets:first').attr("style", "margin-top:5px");

        }
    });
    $("#contentContainer img[hspace]").each(function() {

        var hspaceleft = $(this).attr("hspace");
        var hspaceright = $(this).attr("hspace");

        var vspacetop = $(this).attr("vspace");
        var vspacebottom = $(this).attr("vspace");

        if (hspaceleft != "-1" && hspaceright != "-1" && vspacetop != "-1" && vspacebottom != "-1" && hspaceleft != "0" && hspaceright != "0" && vspacetop != "0" && vspacebottom != "0") {
            var style = "padding-left:" + hspaceleft + "px;padding-right:" + hspaceright + "px;padding-top:" + vspacetop + "px;padding-bottom:" + vspacebottom + "px;";
            $(this).attr("style", style);
        }
        $(this).removeAttr("hspace");

        $(this).removeAttr("vspace");
    });

    // Blue - #3399CC
    // Orange - #E88A1A
    // White - #FFFFFF

    var args = document.URL.split("//"); // split at protocol
    args = args[1].split("?"); // remove query string
    args = args[0].split("/");
    for (var i = 0; i < args.length; i++) {
        if (args[i] == "professional" || args[i] == "consumer" || args[i] == "about") {
            $("#headerBackground").removeClass();
            if (args[i] == "professional") {
                $("#headerBackground").addClass("professional");
            }
            else if (args[i] == "about") {
                $("#headerBackground").addClass("aboutus");
            }
            else if (args[i] == "consumer") {
                $("#headerBackground").addClass("consumer");
            }
        }
    }
});

// LEFT MENU INIT 
if (ddaccordion) {
    ddaccordion.init({
        headerclass: "expandable", //Shared CSS class name of headers group that are expandable
        contentclass: "categoryitems", //Shared CSS class name of contents group
        revealtype: "clickgo", //Reveal content when user clicks or onmouseover the header? Valid value: "click" or "mouseover
        collapseprev: true, //Collapse previous content (so only one open at any time)? true/false 
        defaultexpanded: [], //index of content(s) open by default [index1, index2, etc]. [] denotes no content
        onemustopen: false, //Specify whether at least one header should be open always (so never all headers closed)
        animatedefault: false, //Should contents open by default be animated into view?
        persiststate: false, //persist state of opened contents within browser session?
        toggleclass: ["", "openheader"], //Two CSS classes to be applied to the header when it's collapsed and expanded, respectively ["class1", "class2"]
        togglehtml: ["suffix", "<img src='/images/greenarrow_bluebkg.gif' class='statusicon' />", "<img src='/images/greenarrow_bluebkg_down.gif' class='statusicon' />"],
        animatespeed: "normal", //speed of animation: "fast", "normal", or "slow"
        oninit: function(headers, expandedindices) { //custom code to run when headers have initalized
            //do nothing
        },
        onopenclose: function(header, index, state, isuseractivated) { //custom code to run whenever a header is opened or closed
            //do nothing
        }
    });

    ddaccordion.init({ //2nd level headers initialization
        headerclass: "subexpandable", //Shared CSS class name of sub headers group that are expandable
        contentclass: "subcategoryitems", //Shared CSS class name of sub contents group
        revealtype: "clickgo", //Reveal content when user clicks or onmouseover the header? Valid value: "click" or "mouseover"
        collapseprev: true, //Collapse previous content (so only one open at any time)? true/false 
        defaultexpanded: [], //index of content(s) open by default [index1, index2, etc]. [] denotes no content
        onemustopen: false, //Specify whether at least one header should be open always (so never all headers closed)
        animatedefault: false, //Should contents open by default be animated into view?
        persiststate: false, //persist state of opened contents within browser session?
        toggleclass: ["opensubheader", "closedsubheader"], //Two CSS classes to be applied to the header when it's collapsed and expanded, respectively ["class1", "class2"]
        togglehtml: ["suffix", "<img src='/images/greenarrow_bluebkg.gif' class='statusicon' />", "<img src='/images/greenarrow_bluebkg_down.gif' class='statusicon' />"],
        animatespeed: "normal", //speed of animation: "fast", "normal", or "slow"
        oninit: function(headers, expandedindices) { //custom code to run when headers have initalized
            //do nothing
        },
        onopenclose: function(header, index, state, isuseractivated) { //custom code to run whenever a header is opened or closed
            //do nothing
        }
    });
}
// EXPAND MENU (on pages that need open to specific menu choices) */

function expandContentContainer() {
    var top = $(".hdnPosition").val();
    var sub = $('.hdnVal').val();
    if (top != '') {
        expandMenu('expandable', top);
    }
    if (sub != "-1") {
        expandMenu('subexpandable', sub);
    }

    FixRelatedContentHeight();
    setTimeout(function() {
        var menuHeight = $('.leftmenu').height();
        var contentHeight = $('#contentContainer').height();
        var mainContentHeight = $('#mainContent').height();
        if (menuHeight > mainContentHeight) {
            $('#contentContainer').height(menuHeight + 65);
            var CONTENTOFFSET = menuHeight - contentHeight;

        }
        else {
            var CONTENTOFFSET = 0;
            $('#contentContainer').height(mainContentHeight);

        }


    }, 435);

}

function expand() {
    var top = $(".hdnPosition").val();
    var sub = $('.hdnVal').val();
    if (top != '') {
        expandMenu('expandable', top);
    }
    if (sub != "-1") {
        expandMenu('subexpandable', sub);
    }

    FixRelatedContentHeight();
    setTimeout(function() {
        var menuHeight = $('.leftmenu').height();
        var contentHeight = $('#contentContainer').height();
        // for ie6, set height since min-height isn't supported
        if ($.browser.msie && $.browser.version == 6.0) { $('#contentContainer').css({ 'height': menuHeight + 65 }); }
        // for all other browsers, including ie9 and FF4
        $('#contentContainer').css({ 'min-height': menuHeight + 65 });
        if (menuHeight > contentHeight) {
            CONTENTOFFSET = menuHeight - contentHeight;
        }
        else {
            CONTENTOFFSET = 0;
        }
    }, 435);
}



function FixRelatedContentHeight() {
    var relatedContainer = $('.relatedContent').height();
    var contentHeight = $('.relatedContentLeft').height();

    if (contentHeight > relatedContainer) {
        $('.relatedContent').height(contentHeight + 20);
    }
}

var menuHeight = $('.leftmenu').height();
var contentHeight = $('#contentContainer').height();

if (contentHeight < menuHeight) {
    $('#contentContainer').height(menuHeight + 65);
}

function expandMenu(menuClass, index) {
    ddaccordion.expandone(menuClass, index);
}

// SELECT ELEMENT REPLACEMENT (for language dropdowns)
function selectReplacement(obj) {
    // create list for styling
    var ul = document.createElement('ul');
    ul.className = 'selectReplacement';
    var opts = obj.options;
    for (var i = 0; i < opts.length; i++) {
        var selectedOpt;
        if (opts[i].selected) {
            selectedOpt = i;
            break;
        } else {
            selectedOpt = 0;
        }
    }
    for (var i = 0; i < opts.length; i++) {
        var li = document.createElement('li');

        var aHref = document.createElement('a');
        aHref.href = "http:/" + $("select.langSelect")[0].options[i].value;
        aHref.title = opts[i].title;

        if ($("select.langSelect")[0].options[i].label != "") {
            var img = document.createElement("img");
            img.src = $("select.langSelect")[0].options[i].label;
            img.alt = "";
            aHref.setAttribute("style", "color:white;text-decoration:none;padding-top:5px;width:85px;");
            aHref.appendChild(img);
        }
        else {
            var txt = document.createTextNode(opts[i].title);
            aHref.setAttribute("style", "color:white;text-decoration:none;width:85px;");
            aHref.appendChild(txt);

        }

        li.appendChild(aHref);

        li.selIndex = opts[i].index;
        li.selectID = obj.id;
        li.onclick = function() {
            selectMe(this);
        }
        if (i == selectedOpt) {
            li.className = 'selected';
            li.onclick = function() {
                this.parentNode.className += ' selectOpen';
                this.onclick = function() {
                    selectMe(this);
                }
            }
        }
        if (window.attachEvent) {
            li.onmouseover = function() {
                this.className += ' hover';
            }
            li.onmouseout = function() {
                this.className =
		  this.className.replace(new RegExp(" hover\\b"), '');
            }
        }
        ul.appendChild(li);
    }
    // add the input and the ul
    obj.parentNode.appendChild(ul);
}
function selectMe(obj) {

    var lis = obj.parentNode.getElementsByTagName('li');
    for (var i = 0; i < lis.length; i++) {
        if (lis[i] != obj) { // not the selected list item
            lis[i].className = '';
            lis[i].onclick = function() {
                selectMe(this);
            }
        } else {
            setVal(obj.selectID, obj.selIndex);
            obj.className = 'selected';
            obj.parentNode.className = obj.parentNode.className.replace(new RegExp(" selectOpen\\b"), '');
            //window.location = lis[obj.selIndex].childNodes[0].href;
            obj.onclick = function() {
                obj.parentNode.className += ' selectOpen';
                this.onclick = function() {
                    selectMe(this);
                }
            }
        }
    }
}
function setVal(objID, selIndex) {
    var obj = document.getElementById(objID);
    obj.selectedIndex = selIndex;
}
function closeSel(obj) {
    // close the ul
}

// THICKBOX CALL (for overlays)


function openBox(w, h, box) {
    tb_show('', '#TB_inline?width=' + w + '&height=' + h + '&inlineId=' + box + '&modal=true', '');
}

function closeBox() {
    self.parent.tb_remove();
}



// BROWSER DETECTION (used for ddaccordion.js IE6 exception)
var BrowserDetect = {
    init: function() {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function(data) {
        for (var i = 0; i < data.length; i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function(dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
    },
    dataBrowser: [
		{
		    string: navigator.userAgent,
		    subString: "Chrome",
		    identity: "Chrome"
		},
		{ string: navigator.userAgent,
		    subString: "OmniWeb",
		    versionSearch: "OmniWeb/",
		    identity: "OmniWeb"
		},
		{
		    string: navigator.vendor,
		    subString: "Apple",
		    identity: "Safari",
		    versionSearch: "Version"
		},
		{
		    prop: window.opera,
		    identity: "Opera"
		},
		{
		    string: navigator.vendor,
		    subString: "iCab",
		    identity: "iCab"
		},
		{
		    string: navigator.vendor,
		    subString: "KDE",
		    identity: "Konqueror"
		},
		{
		    string: navigator.userAgent,
		    subString: "Firefox",
		    identity: "Firefox"
		},
		{
		    string: navigator.vendor,
		    subString: "Camino",
		    identity: "Camino"
		},
		{		// for newer Netscapes (6+)
		    string: navigator.userAgent,
		    subString: "Netscape",
		    identity: "Netscape"
		},
		{
		    string: navigator.userAgent,
		    subString: "MSIE",
		    identity: "Explorer",
		    versionSearch: "MSIE"
		},
		{
		    string: navigator.userAgent,
		    subString: "Gecko",
		    identity: "Mozilla",
		    versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
		    string: navigator.userAgent,
		    subString: "Mozilla",
		    identity: "Netscape",
		    versionSearch: "Mozilla"
		}
	],
    dataOS: [
		{
		    string: navigator.platform,
		    subString: "Win",
		    identity: "Windows"
		},
		{
		    string: navigator.platform,
		    subString: "Mac",
		    identity: "Mac"
		},
		{
		    string: navigator.userAgent,
		    subString: "iPhone",
		    identity: "iPhone/iPod"
		},
		{
		    string: navigator.platform,
		    subString: "Linux",
		    identity: "Linux"
		}
	]

};
BrowserDetect.init();

function disableEnterKey(e) {
    var key;
    if (window.event)
        key = window.event.keyCode; //IE
    else
        key = e.which; //firefox     

    return (key != 13);
}

function processEnterKey(evt) {
    var evt = (evt) ? evt : ((event) ? event : null);
    var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
    if (evt.keyCode == 13) {
        if (node.name == "searchInputBox") {
            submitSearch(document.forms[0].searchInputBox.value);
        } else if (node.name == "q") {
            submitSearch(document.forms[0].q.value);
        }
        else if (node.name == "gmaps") {
            searchCine();
        }
        return false;
    }
    return true;
}

//function submitSearch(searchValue) {
//    window.location = "/sitesearch/index.aspx?q=" + encodeURI(searchValue);
//    return false;
//}

function submitSearch(searchValue) {
    var pUrl = parent.document.URL;
    
    if (pUrl.indexOf("us/en") != -1)
        window.location = "/us/en/sitesearch/index.aspx?q=" + encodeURI(searchValue);
    else if(pUrl.indexOf("gb/en") != -1)
        window.location = "/gb/en/sitesearch/index.aspx?q=" + encodeURI(searchValue);
    else if (pUrl.indexOf("jp/ja") != -1)
        window.location = "/jp/ja/sitesearch/index.aspx?q=" + encodeURI(searchValue);
    else if (pUrl.indexOf("cn/zh") != -1)
        window.location = "/cn/zh/sitesearch/index.aspx?q=" + encodeURI(searchValue);
    else
        window.location = "/us/en/sitesearch/index.aspx?q=" + encodeURI(searchValue);
    return false;
}

function clearInputBox(theBox, str) {
    if (theBox.value == str)
        theBox.value = "";
}
function populateInputBox(theBox, str) {
    if (theBox.value.replace(/^\s+|\s+$/g, "") == "")
        theBox.value = str;
}
function rollImage(theImage, newImage) {
    theImage.src = newImage.src;
}
function searchCine() {
    var srcTextField = document.getElementById('gmapsearch');
    if (srcTextField.value != "")
        window.location.href = "/consumer/product/movies/theater/find-a-cinema.html?onlnk=icf|hl-find&cq=" + srcTextField.value + "";
}

