var $j = jQuery.noConflict();

var buttonPopout;
var onBar = false;
var barTimer;

function swapLayers() {
    if (currentFeatureLayer == 2) {
        $j("#featuredContainer1").css('zIndex', 10);
        $j("#featuredContainer2").css('zIndex', 9);
        currentFeatureLayer = 1;
    }
    else if (currentFeatureLayer == 1) {
        $j("#featuredContainer2").css('zIndex', 10);
        $j("#featuredContainer1").css('zIndex', 9);
        currentFeatureLayer = 2;
    }

    setTimeout('changeFeature()', 7500);
}

$j(document).ready(function () {

    //Adds "click" class to the menu buttons when clicked (changes background of button)
    $j("#pageHeader > ul > li > a.link").mousedown(function () {
        $j(this).addClass("click");
    });

    //Removes "click" class from the menu buttons on unclick (changes background of button)
    $j("#pageHeader > ul > li > a.link").mouseup(function () {
        $j(this).removeClass("click");
    });

    //Opens the popout menu when the mouse moves over a button
    //$("#pageHeader > ul > li > a.button").mouseenter(function () {
    //    $("#popoutMenu").css("display", "block");
    //});

    //Opens the popout menu when the mouse moves over a button
    $j("#pageHeader > ul > li > a.button").mouseenter(function () {
        if (onBar) {
            $j("#popoutMenu").css("display", "block");
        } else {
            barTimer = setTimeout(function () {
                $j("#popoutMenu").css("display", "block");
            }, 500);
        }
        onBar = true;
    });


    $j(".link1").mouseenter(function () {
        $j("#popout1").css("display", "block");
        $j("#popout1 > ul > li > a").css("display", "block");
        $j("#popout2").css("display", "none");
        $j("#popout2 > ul > li > a").css("display", "none");
        $j("#popout3").css("display", "none");
        $j("#popout3 > ul > li > a").css("display", "none");

        buttonPopout = "linkProducts";
    });

    $j(".link2").mouseenter(function () {
        $j("#popout1").css("display", "none");
        $j("#popout1 > ul > li > a").css("display", "none");
        $j("#popout2").css("display", "block");
        $j("#popout2 > ul > li > a").css("display", "block");
        $j("#popout3").css("display", "none");
        $j("#popout3 > ul > li > a").css("display", "none");

        buttonPopout = "linkResources";
    });

    $j(".link3").mouseenter(function () {
        $j("#popout1").css("display", "none");
        $j("#popout1 > ul > li > a").css("display", "none");
        $j("#popout2").css("display", "none");
        $j("#popout2 > ul > li > a").css("display", "none");
        $j("#popout3").css("display", "block");
        $j("#popout3 > ul > li > a").css("display", "block");

        buttonPopout = "linkSupport";
    });

    //Hides the popout menu when the mouse leave a button
    $j("#pageHeader > ul > li > a.button").mouseleave(function () {
        $j("#popoutMenu").css("display", "none");
    });

    //Keeps the popout menu open if a user moves the mouse from a button to the popout menu
    $j("#popoutMenu").mouseenter(function () {
        $j("#popoutMenu").css("display", "block");

        if (buttonPopout == "linkProducts")
            $j(".link1").addClass("popout");

        if (buttonPopout == "linkResources")
            $j(".link2").addClass("popout");

        if (buttonPopout == "linkSupport")
            $j(".link3").addClass("popout");
    });

    //added
    $j("#pageHeader").mouseleave(function () {
        onBar = false;
        clearTimeout(barTimer);
    });

    //Hides the popout menu if a user moves the mouse out of the popout menu
    $j("#popoutMenu").mouseleave(function () {
        $j("#popoutMenu").css("display", "none");

        if (buttonPopout == "link1")
            $j(".link1").removeClass("popout");

        if (buttonPopout == "link2")
            $j(".link2").removeClass("popout");

        if (buttonPopout == "link3")
            $j(".link3").removeClass("popout");
    });

    $j(".compLink").click(function (e) {
        // Hide all previous open popups
        $j("div.compPopUpContainer").hide();

        // Calculate the offset information for the currently requested popup
        var containerTop = $j('.pageContainer').offset().top - 10;
        var containerLeft = $j('.pageContainer').offset().left + 50;

        if ($j(this).closest('.kazusaSearchResults').length > 0) {
            $j(this).next('.compPopUpContainer').css({
                display: 'block',
                top: (e.pageY - containerTop),
                right: '30px'
            });
        } else {
            $j(this).closest('ul').next('.compPopUpContainer').css({
                display: "block",
                top: (e.pageY - containerTop),
                left: (e.pageX - containerLeft)
            });
        }
        return false;
    });

    $j(".close").click(function (e) {
        $j(".compPopUpContainer").hide();
    });

    // For the support pages to display the region-appropriate div on load
    //$(".supportFull").css('display', 'none');
    //$(".supportLocalized").css('display','block');



    // start new tab code
    if (jQuery("div.pageContainer ul.tab").length > 0) {
        var $tabContents = jQuery("div.tabContents"),
			$subTabContent = jQuery('div.tabContents div.tabContents').eq(0);

        // If there's a tab bar, hide all tab content divs
        //jQuery("div.tabContents").hide();
        $tabContents.hide();

        // Then show the first
        //jQuery("div.tabContents").eq(0).show();
        $tabContents.eq(0).show();

        // Show the first sub-tab within the active tab
        $subTabContent.show();
    }

    // New Tab Behavior
    $j("div.pageContainer ul.tab li.tab").click(function () {
        var $this = jQuery(this),
			$parent = $this.parent(),
			$active = $parent.nextAll("div.tab" + $this.index());

        // Hide all tab content divs
        if ($parent.hasClass('subTab')) {
            // Hide all other tabs
            $parent.parent().nextAll('div.tabContents').hide();

            // Show proper tab
            $parent.parent().nextAll('div.tab' + $this.index()).show();
        } else {
            // Hide all other tabs
            $parent.nextAll('div.tabContents').hide();

            // Show the proper tab
            $active.show();
        }

        // Remove the selected class from all tabs
        $parent.children("li.tab").removeClass("selected");

        // Highlight the currently clicked tab
        $this.addClass("selected");
    });

    // end new tab code
});

function setActiveTab(active) {
    // use this to override the initial active tab
    var activeTab = $j('.' + active),
		activeIndex = active.indexOf('tab'),
		activeNumber = active.charAt(activeIndex + 3);

    $j('div.tabContainer div.tabContents').hide();
    activeTab.show();
    $j('div.tabContainer > ul.tab li').removeClass('selected');
    $j('div.tabContainer > ul.tab li:eq(' + activeNumber + ')').addClass('selected');
}


//assigning x,y coordinates of popup based on cursor position

$j("#compLink").mousedown(function () {
    alert("works");
});


function swapTab(page, tag) {
    $j(".compPopUpContainer").css('display', 'none');
    var i = 1;
    var el;
    while (el = document.getElementById(tag + i)) {
        if (i == page)
            el.style.display = 'block';
        else
            el.style.display = 'none';
        i++;
    }
}

// Added by Sober to allow swapping out of Region divs on Support page. May need refactor.
function swapDiv(page, tag) {
    var i = 1;
    var el;
    while (el = document.getElementById(tag + i)) {
        if (i == page)
            el.style.display = 'block';
        else
            el.style.display = 'none';
        i++;
    }
}

// Added by Sober to enable the Support page refactor. May need review.
function swapVisibility(d) {
    if (document.getElementById(d).style.display != "block") {
        document.getElementById(d).style.display = "block";
    }
    else {
        document.getElementById(d).style.display = "none";
    }
}

/* function expand(d) {
if (document.getElementById(d).style.display != "block") {
document.getElementById(d).style.display = "block";
document.getElementById('contentBlockFullLess').style.display = "none"
document.getElementById('moreLink').innerHTML = "Less &raquo;";
}
else {
document.getElementById(d).style.display = "none";
document.getElementById('contentBlockFullLess').style.display = "block"
document.getElementById('moreLink').innerHTML = "More &raquo;";
}
} */
function expand(d, e, f) {
    var doc = document,
		el = doc.getElementById(d),
		moreLink = doc.getElementById(d + '-more');

    if (el.style.display !== 'block') {
        el.style.display = 'block';
        if (moreLink) {
            if (f) {
                moreLink.innerHTML = e;
            } else {
                moreLink.innerHTML = '&laquo; Less';
            }
        }
    } else {
        el.style.display = 'none';
        if (moreLink) {
            if (e) {
                moreLink.innerHTML = f;
            } else {
                moreLink.innerHTML = 'More &raquo;';
            }
        }
    }
}

// pass in container and href id's
function namedExpand(d, e, f, g) {
    var doc = document,
		el = doc.getElementById(d),
		moreLink = doc.getElementById(e);
    if (el.style.display !== 'block') {
        el.style.display = 'block';
        if (moreLink) {
            if (f) {
                moreLink.innerHTML = f;
            } else {
                moreLink.innerHTML = '&laquo; Less';
            }
        }
    } else {
        el.style.display = 'none';
        if (moreLink) {
            if (g) {
                moreLink.innerHTML = g;
            } else {
                moreLink.innerHTML = 'More &raquo;';
            }
        }
    }
}

//added for button press on search

function expandProductDescription(d, b) {
    var doc = document,
                   el1 = doc.getElementById(d),
                   el2 = doc.getElementById(b);

    if (el1.style.display !== 'block') {
        el1.style.display = 'block';
        el2.style.display = 'none';
    } else {
        el1.style.display = 'none';
        el2.style.display = 'block';
    }
}

function keyDownSubmitButton(event, link) {
    if (event.which || event.keyCode) {
        /// Enter key
        if ((event.which == 13) || (event.keyCode == 13)) {
            /// In order to handle the "enter button submits the form" issue, we need to prevent the default behavior and set the return value to false
            if (event.preventDefault) {
                // Most browsers
                event.preventDefault();
            }

            /// Cancel the "enter" press event to avoid submitting the form.
            event.cancelBubble = true;
            event.returnValue = false;

            /// Do click the link
            document.location = document.getElementById(link).href;
        }
    } else {
        return true;
    }
}

function performSearch(searchPageUrl, searchTextBox, sortBy) {
    var searchQuery = document.getElementById(searchTextBox).value;
    if (searchQuery) {
        var redirectLocation = searchPageUrl + "?q=" + encodeURIComponent(searchQuery);
        if (sortBy) {
            redirectLocation += "&s=" + sortBy;
        }
        document.location = redirectLocation;
    }
}

function sortSearchResults(sortingDropDownList) {
    /// Get the selected sort-by field
    var sortField = sortingDropDownList.options[sortingDropDownList.selectedIndex].value;

    /// Redirect
    document.location = addOrReplaceQueryStringParameter(document.location, "s", sortField);
}

function openContact(url) {
    newWin = window.open(url, 'Contact', 'SCROLLBARS=NO,RESIZABLE=YES');
    if (window.focus) { newWin.focus(); }
    return false; //this protects this page from errors on the popup.  will allow the link to work as a direct link
}

function changeMSDSLinks(LanguagesDropDownList, link1ID, link2ID) {
    /// Get the URL that's stored in the drop-down list's value
    var newUrl = LanguagesDropDownList.value;

    /// Get the link(s) to update
    var link1 = document.getElementById(link1ID);
    var link2 = document.getElementById(link2ID);

    /// Update them.
    if (link1) {
        link1.href = newUrl;
    }
    if (link2) {
        link2.href = newUrl;
    }
}

function changeSearchResultsPageSize(pageSizeDropDownList) {
    /// Get the selected page size
    var pageSize = pageSizeDropDownList.options[pageSizeDropDownList.selectedIndex].value;

    /// Redirect
    var newLocation = addOrReplaceQueryStringParameter(document.location, "ps", pageSize);
    document.location = addOrReplaceQueryStringParameter(newLocation, "pg", 1);
}

function addOrReplaceQueryStringParameter(urlToProcess, queryStringParameterName, queryStringParameterValue) {

    var startLocation = new String(urlToProcess);
    var finalLocation = null;
    var extraQueryString = null;

    /// Check to see if the parameter is already in the query string, either with a ? or a & before it
    var indexOfQueryStringParameter = startLocation.indexOf("?" + queryStringParameterName + "=");
    if (indexOfQueryStringParameter <= 0) {
        indexOfQueryStringParameter = startLocation.indexOf("&" + queryStringParameterName + "=");
    }

    if (indexOfQueryStringParameter >= 0) {
        /// Check to see if there's more AFTER the query string parameter
        var indexOfAmpersand = startLocation.indexOf("&", indexOfQueryStringParameter + 1);

        finalLocation = startLocation.substring(0, indexOfQueryStringParameter);

        /// If there's more (not just an &, but also more beyond that), hold onto it for after we add the current param
        if (indexOfAmpersand >= 0 && startLocation.length > indexOfAmpersand + 1) {
        	extraQueryString = startLocation.substring(indexOfAmpersand);
        }
    } else {
        finalLocation = startLocation;
    }

    /// If there's a query string already, add an ampersand. If not, add a question mark.
    if (finalLocation.indexOf("?") >= 0) {
        finalLocation += "&";
    } else {
        finalLocation += "?";
    }

    /// Add the querystring param and value to the end
    finalLocation += queryStringParameterName + "=" + queryStringParameterValue;

    if (extraQueryString !== null) {
    	finalLocation += extraQueryString;
    }

    return finalLocation;
}


function getCountryFlagImageUrlForCountry(country) {
    /// If we don't have a flag for this country, we'll use the default: a globe.
    var imageSource = "/~/media/Images/Flags/Footer%20Flags/Globe.ashx";

    var countriesWithFlags = "ALB;AND;AUS;AUT;BEL;BGR;BIH;BLR;BRA;CHE;CHN;CYP;CZE;DEU;DNK;ESP;EST;FIN;FRA;FRO;GBR;GEO;GIB;GRC;HRV;HUN;IRL;ISL;ITA;JPN;KOR;LIE;LUX;LVA;MAR;MDA;MKD;MLT;NLD;NOR;POL;PRT;ROU;RUS;SGP;SJM;SMR;SVK;SVN;SWE;TUR;UKR;USA;ABW;AGO;AIA;ANT;ARE;ARG;ARM;ASM;ATA;ATF;ATG;AZE;BDI;BEN;BFA;BGD;BHR;BHS;BLZ;BMU;BOL;BRB;BRN;BTN;BVT;BWA;CAF;CAN;CCK;CHL;CIV;CMR;COG;COK;COL;COM;CPV;CRI;CUB;CXR;CYM;DJI;DMA;DOM;DZA;ECU;EGY;ERI;ESH;ETH;FJI;FLK;FSM;GAB;GHA;GIN;GLP;GMB;GNB;GNQ;GRD;GRL;GTM;GUF;GUM;GUY;HKG;HMD;HND;HTI;IDN;IND;IOT;IRN;IRQ;ISR;JAM;JOR;KAZ;KEN;KGZ;KHM;KIR;KNA;KWT;LAO;LBN;LBR;LBY;LCA;LKA;LOS;LTU;MAC;MCO;MDG;MDV;MEX;MHL;MLI;MMR;MNG;MNP;MOZ;MRT;MSR;MTQ;MUS;MWI;MYS;MYT;NAM;NCL;NER;NFK;NGA;NIC;NIU;NPL;NRU;NZL;OMN;PAK;PAN;PCN;PER;PHL;PLW;PNG;PRI;PRK;PRY;PYF;QAT;REU;RWA;SAU;SCG;SDN;SEN;SGS;SHN;SLB;SLE;SLV;SOM;SPM;STP;SUR;SWZ;SYC;SYR;TCA;TCD;TGO;THA;TJK;TKL;TKM;TMP;TON;TTO;TUN;TUV;TWN;TZA;UGA;UMI;URY;UZB;VAT;VCT;VEN;VGB;VIR;VNM;VUT;WLF;WSM;YEM;YUG;ZAF;ZAR;ZMB;ZWE";

    if (countriesWithFlags.indexOf(country) != -1) {
        imageSource = "/~/media/Images/Flags/Footer%20Flags/" + country + ".ashx";
    }

    return imageSource;
}

function openContact(url) {
    newWin = window.open(url, 'Contact', 'SCROLLBARS=NO,RESIZABLE=YES');
    if (window.focus) { newWin.focus(); }
    return false; //this protects this page from errors on the popup.  will allow the link to work as a direct link
}
