function GetUserInfo()  {
    //debugger;
    //    var ShowLastOrderPopup = true;

    //     var needDeals = PageNeedsDeals();

    $('.noThanks, .close, #modalBackground').click(function(){
        deleteCookie("_qoord");
    });

    if (getCookie("_qouid"))
    {
        var user_cookie_string = base64_decode(getCookie("_qouid"));

        if (user_cookie_string != "~~~~~~~~~~") {
            var user_cookies = user_cookie_string.split("~", 11);
            var user_data = {
                addr_street:   user_cookies[0],
                addr_zip:      user_cookies[1],
                addr_city:     user_cookies[2],
                addr_state:    user_cookies[3],
                store:         user_cookies[4],
                delivery_type: user_cookies[5],
                uid:           user_cookies[6],
                first_name:    user_cookies[7].toProperCase(),
                last_name:     user_cookies[8],
                total_orders:  user_cookies[9],
                seamless_flag: user_cookies[10],
                flip_occasion: user_cookies[11]
            };

            if (user_data.first_name == null || user_data.first_name == "") {
                $("#welcomeLI").html("Welcome Back, Guest! <a href='javascript:GotoQuikOrder(\"si\");'>(Sign In)</a><span class='sep'>|</span>").show();
//                $("#myAccountLI").html("<a href='javascript:GotoQuikOrder(\"si\");'>(Sign In)</a>").show();
                $("#signOutLI").html("<span>Sign Out</span><span class='sep'>|</span>").show();
                $("#signInLI").hide();
            } else {
                $("#welcomeLI").html("Welcome Back, " + user_data.first_name + "!<span class='sep'>|</span>");
                $('#myAccountLI').html("<a href='javascript:GotoMyAccount();'>My Account</a><span class='sep'>|</span>");
                $("#signOutLI").html("<span>Sign Out</span><span class='sep'>|</span>");
                $("#registerLI").hide();
                $("#signInLI").hide();
            }

            $("#signOutLI, .signOutUser").css('cursor', 'pointer').click(function() {
                $.ajax({
                    type:  'POST',
                    url:   WEB_AJAX_PATH + 'controller/SignOutController.php',
                    data:  {
                        func: 'signOut'
                    },
                    success: function() {
                        location.reload();
                    },
                    error: function () {
                    }
                });
            });
        }
    }
}

function DoClickTab(el) {
    if (getCookie("_qouid")) {
        var user_cookie_string = base64_decode(getCookie("_qouid"));
        if (user_cookie_string != "~~~~~~~~~~") {
            var tab = $(el).attr('id').toUpperCase().substring(3) + 'V2';
            addItemToCart('MENU', tab, '', '');
            return false;
        }
    }
    return true;
}

/*-- MUSIC PLAYER --*/

/**
 * 1.) Click once to play
 * 2.) Click again to make it stop. You now learned your lesson!
 * 3.) Song Length in seconds
 **/
function playMusic(baseFileName, songLength) {
    /*-- HTML 5 --*/
    if("Audio" in window && (window['musicPlayerHTML5Override'] == undefined || !musicPlayerHTML5Override )){
      if (window['playMusicGlobal'] == undefined) {
          /*-- Setup Only Once --*/
          
          musicPlayerGlobal = new Audio();
          
          if(!!(musicPlayerGlobal.canPlayType && musicPlayerGlobal.canPlayType('audio/mpeg;').replace(/no/, ''))) {
            musicPlayerGlobal.src = "http://quikorder.pizzahut.com/QOcontent2/music/" + baseFileName + ".mp3";
          } else if(!!(musicPlayerGlobal.canPlayType && musicPlayerGlobal.canPlayType('audio/ogg; codecs="vorbis"').replace(/no/, ''))) {
            musicPlayerGlobal.src = "http://quikorder.pizzahut.com/QOcontent2/music/" + baseFileName + ".ogg";
          } else if(!!(musicPlayerGlobal.canPlayType && musicPlayerGlobal.canPlayType('audio/mp4; codecs="mp4a.40.2"').replace(/no/, ''))) {
            musicPlayerGlobal.src = "http://quikorder.pizzahut.com/QOcontent2/music/" + baseFileName + ".m4a";
          } else {
            musicPlayerHTML5Override = true;
            playMusic(baseFileName, songLength);
            return;
          }
          playMusicGlobal = true;
      }
      
      if (musicPlayerGlobal.ended || musicPlayerGlobal.paused) {
        musicPlayerGlobal.play();
        _gaq.push(['_trackEvent', 'Audio', 'Play', baseFileName]);
      } else {
        musicPlayerGlobal.pause();
        musicPlayerGlobal.currentTime = 0;
      }
      
    } else {
        //alert("else");
        /*-- NON HTML 5 HACK --*/
        if (window['playMusicGlobal'] == undefined) {
            /*-- Setup Only Once --*/
            var music_url = "http://quikorder.pizzahut.com/QOcontent2/music/" + baseFileName;
            musicHtmlGLobal = '';
            
            //Check if it is IE, else check for plugins
            if (navigator.appName == 'Microsoft Internet Explorer') {
                musicTypeGlobal = musicPluginIEDetection();
            } else {
                musicTypeGlobal = musicPluginDetection();
            }
            //alert(musicTypeGlobal);
            //if (musicTypeGlobal == "IE NATIVE") {
            //    musicHtmlGLobal = '<div><BGSOUND SRC="' + baseFileName + '.wav" LOOP="1" AUTOSTART="autostart">asdfasdf</div>';
            if (musicTypeGlobal == "QuickTime" || musicTypeGlobal == 'Windows Media' ) {
                if (musicTypeGlobal == "QuickTime") {
                    musicHtmlGLobal = '<embed src="' + music_url + '.wav" width="1" height="1" autostart="true" loop="false"></embed>';
                } else {
                    musicHtmlGLobal = '<embed src="' + music_url + '.mp3" width="1" height="1" autostart="true" loop="false"></embed>';
                }
            } else if( musicTypeGlobal == 'RealPlayer' ) {
                musicHtmlGLobal = '<embed type="audio/x-pn-realaudio-plugin" style="height:0" id="phi_generic_music_player" src="' + music_url + '.mp3" loop="false" autostart="true" hidden="true"/>';
            } else {
                //No Luck, use flash
                musicHtmlGLobal = '<embed type="application/x-shockwave-flash" wmode="transparent" src="http://www.google.com/reader/ui/3523697345-audio-player.swf?audioUrl=' + music_url + '.mp3&autoPlay=true" height="1" width="1"></embed>'; 
            }
            
            playMusicGlobal = true;
        }
    
        if (playMusicGlobal) {
            $("#phMusicContent").html(musicHtmlGLobal);
            playMusicTimeOutGlobal = setTimeout("$('#phMusicContent').html(''); playMusicGlobal = true;", (songLength + 5) * 1000); //remove element after song finished
            _gaq.push(['_trackEvent', 'Audio', 'Play', baseFileName]);
            playMusicGlobal = false;
        } else {
            $("#phMusicContent").html('');
            clearTimeout(playMusicTimeOutGlobal);
            playMusicGlobal = true;
        }
    }
}



function musicPluginIEDetection() {
    if ( window.ActiveXObject) {
        var control = null;
        try {
            control = new ActiveXObject('WMPlayer.OCX');
            return "Windows Media";
        } catch (e) {
         // Do nothing
        }
        try {
            control = new ActiveXObject('QuickTime.QuickTime');
            return "QuickTime";
        } catch (e) {
         // Do nothing
        }

        
        return "None";
    }
}

function musicPluginDetection() {
    if (navigator.plugins) {
        for (var i = 0; i < navigator.plugins.length; i++ ) {
            if (navigator.plugins[i].name.indexOf("Windows Media") >= 0) {
                return "Windows Media";
            }
            if (navigator.plugins[i].name.indexOf("QuickTime") >= 0) {
                return "QuickTime";
            }
            if (navigator.plugins[i].name.indexOf("RealPlayer") >= 0) {
                return "RealPlayer";
            }            
        }
    }
    return "None";
}

/*-- GIFT CARD --*/
function checkGiftCardBalance(cardNumber, cardPin)
{
    if (pageControl.getLock("recaptchaVerification")) {
        return;
    }
    pageControl.lock("recaptchaVerification");

    var data = new Object();
    
    data.cardNumber = cardNumber;
    data.cardPin = cardPin;
    data.captchaChallenge = Recaptcha.get_challenge();
    data.captchaResponse = Recaptcha.get_response();

    var dataString = $.toJSON(data);
    $.ajax({
        type:  'POST',
        url: QO_AJAX_PATH + 'FirstDataGiftCardController.php',
        data: {func: 'postGetGiftCardBalance', data: dataString},
            success: function(d, textStatus){
                var obj = $.evalJSON(d);
                if(obj!=null){
                    if (obj.result == 0) {
                        //Set Balance amount result;
                        if (obj.balance_amount && !isNaN(obj.balance_amount)) {
                            var dollars_amount = parseInt(obj.balance_amount / 100);
                            var cents_amount = obj.balance_amount % 100;
                            
                            if (cents_amount < 10) {
                                cents_amount = '0' + cents_amount;
                            }
                            //Format to money, from cents
                            giftCardMoveToBalanceResult(dollars_amount + '.' + cents_amount);
                        } else {
                            $("#error_generic_submit_error_text").text("An error occured with the process. Please try again.")
                            $("#error_generic_submit_error_text").show(); 
                        }
                    } else {
                        if (obj.result == -1) {
                            if (obj.msg == "INVALID_MISMATCH_RECAPTURE") {
                                $("#error_generic_captcha_text").text("Your entry did not match the two words below. Please try again.");
                                $("#error_generic_captcha_text").show();
                            } else {
                                var testing = obj.msg;
                                $("#error_generic_submit_error_text").text(testing)
                                $("#error_generic_submit_error_text").show(); 
                            }
                        } else {
                            $("#error_generic_submit_error_text").text("An error occured with the process. Please try again.")
                            $("#error_generic_submit_error_text").show(); 
                        }
                    }

                } else {
                    $("#error_generic_submit_error_text").text("An error occured with the process. Please try again.")
                    $("#error_generic_submit_error_text").show();                     
                }
                Recaptcha.reload();
                pageControl.unlock("recaptchaVerification");
            },
            error: function () {
                Recaptcha.reload();
                pageControl.unlock("recaptchaVerification");
            }
        });
}

function formatMoney(n) {
    return n.toLocaleString().split(".")[0] + "."
        + n.toFixed(2).split(".")[1];
}



function getFormatedStringDateTime() {
    var d=new Date();
    var month=new Array(12);
    var hours = d.getHours();
    var minutes = d.getMinutes();
    var timeValue = "" + ((hours >12) ? hours -12 :hours);
    if (timeValue == "0") {timeValue = 12;}
    timeValue += ((minutes < 10) ? ":0" : ":") + minutes;
    timeValue += (hours >= 12) ? " PM" : " AM"
    
       
    
    month[0]="January";
    month[1]="February";
    month[2]="March";
    month[3]="April";
    month[4]="May";
    month[5]="June";
    month[6]="July";
    month[7]="August";
    month[8]="September";
    month[9]="October";
    month[10]="November";
    month[11]="December";
    return "as of " + month[d.getMonth()] + " " + d.getDate() + ", " + d.getFullYear() + " at " + timeValue;
}

function giftCardValidation() {
    var cardNumber = $('#giftCardNumberInputField').val();
    var cardPin = $('#giftCardPINInputField').val();
    var captchaEntry = $('#recaptcha_response_field').val();
    var allValid = true;
    cardNumber = cardNumber.split(' ').join('');
    cardPin = cardPin.split(' ').join('');
    
    $('.error_gift_card_text_container').hide();
    //$('#error_gift_card_text').hide();
    //$('#error_captcha_text').hide();
    if (cardNumber.length < 12 || isNaN(cardNumber) || cardPin.length < 4 || isNaN(cardPin)) {
        $('#error_gift_card_text').show();
        allValid = false;
    }
    if (captchaEntry.length < 1) {
        $('#error_captcha_text').show();
        allValid = false;
    }
    
    if (allValid){
        //check gift card
        checkGiftCardBalance(cardNumber, cardPin);
    }
    

    $('.giftCardBalanceChkDateStamp').text(getFormatedStringDateTime());
}

function giftCardMoveToBalanceForm() {
    //Do this again just in case
    $('#giftCardNumberInputField').val("");
    $('#giftCardPINInputField').val("");
    $('#gift_card_result_amount').text("");
    $('.error_gift_card_text_container').hide();
    $('#giftCardBalanceSection').show();
    $('#giftCardBalanceResultSection').hide();
}

function giftCardMoveToBalanceResult(balanceAmount) {
    //Clear form and move to giftCard result
    $('#giftCardNumberInputField').val("");
    $('#giftCardPINInputField').val("");
    $('#gift_card_result_amount').text("$" + balanceAmount);
    $('.error_gift_card_text_container').hide();
    $('#giftCardBalanceSection').hide();
    $('#giftCardBalanceResultSection').show();
}

function phGiftCardWhatsThisShow() {
    if ($('#gift_card_container').length == 0) {
        $('body').append('<div id="gift_card_container" style="display:none;"></div>');
        $('#gift_card_container').load('ccGiftCardHelp.php');
    }

    $.getScript("JavaScript/jquery.blockUI.js", function() {
        $.blockUI.defaults.css = {};
        $.blockUI({
        message: $('#gift_card_container'),
        css: {
        position:'fixed',
        top:'1px',
        width:'100%',
        'z-index':'1001',
        left:'0px',
        top:'30px'
        },
        overlayCSS: {
        opacity:0.7
        }
        });
    });
}

function phGiftCardWhatsThisHide() {
    $.unblockUI();
} 

function GotoQuikOrder(target, tracking, default_occ) {
    setCookie('login_target', target);
    
    if (default_occ == undefined) {
        setCookie('default_occ', '');
    }

    if (getCookie('ga_syo_tracking') == null) {
        setCookie('ga_syo_tracking', 'SYO Button Click');
    }

    tracking = (tracking) ? '?' + tracking : '';

   // console.log(SwitchToSSL(QO_PATH + tracking + "#login"));

   if(target == 'sl') {
       window.location = WEB_FULL_PATH + 'locations.html';
   } else {
       window.location = SwitchToSSL(QO_PATH + tracking + "#login");
   }
}

function GotoStoreLocations(dataInputParams, tracking) {
 
	setCookie('login_target', 'locationList');
	
	var value =  dataInputParams.address + '~' + dataInputParams.city + '~' + dataInputParams.state + '~' + dataInputParams.zip + '~' + dataInputParams.checkCase;
	setCookie('location', value);
	
    tracking = (tracking) ? '?' + tracking : '';

   // console.log(SwitchToSSL(QO_PATH + tracking + "#phlocationlist"));

   window.location = SwitchToSSL(QO_PATH + tracking + "#phlocationlist");
}

function GotoChangeLocation() {
    setCookie('login_target', 'sl');
    window.location = SwitchToSSL(QO_PATH + "#login");
}

function GotoMyAccount() {
    setCookie('login_target', 'ma');
    window.location = SwitchToSSL(QO_PATH + "#login");
}

function addItemToCart(itemType, tabCode, itemCode, tracking, syoimage, ga_syo_tracking, default_occ) {

    if (ga_syo_tracking) {
        setCookie('ga_syo_tracking', ga_syo_tracking);
    } else {
        setCookie('ga_syo_tracking', 'SYO Button Click');
    }
    
    if (default_occ) {
        setCookie('default_occ', default_occ);
    } else {
        setCookie('default_occ', '');
    }

    var value = itemType + "~" + tabCode + "~" + itemCode;
    //var expires = 10;
    setCookie( "_qoord", value);

    if (syoimage) {
        setCookie('promo_img', syoimage);
    }

    //GotoStartOrder();
    GotoQuikOrder('so', tracking, default_occ);
}

function setCookie(name, value, expires) {
    // set time, it's in milliseconds, parameter is in seconds
    // domain defaults to quikorder.pizzahut.com if none is supplied
    //debugger;
    var today = new Date();
    today.setTime( today.getTime() );

    if (expires) {
        expires = (expires * 60) * 1000;
    } else {
        expires = 0; //(10 * 60) * 1000;
    }
    
    var expires_date = (expires != 0 ? new Date(today.getTime() + (expires)) : new Date(today.getTime() + 600000));

    if (name == "_qouid") {
        expires_date.setDate(expires_date.getDate() + 30);
    }

    var url = parseUri(location.href);
    var domain;

    if (url.domain == 'localhost') {
        domain = '';
    } else {
        var exploded_domain = url.domain.split(".");
        if (exploded_domain[exploded_domain.length - 1] == "com") {
            domain = '.' + exploded_domain[exploded_domain.length - 2] + '.' + exploded_domain[exploded_domain.length - 1];
        }
    }

    var expstr = (expires != 0 ? "expires=" + expires_date.toGMTString() + ";" :'');
    var cookie_string = name + "=" + escape(value) + ";" + expstr + "path=/;";

    if (domain) {
        cookie_string += "domain=" + domain;
    }

    document.cookie = cookie_string;
}

function setCookieNonPersistant( name, value) {

    document.cookie = name + "=" +escape( value ) +  ";path=/;domain=" + DefaultDomain;


}

function getCookie( check_name ) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for ( i = 0; i < a_all_cookies.length; i++ )
    {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split( '=' );


        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if ( cookie_name == check_name )
        {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if ( a_temp_cookie.length > 1 )
            {
                cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if ( !b_cookie_found )
    {
        return null;
    }
}

// this deletes the cookie when called
function deleteCookie( name ) {
    document.cookie = name + '=;path=/;expires=Thu, 01-Jan-70 00:00:01 GMT;';
//    if ( getCookie( name ) )
//    {
//        document.cookie = name + "= " + ";expires=Thu, 01-Jan-1970 00:00:01 GMT;"
//
//    }
}

function WebLoadPageData($page_data) {
    $('body').removeClass($('body').attr('Class'));
    $('#mainContent').html($page_data.html);
}

//the img_track array is used to hold the image src for tracking purposes, so it can do the tracking when DOM is ready.
var img_track = [];
function ShowFeature(feature_data) {
    var feature, features, start_time, end_time, d, current_time, random_number, test_group_my_rolls, test_group_current, lower_limit, upper_limit, this_feature;
    // Feature data includes the HTML and the times to show, plus the test group

    d = new Date();
    current_time = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds() - 21600;

    // 1.  Loop from the lowest to the highest
    features = feature_data.data;
    test_group_my_rolls = {};
    test_group_current = {};
    for (feature in features) {
        this_feature = features[feature];

        feature_test_group_val = {};
        if (this_feature.hasOwnProperty('start_time')) {
            start_time = this_feature.start_time;
            end_time = this_feature.end_time;


            if (start_time >= end_time) {
                continue;
            }

            if (current_time < 0) {
                current_time += 86400;
            }

            // console.log(current_time + ' ' + start_time + '(' + feature_data[feature].start_time +  ')' + ' ' + end_time + '(' + feature_data[feature].end_time +  ')');

            if (current_time >= start_time && current_time <= end_time) {
                if (this_feature.hasOwnProperty('test_group') && this_feature.test_group !== '' && this_feature.hasOwnProperty('test_group_per') && this_feature.test_group_per < 100) {
                    if (!test_group_my_rolls.hasOwnProperty(this_feature.test_group)) {
                        test_group_my_rolls[this_feature.test_group] = getCookie('testgroup_' + this_feature.test_group);
                        if (test_group_my_rolls[this_feature.test_group] == null) {
                            test_group_my_rolls[this_feature.test_group] =  Math.floor(Math.random() * 100) + 1;
                            setCookie('testgroup_' + this_feature.test_group, test_group_my_rolls[this_feature.test_group], 1440);
                        } else {
                            test_group_my_rolls[this_feature.test_group] = parseInt(test_group_my_rolls[this_feature.test_group]);
                        }
                    }

                    //console.log(this_feature.test_group);

                    lower_limit = (test_group_current.hasOwnProperty(this_feature.test_group)) ? test_group_current[this_feature.test_group] + 1: 1;
                    upper_limit = test_group_current[this_feature.test_group] = lower_limit + this_feature.test_group_per - 1;

                    //console.log(lower_limit + ' ' + upper_limit + ' ' + test_group_my_rolls[this_feature.test_group]);


                    if (test_group_my_rolls[this_feature.test_group] < lower_limit || test_group_my_rolls[this_feature.test_group] > upper_limit) {
                        continue;
                    }
                }

                feature_data.target.append(features[feature].html);

//                if (features[feature].hasOwnProperty('img')) {
//                    img_track.push(features[feature].img.src);
//                }
//
//                $(document).ready(
//                    function(){
//                        while(img_track.length > 0) {
//                             dcsMultiTrack('DCS.dcssip', 'www.pizzahut.com', 'DCS.dcsuri', img_track.pop());
//                     }
//                })
//
                if (feature_data.hasOwnProperty('single') && feature_data.single === true) {
                    break;
                }
            }
        }
    }
}




String.prototype.toProperCase = function()
{
    return this.toLowerCase().replace(/^(.)|\s(.)/g,
        function($1) {
            return $1.toUpperCase();
        });
}

function PageNeedsDeals() {

    var path = window.location.pathname;
    var page = path.substring(path.lastIndexOf('/') + 1).toLowerCase();
    //var needDeals = ((page.indexOf("yeti") >= 0) || (page.indexOf("slinky") >= 0) || (page.length == 0));

    return true;
}

function Login(userID, userPW, isDelivery) {

    // var userID = "mtest997";
    // var userPW =  "test";
    //        var userID = document.getElementById("<%= ReturnUsernameLL.ClientID %>").value;
    //        var userPW = document.getElementById("<%= ReturnPasswordLL.ClientID %>").value;
    //debugger;

    //Gomez Tracking for Login SUBMIT
    GomezStartInterval("LOGIN_SUBMIT");

    DeliveryFlagForUser = isDelivery;

// PizzaHut.Web.WS.AEPersonalizationWS.Login(userID, userPW, OnWSRequestLoginComplete, OnWSRequestFailed);
// if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
}

function OnWSRequestLoginComplete(result) {
    //debugger;
    if (result != null)
    {
        if (result.indexOf("<error>") > 0)
        {
            $('#invalidAccountWD, #invalidAccountLL, #invalidAccountMH, #invalidAccountDE').slideDown();
        }
        else if (result == "")
        {
            //Any Exception on Login WebService. Still push to Quick Order site.
            window.location = baseQuickOrderLoginURL;
        }
        else
        {

            WriteUserCookie(result);
            closeLightbox();
        }
    }
    else
    {
        window.location = baseQuickOrderLoginURL;
    }
}

function closeLightbox()
{
    $('#loginLightboxWrapper, #orderNowForm, #lastOrderPopup').hide();
    $('#modalBackground').fadeOut(500);
}

function UpdateNavigation(isAuthenticated) {
    //var user = User(null);
    if (isAuthenticated) {

    // PizzaHut.Web.WS.AEPersonalizationWS.GetNavigationReplacers(OnNavigationRequestComplete, OnWSRequestFailed);
    }
    else {
        deleteCookie("_auth");
        if($("#welcomeLI") == null) return false;
        if($("#signOutLI") == null) return false;
        $("#welcomeLI").innerHTML = "";
        $("#signOutLI").innerHTML = "";
    }
}

function OnNavigationRequestComplete(navigationReplacers) {
    if (navigationReplacers != null) {
        for (var navigationReplacer in navigationReplacers) {
            var link = document.getElementById(navigationReplacers[navigationReplacer].HrefID);
            if (link != null) {
                if (link.href != null)
                    link.href = navigationReplacers[navigationReplacer].AuthenticatedUrl;
            }
        }
    }
}

// The valid parameters (subject to change) are:
//      unitID: 1 (not get line item detail for offer) 997 [store number to pull data for (#997 is default test store)]
//      locale: N L or N,L
//      template: Vertical or Carousel
//      filter: pizza_offer, wingstreet_offer, meal_deal_offer, catering_offer (or comma delimited list if multiple offers are requested)
function GetDealsHTML(unitID, locale, totalorders) {
    var template = GetHomePage();

    //GoMez: StartTracking - Deals
    var cookieOriginValue = getCookie("www-origin");

    if (cookieOriginValue == null)
        cookieOriginValue = "yeti";

    //TrackGomez(GomezEnvironment, cookieOriginValue +  "-HomePage", "Deals");

    GomezStartInterval("Deals");


// PizzaHut.Web.WS.AEPersonalizationWS.GetDealsHTML(unitID, locale, null, template, totalorders, OnWSRequestDealsComplete, OnWSRequestFailed);
// if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
}

function OnWSRequestDealsComplete(featuredDealsHTML) {

    if (featuredDealsHTML != null)
    {
        if(!$("#DealsRepeaterPlaceholder")){
            return false
        };
        $("#DealsRepeaterPlaceholder").html(featuredDealsHTML);
        //$("#DealsRepeaterPlaceholder").innerHTML = featuredDealsHTML;

        GomezEndInterval("Deals");

        GomezEndInterval("DefaultPage");
    //GoMez: EndTracking - Deals

    }
}

function GetHomePage() {
    //debugger;
    if(!$("#hiddenSpan")){
        return false
    };
    //return  $("#hiddenSpan").innerText;
    return $("#hiddenSpan").filter(':first-child').data;
}

function ShowItem(itemType, itemCode, redirectKey) {
    //debugger;
    addItemToCart(itemType, itemCode, redirectKey);
    if (getCookie("_qouid"))
    {
        // cookied user so pop up confirmation lightbox
        // on confirm do redirect
        window.location = getQuickOrderRedirectURL();
    }

    else
    {
        CreateOverlay();
        Center($('#loginLightboxWrapper'));
        //$(window).resize(AdjustOverlay);
        $(window).resize(Center($('#loginLightboxWrapper')));
        $(window).scroll(Center($('#loginLightboxWrapper')));
        $(modalBack).fadeIn(500, function(){
            $('#loginLightboxWrapper').show();
        });
    }
}

function GetLightboxContent(lightboxName) {
    $.get('GetLightbox.php', {
        lightbox: lightboxName
    }, function(data) {
        $('#loginLightboxWrapper').append(data);
        var loginModal = new ModalPopup({
            popupSelector: "#loginLightboxWrapper",
            triggerSelector: ".lightbox",
            alternatePos: false,
            closeSelector: "#loginLightboxWrapper .close, .noThanks, #modalBackground",
            slide: false
        });
        Center($('#loginLightboxWrapper'));
    }, 'html');
}

function ProcessLastOrder() {
    //debugger;
    //Get Coupon Code
    if (getCookie("_qolastord"))
    {
        var base64info1 = getCookie("_qolastord");
        var lastorderValue = base64_decode(base64info1);
        var lastorderInfo =  lastorderValue.split("~", 9);
        var lastordernumber  = lastorderInfo[1];
        //function addItemToCart(itemType, tabCode, itemCode, redirectKey, tracking)
        addItemToCart("LASTORD", lastordernumber, '', 'lastOrder');
        if (getCookie("_qouid"))
        {
            window.location = getQuickOrderRedirectURL();
        }
    }
}

function getQuickOrderRedirectURL() {

    // Look in PersonalizationVars.js for Default URL value.

    if (getCookie("qoRedirect"))
    {
        var base64URL = getCookie("qoRedirect");
        QuickOrderRedirectURL = base64_decode(base64URL);
    //setCookie("_qoredirecttest", QuickOrderRedirectURL, 10);
    }

    return QuickOrderRedirectURL;
}

function sendToQuikorder()
{
    window.location = getQuickOrderRedirectURL() + webTrendCode;
    return false;
}

function WriteSeemlessCookie(userAddress, userZip, userCity, userState, isDelivery) {
    //debugger;
    //        var userAddress = document.getElementById("<%= NewAddressLL.ClientID %>").value;
    //        var userZip = document.getElementById("<%= NewZipLL.ClientID %>").value;
    //        var rdo = document.getElementById('<%=NewDeliveryLL.ClientID%>');
    //        var userCity = null;
    //        var userState = null;
    if (userCity == "Enter your City")
    {
        userCity = "";
    }


    var cookieValue = ( (userAddress) ? escape( userAddress ) : " " ) +
    ( ( userZip ) ? "~" + userZip : "~" ) +
    ( ( userCity ) ? "~" + userCity : "~" ) +
    ( ( userState ) ? "~" + userState : "~" ) +   "~" +
    ( ( isDelivery ) ? "~D" : "~C"  ) + "~~~~~Y";
    var b64value = base64_encode(cookieValue);
    setCookie( "_qouid", b64value, 10);
    //setCookie( "_qouidseemless", cookieValue, 10);

    window.location = getQuickOrderRedirectURL() + webTrendCode;

}

function WriteSeemlessCookieWingStreet(userAddress, userZip, userCity, userState, ActionType, Action)
{
    //debugger;
    //        var userAddress = document.getElementById("<%= NewAddressLL.ClientID %>").value;
    //        var userZip = document.getElementById("<%= NewZipLL.ClientID %>").value;
    //        var rdo = document.getElementById('<%=NewDeliveryLL.ClientID%>');
    //        var userCity = null;
    //        var userState = null;
    if (userCity == "Enter your City")
    {
        userCity = "";
    }


    var cookieValue = ( (userAddress) ? escape( userAddress ) : " " ) +
    ( ( userZip ) ? "~" + userZip : "~" ) +
    ( ( userCity ) ? "~" + userCity : "~" ) +
    ( ( userState ) ? "~" + userState : "~" ) +   "~" +
    ActionType   + "~~~~~Y";


    if (Action == "NewFAL")
    {
        cookieValue = ( (userAddress) ? escape( userAddress ) : " " ) +
        ( ( userZip ) ? "~" + userZip : "~" ) +
        ( ( userCity ) ? "~" + userCity : "~" ) +
        ( ( userState ) ? "~" + userState : "~" ) +   "~~"  +
        ActionType   + "~~~~~SL";
    }
    else
    {
        cookieValue = ( (userAddress) ? escape( userAddress ) : " " ) +
        ( ( userZip ) ? "~" + userZip : "~" ) +
        ( ( userCity ) ? "~" + userCity : "~" ) +
        ( ( userState ) ? "~" + userState : "~" ) +   "~" +
        ( ( ActionType ) ? "~D" : "~C"  ) + "~~~~~Y";

    }

    var b64value = base64_encode(cookieValue);
    setCookie( "_qouid", b64value, 10);
    //setCookie( "_qouidseemless", cookieValue, 10);

    if (Action == "NewFAL")
    {
        window.location = QOEnvironmaneURL;

    }
    else
    {
        window.location = getQuickOrderRedirectURL() + webTrendCode;
    }

}

function WriteUserCookie(userInfo) {

//debugger;
// PizzaHut.Web.WS.AEPersonalizationWS.GetQOuidCookieValue(userInfo, DeliveryFlagForUser, OnWSRequestCookieValue, OnWSRequestFailed);
//if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

}

function OnWSRequestCookieValue(value) {
    //debugger;
    //
    var userInfo =  value.split("sessiontoken", 2);

    setCookie("_qosessid", userInfo[1], 10);
    setCookie( "_qouid", userInfo[0], 10);
    var usercookievaluetest = base64_decode(userInfo[0]);
    //setCookie( "_qouidtest", usercookievaluetest, 10);

    setCookieNonPersistant("_auth", "auth");
    //Write Session Cookie

    //Gomez Tracking for LOGIN_SUBMIT. END
    GomezEndInterval("LOGIN_SUBMIT");

    window.location = getQuickOrderRedirectURL() + authenticatedWebTrendCode;
}

function base64_encode( data ) {
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc="", tmp_arr = [];

    if (!data) {
        return data;
    }

    data = utf8_encode(data+'');

    do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);

        bits = o1<<16 | o2<<8 | o3;

        h1 = bits>>18 & 0x3f;
        h2 = bits>>12 & 0x3f;
        h3 = bits>>6 & 0x3f;
        h4 = bits & 0x3f;

        // use hexets to index into b64, and append result to encoded string
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
    } while (i < data.length);

    enc = tmp_arr.join('');

    switch( data.length % 3 ){
        case 1:
            enc = enc.slice(0, -2) + '==';
            break;
        case 2:
            enc = enc.slice(0, -1) + '=';
            break;
    }

    return enc;
}

function base64_decode( data ) {

    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = [];

    if (!data) {
        return data;
    }

    data += '';

    do {  // unpack four hexets into three octets using index points in b64
        h1 = b64.indexOf(data.charAt(i++));
        h2 = b64.indexOf(data.charAt(i++));
        h3 = b64.indexOf(data.charAt(i++));
        h4 = b64.indexOf(data.charAt(i++));

        bits = h1<<18 | h2<<12 | h3<<6 | h4;

        o1 = bits>>16 & 0xff;
        o2 = bits>>8 & 0xff;
        o3 = bits & 0xff;

        if (h3 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1);
        } else if (h4 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1, o2);
        } else {
            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
        }
    } while (i < data.length);

    dec = tmp_arr.join('');
    dec = utf8_decode(dec);

    return dec;
}

function utf8_decode ( str_data ) {

    var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;

    str_data += '';

    while ( i < str_data.length ) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if ((c1 > 191) && (c1 < 224)) {
            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }

    return tmp_arr.join('');
}

function utf8_encode ( string ) {

    string = (string+'').replace(/\r\n/g, "\n").replace(/\r/g, "\n");

    var utftext = "";
    var start, end;
    var stringl = 0;

    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;

        if (c1 < 128) {
            end++;
        } else if((c1 > 127) && (c1 < 2048)) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc != null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }

    if (end > start) {
        utftext += string.substring(start, string.length);
    }

    return utftext;
}

function User(cookieVal) {

    if (cookieVal != null) {
    }

    return {
        IsAuthenticated: false
    };

}

function Center(popup)
{
    var windowWidth = $(window).width();
    var windowHeight = $(window).height();
    var scrollLeft = $(window).scrollLeft();
    var scrollTop = $(window).scrollTop();
    var popupWidth = popup.width();
    var popupHeight = popup.height();
    if($.browser.safari)
    {

        windowHeight = document.documentElement.clientHeight;

    }
    var leftPos = (windowWidth - popupWidth) / 2 + scrollLeft;
    var topPos = (windowHeight - popupHeight) / 2 + scrollTop;

    popup.css({
        "left" : leftPos,
        "top" : topPos
    })
}

function CreateOverlay()
{
    if(!$('#modalBackground').length)
    {
        var modalBack = document.createElement('div');
        var modalId = "modalBackground";
        modalBack.setAttribute("id", modalId);
        document.body.appendChild(modalBack);
        $(modalBack).css({
            "display": "none",
            "background-color": modalBackground,
            "opacity": opacity,
            "z-index": "50"
        });
    }
}

function AdjustOverlay()
{
    var windowWidth = $('body').width();
    var windowHeight = $('body').height();
//$('#modalBackground').css({"width":windowWidth, "height":windowHeight});
}

function redirect(redirectKey, tracking)
{
    if(tracking == null || tracking == undefined)
    {
        tracking = "";
    }
    var url = mapRedirectURL(redirectKey, tracking);
    window.location=url;
    return;
}

function VerifyUrl(Imc2url, qikorderUrl)
{
    if (IsCookied == "Y")
    {
        window.location = qikorderUrl;
    }
    else
    {
        if(Imc2url != '')
        {
            window.location = Imc2url;
        }
    }
}

function mapRedirectURL(redirectKey, tracking) {
    //alert(tracking);
    // Look in PersonalizationVars.JS for Default Value
    switch (redirectKey){

        case "myhut":
            return baseQuickOrderURL + PageMyHut + tracking;
            break;

        case "pizza":
            return baseQuickOrderURL + PagePizza + tracking;
            break;

        case "pasta":
            return baseQuickOrderURL + PagePasta + tracking;
            break;

        case "wings":
            return baseQuickOrderURL + PageWings + tracking;
            break;

        case "pzone":
            return baseQuickOrderURL + PagePZone + tracking;
            break;

        case "sides":
            return baseQuickOrderURL + PageSides + tracking;
            break;

        case "drinks":
            return baseQuickOrderURL + PageDrinks + tracking;
            break;

        case "deals":
            return baseQuickOrderURL + PageDeals + tracking;
            break;

        case "moreDeals":
            return baseQuickOrderURL + PageMoreDeals + tracking;
            break;

        case "lastOrder":
            return lastorderLink;
            break;

        case "value":
            return baseQuickOrderURL + valueMenu + tracking;
            break;

        default :
            return baseQuickOrderURL + PageMyHut;

    }
}

function TrackGomez(Environment, PageID, GroupID)
{
    //debugger;
    var bPath = $('body').attr('class');
    if (bPath.toLowerCase() == "slinky" || bPath.toLowerCase() == "yeti")
    {
        //alert("AcctID:" + acctId + "\n" + "PageID:" + pgID + "\n" + "GroupID:" + grpID);
        gomez.acctID= 'BD1D5F';
        gomez.pgId = Environment + PageID;
        gomez.grpId = GroupID;
    }
// gomez.nameEvent("AcctID:" + acctId + "|" + "PageID:" + pgID + "|" + "GroupID:" + grpID); //
}

function GomezStartInterval(IntervalName)
{
    //debugger;
    var bPath = $('body').attr('class');
    if (bPath.toLowerCase() == "slinky" || bPath.toLowerCase() == "yeti")
    {
        if (GomezEnvironment == "PRODUCTION")
        {
            gomez.startInterval(IntervalName);
        }
    }
}

function GomezEndInterval(IntervalName)
{
    //debugger;
    var bPath = $('body').attr('class');
    if (bPath.toLowerCase() == "slinky" || bPath.toLowerCase() == "yeti")
    {
        if (GomezEnvironment == "PRODUCTION")
        {
            gomez.endInterval(IntervalName);
        }
    }
}

function SwitchToSSL(path) {
    if (path.substring(0, 6) == 'https:') return path;
    var url = location.href;
    if (path.substring(0, 5) == 'http:') {
        url = path;
        path = '';
    }

    url = parseUri(url);

    // If the URL already points to an https page, don't do anything
    if (url.protocol != 'https') {
        if (path.substring(0, 1) == '/') {
            // Path is a full path, so just append it on to the domain
            path = "https://" + url.authority + path;
        } else  if (path.length > 0) {
            // Path is a relative path, so just append it on to the current dir
            path = "https://" + url.authority + url.directoryPath + path;
        } else {
            // Full path was provided, so just replace protocol
            path = url.source.replace('http:','https:');
        }
    }

    return path;
}



/* parseUri JS v0.1, by Steven Levithan (http://badassery.blogspot.com)
Splits any well-formed URI into the following parts (all are optional):
----------------------
? source (since the exec() method returns backreference 0 [i.e., the entire match] as key 0, we might as well use it)
? protocol (scheme)
? authority (includes both the domain and port)
    ? domain (part of the authority; can be an IP address)
    ? port (part of the authority)
? path (includes both the directory path and filename)
    ? directoryPath (part of the path; supports directories with periods, and without a trailing backslash)
    ? fileName (part of the path)
? query (does not include the leading question mark)
? anchor (fragment)
*/
function parseUri(sourceUri){
    var uriPartNames = ["source","protocol","authority","domain","port","path","directoryPath","fileName","query","anchor"];
    var uriParts = new RegExp("^(?:([^:/?#.]+):)?(?://)?(([^:/?#]*)(?::(\\d*))?)?((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[\\?#]|$)))*/?)?([^?#/]*))?(?:\\?([^#]*))?(?:#(.*))?").exec(sourceUri);
    var uri = {};

    for(var i = 0; i < 10; i++){
        uri[uriPartNames[i]] = (uriParts[i] ? uriParts[i] : "");
    }

    // Always end directoryPath with a trailing backslash if a path was present in the source URI
    // Note that a trailing backslash is NOT automatically inserted within or appended to the "path" key
    if(uri.directoryPath.length > 0){
        uri.directoryPath = uri.directoryPath.replace(/\/?$/, "/");
    }

    return uri;
}

function showMore(element) {
    $(element).parent().slideUp("fast", function(){$(element).parent().siblings(".view_more_description").slideDown("fast")});
}

function showLess(element) {
     $(element).parent().slideUp("fast", function(){$(element).parent().siblings(".view_less_description").slideDown("fast")});
}

