

/* EDP_HeaderController */
/* pts ticker badge */
var dontHideBadgeOffers = false;
var whichPageLoaded = null;

window.onresize = loadim;

$j(window).ready(scrollToTarget);

function scrollToTarget() {
    var anchorParameters = {
        'scrollToName'  : '[name="{{query}}"]',
        'scrollToID'    : '#{{query}}',
        'scrollToClass' : '.{{query}}'
    };

    $j.each(anchorParameters, function(key, value) {
        var index = document.URL.toLocaleLowerCase().indexOf(key.toLowerCase());

        if (index >= 0) {
            var target = document.URL.substring(index).split('/')[1];

            if (target !== undefined && target.length >= 3 &&(target = $j(value.replace('{{query}}', target))).length > 0) {
                $j("html, body").animate({ scrollTop: target.first().offset().top }, 1000);
            }

            return false;
        }
    });
}

function loadim() {
    var img = document.getElementById('catbgimg');
    if(img){
        var ratio = document.body.offsetWidth / img.width;
        img.height = img.height * ratio;
        img.width = img.width * ratio;
    }
}

function setDontHideBadgeOffers(value)
{
    dontHideBadgeOffers = value;
}

function getDontHideBadgeOffers()
{
    return dontHideBadgeOffers;
}

function showBadgeOffers()
{
    setDontHideBadgeOffers(true);
    setTimeout('_showBadgeOffers()',10);

    $('starAdvArrow').src = 'https://imga.corporateperks.com/emp_image/UserRank/header/header_arrow_up.gif';
    $('starAdvantageReadoutContainer').stopObserving('click', showBadgeOffers);
    $('starAdvantageReadoutContainer').observe('click', hideBadgeOffers);
}

function _showBadgeOffers() {
    setDontHideBadgeOffers(false);

    $('ptsTickerNormalBG').style.visibility = 'hidden';
    $('ptsTickerBadgeBG').style.visibility = 'visible';

    $('ptsBadgeOffers').innerHTML = '<center><img alt="Loading Offers" src="https://imga.corporateperks.com/emp_image/invitefriend/loading.gif" title="Loading Offers"></center>';

    var howManyPerPage = 4;
    new Ajax.Request('/header/getstaradvantage/', {
        method:'get',
        onSuccess:loadStarAdvantage
    });
}


function loadStarAdvantage(ajax_request){
    $('ptsBadgeOffers').innerHTML = ajax_request.responseText;
    if($('hpbRed_0')) {
        var bonusCount = parseInt($('bonusCountHeader').value);
        for (var i = 0; i < bonusCount; i++){
            var timeleft = parseInt($('timeLeftHeader_' + i).value);
            var timetotal = parseInt($('timeTotalHeader_' + i).value);
            if (timetotal != 0) {
                new Effect.Morph('hpbRed_' + i, {style:'width:' + timeleft*(233/timetotal) + 'px', duration:1});
            }
        }
    }
    if($('hpbBlue')) {
        var lastYear = parseInt($('lastYearHeader').value);
        var userRankLastYear = parseInt($('userRankLastYearHeader').value);
        var userRankThisYear = parseInt($('userRankThisYearHeader').value);
        var qualPtsEarnedThisYear = parseInt($('qualPointsEarnedThisYearHeader').value);

        if (userRankThisYear == 5 || userRankLastYear == 5) {
            new Effect.Morph('hpbBlue', {style:'width:233px', duration:1});
        } else if (lastYear == 1) {
            var nextLevel = userRankLastYear + 1;
            new Effect.Morph('hpbBlue', {style:'width:' + qualPtsEarnedThisYear*(233/(nextLevel*1000)) + 'px', duration:1});
        } else {
            qualPtsEarnedThisYear = qualPtsEarnedThisYear - (userRankThisYear*1000);
            new Effect.Morph('hpbBlue', {style:'width:' + qualPtsEarnedThisYear*.233 + 'px', duration:1});
        }
    }
}



function hideBadgeOffers()
{
    pointsActivity.hideInfo();
}



/* pts ticker */
function flashCounter(message, param, param2)
{
    if (message == 'winner')
        var bgImageAddress = 'https://imga.corporateperks.com/emp_image/header/pts_ticker_winner.gif';
    else
        return; /* for now, only 'winner' supported */

    for (var f = 1; f <= 7; f++)
        $('ptsTickerDigit'+f).style.backgroundImage = "url('"+bgImageAddress+"')";

    var normalFlashDuration = 150;
    var lastFlashDuration = 2000;
    var delayBeforeCountUp = 3000;

    for (var i = 0; i < 40; i += 2)
    {
        setTimeout('flashCounterWinnerB()', i*normalFlashDuration);
        setTimeout('flashCounterWinnerA()', (i+1)*normalFlashDuration);
    }

    var resetDigitBackgrounds = "";
    for (f = 1; f <= 7; f++) {
        resetDigitBackgrounds += "$('ptsTickerDigit"+f+"').style.backgroundImage = \"url('https://imga.corporateperks.com/emp_image/header/pts_ticker_digits_2b.gif')\";";
    }
    setTimeout(resetDigitBackgrounds, (i-1)*normalFlashDuration+lastFlashDuration);

    setTimeout("resetCounterTo("+param+",'ptsTickerDigit');", (i-1)*normalFlashDuration+lastFlashDuration);
    if(!(param && param2 && param == param2)) {
        for (f = 0; f < 15; f += 2)
        {
            setTimeout("resetCounterTo(null,'ptsTickerDigit');", (i-1)*normalFlashDuration+lastFlashDuration*2 + f*normalFlashDuration);
            setTimeout("resetCounterTo("+param+",'ptsTickerDigit');", (i-1)*normalFlashDuration+lastFlashDuration*2 + (f+1)*normalFlashDuration);
        }
        setTimeout("spinCounter("+param2+",'ptsTickerDigit');", (i-1)*normalFlashDuration+lastFlashDuration+(f-1)*normalFlashDuration+delayBeforeCountUp);
    }
}

function flashCounterWinnerA()
{
    changeBackgroundPosition('ptsTickerDigit1', -47, 0);
    changeBackgroundPosition('ptsTickerDigit2', -70, 0);
    changeBackgroundPosition('ptsTickerDigit3', -94, 0);
    changeBackgroundPosition('ptsTickerDigit4', -117, 0);
    changeBackgroundPosition('ptsTickerDigit5', -140, 0);
    changeBackgroundPosition('ptsTickerDigit6', -164, 0);
    changeBackgroundPosition('ptsTickerDigit7', -187, 0);
}

function flashCounterWinnerB()
{
    changeBackgroundPosition('ptsTickerDigit1', -47, -39.5);
    changeBackgroundPosition('ptsTickerDigit2', -70, -39.5);
    changeBackgroundPosition('ptsTickerDigit3', -94, -39.5);
    changeBackgroundPosition('ptsTickerDigit4', -117, -39.5);
    changeBackgroundPosition('ptsTickerDigit5', -140, -39.5);
    changeBackgroundPosition('ptsTickerDigit6', -164, -39.5);
    changeBackgroundPosition('ptsTickerDigit7', -187, -39.5);
}



/* ptspopup */
function findPosY(obj)
{
    var curtop = 0;
    if(obj.offsetParent) {
        while(1)
        {
            curtop += obj.offsetTop;
            if(!obj.offsetParent){
                break;
            }
            obj = obj.offsetParent;
        }
    }
    else if(obj.y) {
        curtop += obj.y;
    }
    return curtop;
}

function findPosX(obj)
{
    var curleft = 0;
    if(obj.offsetParent) {
        while(1)
        {
            curleft += obj.offsetLeft;
            if(!obj.offsetParent)
                break;
            obj = obj.offsetParent;
        }
    }
    else if(obj.x) {
        curleft += obj.x;
    }
    return curleft;
}


function getPosY(e) {
    var posy = 0;
    if (!e) var e = window.event;

    if (e.clientY) {
        posy = e.clientY
    } else if (e.pageY) {
        posy = e.pageY;
    }


    if(document.body.scrollTop && document.body.scrollTop > 0) {
        posy = posy + document.body.scrollTop;
    }
    else if (document.documentElement.scrollTop && document.documentElement.scrollTop > 0) {
        posy = posy + document.documentElement.scrollTop;
    }
    else if (e.pageYOffset && e.pageYOffset > 0) {
        posy = posy + e.pageYOffset;
    }

    return posy;
}

function getPosX(e) {
    var posx = 0;
    if (!e) var e = window.event;
    if (e.clientX) {
        posx = e.clientX
    } else if (e.pageX) {
        posx = e.pageX;
    }

    if(document.body.scrollLeft && document.body.scrollLeft > 0) {
        posx = posx + document.body.scrollLeft;
    }
    else if (document.documentElement.scrollLeft && document.documentElement.scrollLeft > 0) {
        posx = posx + document.documentElement.scrollLeft;
    }
    else if (e.pageXOffset && e.pageXOffset > 0) {
        posx = posx + e.pageXOffset;
    }

    return posx;
}

function getMouseXY(e) {
    if (IE) { // grab the x-y pos.s if browser is IE
        tempX = event.clientX + document.body.scrollLeft
        tempY = event.clientY + document.body.scrollTop
    } else {  // grab the x-y pos.s if browser is NS
        tempX = e.pageX
        tempY = e.pageY
    }
    // catch possible negative values in NS4
    if (tempX < 0){tempX = 0}
    if (tempY < 0){tempY = 0}
    // show the position values in the form named Show
    // in the text fields named MouseX and MouseY
    document.Show.MouseX.value = tempX
    document.Show.MouseY.value = tempY
    return true
}

//
function togglelogin(event)
{


    if(getPosY(event)>1200)
        $("loginpopup").style.top = "950px";
    else
    {
        if(getPosY(event)>400)
            $("loginpopup").style.top = "" + (0 + getPosY(event) -220) + "px";
        else
            $("loginpopup").style.top = "0px";
    }



    if($("SIBack"))
    {
        if($("SIBack").style.display =='block')
        {
            document.body.style.background='#fff';
            $("loginpopup").style.display='none';
            $("SIBack").style.display ='none';
        }
        else
        {
            document.body.style.background='#e8e8e8';
            $("outer-container").style.background='#fff';
            $("loginpopup").style.display='block';

            $("SIBack").style.display ='block';
        }

    }
}

function toggleloginnewdeal(event)
{


    if(getPosY(event)>1200)
        $("loginpopup").style.top = "950px";
    else
    {
        if(getPosY(event)>400)
            $("loginpopup").style.top = "" + (0 + getPosY(event) -320) + "px";
        else
            $("loginpopup").style.top = "0px";
    }



    if($("SIBack"))
    {
        if($("SIBack").style.display =='block')
        {
            document.body.style.background='#fff';
            $("loginpopup").style.display='none';
            $("SIBack").style.display ='none';
        }
        else
        {
            document.body.style.background='#e8e8e8';
            $("outer-container").style.background='#fff';
            $("loginpopup").style.display='block';

            $("SIBack").style.display ='block';
        }

    }
}

function validateJoin1() {
    if (validate_email($("joinEmail1").value)) {
        return true;
    } else {
        $('error-message11').style.display='block';
        $('error-space1').style.display='none';
        $('error-message11').update("The email address you provided doesn't appear to be valid.");
        return false;
    }
}

function validatePassword1() {
    if ($("loginPasswordStar1").value.length > 0) {
        return true;
    } else {
        $('error-message11').style.display='block';
        $('error-space1').style.display='none';
        $('error-message11').update("Please enter a password.");
        return false;
    }
}

function submitJoin1() {
    if (validateJoin1()) {
        document.join1.submit();
    }
}

function submitLogin1() {

    if (validateEmail1() && validatePassword1()) {

        document.login1.submit();

        return true;
    }
//  else return false;
}
//
function validateEmail1() {
    if (validate_email($("loginEmail1").value)) {
        return true;
    } else {
        $('error-message11').style.display='block';
        $('error-space1').style.display='none';
        $('error-message11').update("A valid email address is required.");
        return false;
    }
}

function hide(divID){
    if ($(divID) && $(divID).style.display == 'block')
        $(divID).style.display = 'none';
}

function bodyClick(){
    //maincatnavoff();

    var urlpath = window.location.pathname;
    var path_array = urlpath.split("/");

    hide('filter_dropdown');
    hide('org_dropdown');
    hide('category_dropdown');
    hide('accountdropdown');
    hide('helpdropdown');
    hide('pointdropdown');
    if(path_array[1]=="feedback"){
        hide('contactusdropdown');
        hide('faqsdropdown');
    }
    hide('accountdropdown');
    if($('filterList') != 'undefined' && $('filterList') != null){
        hide('filterList');
    }
    if($('tynFilterList') != 'undefined' && $('tynFilterList') != null)
        hide('tynFilterList');
    if($('tywFilterList') != 'undefined' && $('tywFilterList') != null)
        hide('tywFilterList');
    if($('destFilterList') != 'undefined' && $('destFilterList') != null)
        hide('destFilterList');
    if($('reminderCatFilterList') != 'undefined' && $('reminderCatFilterList') != null)
        hide('reminderCatFilterList');
    if($('reminderSortFilterList') != 'undefined' && $('reminderSortFilterList') != null)
        hide('reminderSortFilterList');
    if($('listHeaderSubCatsHidden') != 'undefined' && $('listHeaderSubCatsHidden') != null)
        hide('listHeaderSubCatsHidden');
    if ($('allTimespans')) {
        $('allTimespans').hide();
        $('allDisplayModes').hide();
    }
    $$('.inviteAutocompleteResults').each(function(e) {
        $(e).hide();
    });
    //hide the drop down from lto page
    if( typeof isLTO =="undefined") {
    }else{
        hide('CBdropdown');
    }

    //hide the drop down category list of best selling product widget
    if (typeof showingHGOG=="undefined") {
    } else {
        if (showingHGOG) {
            setTimeout("guidehideDivCat();",20);
        }
    }

    if(typeof(menuUp) == 'undefined'){
    }else if(menuUp){
        menuUp = false;
    }else if(typeof(hideAllHomeEscapesDropDownMenus) != 'undefined'){
        hideAllHomeEscapesDropDownMenus();
    }else if(typeof(hideAllPricelineDropDownMenus) != 'undefined'){
        hideAllPricelineDropDownMenus();
    }
}

function getPosX(e) {
    var posx = 0;
    if (!e) var e = window.event;
    if (e.clientX) {
        posx = e.clientX;
    } else if (e.pageX) {
        posx = e.pageX;
    }
    if(document.body.scrollLeft && document.body.scrollLeft > 0) {
        posx = posx + document.body.scrollLeft;
    }else if (document.documentElement.scrollLeft && document.documentElement.scrollLeft > 0) {
        posx = posx + document.documentElement.scrollLeft;
    }else if (e.pageXOffset && e.pageXOffset > 0) {
        posx = posx + e.pageXOffset;
    }
    return posx;
}

function getPosY(e) {
    var posy = 0;
    if (!e) var e = window.event;
    if (e.clientY) {
        posy = e.clientY;
    } else if (e.pageY) {
        posy = e.pageY;
    }
    if(document.body.scrollTop && document.body.scrollTop > 0) {
        posy = posy + document.body.scrollTop;
    }else if (document.documentElement.scrollTop && document.documentElement.scrollTop > 0) {
        posy = posy + document.documentElement.scrollTop;
    }else if (e.pageYOffset && e.pageYOffset > 0) {
        posy = posy + e.pageYOffset;
    }
    return posy;
}


var rev_keepmainnav = false;

var keepmainnav = false;
var mlHoverOpen = false;
var mlClickOpen = false;

var isOpeningMainNav = false;
var openingMainNav = false;
var clickedMainNav = false;

function toggleDiv(name){
    if ( $(name).style.display=='block' ) {
        $(name).style.display='none';
    } else {
        setTimeout("$('"+name+"').style.display='block';",50);
    }
}

function toggleUserrankUpdateBox() {
    if ($('userrankUpdateBox').style.display == 'block') {
        hide('userrankUpdateBox');
    } else {
        $('userrankUpdateBox').style.display = 'block';
        hide('pointsUpdateBox');
        hide('accountdropdown');
        hide('helpdropdown');
        hide('pointdropdown');
    }
}

function togglePointsUpdateBox() {
    if ($('pointsUpdateBox').style.display == 'block') {
        hide('pointsUpdateBox');
    } else {
        $('pointsUpdateBox').style.display = 'block';
        hide('userrankUpdateBox');
        hide('accountdropdown');
        hide('helpdropdown');
        hide('pointdropdown');
    }
}

var pollHandle = null;

/* Hook to be fed to the Counter to format the text before displaying */
function checkinTextDisplayHook(count) {
    return addCommas(count);
}

/* Number formater */
function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

/* Start polling the checkin count engine */
function startPollingCheckinCount(ooId, interval) {
    if(pollHandle != null) {
        clearInterval(pollHandle);
    }
    pollHandle = setInterval(function() { pollCheckinCount(ooId); }, interval);
}

/* Stop polling the checkin count engine */
function stopPollingCheckinCount() {
    if(pollHandle != null) {
        clearInterval(pollHandle);
    }
}

function parseAndEvalJs(elem) {
    if(elem) {
        var scriptNodes = elem.getElementsBySelector('script');
        for(var i=0; i < scriptNodes.length; i++) {
            eval(scriptNodes[i].innerHTML);
        }
    }
}


function loadDropDown(version) {
    var actionName = 'dropdown';
    var params = '';
    var myAjax = new Ajax.Request('/header/' + actionName + '/version/' + version, {
        parameters:params,
        method:'get',
        onComplete:function(response) {
            if($('ajaxedCategoryMenu')) {
                $('ajaxedCategoryMenu').innerHTML = response.responseText;
            }
        }
    });
}

// Load category nav bar subcats if applicable
Event.observe(window,'load',function(){
    var menus = $$('.fancyNavMenu'), cats = [], i = 0;
    for(var l=menus.length; i<l; ++i){
        cats[i] = menus[i].getAttribute('data-category');
    }
    if(cats.length<1) return;
    new Ajax.Request('/header/fetchnavsubcats', {
        method:'get'
        ,parameters:{
            categories:cats.join(',')
            ,zipcode:($('navRestZip') ? $('navRestZip').innerHTML : "")
        }
        ,onSuccess:function(t){
            try{
                var data = t.responseText.evalJSON();
                for(var j=0,m=(data?data.length:0); j<m; ++j){
                    var menu = $('navMenu'+data[j].categoryid);
                    if (!menu) continue; // this navbar was prevented from rendering, don't activate the dropdown (DNE)
                    var merchants = menu.select(data[j].categoryid==540 ? '.restaurantHalf' : '.merchantHalf')[0];
                    var offers = menu.select(data[j].categoryid==540 ? '.takeoutHalf' : '.offerHalf')[0];
                    var max = data[j].categoryid==540 ? 7 : 5;

                    // popular brands
                    var heading = null;
                    if (data[j].categoryid != 540) {
                        heading = $(document.createElement('div'));
                        heading.update('Popular Brands');
                        heading.addClassName('navMenuTitle');
                        merchants.appendChild(heading);
                    }
                    if (data[j].categoryid == 760 || data[j].categoryid == 398) {
                        heading = $$('#nav-cell-760 .offerHalf .navMenuTitle').first() || $$('#nav-cell-398 .offerHalf .navMenuTitle').first();
                        // heading.update('New Releases');
                    }

                    // detect IE version
                    var ieVersion = -1; // Return value assumes non-IE
                    if (navigator.appName == 'Microsoft Internet Explorer')
                    {
                        var ua = navigator.userAgent;
                        var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
                        if (re.exec(ua) != null)
                            ieVersion = parseFloat( RegExp.$1 );
                    }

                    // the ribbon
                    if(data[j] && data[j].type3offers[0]){
                        var enableOET = data[j].type3offers[0].title === 'OETOFFER';
                    }
                    if (enableOET && (ieVersion >= 8 || ieVersion == -1)) {

                        // create the ribbon div
                        var ribbon = $(document.createElement('div'));
                        ribbon.addClassName('navDropdownRibbon');
                        merchants.appendChild(ribbon);

                        // oet logo
                        var titlebox = $(document.createElement('div'));
                        titlebox.addClassName('OETRibbonTitleBox');
                        ribbon.appendChild(titlebox);
                        var logo = $(document.createElement('img'));
                        logo.setAttribute('src', 'https://imgb.corporateperks.com/emp_image/oet/gg.png');
                        logo.addClassName('OETRibbonOOLogo');
                        titlebox.appendChild(logo);
                        var title = $(document.createElement('img'));
                        title.setAttribute('src', 'https://imga.corporateperks.com/emp_image/oet/OET.png');
                        title.addClassName('OETRibbonOETLogo');
                        titlebox.appendChild(title);

                        // merchant image
                        // hardcoded as all getout
                        var inner = $(document.createElement('img'));
                        var oid = data[j].type3offers[0].offerid;
                        var imgsrc = '//imgb.nxjimg.com/secured/offer/merchant/'+ oid +'\/images/VendorLogo.gif';
                        inner.src = imgsrc;
                        var mer = $(document.createElement('a'));
                        mer.addClassName('navMenuOETLogo');
                        if(data[j].type3offers[0].title == 'Priceline'){
                            mer.setAttribute('href','/category/supercategory/categoryId/174/usource/hnmnu');
                        } else if(data[j].type3offers[0].title == 'Hertz'){
                            mer.setAttribute('href','/category/supercategory/categoryId/174/subcategoryid/276/usource/hnmnu');
                        } else {
                            mer.setAttribute('href','/offer/index/offerid/'+data[j].type3offers[0].offerid+'/usource/NVRBN');
                        }
                        mer.appendChild(inner);
                        ribbon.appendChild(mer);

                        // the subtext
                        var subtext = $(document.createElement('div'));
                        // subtext.update('is matching all donations<br />we make this week.');
                        subtext.update('is matching donations on<br />all of their sales this week.');
                        subtext.setAttribute('style', 'position:absolute;left:40px;top:75px;color:#777777;font-family:Arial,Helvetica,sans-serif;');
                        ribbon.appendChild(subtext);

                        // make sure first merchant doesn't overlap ribbon
                        if (data[j].categoryid != 540) {
                            heading.style.margin = "20px 0px 140px 0px";
                        } else {
                            $$('.restaurantHalf')[0].down('.navMenuTitle').style.margin = "140px 0 5px";
                            $$('.navDropdownRibbon')[0].style.top = "10px"; // setStyle = {top: '10px'};
                        }
                    }

                    // normal popular brands, have to make space if OET enabled
                    var startSubCat = 0;
                    if (enableOET) {
                        startSubCat = 1;
                        if ((ieVersion >= 8) || (ieVersion == -1)) max -= 1;
                        else max += 1;
                    }
                    for(var k=startSubCat,n=Math.min(max,data[j].type3offers.length); k < n; ++k){
                        if(data[j].categoryid == 540){
                            if(!data[j].type3offers[k].defaultCertificate || data[j].type3offers[k].defaultCertificate['price'] == 0) continue;
                            var inner1 = $(document.createElement('div')),
                                inner2 = $(document.createElement('div')),
                                deal = '$' + data[j].type3offers[k].defaultCertificate.price + ' for $' + data[j].type3offers[k].defaultCertificate.value + ' Certificates';
                            inner1.update(data[j].type3offers[k].name);
                            inner2.update(deal);
                            inner2.addClassName('grey');
                            var rest = $(document.createElement('a'));
                            rest.addClassName('navMenuRest');
                            rest.setAttribute('href','/localdeals/restaurant/id/'+data[j].type3offers[k].id+'/useApi/0/usource/hnmnu');
                            rest.appendChild(inner1);
                            rest.appendChild(inner2);
                            merchants.appendChild(rest);
                        }else{
                            var inner = $(document.createElement('img'));
                            if(data[j].type3offers[k].imageavailable !== undefined && data[j].type3offers[k].merchantdir !== undefined && data[j].type3offers[k].imageavailable == "0"){
                                inner.src = '//imgb.corporateperks.com/secured/offer/merchant/'+data[j].type3offers[k].merchantdir+'/images/Vendor'+'Logo.gif';
                            }else{
                                inner.src = '//imgb.corporateperks.com/secured/offer/merchant/'+data[j].type3offers[k].offerid+'/images/Vendor'+'Logo.gif';
                            }
                            var mer = $(document.createElement('a'));
                            mer.addClassName('navMenuLogo');
                            mer.setAttribute('title',data[j].type3offers[k].title);
                            if(data[j].type3offers[k].title == 'Priceline'){
                                mer.setAttribute('href','/category/supercategory/categoryId/174/usource/hnmnu');
                            } else if(data[j].type3offers[k].title == 'Hertz'){
                                mer.setAttribute('href','/category/supercategory/categoryId/174/subcategoryid/276/usource/hnmnu');
                            }else{
                                mer.setAttribute('href','/offer/index/offerid/'+data[j].type3offers[k].offerid+'/categoryId/'+data[j].categoryid+'/usource/hnmnu');
                            }
                            mer.appendChild(inner);

                            if (data[j].categoryid == 230 && data[j].type3offers[k].percentoff) {
                                var percentoff = new Element('div', {
                                    'class': 'percent-off ' + data[j].type3offers[k].merchantdir.toLowerCase()
                                }).update('<div class="subtext">Save</div><div class="percent">' + (data[j].type3offers[k].percentoff * 100) + '%</div>');
                                mer.appendChild(percentoff);
                            }
                            merchants.appendChild(mer);
                            if(k<n-1) merchants.appendChild($(document.createElement('div')).addClassName('clear'));
                        }
                    }
                    max = data[j].categoryid==540 ? 7 : 5;

                    //GrubHub logo logic
                    // if(data[j].categoryid == 540){
                    //  var logo1 = $(document.createElement('a'));
                    //  var logoimg1 = $(document.createElement('img'));
                    //  logo1.addClassName('navMenuLogo');
                    //  logo1.setAttribute('title','GrubHub');
                    //  logo1.setAttribute('href','/takeout/index/usource/hnmnu');
                    //  logoimg1.src = 'https://imga.corporateperks.com/secured/offer/merchant/grubhub/images/VendorLogo.gif';
                    //  logo1.appendChild(logoimg1);
                    //  offers.appendChild(logo1);
                    // }

                    for(var k=0,n=Math.min(max,data[j].subcategories.length); k<n; ++k){
                        var inner = $(document.createElement('div'));
                        var off = $(document.createElement('a'));
                        if(data[j].categoryid == 540){
                            if(!data[j].subcategories[k].title) continue;
                            off.addClassName('navMenuCuisine');
                            inner.setAttribute('style','padding-left:10px;');
                            inner.update(data[j].subcategories[k].title);
                            off.setAttribute('href',data[j].subcategories[k].url);
                            off.appendChild(inner);
                            offers.appendChild(off);
                        }else if(data[j].categoryid == 760 || data[j].categoryid == 398){
                            //if(!data[j].subcategories[k].title) continue;
                            off.addClassName('navMenuOffer');
                            inner.setAttribute('style','padding-left:10px;');
                            inner.update(data[j].subcategories[k].description+'<br />');
                            if(data[j].subcategories[k].hasOwnProperty('url')) {
                                off.setAttribute('href',''+data[j].subcategories[k].url+'/uSource/hnmnu');
                            } else {
                                off.setAttribute('href','/category/supercategory/categoryid/'+data[j].categoryid+'/subcategoryid/'+data[j].subcategories[k].pk_offer_categoryid+'/usource/hnmnu');
                            }
                            off.appendChild(inner);
                            offers.appendChild(off);
                            if(k<n-1) offers.appendChild($(document.createElement('div')).addClassName('subcatDivider'));
                        }else if(data[j].subcategories[k].pk_offer_categoryid == 258){
                            //HACK - mhirth - Link electronics cell phone to regular cell phone
                            if(!data[j].subcategories[k].description) continue;
                            off.addClassName('navMenuOffer');
                            inner.update('Cell Phones');
                            //if suppressed then only rename from mobile phones (can't rename in offer tool)
                            if(!data[j].isCellPhoneSuppressed) {
                                off.setAttribute('href','/category/supercategory/categoryid/230/usource/hnmnu');
                            }else{
                                off.setAttribute('href','/category/supercategory/categoryid/'+data[j].categoryid+'/subcategoryid/'+data[j].subcategories[k].pk_offer_categoryid+'/usource/hnmnu');
                            }
                            off.appendChild(inner);
                            offers.appendChild(off);
                            if(k<n-1) offers.appendChild($(document.createElement('div')).addClassName('subcatDivider'));
                        }else{
                            if(!data[j].subcategories[k].description) continue;
                            off.addClassName('navMenuOffer');
                            inner.update(data[j].subcategories[k].description);
                            if(data[j].subcategories[k].pk_offer_categoryid==760){
                                // hack: hardcoding for movies
                                off.setAttribute('href','/movies/index/categoryid/'+data[j].categoryid+'/subcategoryid/'+data[j].subcategories[k].pk_offer_categoryid+'/usource/hnmnu');
                            }
                            else{
                                off.setAttribute('href','/category/supercategory/categoryid/'+data[j].categoryid+'/subcategoryid/'+data[j].subcategories[k].pk_offer_categoryid+'/usource/hnmnu');
                            }
                            off.appendChild(inner);
                            offers.appendChild(off);
                            if(k<n-1) offers.appendChild($(document.createElement('div')).addClassName('subcatDivider'));
                        }
                    }

                    if(data[j].categoryid == 540){
                        var innerTakeOut = $(document.createElement('div'));
                        // var offTakeOut = $(document.createElement('a'));
                        // offTakeOut.addClassName('navMenuOffer');
                        // innerTakeOut.update('See All Restaurants');
                        // offTakeOut.setAttribute('href','/takeout/index/uSource/H11');
                        // offTakeOut.setAttribute('style','color:#1F6CE0;');
                        // offTakeOut.appendChild(innerTakeOut);
                        // offers.appendChild(offTakeOut);

                        var innerAll = $(document.createElement('div'));
                        var offAll = $(document.createElement('a'));
                        offAll.addClassName('navMenuOffer');
                        innerAll.update('See All Restaurants');
                        offAll.setAttribute('href','/localdeals/restaurants/uSource/H11');
                        offAll.setAttribute('style','color:#1F6CE0;');
                        offAll.appendChild(innerAll);
                        offers.appendChild(offAll);
                    }

                    var product = $(document.createElement('img'));
                    product.addClassName('navMenuProduct');
                    if (data[j].categoryid != 540) {
                        product.setAttribute('src','//imga.nxjimg.com/emp_image/home/scrollwidget/products/'+data[j].categoryid+'.jpg');
                        offers.appendChild(product);
                    }
                    else{   //eating columns are reversed, so image needs to go on the other side; may also change image and location in future versions
                        product.setAttribute('src','//imga.nxjimg.com/emp_image/home/scrollwidget/products/'+data[j].categoryid+'.jpg');
                        offers.appendChild(product);
                    }

                    menu.show();
                }
            }catch(e){ console.log(e);return; }
        }
    });
    if($('moreArrow')){
        var moreDropdown = $$('a.navMore')[0];
        $('navbarnew').select('.moreCell')[0].observe('mouseenter', function(){ $('moreArrow').src = 'https://imgb.corporateperks.com/emp_image/header/black/down_arrow_blue.gif'; });
        $('navbarnew').select('.moreCell')[0].observe('mouseleave', function(){ $('moreArrow').src = 'https://imgb.corporateperks.com/emp_image/header/black/down_arrow.gif'; });
    }
    //display same dropdown for giving back causes
    if($('navMenuCauses')){
        var causes = $('nav-cell-causes');
        causes.observe('mouseenter', function(){$('navMenuCauses').show();});
        causes.observe('mouseleave', function(){$('navMenuCauses').hide();});
    }

});

function toggleMoreDropDown(){
    if($('ajaxedCategoryMenu').visible()){
        hideAllMoreCats();
        $('ajaxedCategoryMenu').hide();
    }else{
        setTimeout("$('ajaxedCategoryMenu').show();", 20);
    }
}
function expandMoreCat(cat){
    /* These functions are removed until the subnavs are added back to the 'More' menu
     hideAllMoreCats();
     $('subCatMenu-'+cat).show();
     */
}
function collapseMoreCat(cat){
    /*
     $('subCatMenu-'+cat).hide();
     */
}
function hideAllMoreCats(){
    /*
     $$('.subcatbox').invoke(hide);
     */
}
function loadDropDown(){
    if(!$('perks_at_work_header')) {
        var actionName = 'dropdown';
        var params = '';
        var myAjax = new Ajax.Request('/header/' + actionName, {
            parameters:params,
            method:'get',
            onComplete:function(response) {
                if($('ajaxedCategoryMenu')) {
                    $('ajaxedCategoryMenu').innerHTML = response.responseText;
                }
            }
        });
    }
}

Event.observe(window, 'load', function() {

    /**
     * Supports the auto-suggest for the header search box
     */
    /*
     if(document.getElementById('searchInput') != null)
     {
     new Autocomplete('searchInput', {
     width:141
     , serviceUrl: '/api/search-auto-complete'
     , container:'autoSuggestContainer'
     });
     }
     */
    if(typeof positionNew == 'function'){
        positionNew();
    }
    header_initHidableContainers();
    loadDropDown();

    if(navigator.userAgent.indexOf('MSIE 6') != -1){
        $$('.hasMenu').invoke('observe', 'mouseenter', function(event){
            this.addClassName('hover');
        }).invoke('observe', 'mouseleave', function(event){
            this.removeClassName('hover');
        });
    }

    /* ADDED TO SUPPORT FTU LIGHTBOX CLICK ON PTS TICKER, HEADER, OO, ETC*/
    buildFTULightbox('ptsTickerDivMyPoints');
    buildFTULightbox('ftuLBHeaderLink');
    buildFTULightbox('OOHomeShowHIW');
    buildFTULightbox('OOCarouselShowHIW');
    buildFTULightbox('showCharityHIW');
});

var googleMapsLoaded = false;
function loadGoogleMaps(){
    if(!googleMapsLoaded){
        googleMapsLoaded = true;
        Event.observe(window, 'load', function(){
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.src = "//maps.google.com/maps/api/js?sensor=false&callback=empty";
            document.body.appendChild(script);
        });
    }
}
function empty(){}


/* ADDED TO SUPPORT FTU LIGHTBOX CLICK ON PTS TICKER*/
function buildFTULightbox(div){
    if ($(div)) {
        $(div).observe('click', function() {
            if (!$('ftuHowItWorks')){
                var url = '/lightbox/ftuhowitworks';
                new Ajax.Request(url, {
                    method: 'post',
                    onSuccess: function(response) {
                        var container = $$('body')[0];
                        var lightbox = new Element('div');
                        lightbox.update(response.responseText);
                        Element.insert(container, {'bottom': lightbox});
                        initializeFTULightbox('Header');
                    }
                });
            } else {
                $('ftuHowItWorks').show();
            }
        });
    }
}

function initializeFTULightbox(page) {
    $$('.popupContainerClose').each(function(event) {
        event.observe('click', function() {
            var url = '/recordclick/recordlink';
            new Ajax.Request(url, {
                method: 'get',
                parameters: {
                    source: page,
                    page: 'ClosedFtuLb'
                }
            });
            $('ftuHowItWorks').hide();
        });
    });
    $$('.startEarningButton').each(function(event) {
        event.observe('click', function() {
            var url = '/recordclick/recordlink';
            new Ajax.Request(url, {
                method: 'get',
                parameters: {
                    source: page,
                    page: 'StartShoppingFtuLb'
                }
            });
            $('ftuHowItWorks').hide();
            window.location='/login/registerform'; return false;
        });
    });
    var url = '/recordclick/recordlink';
    new Ajax.Request(url, {
        method: 'get',
        parameters: {
            source: page,
            page: 'EmpPricingFtuLb'
        }
    });
}


/* set cookie to hide top alert bar - currently used only on OO.com */
function setAlertBarCookie(name) {
    document.cookie=name + "=true;path=/";
}


function updateSession() {
    var myAjax = new Ajax.Request('/employeecenter/settipsessionvalue', {
        method:'post',
        onSuccess:function(data){
            $('pointdropdown').show();
            $('shpltr_tooltip_left').hide();
        }
    });
}

function updateSession2() {
    var myAjax = new Ajax.Request('/obsessions/settipsessionvalue', {
        method:'post',
        onSuccess:function(data){
            $('pointdropdown').show();
            $('shpltr_tooltip_left').hide();
        }
    });
}

function showUserPendingTransactions(e){
    if(!$('ptsTickerUserPendingTransactions')) return;
    $('ptsTickerUserPendingTransactions').show();
    $('ptsTickerBG').addClassName('ptsTickerExpanded');
    if(!$('ptsTickerUserPendingTransactions').hasClassName('userPendingTransactionLoaded') || $('ptsTickerUserPendingTransactions').hasClassName('userPendingTransactionNeedsReload')){
        new Ajax.Request('/healthypointswidget/getuserpendingtransactiondetails', {
            method:'get'
            ,parameters:{}
            ,onSuccess:function(t){
                $('ptsTickerUserPendingTransactions').innerHTML = t.responseText;
                $('ptsTickerUserPendingTransactions').addClassName('userPendingTransactionLoaded');
                $('ptsTickerUserPendingTransactions').removeClassName('userPendingTransactionNeedsReload');
            }
        });
    }
}
function hideUserPendingTransactions(e){

    if(!$('ptsTickerUserPendingTransactions')) return;
    $('ptsTickerBG').removeClassName('ptsTickerExpanded');
    $('ptsTickerUserPendingTransactions').hide();
}

function nxjActivateInputs(inp){
    if(inp){
        nxjActivateOneInput($(inp));
    }else{
        $$('input.nxj_input').each(nxjActivateOneInput);
    }
}
function nxjActivateOneInput(inp){
    // Get the placeholder text and return if it's not supplied
    var ph = inp.getAttribute('placeholder');
    if(!ph) return;

    // If this browser supports placeholders
    if(nxjSupportsPlaceholder){
        // Remove the placeholder on focus
        inp.observe('focus', function(e){
            inp.setAttribute('placeholderAlt', ph);
            inp.removeAttribute('placeholder');
        });
        // Restore the placeholder on blur
        inp.observe('blur', function(e){
            inp.setAttribute('placeholder', ph);
            inp.removeAttribute('placeholderAlt');
        });
        // Else this browser does not support placeholders... *cough* *cough* IE9
    }else{
        // Restore styling and clear the value on focus
        inp.observe('focus', function(e){
            inp.removeClassName('empty');
            if(inp.value == ph) inp.value = "";
        });
        // Hide the input on blur
        inp.observe('blur', function(e){
            if(inp.value){
                inp.removeClassName('empty');
            }else{
                inp.addClassName('empty');
                inp.value = ph;
            }
        });
        // Initialize the placeholder
        if(!inp.value){
            inp.addClassName('empty');
            inp.value = ph;
        }
    }
}
function nxjActivateSelects(sel){
    if(sel){
        nxjActivateOneSelect($(sel));
    }else{
        $$('div.nxj_select').each(nxjActivateOneSelect);
    }
}
function nxjActivateOneSelect(sel){
    sel.stopObserving('click');
    sel.observe('click', function(e){
        if(sel.hasClassName('nxj_selectOpen')) {
            sel.removeClassName('nxj_selectOpen');
        } else if(!sel.hasClassName('disabled')) {
            sel.addClassName('nxj_selectOpen');
        }
        $(e).stop();
    });
    sel.select('.nxj_selectOption').each(function(j){
        if(j.hasAttribute("data-default")){
            (sel.select('.nxj_selectValue'))[0].value = j.getAttribute('data-value');
            (sel.select('.nxj_selectDisplay'))[0].update(j.innerHTML);
            (sel.select('.nxj_selectDisplay'))[0].removeClassName('default');
        }
        j.stopObserving('click');
        j.observe('click', function(e){
            (sel.select('.nxj_selectValue'))[0].value = j.getAttribute('data-value');
            (sel.select('.nxj_selectDisplay'))[0].update(j.innerHTML);
            (sel.select('.nxj_selectDisplay'))[0].removeClassName('default');
            sel.removeClassName('nxj_selectOpen');
            $(e).stop();
        });
    });
}
function nxjActivateDatePickers(dpk){
    if(dpk){
        nxjActivateOneDatePicker($(dpk));
    }else{
        $$('div.nxj_datePicker').each(nxjActivateOneDatePicker);
    }
}
function nxjActivateOneDatePicker(dpk){
    var type = dpk.getAttribute('data-type');
    var displays = (dpk.select('.nxj_input'));
    var reals = (dpk.select('.nxj_datePickerReal'));
    var icons = (dpk.select('.calendar_icon'));
    var left = (dpk.select('.monthScroll.left'))[0];
    var right = (dpk.select('.monthScroll.right'))[0];
    var allowPast = parseInt(dpk.getAttribute('data-allowpast'));
    var callback = dpk.hasAttribute('data-callback') ? window[dpk.getAttribute('data-callback')] : null;
    var showYear = dpk.getAttribute('data-showyear');
    dpk.setAttribute('data-arrowed', 0);
    dpk.observe('click', function(evt){
        Event.stop(evt);
        displays[dpk.getAttribute('data-period')=='end'?1:0].focus();
    });
    displays.each(function(oneDisplay){
        oneDisplay.observe('click', function(evt){
            Event.stop(evt);
            oneDisplay.focus();
        });
        oneDisplay.observe('focus', function(){
            $$('div.nxj_datePicker').each(function(onePicker){ onePicker.removeClassName('open'); });
            dpk.setAttribute('data-period', oneDisplay.getAttribute('data-period'));
            if(!parseInt(dpk.getAttribute('data-arrowed'))){
                var start = (dpk.getAttribute('data-period')=='start' ? new Date(parseInt(dpk.getAttribute('data-start'))*1000) : new Date(parseInt(dpk.getAttribute('data-end'))*1000));
                start.setDate(1);
                start.setHours(0,0,0,0);
                dpk.setAttribute('data-firstshown', Math.floor(start.getTime()/1000));
            }else{
                dpk.setAttribute('data-arrowed', 0);
            }
            nxjPopulateOneDatePicker(dpk);
            dpk.addClassName('open');
        });
    });
    displays.each(function(oneDisplay){
        oneDisplay.observe('keydown', function(evt){
            var key = evt.which || window.event.keyCode;
            if(key==9 || key==13){ // Tab out of the input
                dpk.removeClassName('open');
            }
        });
    });
    icons.each(function(oneIcon){
        oneIcon.observe('click', function(evt){
            Event.stop(evt);
            displays[oneIcon.getAttribute('data-period')=='end' ? 1 : 0].focus();
        });
    });
    left.observe('click', function(){
        dpk.setAttribute('data-arrowed', 1);
        var start = new Date(parseInt(dpk.getAttribute('data-firstshown'))*1000);
        start.setDate(1);
        start.setMonth(start.getMonth()-1);
        dpk.setAttribute('data-firstshown', Math.floor(start.getTime()/1000));
        nxjPopulateOneDatePicker(dpk);
    });
    right.observe('click', function(){
        dpk.setAttribute('data-arrowed', 1);
        var start = new Date(parseInt(dpk.getAttribute('data-firstshown'))*1000);
        start.setDate(1);
        start.setMonth(start.getMonth()+1);
        dpk.setAttribute('data-firstshown', Math.floor(start.getTime()/1000));
        nxjPopulateOneDatePicker(dpk);
    });
    nxjPopulateOneDatePicker(dpk);

    displays.each(function(oneDisplay){
        oneDisplay.observe('change', function(){
            var userTime = Date.parse(oneDisplay.value);
            if(isNaN(userTime)){
                oneDisplay.addClassName('red');
            }else{
                var period = oneDisplay.getAttribute('data-period');
                dpk.setAttribute('data-'+period, Math.floor(userTime/1000));
                nxjPopulateOneDatePicker(dpk);
                if(callback){
                    if(type=='range'){
                        callback(
                            reals[0].value
                            ,reals[1].value
                            ,displays[0].value
                            ,displays[1].value
                            ,new Date(parseInt(dpk.getAttribute('data-start'))*1000)
                            ,new Date(parseInt(dpk.getAttribute('data-end'))*1000)
                        );
                    }else{
                        callback(
                            reals[0].value
                            ,displays[0].value
                            ,new Date(parseInt(dpk.getAttribute('data-start'))*1000)
                        );
                    }
                }
            }
        });
    });
}

function nxjUpdateOneDatePicker(dpk) {
    dpk.select('.nxj_input').each(function(oneDisplay){
        var userTime = Date.parse(oneDisplay.value);
        var period = oneDisplay.getAttribute('data-period');
        dpk.setAttribute('data-'+period, Math.floor(userTime/1000));
    });
    dpk.setAttribute('data-firstshown', dpk.getAttribute('data-start'));
    nxjPopulateOneDatePicker(dpk);
}
function nxjPopulateOneDatePicker(dpk){
    var type = dpk.getAttribute('data-type');
    var displays = (dpk.select('.nxj_input'));
    var reals = (dpk.select('.nxj_datePickerReal'));
    var monthCount = parseInt(dpk.getAttribute('data-monthcount'));
    var currentDate = new Date(parseInt(dpk.getAttribute('data-firstshown'))*1000);
    var start = new Date(parseInt(dpk.getAttribute('data-start'))*1000); start.setHours(0,0,0,0);
    var end = type=='range'
        ? new Date(parseInt(dpk.getAttribute('data-end'))*1000)
        : start;
    end.setHours(0,0,0,0);
    var allowPast = parseInt(dpk.getAttribute('data-allowpast'));
    var today = new Date(); today.setHours(0,0,0,0);
    var tomorrow = new Date(today); tomorrow.setDate(tomorrow.getDate()+1);
    var callback = dpk.hasAttribute('data-callback') ? window[dpk.getAttribute('data-callback')] : null;
    var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
    var showYear = dpk.getAttribute('data-showyear');
    if(end < start){
        displays.each(function(oneDisplay){
            oneDisplay.removeClassName('red');
        });
        return false;
    }

    displays.each(function(oneDisplay){
        oneDisplay.removeClassName('red');
    });

    if(showYear == 1) {
        displays[0].value = "" + (start.getMonth()+1) + "/" + start.getDate() + "/" + start.getFullYear();
    } else {
        displays[0].value = "" + (start.getMonth()+1) + "/" + start.getDate();
    }
    reals[0].value = Math.floor(start.getTime()/1000);
    if(type=='range'){
        displays[1].value = "" + (end.getMonth()+1) + "/" + end.getDate() + "/" + end.getFullYear();
        reals[1].value = Math.floor(end.getTime()/1000);
    }

    dpk.select('.nxj_month').each(function(monthDiv){
        currentDate.setDate(1);
        currentDate.setHours(0,0,0,0);

        if(showYear == 1) {
            (monthDiv.select('.monthName'))[0].update(
                monthNames[currentDate.getMonth()] + ' ' + currentDate.getFullYear()
            );
        } else {
            (monthDiv.select('.monthName'))[0].update(
                monthNames[currentDate.getMonth()]
            );
        }

        var monthBody = (monthDiv.select('.nxj_monthBody'))[0]
            ,col
            ,row
            ,printed = 0
            ,newDay
            ,daysInMonth = new Date(currentDate.getYear(), currentDate.getMonth()+1, 0).getDate();
        monthBody.update();
        for(row=0; row<6; ++row){
            for(col=0; col<7; ++col){
                newDay = document.createElement('div');
                newDay.addClassName('dayValue');
                if((!printed && col<currentDate.getDay()) || printed>=daysInMonth){
                    newDay.addClassName('empty');
                    newDay.update('&nbsp;');
                }else{
                    currentDate.setDate(++printed);
                    newDay.update(currentDate.getDate());
                    newDay.setAttribute('data-date', Math.floor(currentDate.getTime()/1000));
                    if(currentDate<today && !allowPast){
                        newDay.addClassName('past');
                    }else{
                        if(currentDate>=today && currentDate<tomorrow){
                            newDay.addClassName('today');
                        }
                        if(currentDate>=start && currentDate<=start || currentDate>=end && currentDate<=end){
                            newDay.addClassName('selected');
                        }else if(currentDate>=start && currentDate<=end){
                            newDay.addClassName('spanned');
                        }
                        newDay.observe('click', function(){
                            var dayDate = new Date(parseInt(this.getAttribute('data-date'))*1000);
                            if(type=='range'){
                                var cmpName = dpk.getAttribute('data-period')=='start' ? 'end' : 'start';
                                var cmpDate = new Date(parseInt(dpk.getAttribute('data-'+cmpName))*1000);
                                if(cmpName=='end'&&dayDate>cmpDate || cmpName=='start'&&dayDate<cmpDate){
                                    dpk.setAttribute('data-start', parseInt(this.getAttribute('data-date')));
                                    dpk.setAttribute('data-end', parseInt(this.getAttribute('data-date')));
                                }else{
                                    dpk.setAttribute('data-'+dpk.getAttribute('data-period'), parseInt(this.getAttribute('data-date')));
                                }
                            }else{
                                dpk.setAttribute('data-start', parseInt(this.getAttribute('data-date')));
                            }
                            nxjPopulateOneDatePicker(dpk);
                            if(callback){
                                if(type=='range'){
                                    callback(
                                        reals[0].value
                                        ,reals[1].value
                                        ,displays[0].value
                                        ,displays[1].value
                                        ,new Date(parseInt(dpk.getAttribute('data-start'))*1000)
                                        ,new Date(parseInt(dpk.getAttribute('data-end'))*1000)
                                    );
                                }else{
                                    callback(
                                        reals[0].value
                                        ,displays[0].value
                                        ,new Date(parseInt(dpk.getAttribute('data-start'))*1000)
                                    );
                                }
                            }
                        });
                    }
                }
                monthBody.appendChild(newDay);
            }
        }

        currentDate.setDate(1);
        currentDate.setMonth(currentDate.getMonth()+1);
    });
}
function nxjActivateSliders(sld){
    if(sld){
        nxjActivateOneSlider($(sld));
    }else{
        $$('div.nxj_slider').each(nxjActivateOneSlider);
    }
}
function nxjActivateOneSlider(sld){
    if(sld.hasClassName('disabled')) return;
    var type = sld.getAttribute('data-type');
    var mode = sld.getAttribute('data-mode');
    var decimals = parseInt(sld.getAttribute('data-decimals'));
    var min = decimals ? parseFloat(sld.getAttribute('data-min')) : parseInt(sld.getAttribute('data-min'));
    var max = decimals ? parseFloat(sld.getAttribute('data-max')) : parseInt(sld.getAttribute('data-max'));
    var scale = parseFloat(sld.getAttribute('data-scale'));
    var marker = sld.getAttribute('data-marker');
    var increment = decimals ? parseFloat(sld.getAttribute('data-increment')) : parseInt(sld.getAttribute('data-increment'));
    var handleLeft = sld.select('.handleLeft')[0];
    var handleRight = sld.select('.handleRight')[0];
    var inputLeft = sld.select('.nxj_sliderInput_left')[0];
    var inputRight = sld.select('.nxj_sliderInput_right')[0];
    var segment = sld.select('.nxj_sliderSegment')[0];
    var markers = sld.select('.nxj_sliderMarker');
    var callback = sld.hasAttribute('data-callback') ? window[sld.getAttribute('data-callback')] : null;
    var preventOverlap = sld.getAttribute('data-preventoverlap') == '1';

    var dragStart = function(handle, evt){
        $(window.document.body).addClassName('noUserSelect');
        $(window.document.body).onselectstart = function(){ return false; };
        handle.addClassName('dragging');
        handle.setAttribute('data-start-x', evt.clientX);
        handle.setAttribute('data-start-left', parseFloat(handle.getStyle('left')));
        segment.setAttribute('data-start-left', parseFloat(segment.getStyle('left')));
        segment.setAttribute('data-start-width', parseFloat(segment.getStyle('width')));
        inputRight.setAttribute('data-start-val', $F(inputRight));
        if(inputLeft){
            inputLeft.setAttribute('data-start-val', $F(inputLeft));
        }
    };
    var dragEnd = function(handle){
        $(window.document.body).removeClassName('noUserSelect');
        $(window.document.body).onselectstart = null;
        handle.removeClassName('dragging');
        if(callback){
            if(type=='range'){
                callback(parseFloat($F(inputLeft)), parseFloat($F(inputRight)), true);
            }else{
                callback(parseFloat($F(inputRight)), true);
            }
        }
    };
    var dragMove = function(handle, evt){
        if(!handle.hasClassName('dragging')) return;
        var startX = parseFloat(handle.getAttribute('data-start-x'));
        var startLeft = parseFloat(handle.getAttribute('data-start-left'));
        var startVal = handle.hasClassName('handleLeft')
            ? parseFloat(inputLeft.getAttribute('data-start-val'))
            : parseFloat(inputRight.getAttribute('data-start-val'));
        var move = evt.clientX-startX;
        var scaledMove = move/scale;
        if(mode=='discrete'){
            scaledMove = Math.round(scaledMove/increment) * increment;
        }
        var scaledUpper = handle.hasClassName('handleLeft')
            ? parseFloat($F(inputRight))
            : max;
        var scaledLower = handle.hasClassName('handleLeft')
            ? min
            : (type=='range' ? parseFloat($F(inputLeft)) : min);
        scaledUpper -= startVal; scaledLower -= startVal;
        scaledMove = Math.max(scaledLower, Math.min(scaledUpper, scaledMove));
        move = scaledMove*scale;

        if(preventOverlap) {
            var leftMove = 0,
                rightMove = 0;
            if(handle.hasClassName('handleLeft')){
                leftMove = scaledMove;
            } else {
                rightMove = scaledMove;
            }
            var newLeftValue = Math.max(min, Math.min(max, (parseFloat(inputLeft.getAttribute('data-start-val'))+leftMove).toFixed(decimals))),
                newRightValue = Math.max(min, Math.min(max, (parseFloat(inputRight.getAttribute('data-start-val'))+rightMove).toFixed(decimals)));

            if(newLeftValue == newRightValue) {
                return;
            }
        }

        handle.setStyle({'left' : ''+(startLeft+move)+'px'});
        if(handle.hasClassName('handleLeft')){
            var segLeft = parseFloat(segment.getAttribute('data-start-left'));
            segment.setStyle({'left' : ''+(segLeft+move)+'px'});

            var segWidth = parseFloat(segment.getAttribute('data-start-width'));
            segment.setStyle({'width' : ''+(segWidth-move)+'px'});

            inputLeft.value = (parseFloat(inputLeft.getAttribute('data-start-val'))+scaledMove).toFixed(decimals);
        }else{
            var segWidth = parseFloat(segment.getAttribute('data-start-width'));
            segment.setStyle({'width' : ''+(segWidth+move)+'px'});

            inputRight.value = (parseFloat(inputRight.getAttribute('data-start-val'))+scaledMove).toFixed(decimals);
        }
        if(callback && move){
            if(type=='range'){
                callback(parseFloat($F(inputLeft)), parseFloat($F(inputRight)), false);
            }else{
                callback(parseFloat($F(inputRight)), false);
            }
        }
    }

    if(handleLeft){
        handleLeft.observe('touchstart', function(evt){ dragStart(handleLeft, evt.changedTouches[0]); });
        handleLeft.observe('mousedown', function(evt){ dragStart(handleLeft, evt); });
    }
    handleRight.observe('touchstart', function(evt){ dragStart(handleRight, evt.changedTouches[0]); });
    handleRight.observe('mousedown', function(evt){ dragStart(handleRight, evt); });
    var match = navigator.userAgent.match(/MSIE (\d*)/);
    var target, IEVersion = match ? parseInt(match[1]) : 0;
    if(IEVersion && IEVersion < 9){
        target = window.document.body;
    }else{
        target = window;
    }
    Event.observe(target, 'touchmove', function(evt){
        sld.select('.nxj_sliderHandle').each(function(oneHandle){ dragMove(oneHandle, evt.changedTouches[0]); });
    });
    Event.observe(target, 'mousemove', function(evt){
        sld.select('.nxj_sliderHandle').each(function(oneHandle){ dragMove(oneHandle, evt); });
    });
    Event.observe(target, 'touchend', function(evt){
        sld.select('.nxj_sliderHandle').each(function(oneHandle){
            if(oneHandle.hasClassName('dragging')) {
                dragEnd(oneHandle);
            }
        });
    });
    Event.observe(target, 'mouseup', function(evt){
        sld.select('.nxj_sliderHandle').each(function(oneHandle){
            if(oneHandle.hasClassName('dragging')) {
                dragEnd(oneHandle);
            }
        });
    });
}
var browserBarThickness = 17;
function nxjActivateScrollBars(scr){
    if(scr){
        nxjActivateOneScrollBar($(scr));
    }else{
        $$('div.nxj_scrollable').each(nxjActivateOneScrollBar);
    }
}
function nxjActivateOneScrollBar(scr){
    var content = scr.select('.nxj_scrollableContent')[0];
    var inner = scr.select('.nxj_scrollableInner')[0];
    var barX = scr.select('.nxj_scrollBarX')[0];
    var barY = scr.select('.nxj_scrollBarY')[0];
    var overflowX = (scr.hasAttribute('data-overflowx') ? scr.getAttribute('data-overflowx') : 'auto');
    var overflowY = (scr.hasAttribute('data-overflowy') ? scr.getAttribute('data-overflowy') : 'auto');
    var contW = content.scrollWidth;
    var contH = content.scrollHeight;
    var scrW = scr.getWidth();
    var scrH = scr.getHeight();
    var offsetX = (content.scrollWidth==scrW&&content.scrollHeight==scrH ? 0 : contW-scrW);
    var offsetY = (content.scrollWidth==scrW&&content.scrollHeight==scrH ? 0 : contH-scrH);
    var barLengthX = contW ? Math.floor(scrW * scrW / contW) : 0 || 0;
    var barLengthY = contH ? Math.floor(scrH * scrH / contH) : 0 || 0;
    var callback = scr.hasAttribute('data-callback') ? window[scr.getAttribute('data-callback')] : null;
    barX.setStyle({
        width: barLengthX+'px'
        ,height: scr.getAttribute('data-barthickness')+'px'
        ,display: (offsetX>0&&overflowX!='hidden' ? 'block' : 'none')
    });
    barY.setStyle({
        height: barLengthY+'px'
        ,width: scr.getAttribute('data-barthickness')+'px'
        ,display: (offsetY>0&&overflowY!='hidden' ? 'block' : 'none')
    });
    content.setStyle({
        paddingBottom: (offsetX>0 ? browserBarThickness+'px' : '0')
        ,paddingRight: (offsetY>0 ? browserBarThickness+'px' : '0')
    });
    content.setStyle({
        width: scrW+'px'
        ,height: scrH+'px'
    });
    inner.setStyle({
        width: scrW+'px'
        ,height: scrH+'px'
    });
    var scaleX = (scrW-barLengthX)/(content.scrollWidth-scrW);
    var scaleY = (scrH-barLengthY)/(content.scrollHeight-scrH);

    var dragStartX = function(e){
        $(window.document.body).addClassName('noUserSelect');
        $(window.document.body).onselectstart = function(){ return false; };
        barX.addClassName('dragging');
        barX.setAttribute('data-start-x', e.clientX);
        barX.setAttribute('data-start-left', parseFloat(barX.getStyle('left')));
    };
    var dragStartY = function(e){
        $(window.document.body).addClassName('noUserSelect');
        $(window.document.body).onselectstart = function(){ return false; };
        barY.addClassName('dragging');
        barY.setAttribute('data-start-y', e.clientY);
        barY.setAttribute('data-start-top', parseFloat(barY.getStyle('top')));
    };
    var dragEnd = function(e){
        $(window.document.body).removeClassName('noUserSelect');
        $(window.document.body).onselectstart = null;
        barX.removeClassName('dragging');
        barY.removeClassName('dragging');
        if(callback){
            callback(content.scrollLeft, content.scrollTop, true);
        }
    };
    var dragMove = function(e){
        scr.select('.dragging').each(function(bar){
            if(bar.hasClassName('nxj_scrollBarX')){
                var startX = parseFloat(bar.getAttribute('data-start-x'));
                var startLeft = parseFloat(bar.getAttribute('data-start-left'));
                var move = e.clientX-startX;
                barX.setStyle({left: (Math.max(0, Math.min(scrW-barLengthX, parseFloat(barX.getAttribute('data-start-left'))+move)))+'px'});
                content.scrollLeft = parseFloat(barX.getStyle('left'))/scaleX;
            }else{
                var startY = parseFloat(bar.getAttribute('data-start-y'));
                var startTop = parseFloat(bar.getAttribute('data-start-top'));
                var move = e.clientY-startY;
                barY.setStyle({top: (Math.max(0, Math.min(scrH-barLengthY, parseFloat(barY.getAttribute('data-start-top'))+move)))+'px'});
                content.scrollTop = parseFloat(barY.getStyle('top'))/scaleY;
            }
            if(callback){
                callback(content.scrollLeft, content.scrollTop, false);
            }
        });
    }

    content.observe('scroll', function(e){
        barX.setStyle({left: (content.scrollLeft * scaleX)+'px'});
        barY.setStyle({top: (content.scrollTop * scaleY)+'px'});
    });
    barX.observe('mousedown', dragStartX);
    barY.observe('mousedown', dragStartY);
    $(document).observe('mouseup', dragEnd);
    $(document).observe('mousemove', dragMove);
}
Event.observe(window, 'load', function(){
    document.observe('click', function(){
        $$('div.nxj_select').each(function(sel){
            sel.removeClassName('nxj_selectOpen');
        });
        $$('div.nxj_datePicker').each(function(dpk){
            dpk.removeClassName('open');
        });
    });

    var outer = new Element('div');//document.createElement('div');
    outer.setStyle({width:'50px', height:'50px', overflow:'auto'});
    document.body.appendChild(outer);
    var inner = new Element('div');
    outer.appendChild(inner.setStyle({width:'100px', height:'100px'}));
    browserBarThickness = 50-outer.clientHeight;
    $(outer).remove();

    nxjSupportsPlaceholder = ('placeholder' in document.createElement('input'));
    nxjActivateSelects();
    nxjActivateInputs();
    nxjActivateDatePickers();
    nxjActivateSliders();
    nxjActivateScrollBars();
});

// UILibrary - pagination
// resetPaginate updates the pagination UI to match the currently shown page
function resetPaginate(current, max, showall, callback, reset){

    // if "View All" is available, check that first
    if(showall == true){
        if(current == 0){
            $('p_prev').addClassName('disabled');
            $('p_next').addClassName('disabled');

            for(i=1;i<=max;i++){
                if($('p_'+i).className.indexOf('active') >= 0){
                    $('p_'+i).removeClassName('active');
                }
            }

            $('p_all').addClassName('active');
            return;
        }
        else{
            $('p_all').removeClassName('active');
        }
    }

    // if "Prev" or "Next", figure out which page was selected
    if(current < 0){
        var last = 0;
        for(i=1;i<=max;i++){
            if($('p_'+i).className.indexOf('active') >= 0){
                last = i;
            }
        }

        if(current == -1){
            current = last-1;
        }
        if(current == -2){
            current = last+1;
        }
    }

    // disable Previous if 1st page
    if(current == 1){
        $('p_prev').addClassName('disabled');
        $('p_prev').setAttribute('onclick','');
    }else{
        $('p_prev').removeClassName('disabled');
        cbStr = callback+'(-1);';
        if(reset == true){
            cbStr = cbStr + 'resetPaginate(-1,'+max+','+showall+','+'\''+callback+'\''+',1);';
        }
        $('p_prev').setAttribute('onclick',cbStr);
    }

    // determine if ellipses are needed; shows 5 pages if 7+ available
    if(max > 6){
        // set for previous pages
        if(current - 2 > 1){
            if($('p_prel').className.indexOf('hidden') >= 0){
                $('p_prel').removeClassName('hidden');
            }
        }else{
            if(!$('p_prel').className.indexOf('hidden') >= 0){
                $('p_prel').addClassName('hidden');
            }
        }

        // set for upcoming pages
        if(current + 2 < max){
            if($('p_nxel').className.indexOf('hidden') >= 0){
                $('p_nxel').removeClassName('hidden');
            }
        }else{
            if(!$('p_nxel').className.indexOf('hidden') >= 0){
                $('p_nxel').addClassName('hidden');
            }
        }
    }

    // clean up page links
    for(i=1;i<=max;i++){
        if(($('p_'+i).className.indexOf('active') >= 0) && i != current){
            $('p_'+i).removeClassName('active');
        }
        if(i == current){
            $('p_'+i).addClassName('active');
        }
        if(max > 6){
            // if ellipses used, hide those beyond range
            if((i > current+2) || (i < current-2)){
                if(!$('p_'+i).className.indexOf('hidden') >= 0){
                    $('p_'+i).addClassName('hidden');
                }
            } else {
                if($('p_'+i).className.indexOf('hidden') >= 0){
                    $('p_'+i).removeClassName('hidden');
                }
            }
        }
    }

    // disable Next if last page
    if(current == max){
        $('p_next').addClassName('disabled');
        $('p_next').setAttribute('onclick','');
    }else{
        $('p_next').removeClassName('disabled');
        cbStr = callback+'(-2);';
        if(reset == true){
            cbStr = cbStr + 'resetPaginate(-2,'+max+','+showall+','+'\''+callback+'\''+',1)';
        }
        $('p_next').setAttribute('onclick',cbStr);
    }
}

function header_initHidableContainers() {
    // Generic bit of code to show hide a container. Just give correct elements
    // correct classes. Assumes default hidden.
    $$('.hideableContainer').each(function(container) {
        if (container.down('.containerHiderClose')) {
            container.down('.containerContent').hide();
        }

        if (container.down('.containerHider input[type=radio]')) {
            if (container.down('.containerHider input[type=radio]').checked == false) {
                container.down('.containerContent').hide();
            }
        }
        container.down('.containerHider').observe('click', function(event) {
            if ($$('.hideableContainer .animating').length > 0) {
                event.stop();
                return false;
            }
            var hidableContainer = container.down('.containerContent');
            if (hidableContainer.id == '') {
                hidableContainer.id = new Date().getTime();
            }

            if (container.down('.containerHider input[type=radio]')) {
                var radio = container.down('.containerHider input[type=radio]');
                if (!hidableContainer.visible()) {
                    radio.checked = true;
                    hidableContainer.addClassName('animating');
                    Effect.SlideDown(hidableContainer.id, {
                        duration: 1.0,
                        afterFinish:function() {
                            hidableContainer.removeClassName('animating');
                        }
                    });
                    var radioName = radio.readAttribute('name');
                    $$('.hideableContainer .containerHider input[name=' + radioName + ']:not(input:checked)').each(function(otherRadio) {
                        var container = otherRadio.up('.hideableContainer').down('.containerContent');
                        if (container.id == '') {
                            container.id = new Date().getTime();
                        }
                        if (otherRadio.checked == false && container.visible()) {
                            container.addClassName('animating');
                            Effect.SlideUp(container.id, {
                                duration: 1.0,
                                afterFinish:function() {
                                    container.removeClassName('animating');
                                }
                            });
                        }
                    });
                }
            } else {
                Effect.toggle(hidableContainer.id, 'slide', {
                    afterFinish:function() {
                        hidableContainer.removeClassName('animating');
                    }
                });
                container.down('.containerHiderImage').toggleClassName('containerHiderOpen');
                container.down('.containerHiderImage').toggleClassName('containerHiderClose');
            }
        });
    });
    // force repaint - necessary for IE7
    $$('.hideableContainer').each(function(container) {
        var element = container.down('.containerContent');
        element.className = element.className;
    });
}


//called by individual page that tracks heatmap (in partials)
function heatmap(logDivId, displayDivId, shiftCanvasDownBy, isNxj, isCategory) {

    var urlParts = window.location.pathname.split('/');
    var controller = urlParts[1],
        action = urlParts[2];

    if (!isCategory) {
        //log click position into database through ajax
        var ele = $(logDivId);

        if (ele) {
            $(logDivId).observe('click', function(e){
                var x = Math.round(e.pageX - ele.offsetLeft);
                var y = Math.round(e.pageY - ele.offsetTop);

                //new Ajax.Request('/travel/logheatmap', {
                //method: 'post',
                //parameters: {controllerName: controller, actionName:action, x:x, y:y },
                //dataType: 'json',
                //onSuccess: function(xhr) {
                //return;
                //}
                //});
            });
        }
    } else {
        if(!urlParts[6]) {
            action = 'hotels';
        }else{
            var catMapping = {'275':'hotels', '274':'flights', '276':'cars', '179':'vacations', '176':'cruises'};
            if (controller == 'category') {
                var subCat = urlParts[6];
                action = catMapping[subCat];
            }
        }

        //log click position into database through ajax
        var ele = $(logDivId);

        if (ele) {
            $(logDivId).observe('click', function(e){
                //detect tab switching

                var tab = e.findElement('.tab');
                if (tab) {
                    action = tab.getAttribute('data-target');
                }

                var x = Math.round(e.pageX - ele.offsetLeft);
                var y = Math.round(e.pageY - ele.offsetTop);

                //new Ajax.Request('/travel/logheatmap', {
                //method: 'post',
                //parameters: {controllerName: controller, actionName:action, x:x, y:y },
                //dataType: 'json',
                //onSuccess: function(xhr) {
                //return;
                //}
                //});
            });
        }
    }

    //if heatmap=1 is set in url and is on next jump, display heatmap
    var params = document.URL.toQueryParams();
    var heatMapOn = params.heatmap ? params.heatmap : false;
    var startDate = params.hmstartdate ? params.hmstartdate : null;

    if(isNxj != 0 && heatMapOn != 0) {
        document.body.style.width = '960px';

        var config_display = {
            element: document.getElementById(displayDivId),
            radius: 20,
            opacity: 50,
            height: 5000
        };
        var heatmap_display = h337.create(config_display);

        var canvasList = document.getElementsByTagName('canvas');

        new Ajax.Request('/travel/displayheatmap', {
            method: 'post',
            parameters: {controllerName: controller, actionName:action, startDate:startDate},
            dataType: 'json',
            onSuccess: function(xhr) {
                var json = JSON.parse(xhr.responseText);

                for(var i = 0, max = json.length; i < max; i++) {
                    var obj = json[i];
                    heatmap_display.store.addDataPoint(obj.x_coordinate, obj.y_coordinate, obj.count);
                }

                var canvasList = document.getElementsByTagName('canvas');
                for(var i=0; i<canvasList.length; i++) {
                    canvasList[i].style.top = shiftCanvasDownBy + 'px';
                }
            }
        });
    }
}

var nxj = window.nxj || {};

nxj.header = nxj.header || {};

// ////////////////////////////////////////////////////////////////////////////
// Notifications
// ////////////////////////////////////////////////////////////////////////////

nxj.header.notification = (function() {
    var self = {};

    self.setValue = function(name, value) {
        var notification = getElem(name);
        if(notification) {
            value = parseInt(value, 10);

            if(value == 0) {
                notification.removeClassName('header_sprite_notification_on').addClassName('header_sprite_notification_off');
                if(notification.hasAttribute('hide-empty-notification')) {
                    notification.hide();
                }
            } else {
                notification.addClassName('header_sprite_notification_on').removeClassName('header_sprite_notification_off');
                notification.show();
            }

            notification.update(value);
        }
    };

    self.addValue = function(name, value) {
        var notification = getElem(name);
        if(notification) {
            var newValue = (notification.innerHTML != '' ? parseInt(notification.innerHTML, 10) : 0) + parseInt(value, 10);

            self.setValue(name, newValue);
        }
    };

    function getElem(name) {
        var elems = $$('.' + name + '.header_notification, #' + name + '.header_notification');
        if(elems.length > 0) {
            return elems.first();
        }
        return null;
    }

    return self;
}());

// ////////////////////////////////////////////////////////////////////////////
// Navigation
// ////////////////////////////////////////////////////////////////////////////

nxj.header.navigation = (function($) {
    var self = {};

    self.loadCustomNavDropdown = function(customTag, content) {
        var textTemplate = self.readTemplate('#savings_nav_uk_custom');
        var imgTemplate = self.readTemplate('#savings_nav_uk_custom_image');
        var headerMenu = $j('.savings_nav_item.' + customTag +' > .header_menu');

        var menuItemsContent = "";
        for (var i = 0; i < content.length; i++) {
            var template = (content[i].image != false) ? imgTemplate : textTemplate;
            menuItemsContent += template.evaluate($.extend(content[i], {
                name:  content[i].name,
                image: content[i].image,
                link:  content[i].link
            }));
        }

        headerMenu.html(menuItemsContent);
        headerMenu.addClass('menu_loaded');
    };

    self.loadNewNavDropdowns = function() {
        var categoryIds = $.map($('.savings_nav_item_has_menu.savings_nav_item_category'), function(e, i) { return $(e).attr('data-catid'); });

        if (categoryIds.length > 0) {
            var savingsNavDropdownTemplate = self.readTemplate('#savings_nav_dropdown_template'),
                savingsNavNamedLinkTemplate = self.readTemplate('#savings_nav_named_link_template'),
                savingsNavSubCategoryTemplate = self.readTemplate('#savings_nav_subcat_template'),
                savingsNavOfferSetTemplate = self.readTemplate('#savings_nav_offerset_template'),
                savingsNavCategoryProductListTemplate = self.readTemplate('#savings_nav_category_product_list_template'),
                savingsNavCategoryProductGridTemplate = self.readTemplate('#savings_nav_category_product_grid_template'),
                savingsNavImageTemplate = self.readTemplate('#savings_nav_header_menu_image_template');

            // Remove blank category ids from UK custom nav placements
            var tempCatIds = [];
            categoryIds.forEach(function(ele){
                if (ele !== "") {
                    tempCatIds.push(ele);
                }
            });
            categoryIds = tempCatIds;

            $.ajax({
                url: '/header/fetchnavsubcatsnew',
                dataType: 'json',
                headers: {
                    'X-NxJ-Index': nxj.header.headerCacheIndex ? nxj.header.headerCacheIndex : new Date().getTime()
                },
                data: {
                    categories : categoryIds.join(',')
                },
                success: function(d) {
                    try {
                        var dropdownData = d;
                        nxj.header.dropdown_data = d;

                        for (var i = 0; i < dropdownData.length; i++) {
                            var data = dropdownData[i],
                                $navItem = $('.savings_nav_item_has_menu.savings_nav_item_' + data.categoryId).first();

                            if (data.customTag !== undefined) {
                                self.loadCustomNavDropdown(data.customTag, data.content);
                                continue;
                            }

                            if ($navItem) {
                                var dataColumns = data.offerSets.length + 1; // +1 for See All
                                if (data.products.length > 0) {
                                    dataColumns = dataColumns + 1;
                                }
                                var colWidth = 12 / dataColumns;
                                var subcats = [];
                                for (var j = 0; j < data.subcategories.length; j++) {
                                    var image = '';
                                    if(data.platform == 'edp') {
                                        image = 'https://img.nxjimg.com/emp_image/header/subcat/'+data.subcategories[j].categoryId+'.png';
                                        subcats.push(savingsNavSubCategoryTemplate.evaluate($.extend(data.subcategories[j], {
                                            image: image
                                        })));
                                    } else {
                                        subcats.push(savingsNavNamedLinkTemplate.evaluate($.extend(data.subcategories[j], {
                                                size:            'h5',
                                                margin:          'margin_b_15',
                                                expires_style:   'display:none',
                                                subtitle_style:  'display:none',
                                                strikeout_style: 'display:none'
                                        })));
                                    }

                                }

                                var categoryContent = [],
                                    totalColumns = 0;

                                for (var j = 0; j < data.offerSets.length; j++) {
                                    var set = data.offerSets[j],
                                        offers = [];

                                    for (var k = 0; k < set.offers.length; k++) {
                                        offers.push(savingsNavNamedLinkTemplate.evaluate($.extend(set.offers[k], {
                                            size:            'h6',
                                            margin:          'margin_b',
                                            expires_style:   set.offers[k].expires ? '' : 'display:none',
                                            subtitle_style:  set.offers[k].subtitle ? '' : 'display:none',
                                            strikeout_style: set.offers[k].strikeout ? '' : 'display:none'
                                        })));
                                    }

                                    set.offers = offers.join('');

                                    var titleStyle = '';
                                    if(set.name == 'Offers Ending Soon') {
                                        titleStyle = 'header_text_red';
                                    }
                                    categoryContent.push(savingsNavOfferSetTemplate.evaluate($.extend(set, {
                                        gridWidth : 3,colWidth : colWidth,
                                        titleStyle: titleStyle
                                    })));

                                    totalColumns += 1;
                                }

                                var products = [],
                                    productList = '';

                                if (data.products.length > 0) {
                                    var productTemplate = data.productListStyle == 'list' ? savingsNavCategoryProductListTemplate : savingsNavCategoryProductGridTemplate;

                                    for (var j = 0; j < data.products.length; j++) {
                                        products.push(productTemplate.evaluate($.extend(data.products[j], {
                                            regularPriceStyle : (data.products[j].regularPrice > data.products[j].salePrice) ? '' : 'display:none',
                                            clear : j == (data.products.length / 2) - 1 ? '<div class="grid_clear"></div>' : '',
                                            colWidth : colWidth
                                        })));
                                    }

                                    var productColumns = data.productListStyle == 'list' ? (data.products.length >= 6 ? 2 : 1) : (data.products.length > 6 ? 2 : 1);

                                    productList = savingsNavOfferSetTemplate.evaluate({
                                        name : data.productsTitle,
                                        offers : products.join(''),
                                        gridWidth : productColumns * 3,
                                        colWidth : colWidth
                                    });

                                    categoryContent.push(productList);

                                    totalColumns += productColumns;
                                }

                                var offset = ((totalColumns + 1) * 240);

                                var categoryUrl = $navItem.find('.savings_nav_category_link').attr('href');

                                var categoryData = {
                                    categoryId : data.categoryId,
                                    subcategories : subcats.join(''),
                                    categoryContent : categoryContent.join(''),
                                    categoryUrl : categoryUrl,
                                    imageOffset : offset
                                };

                                var categoryImage = '';
                                if (!data.hideCategoryImage) {
                                    categoryImage = savingsNavImageTemplate.evaluate(categoryData);
                                }

                                var $menu = $navItem.find('.header_menu');
                                $menu.addClass('multicolumns-' + dataColumns);
                                $menu.html(savingsNavDropdownTemplate.evaluate($.extend(categoryData, {
                                    image : categoryImage,
                                    colWidth : colWidth
                                })));
                                $navItem.addClass('menu_loaded');
                            }
                        }
                    } catch (e) {
                    }
                }
            });
        }
    };

    self.loadNewSeeAllDropdown = function() {
        var $dropdown = $('.savings_nav_item_see_all').first();
        if ($dropdown && $dropdown[0]) {
            var seeAllDropdownTemplate = self.readTemplate('#savings_nav_see_all_template'),
                savingsNavNamedLinkTemplate = self.readTemplate('#savings_nav_named_link_template'),
                seeAllColumnTemplate = self.readTemplate('#savings_nav_see_all_column_template');

            $.ajax({
                url: '/header/dropdownnew',
                dataType: 'json',
                headers: {
                    'X-NxJ-Index': (nxj && nxj.header && nxj.header.headerCacheIndex) ? nxj.header.headerCacheIndex : new Date().getTime()
                },
                success: function(d) {
                    if (nxj && nxj.header) {
                      nxj.header.dropdownNewReturnValue = d;
                    }
                    try {
                        var data = d;
                        var numColumns = 4;
                        var columns = [];
                        var idx = 0,
                            rows = Math.ceil(data.length / numColumns);
                        var $cartIcon = $('<img>', {
                            'class': 'margin_r',
                            'style': 'height: 12px;width: auto;vertical-align: -8%;margin-left: -29px',
                            'src':   'https://imga.corporateperks.com/emp_image/onecart/logos/onecart_new_small.png',
                            'alt': 'onecart icon'
                        });
                        var $newIcon = $('<img>', {
                            'class': 'margin_r',
                            'style': 'height: 12px;width: auto;vertical-align: -8%;margin-left: -39px',
                            'src':   '//img.nxjimg.com/emp_image/travel/cruises/new.png',
                            'alt': 'new icon'
                        });

                        for (var i = 0; i < numColumns; i++) {
                            var col = [];
                            for (; idx < Math.min((rows * (i + 1)), data.length); idx++) {
                                col.push(savingsNavNamedLinkTemplate.evaluate($.extend(data[idx], {
                                    size:            'h6',
                                    margin:          'margin_b_15',
                                    bold:            data[idx].isONECart ? 'Bold' : '',
                                    extra:           data[idx].isNew ? $newIcon[0].outerHTML : (data[idx].isONECart ? $cartIcon[0].outerHTML : ''),
                                    expires_style:   'display:none',
                                    subtitle_style:  'display:none',
                                    strikeout_style: 'display:none'
                                })));
                            }
                            columns.push(seeAllColumnTemplate.evaluate({ categories : col.join('')}));
                        }

                        var menu = $dropdown.find('.header_menu');
                        menu.html(seeAllDropdownTemplate.evaluate({
                            columns : columns.join('')
                        }));

                        $dropdown.addClass('menu_loaded');
                    } catch(e) {
                    }
                }
            });
        }
    };

    self.initCartContentsNew = function() {
        if ($('#perks_at_work_header') && $('.account-header-cart-menu').length > 0) {
            var lastChange = $('#header_cart_last_change').val() ? $('#header_cart_last_change').val() : 0;

            $.ajax({
                url: '/onecart/contents',
                dataType: 'json',
                data: {
                    t: lastChange
                },
                success: function(data) {
                    var cartItemTemplate = self.readTemplate('#header_cart_contents_item_template'),
                        cartEmptyTemplate = self.readTemplate('#header_cart_contents_empty_template'),
                        cartMoreItemsTemplate = self.readTemplate('#header_cart_contents_more_items_template');
                    var itemHTML = '';

                    if (data.length > 0) {
                        var items = [];
                        for (var i = 0; i < Math.min(data.length, 3); i++) {
                            items.push(cartItemTemplate.evaluate(data[i]));
                        }

                        if (data.length > 3) {
                            var remaining = data.length - 3;
                            items.push(cartMoreItemsTemplate.evaluate({
                                count : remaining,
                                pluralization : remaining == 1 ? '' : 's'
                            }));
                        }

                        itemHTML = items.join('');
                        $('.header_cart_menu_inner').html(itemHTML);
                    } else {
                        $('.account-header-cart-menu').html(cartEmptyTemplate.evaluate({}));
                        $('.account-header-cart-menu').addClass('header_cart_menu_empty');

                        $.ajax({
                            url: '/onecart/featuredmerchants',
                            dataType: 'json',
                            headers: {
                                'X-NxJ-Index': nxj.header.headerCacheIndex ? nxj.header.headerCacheIndex : new Date().getTime()
                            },
                            data: {},
                            success: function(data) {
                                var merchants = [];
                                var logoTemplate = self.readTemplate('#header_cart_contents_merchant_logo_template');

                                for (var i = 0; i < data.length; i++) {
                                    merchants.push(logoTemplate.evaluate(data[i]).strip());
                                }

                                $('.header_cart_all_merchants').html(merchants.join(''));
                            }
                        });
                    }
                }
            });
        }
    };

    self.readTemplate = function(name) {
        if ($(name) && $(name)[0]) {
            // Prototype JS Templates
            return new Template($(name).html());
        }
        return new Template('');
    };

    return self;
})($j);

$j(document).ready(function() {
    nxj.header.navigation.loadNewNavDropdowns();
    nxj.header.navigation.loadNewSeeAllDropdown();
    nxj.header.navigation.initCartContentsNew();
});

// Deprecated
function loadNewNavDropdowns() {
    return nxj.header.navigation.loadNewNavDropdowns();
}

// Deprecated
function loadNewSeeAllDropdown() {
    return nxj.header.navigation.loadNewSeeAllDropdown();
}

// Deprecated
function initCartContentsNew() {
    return nxj.header.navigation.initCartContentsNew();
}

Event.observe(window, 'load', initHeaderSearch);

function initHeaderSearch() {
    if(!$('perks_at_work_savings_nav')) {
        return;
    }

    var isAnimating = false;

    $$('.savings_nav_search_icon').invoke('observe', 'click', function() {
        if(isAnimating) {
            return;
        }
        var container = $(this).up('.savings_nav_search_inner'),
            searchBarWidth = 303,
            searchInputWidth = searchBarWidth - 44 - 53;

        if(container.hasClassName('search_bar_open')) {
            container.down('input').show();
            container.down('input').focus();
            return;
        }

        isAnimating = true;
        var effects = [];
        effects.push(new Effect.Morph(container, {
            style : 'width:' + searchBarWidth + 'px;background:#FFF;border-left-color:#DDD;border-right-color:#DDD',
            sync : true
        }));
        effects.push(new Effect.Morph(container.down('input'), {
            style : 'width:' + searchInputWidth + 'px',
            sync : true
        }));
        new Effect.Parallel(effects, {
            duration : 0.2,
            afterFinish : function() {
                isAnimating = false;
                container.down('input').show();
                container.down('input').focus();
                container.addClassName('search_bar_open');
            }
        });
    });

    $$('.savings_nav_search_container input').invoke('observe', 'keyup', function(e) {
        if(e.keyCode == 13) {
            // doSearch(this.value);
        } else {
            var val = this.value,
                goButton = $$('.savings_nav_search_go').first();

            if(val != '') {
                if(!goButton.visible()) {
                    if(isAnimating) {
                        return;
                    }
                    isAnimating = true;
                    goButton.appear({
                        duration : 0.2,
                        afterFinish : function() {
                            isAnimating = false;
                        }
                    });
                }
            } else {
                if(goButton.visible()) {
                    if(isAnimating) {
                        return;
                    }
                    isAnimating = true;
                    goButton.fade({
                        duration : 0.2,
                        afterFinish : function() {
                            isAnimating = false;
                        }
                    });
                }
            }
        }
    });

    $$('body').invoke('observe', 'click', function(e) {
        if(isAnimating) {
            return;
        }
        if(!e.findElement('.savings_nav_search_container') && !e.findElement('#header_autocomplete_container')) {
            if($$('.savings_nav_search_inner.search_bar_open').length > 0) {
                isAnimating = true;
                var container = $$('.savings_nav_search_inner').first(),
                    searchBarWidth = 44,
                    searchInputWidth = 0;

                var effects = [];
                effects.push(new Effect.Morph(container, {
                    style : 'width:' + searchBarWidth + 'px;background:#F1F1F1;border-left-color:#F1F1F1;border-right-color:#F1F1F1',
                    sync : true
                }));
                effects.push(new Effect.Morph(container.down('input'), {
                    style : 'width:' + searchInputWidth + 'px',
                    sync : true
                }));

                $$('.savings_nav_search_go').first().hide();
                container.down('input').hide();

                new Effect.Parallel(effects, {
                    duration : 0.2,
                    afterFinish : function() {
                        isAnimating = false;
                        container.down('input').value = '';
                        container.removeClassName('search_bar_open');
                    }
                });
            }
        }
        if(e.findElement('.header_see_all_search_button')) {
            var value = $$('.header_see_all_search').first().value;
            doSearch(value);
        }
    });

    $$('body').invoke('observe', 'keyup', function(e) {
        if(e.findElement('.header_see_all_search') && e.keyCode == 13) {
            doSearch(e.findElement('.header_see_all_search').value);
        }
    });

    // $$('.savings_nav_search_go').invoke('observe', 'click', function() {
    //     var value = $$('.savings_nav_search_container input').first().value;
    //     doSearch(value);
    // });

    function doSearch(value) {
        if(value != '') {
            var form = $('savings_nav_search_form');
            var request = {
                name : value,
                value : 0,
                type : "Search",
                pageIndex : 0
            };
            form['panda-search-term'].value = Object.toJSON(request);
            form.submit();
        }
    }
}

Event.observe(window, 'load', initCartContents);

function initCartContents() {
    if($('perks_at_work_header') && $$('.header_cart_menu').length > 0) {
        var lastChange = $('header_cart_last_change') ? $('header_cart_last_change').value : 0;

        new Ajax.Request('/onecart/contents', {
            method : 'get',
            parameters : {
                t : lastChange
            },
            onSuccess : function(xhr) {
                var data = xhr.responseJSON;

                var cartItemTemplate = readTemplate("header_cart_contents_item_template"),
                    cartEmptyTemplate = readTemplate("header_cart_contents_empty_template"),
                    cartMoreItemsTemplate = readTemplate("header_cart_contents_more_items_template");

                var itemHTML = '';

                if(data.length > 0) {
                    var items = [];
                    for(var i = 0; i < Math.min(data.length, 3); i++) {
                        items.push(cartItemTemplate.evaluate(data[i]));
                    }

                    if(data.length > 3) {
                        var remaining = data.length - 3;
                        items.push(cartMoreItemsTemplate.evaluate({
                            count : remaining,
                            pluralization : remaining == 1 ? '' : 's'
                        }));
                    }

                    itemHTML = items.join('');
                    $$('.header_cart_menu_inner').invoke('update', itemHTML);
                } else {
                    $$('.header_cart_menu').invoke('update', cartEmptyTemplate.evaluate({}));
                    $$('.header_cart_menu').invoke('addClassName', 'header_cart_menu_empty');

                    new Ajax.Request('/onecart/featuredmerchants', {
                        method : 'get',
                        onSuccess : function(xhr) {
                            var data = xhr.responseJSON;

                            var merchants = [];
                            var logoTemplate = readTemplate('header_cart_contents_merchant_logo_template');

                            for(var i = 0; i < data.length; i++) {
                                merchants.push(logoTemplate.evaluate(data[i]).strip());
                            }

                            $$('.header_cart_all_merchants').invoke('update', merchants.join(''));
                        }
                    });
                }
            }
        });
    }

    function readTemplate(name) {
        return new Template($(name).innerHTML);
    }
}

NXJ.load('search.autocompletev2', {
    input: null,
    button: null,
    currentValue: 'Search',
    selectedIndex: -1,
    suggestions: [],
    groups: {},
    handle: null,
    list : "header_autocomplete_container",
    listStyle: {
        top: 0,
        left: 0,
        width: 400,
        offset: 'right'
    },

    init: function(options) {
        for(var option in options) {
            NXJ.search.autocompletev2[option] = options[option];
        }

        var term = NXJ.request.getParam('panda-search-term', null);
        if(term) {
            term = unescape(term).evalJSON(true);
            this.suggestions.push(term);
            this.selectedIndex = 0;
        } else {
            term = {"name":this.currentValue};
        }

        var div = new Element('div', {id : this.list});
        $('perks_at_work_header').insert(div);

        this.input = $(this.input);
        this.list = $(this.list);
        this.button = $(this.button);

        this.currentValue = term.name;
        this.input.setValue(this.currentValue);
        this.input.observe('blur', this.onBlur.bind(this));
        this.input.observe('focus', this.onFocus.bind(this));
        this.input.setAttribute('autocomplete','off');
        this.input.stopObserving('keydown');
        this.button.observe('click', this.select.bind(this));

        this.enable();
    },

    activate: function() {
        this.setListStyle();
        if (this.input.getValue() == 'Search') {
            this.input.setValue('');
        }
        this.input.observe('keydown', this.onKeyPress.bind(this));
    },

    deactivate: function() {
        this.hide();
        this.input.stopObserving('keydown');
        if (this.input.getValue() == "") {
            this.input.setValue('Search');
        }
    },

    setListStyle: function() {
        var offset = this.input.cumulativeOffset();
        this.list.setStyle(
            {
                top: (offset.top + this.listStyle.top) + 'px',
                left: (offset.left + this.listStyle.left) + 'px',
                width: this.listStyle.width + 'px'
            }
        );
    },

    onFocus: function() {
        this.activate();
    },

    onBlur: function() {
        setTimeout(this.deactivate.bind(this), 500);
    },

    onKeyPress: function(e) {
        switch (e.keyCode) {
            case Event.KEY_ESC:
                this.hide();
                break;
            case Event.KEY_RETURN:
                this.select();
                this.setListStyle();
                break;
            case Event.KEY_UP:
                this.moveUp();
                break;
            case Event.KEY_DOWN:
                this.moveDown();
                break;
            default:
                return;
        }
        Event.stop(e);
    },

    onMouseClick: function(index) {
        this.selectedIndex = index;
        this.select();
    },

    getSuggestions: function() {
        var value = this.scrubTerm(this.input.getValue());
        if(value === 'Search') {
            return;
        }
        if(this.scrubTerm(this.currentValue) !== value) {
            this.currentValue = value;
            if(this.currentValue.length > 1) {
                new Ajax.Request('/panda/autocomplete', {
                    method : 'get',
                    parameters : {
                        'version' : '1.0',
                        'data' : this.currentValue
                    },
                    onSuccess :this.processResponse.bind(this),
                    onFailure : function (transport) {
                    }
                });
            } else {
                this.hide();
            }
        }
    },

    processResponse: function(transport) {
        this.suggestions = transport.responseText.evalJSON(true).results.items;
        this.suggestions.splice(0,0,
            {"name":this.currentValue, "value":0, "type":"Search", "pageIndex":0}
        );
        this.selectedIndex = -1;
        this.renderList();
        this.selectListItem();
        this.list.setStyle({'display':'block'});
        if(this.suggestions.length == 0) {
            this.list.hide();
        }
    },

    renderList: function() {
        var groups = {
            "Search":[],
            "Category":[],
            "SubCategory":[],
            "Stores":[],
            "City":[],
            "Cuisine":[],
            "Restaurant":[],
            "Menu Item":[],
            "More Stores":[],
            "Brand":[]
        };
        var regex = new RegExp(this.currentValue.match(/[\s\w]+/g), 'gi');

        for(var i=0; i<this.suggestions.length; i++) {
            if(this.suggestions[i].type === 'Stores') {
                if(!this.scrubTerm(this.suggestions[i].name).match(regex)) {
                    this.suggestions[i].type = 'More Stores';
                }
                // temporary fix for Panasonic
                if (this.suggestions[i].name === 'Panasonic' && this.suggestions[i].merchantId !=389) {
                    continue;
                }
            }
            if(this.suggestions[i].type === 'Category' && !this.isValidCategory(this.suggestions[i].categoryId)) {
                continue;
            }
            groups[this.suggestions[i].type].push(this.suggestions[i]);
        }

        this.suggestions = [];

        var element = new Element("div").addClassName("header_autocomplete_list sourceSans h5 pad_t_5 pad_b_5");

        if(groups["Category"].length > 0) {
            element.insert(this.renderCategoryItem(groups["Category"]));
        }
        if(groups["Stores"].length > 0 && groups["Category"].length > 0) {
            element.insert(this.getDivider());
        }
        if(groups["Stores"].length > 0) {
            element.insert(this.renderStoresItem(groups["Stores"], regex));
        }
        if(groups["Stores"].length > 0 && groups["More Stores"].length > 0) {
            element.insert(this.getDivider());
        }
        if(groups["More Stores"].length > 0) {
            element.insert(this.renderMoreStoresItem(groups["More Stores"].slice(0, 5)));
        }

        this.list.update(element);
    },

    renderCategoryItem : function(list) {
        var section = new Element("div").addClassName("header_autocomplete_category header_text_green");
        for(var i = 0; i < list.length; i++) {
            this.suggestions.push(list[i]);
            var index = this.suggestions.length - 1,
                displayName = "<span class='sourceSansLight'>Shop the</span> <span class='sourceSansBold'>" + list[i].name + " Store</span>";

            section.insert(this.getSingleItem(list[i], '//', index, displayName));
        }
        return section;
    },

    renderStoresItem: function(list, regex) {
        var section = new Element("div");
        for(var i = 0; i < list.length; i++) {
            this.suggestions.push(list[i]);
            var index = this.suggestions.length - 1,
                displayName = list[i].name.replace('<', '&lt;');

            section.insert(this.getSingleItem(list[i], regex, index, displayName));
        }
        return section;
    },

    renderMoreStoresItem: function(list) {
        var section = new Element("div");

        section.insert(new Element("div")
            .addClassName("header_text_grey pad_l pad_b_5 pad_t_5")
            .setStyle({
                "font-size" : "12px"
            })
            .update("Are you looking for...")
        );

        for(var i = 0; i < list.length; i++) {
            this.suggestions.push(list[i]);
            var index = this.suggestions.length - 1,
                displayName = list[i].name.replace('<', '&lt;');

            section.insert(this.getSingleItem(list[i], '//', index, displayName));
        }
        return section;
    },

    getDivider: function() {
        return new Element("div").addClassName("margin_t_5 margin_b_5 margin_l margin_r").setStyle({"border-bottom" : "1px solid #DDD"});
    },

    getSingleItem: function(listItem, regex, index, displayName) {
        var item = new Element("div")
            .addClassName("header_autocomplete_item pad_l pad_r pad_t_5 pad_b_5")
            .addClassName("header_autocomplete_item_" + index)
            .writeAttribute('index', index)
            .update(this.highlite(regex, displayName));

        item.observe('click', function(e) {
            NXJ.search.autocompletev2.onMouseClick(index);
            e.stop();
        });
        item.observe('mouseover', function() {
            this.addClassName("header_autocomplete_selected_item");
        });
        item.observe('mouseout', function() {
            this.removeClassName("header_autocomplete_selected_item");
        });
        return item;
    },

    isValidCategory: function(categoryId) {
        var categories = [174, 123, 144, 398, 119];
        return categories.indexOf(categoryId) !== -1;
    },

    highlite: function(regex, value) {
        return value.replace(regex, function(match){
            return '<span class="header_text_blue sourceSansBold">' + match + '</span>';
        });
    },

    moveUp: function() {
        if(this.selectedIndex <= 0) {
            return;
        }
        this.selectedIndex--;
        this.selectListItem();
    },

    moveDown: function() {
        if(this.selectedIndex >= this.suggestions.length - 1) {
            return;
        }
        this.selectedIndex++;
        this.selectListItem();
    },

    selectListItem: function() {
        this.list.select('.header_autocomplete_item').invoke('removeClassName', 'header_autocomplete_selected_item');
        if(this.selectedIndex > -1) {
            this.list.down('.header_autocomplete_item_' + this.selectedIndex).addClassName('header_autocomplete_selected_item');
        }
    },

    select: function() {
        if(this.selectedIndex === -1) {
            url = '/panda/result/?panda-search-match=false&panda-search-term='
                + escape('{"name":"' + this.scrubTerm(this.input.getValue()) + '", "value":0, "type":"Search", "pageIndex":0}');

            // Guess Category
            var catGuessCandidates = new Array(),
                catIdWinner = undefined,
                confidence = undefined,
                catStreak = 0,
                lastCatSeen = undefined;
            for (var i = 1; i < this.suggestions.length; i++) {
                var catId = this.suggestions[i].categoryId,
                    type = this.suggestions[i].type;
                if (!(type === 'Stores' || type === 'More Stores')) {
                    continue;
                }
                if (i === 0) {
                    lastCatSeen = catId;
                }
                if (catId === lastCatSeen) {
                    catStreak += 1;
                }
                if (catStreak > 1) {
                    catIdWinner = catId;
                    break;
                } else if (catGuessCandidates.length >= 5) {
                    break;
                }
                if (catId !== undefined &&
                    catGuessCandidates.length < 5 &&
                    (type === 'Stores' || type === 'More Stores')) {
                    catGuessCandidates.push(catId);
                }

                lastCatSeen = catId;
            }
            if (catIdWinner !== undefined) {
                confidence = 100;
            } else if (catGuessCandidates.length > 0) {
                // find Mode
                var modeMap = {};
                var maxEl = catGuessCandidates[0], maxCount = 1;
                for(var i = 0; i < catGuessCandidates.length; i++) {
                    var el = catGuessCandidates[i];
                    if(modeMap[el] == null)
                        modeMap[el] = 1;
                    else
                        modeMap[el]++;
                    if(modeMap[el] > maxCount) {
                        maxEl = el;
                        maxCount = modeMap[el];
                    }
                }
                catIdWinner = maxEl;
                confidence = 100 * (maxCount/catGuessCandidates.length);
            }

            if (catIdWinner && confidence) {
                url += '&panda-cat-guess=';
                url += escape('{"categoryId":' + catIdWinner + ',"confidence":' + Math.floor(confidence) + '}');
            }

            window.location.href = url;
            return;
        }
        var suggestion = this.suggestions[this.selectedIndex];
        suggestion.name = NXJ.util.htmlEntityDecode(suggestion.name);
        switch (suggestion.type) {
            case 'Category':
                window.location.href = '/panda/result/?panda-search-match=true&panda-search-term='
                    + escape(Object.toJSON(this.suggestions[this.selectedIndex]));
                return;
            default:
                window.location.href = '/panda/result/?panda-search-match=true&panda-search-term='
                    + escape(Object.toJSON(this.suggestions[this.selectedIndex]));
                return;
        }
        this.hide();
        this.disable();
    },

    hide: function() {
        this.selectedIndex = -1;
        if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
            var ieVersion = new Number(RegExp.$1) // capture x.x portion and store as a number;
            if (ieVersion == 6) {
                return;
            }
        }
        this.list.hide();
    },

    enable: function() {
        this.handle = setInterval(this.getSuggestions.bind(this), 250);
    },

    disable: function() {
        clearInterval(this.handle);
    },

    scrubTerm: function(term) {
        return term.replace(/[\"\'%\!]/g, '');
    }
});

Event.observe(document,
    'dom:loaded',
    function() {
        if($('perks_at_work_header') && $$('.savings_nav_search_container').length > 0) {
            NXJ.search.autocompletev2.init({
                input: "savings_nav_search_bar",
                button: "savings_nav_search_button",
                listStyle: {
                    top: 14,
                    left: -44,
                    width: 301,
                    offset: 'right'
                }
            });
        }

        if ($('perksatwork_mobile_cat_dropdown_header')) {
            var pawCatDropDownShowing = false;
            var pawSearchDropDownShowing = false;
            var pawAccountDropDownShowing = false;

            $('perksatwork_mobile_cat_dropdown_header').observe('click', function (e) {
                if (pawSearchDropDownShowing) {
                    Effect.SlideUp('mobile-paw-search-dropdown', {duration: 0.2});
                    pawSearchDropDownShowing = false;
                }
                if(pawAccountDropDownShowing){
                    Effect.SlideUp('perksatwork_header_user_menu_mobile',{duration:0.2});
                    pawAccountDropDownShowing = false;
                    $('perksatwork-mobile-user-icon').removeClassName('hover');
                }
                if (pawCatDropDownShowing) {
                    Effect.SlideUp('mobile-paw-categories-dropdown', {duration: 0.2});
                    pawCatDropDownShowing = false;
                } else {
                    Effect.SlideDown('mobile-paw-categories-dropdown', {duration: 0.2});
                    pawCatDropDownShowing = true;
                }
            });

            $('paw_header_search_button_mobile').observe('click', function (e) {
                if (pawCatDropDownShowing) {
                    Effect.SlideUp('mobile-paw-categories-dropdown', {duration: 0.2});
                    pawCatDropDownShowing = false;
                }
                if(pawAccountDropDownShowing){
                    Effect.SlideUp('perksatwork_header_user_menu_mobile',{duration:0.2});
                    pawAccountDropDownShowing = false;
                    $('perksatwork-mobile-user-icon').removeClassName('hover');
                }
                if (pawSearchDropDownShowing) {
                    Effect.SlideUp('mobile-paw-search-dropdown', {duration: 0.2});
                    pawSearchDropDownShowing = false;
                } else {
                    Effect.SlideDown('mobile-paw-search-dropdown', {duration: 0.2});
                    pawSearchDropDownShowing = true;
                }
            });

            $('nav-expander').observe('click', function(e){
                if (pawCatDropDownShowing) {
                    Effect.SlideUp('mobile-paw-categories-dropdown', {duration: 0.2});
                    pawCatDropDownShowing = false;
                }
                if (pawSearchDropDownShowing) {
                    Effect.SlideUp('mobile-paw-search-dropdown', {duration: 0.2});
                    pawSearchDropDownShowing = false;
                }
                if(pawAccountDropDownShowing){
                    Effect.SlideUp('perksatwork_header_user_menu_mobile',{duration:0.2});
                    pawAccountDropDownShowing = false;
                    $('perksatwork-mobile-user-icon').removeClassName('hover');
                }else{
                    Effect.SlideDown('perksatwork_header_user_menu_mobile',{duration:0.2});
                    pawAccountDropDownShowing = true;
                    $('perksatwork-mobile-user-icon').addClassName('hover');
                }
            });
        }
    }
);

function updateMissingUserPhoto(photo) {
    var p = $(photo);
    p.up('.header_user_photo_container').addClassName('no_photo');
    p.up('.header_user_photo_container').down('.header_no_user_photo').show();
    p.hide();
}

nxj.header.admin_center = (function() {
    var self = {},
        cleared = false;

    self.init = function() {
        if($$('.admin_center_section').length > 0) {
            getDropdownItems();
        }
    };

    function getDropdownItems() {
        new Ajax.Request('/dashboardnotification/getnotification', {
            method : 'get',
            onSuccess : function(xhr) {
                var res = xhr.responseJSON;
                nxj.header.notification.setValue('admin_center_notification', res.newCount);
                if(res.data.length > 0) {
                    var menuTemplate = readTemplate('header_admin_center_dropdown_template'),
                        itemTemplate = readTemplate('savings_nav_named_link_template');

                    var items = [];
                    for (var i = 0; i < res.data.length; i++) {
                        var notification = res.data[i];

                        var name = notification.desc + "<br/><span class='header_text_grey' style='font-size:12px;'>" + formatDate(notification.date) + '</span>';

                        var item = itemTemplate.evaluate({
                            name : name,
                            url : notification.url,
                            style : i < res.data.length - 1 ? 'border-bottom:1px solid #DDD;padding-bottom:10px;' : '',
                            size : 'h6',
                            margin : 'margin_b',
                            expires_style : 'display:none',
                            subtitle_style : 'display:none'
                        });
                        items.push(item);
                    };

                    var menuHTML = menuTemplate.evaluate({
                        items : items.join('')
                    });
                    $$(".admin_center_menu").invoke('update', menuHTML);
                    $$('.admin_center_section').invoke('removeClassName', 'global_nav_menu_force_hide');
                    $$('.admin_center_section').invoke('addClassName', 'global_nav_menu_container_has_menu');
                    attachListeners();
                }
            }
        })
    }

    function attachListeners() {
        $$(".admin_center_section").invoke('observe', 'mouseenter', clearNotifications);
    }

    function readTemplate(name) {
        return new Template($(name).innerHTML);
    }

    function formatDate(timestamp) {
        var d = new Date(timestamp * 1000);
        return getMonthName(d.getMonth()) + ' ' + d.getDate();
    }

    function getMonthName(monthNumber){
        var month = new Array(
            "January",
            "February",
            "March",
            "April",
            "May",
            "June",
            "July",
            "August",
            "September",
            "October",
            "November",
            "December"
        );
        return month[monthNumber];
    };

    function clearNotifications() {
        if(!cleared) {
            cleared = true;
            nxj.header.notification.setValue('admin_center_notification', 0);
            new Ajax.Request('/dashboardnotification/viewnotification', {
                method : 'post'
            });
        }
    }

    return self;
}());

Event.observe(window, 'load', nxj.header.admin_center.init);

// PAW Notification Stuff (Kate W.) - Moved here by TA
document.observe('dom:loaded', function(event) {
    setupNotifications();
    watchForToggles();
});

function setupNotifications() {
    var reloaded = false;
    if ($('notification-outer')!= undefined) {
        $('notification-outer').observe('mouseover', function (e) {
            /* only do this once per page load */
            if (!reloaded) {
                hoverTimeout = setTimeout(function (ev) {
                    new Ajax.Request('/notification/seen/', {
                        method:     'post',
                        onComplete: function (ev) {
                            reloaded = true;
                        }
                    });
                }, 1000);
            }
        });
        $('notification-outer').observe('mouseout', function (e) {
            clearTimeout(hoverTimeout);
        });
    }
}

function watchForToggles() {
    $$('.toggle_key').each(function(e) {
        var toggle = e.next('.toggle');
        if (toggle) {
            e.observe('mouseover', function(ev) {
                toggle.show();
            });
            e.observe('mouseout', function(ev) {
                toggle.hide();
            });
        }
    });
}


/* FtumessagingController */


/* edp_LightboxController */
Object.extend(Element,{
		setHeight: function(element,h){
			elm = $(element);
			elm.style.height = h + 'px';
		},
		setWidth: function(element,w){
			elm = $(element);
			elm.style.width = w + 'px';
		},
		setInnerHTML: function(element,c){
			elm = $(element);
			elm.innerHTML = c;
		},
		setTop: function(element,t){
			elm = $(element);
			elm.style.top = t;
		},
		setLeft: function(element,l){
			elm = $(element);
			elm.style.left = l;
		},
		setVisible: function(element,o){
			elm = $(element);
			elm.style.visibility = o;
		},
		getOffsetHeight: function(element){
			elm = $(element);
			return elm.offsetHeight;
		},
		getOffsetWidth: function(element){
			elm = $(element);
			return elm.offsetWidth;
		}
});


var Overlay = Class.create();

Overlay.prototype = {
    initialize: function() {
        this.options = Object.extend({
            opacity:    0.8,
            duration:   0.2,
            lightboxId: 'divbox'
        }, arguments[1] || {});

        var objBody = document.getElementsByTagName('body').item(0);
        var objOverlay = document.createElement('div');
        objOverlay.setAttribute('id', 'overlay');
        objOverlay.style.display = 'none';
        objBody.appendChild(objOverlay);
    },

    start: function(topOffset) {
        hideSelectBoxes();
        hideFlash();

        var arrayPageSize = getPageSize();
        Element.setWidth('overlay', arrayPageSize[0]);
        Element.setHeight('overlay', arrayPageSize[1]);

        new Effect.Appear('overlay', { duration: this.options.duration, from: 0.0, to: this.options.opacity });

        var arrScrollPos = getPageScroll();
        var iOffHeight = Element.getHeight(this.options.lightboxId);
        var iOffWidth = Element.getWidth(this.options.lightboxId);
        var sLeft = parseInt(arrScrollPos[0]) + parseInt(arrayPageSize[2] / 2) - parseInt(iOffWidth / 2) + 'px';
        if (sLeft < 0) {
            sLeft = 0;
        }
        if (topOffset != undefined) {
            var sTop = parseInt(topOffset) - parseInt(iOffHeight / 1.3);
            sTop = sTop + 'px';
        } else {
            var sTop = parseInt(arrayPageSize[1] / 2) - parseInt(iOffHeight / 1.3) + 'px';
        }
        Element.setTop(this.options.lightboxId, sTop);
        Element.setLeft(this.options.lightboxId, sLeft);
        Element.show(this.options.lightboxId);
    },

    addElm: function(e) {
        var objBody = document.getElementsByTagName('body').item(0);
        objBody.appendChild(e);
    },

    end: function() {
        Element.hide(this.options.lightboxId);
        new Effect.Fade('overlay', { duration: this.options.duration});
        showSelectBoxes();
        showFlash();
    }
}


var LeftOverlay = Class.create();

LeftOverlay.prototype = {
	initialize: function() {
		this.options = Object.extend({
			opacity:	0.8,
			duration:	0.2
		},arguments[1] || {});
		var objBody = document.getElementsByTagName("body").item(0);

		var objOverlay = document.createElement("div");
		objOverlay.setAttribute('id','overlay');
		objOverlay.style.display = 'none';
		objBody.appendChild(objOverlay);
	},

	start: function(topOffset) {

		hideSelectBoxes();
		hideFlash();

		var arrayPageSize = getPageSize();
		Element.setWidth('overlay', arrayPageSize[4]);
		Element.setHeight('overlay', arrayPageSize[1]);

		new Effect.Appear('overlay', { duration: this.options.duration, from: 0.0, to: this.options.opacity });

		var arrScrollPos = getPageScroll();
		var iOffHeight = Element.getHeight('divbox');
		if(topOffset != undefined){
			var sTop = parseInt(topOffset) - parseInt(iOffHeight/1.3);

			sTop = sTop + "px";
		}else{
			var intTop = parseInt(arrayPageSize[3]/2) - parseInt(iOffHeight/2);
			if(intTop < 10){
				intTop = 100;
			}
			var sTop = intTop + "px";

		}
		Element.setTop('divbox',sTop);
		Element.show('divbox');
	},

	addElm: function(e){
		var objBody = document.getElementsByTagName("body").item(0);
		objBody.appendChild(e);
	},

	end: function() {
		Element.hide('divbox');
		new Effect.Fade('overlay', { duration: this.options.duration});
		showSelectBoxes();
		showFlash();
	}
}


function getPageScroll(){

	var xScroll, yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;
	}

	arrayPageScroll = new Array(xScroll,yScroll);
	return arrayPageScroll;
}

function getPageSize(){

	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else {
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;

	if (self.innerHeight) {
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth;
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) {
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}

	if(xScroll < windowWidth){
		pageWidth = xScroll;
	} else {
		pageWidth = windowWidth;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight,screen.width,screen.height);
	return arrayPageSize;
}

function showSelectBoxes(){
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}
}

function hideSelectBoxes(){
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "hidden";
	}
}

function showFlash(){
	var flashObjects = document.getElementsByTagName("object");
	for (i = 0; i < flashObjects.length; i++) {
		flashObjects[i].style.visibility = "visible";
	}

	var flashEmbeds = document.getElementsByTagName("embed");
	for (i = 0; i < flashEmbeds.length; i++) {
		flashEmbeds[i].style.visibility = "visible";
	}
}

function hideFlash(){
	var flashObjects = document.getElementsByTagName("object");
	for (i = 0; i < flashObjects.length; i++) {
		flashObjects[i].style.visibility = "hidden";
	}

	var flashEmbeds = document.getElementsByTagName("embed");
	for (i = 0; i < flashEmbeds.length; i++) {
		flashEmbeds[i].style.visibility = "hidden";
	}

}

function addReminderLB(merchantId,curRow,merchname) {
	$('reminderLBConfirm').innerHTML= 'Reminder for '+ merchname+' has been added.';
	$('reminderLBConfirm').style.display="block";
    new Ajax.Request("/popularreminders/add/merchantId/" + merchantId,
                   {method: 'post',
                   	params:{uSource:'HRB'},
                   	onLoading:$('rlist'+curRow).src='https://imgb.corporateperks.com/secured/image/f08/home/rightside/loading.gif',
                    onSuccess:$('rlist'+curRow).src='https://imga.corporateperks.com/secured/image/09/sENV_confirm.gif'});
}
//Check for cache refresh
function killOverlay(){
	myOverlay.end();
	$('divbox').innerHTML='';
}


/* FirstTime STW*/

function killOverlay_stw() {
	$('stwContainer').style.display = 'none';
}

function killOverlay_autoenroll() {
		$('UpgradeContainer').style.display = 'none';
}


/* Edp_FooterController */
function Set_Cookie( name, value, expires, path, domain, secure )
{
    var today = new Date();
    today.setTime( today.getTime() );

    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }

    var expires_date = new Date( today.getTime() + (expires) );
    document.cookie = name + "=" +escape( value ) +
                      (( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
                      (( path ) ? ";path=" + path : "" ) +
                      (( domain ) ? ";domain=" + domain : "" ) +
                      (( secure ) ? ";secure" : "" );
}
function on(e){
    e.src = e.src.replace(/_off./,'_on.');
}
function off(e){
    e.src = e.src.replace(/_on./,'_off.');
}
function on_id(id) {
    e = document.getElementById(id);
    e.src = e.src.replace(/_off./,'_on.');
}
function off_id(id) {
    e = document.getElementById(id);
    e.src = e.src.replace(/_on./,'_off.');
}
function setBookmark (url,str){
    if(str=='')str=url;
    if(document.all)window.external.AddFavorite(url,str);
    else alert('To add '+str+' to your bookmarks, press CTRL and D.');
}
function showHide(elementID){
    var divElement = $(elementID);
    if(divElement.style.display == "none"){
        divElement.style.display="block";
    }else{
        divElement.style.display="none";
    }
}
function imageLoader(){
    leftButtonImage = new Image();
    rightButtonImage = new Image();
    leftButtonImage.src = 'https://imga.corporateperks.com/emp_image/button_left_on.gif';
    rightButtonImage.src = 'https://imga.corporateperks.com/emp_image/button_right_on.gif';
}
function showHideDelay(divID){
    if($(divID).style.display=='none'){
        var divObj = $(divID);
        setTimeout(function(){divObj.style.display='block';},100,null,divObj);
    }else{
        $(divID).style.display='none';
    }
}
function closeBanner(){
    new Ajax.Request('/footer/shpltrclicked', {
        method:'post',
        onSuccess:function(data){
            $('shpltrLink').hide();
        }
    });
}
function activateToolTips(){
    if (window.Prototype) {
        $$('.tooltip_box').each(function(tip){
            tip.up(1).observe("mouseover", function(){ tip.show(); });
            tip.up(1).observe("mouseout", function(){ tip.hide(); });
        });
    }
}

$j(document).ready(activateToolTips);









/* edp_LoginController */
function altformCheck(){
	var username = document.login.login.value;
	var j_username = $('j_username');
	var errorMessage = $('errorMessage');
	var errorMessageCopy = $('errorMessageCopy');
	var valid = validate_email(username)
	if(!valid){
		j_username.style.backgroundColor="#ffc9c9";
		errorMessage.style.display="block";
		errorMessageCopy.innerHTML='Please enter a valid e-mail address.';

		document.login.login.focus();
		return false;
	}else{
		document.login.submit();
	}
	return false;
}


function formCheck2(){
	var username = document.login.j_username.value;
	var j_username = document.getElementById('j_username');
	var password = document.login.j_password.value;
	var j_password = document.getElementById('j_password');
	var errorMessage = document.getElementById('errorMessage');
	var errorMessageCopy = document.getElementById('errorMessageCopy');
	if(username == "" || username == null){
		//j_username.style.backgroundColor="#ffc9c9";
		if($('usernameHelpLink')) {
			$('usernameHelpLink').style.display='';
		}
		if(password == "" || password == null){
			//j_password.style.backgroundColor="#ffc9c9";
			if($('passwordHelpLink')) {
				$('passwordHelpLink').style.display='';
			}
		}
		if(document.getElementById('message')){
			document.getElementById('message').innerHTML='Please enter your login credentials.';
		}else{
			errorMessage.style.display="block";
			errorMessageCopy.innerHTML='Please enter your login credentials.';
		}
        if(typeof loginFocus == 'function'){
            loginFocus();
        }else{
		    document.login.j_username.focus();
        }
		return false;
	}else if(password == "" || password == null){
		j_username.style.backgroundColor="#ffffff";
		if($('usernameHelpLink')) {
			$('usernameHelpLink').style.display='none';
		}
		//j_password.style.backgroundColor="#ffc9c9";
		if($('passwordHelpLink')) {
			$('passwordHelpLink').style.display='';
		}
		if(document.getElementById('message')){
			document.getElementById('message').innerHTML='Please enter a password.';
		}else{
			errorMessage.style.display="block";
			errorMessageCopy.innerHTML='Please enter a password.';
		}
        if(typeof passwordFocus == 'function'){
            passwordFocus();
        }else{
            document.login.j_password.focus();
        }
		return false;
	}else{
		errorMessage.style.display="none";
		j_password.style.backgroundColor="#ffffff";
		if($('passwordHelpLink')) {
			$('passwordHelpLink').style.display='none';
		}
		j_username.style.backgroundColor="#ffffff";
		if($('usernameHelpLink')) {
			$('usernameHelpLink').style.display='none';
		}
		//rememUser();
		return true;
	}
	return false;
}

function formcheck3(){
    var username = document.login.j_username.value;
    var j_username = document.getElementById('j_username');
    var password = document.login.j_password.value;
    var j_password = document.getElementById('j_password');
    var errorMessage = document.getElementById('errorMessage');
    var errorMessageCopy = document.getElementById('errorMessageCopy');
    if(username == "" || username == null){
        //j_username.style.backgroundColor="#ffc9c9";
        if($('usernameHelpLink')) {
            $('usernameHelpLink').style.display='';
        }
        if(password == "" || password == null){
            //j_password.style.backgroundColor="#ffc9c9";
            if($('passwordHelpLink')) {
                $('passwordHelpLink').style.display='';
            }
        }
        if(document.getElementById('message')){
            document.getElementById('message').innerHTML='Please enter your login credentials.';
        }else{
            //errorMessage.style.display="block";
            errorMessageCopy.innerHTML='Please enter your login credentials.';
            showerror();
        }
        if(typeof loginFocus == 'function'){
            loginFocus();
        }else{
            j_username.focus();
        }
        return false;
    }else if(password == "" || password == null){
        j_username.style.backgroundColor="#ffffff";
        if($('usernameHelpLink')) {
            $('usernameHelpLink').style.display='none';
        }
        //j_password.style.backgroundColor="#ffc9c9";
        if($('passwordHelpLink')) {
            $('passwordHelpLink').style.display='';
        }
        if(document.getElementById('message')){
            document.getElementById('message').innerHTML='Please enter a password.';
        }else{
            //errorMessage.style.display="block";
            errorMessageCopy.innerHTML='Please enter a password.';
            showerror();
        }
        if(typeof passwordFocus == 'function'){
            passwordFocus();
        }else{
            j_password.focus();
        }
        return false;
    }else{
        //errorMessage.style.display="none";
        //hideerror();
        j_password.style.backgroundColor="#ffffff";
        if($('passwordHelpLink')) {
            $('passwordHelpLink').style.display='none';
        }
        j_username.style.backgroundColor="#ffffff";
        if($('usernameHelpLink')) {
            $('usernameHelpLink').style.display='none';
        }
        //rememUser();
        return true;
    }
    return false;
}


function rememUser()
{
	var user = document.login.j_username.value;
	var pswd = document.login.j_password.value;

	if(document.login.remember && document.login.remember.checked == true)
	{	

	}
	else
	{	

	}
}

function CreateBookmark() {
	var title = document.title; 
	var url = window.location.href;
	var agt = navigator.userAgent.toLowerCase();
	if (agt.indexOf("chrome") != -1) { // Chrome Bookmark Ctrl+D
		alert('Press Ctrl+D to bookmark this page in Chrome.');
	} else if (agt.indexOf("safari") != -1) { // Safari Bookmark Ctrl+D
		alert('Press Ctrl+D to bookmark this page in Safari.');
	} else if (window.sidebar) { // Mozilla Firefox Bookmark Ctrl+D
		alert('Press Ctrl+D to bookmark this page in Firefox.');
	} else if( window.external ) { // IE Favorite Ctrl+D
		window.external.AddFavorite( url, title); 
	} else if(window.opera) { // Opera Hotlist Ctrl+D
		alert('Press Ctrl+D to bookmark this page in Opera.');
	} else {
		alert('Please bookmark this page through your browser.');
	}
}

function LogFromHome() {
	var From_Home_Email = document.getElementById('From_Home_Email');
	var Email_Error = document.getElementById('Email_Error');
	
	var email = From_Home_Email.value;
	var reg = new RegExp("^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$");
	
	if (reg.test(email)) {
		Email_Error.innerHTML = '';
		var oldStuff = FromHomeLoading();
		var url = '/login/emailfromhome/email/'+email;
		//var url = '/login/emailfromhome/email/';
		//alert(url);
		var myAjax = new Ajax.Request(url,{method:'get',onComplete:FromHomeSuccess(oldStuff)});
		
	} else {
		Email_Error.innerHTML = 'Please enter a valid email address';
		
	}
}

function FromHomeLoading() {

	var From_Home_Popup_Form = document.getElementById('From_Home_Popup_Form');
	if (From_Home_Popup_Form != null) {
		var oldCode = From_Home_Popup_Form.innerHTML;
		From_Home_Popup_Form.innerHTML = '<p><strong>Sending email...</strong></p>';
	}
	return oldCode;
}

function FromHomeSuccess(oldHtml) {
	if ($('From_Home_Popup_Form') != null)
		$('From_Home_Popup_Form').innerHTML = '<strong>Email sent!</strong>';
	setTimeout("PopupDisappear()", 2000);
	setTimeout(function() {$('From_Home_Popup_Form').innerHTML = oldHtml;}, 2500);
}

function PopupAppear() {
	var Email_Error = document.getElementById('Email_Error');
	var From_Home_Email = document.getElementById('From_Home_Email');
	var From_Home_Popup = document.getElementById('From_Home_Popup');
	
	if (Email_Error != null && Email_Error.innerHTML.length > 0)
		Email_Error.innerHTML = '';
	if (From_Home_Email != null && From_Home_Email.value != 'your@email.com')
		From_Home_Email.value='your@email.com';
	//setTimeout("$('From_Home_Email').activate()", 500);
	
	Effect.Appear('From_Home_Popup', {duration: 0.5});
	//From_Home_Popup.style.display='block';	
}

function PopupDisappear() {
	var Email_Error = document.getElementById('Email_Error');
	var From_Home_Email = document.getElementById('From_Home_Email');
	var From_Home_Popup = document.getElementById('From_Home_Popup');
	
	if (Email_Error != null && Email_Error.innerHTML.length > 0)
		Email_Error.innerHTML = '';
	if (From_Home_Email != null && From_Home_Email.value.length > 0)
		From_Home_Email.value = '';
	Effect.Fade('From_Home_Popup', {duration: 0.5});
	//From_Home_Popup.style.display='none';
}
function send(){
var From_Home_Email = document.getElementById('From_Home_Email');
if(From_Home_Email.value=='your@email.com') From_Home_Email.value='';

LogFromHome();
}

