﻿// ON DOCUMENT READY
$(document).ready(function() {
    // SET BG IF COOKIE EXISTS
    /*$('body').ready(function() {
    var bgclass = Get_Cookie('myBG');
    if (bgclass != null) {
    $('body').removeClass().addClass(bgclass);
    $('#background a').removeClass();
    $('#bg_' + bgclass).addClass('active');
    }
    });*/

    // BG PICKER
    $('#background a').click(function(event) {
        event.preventDefault();
        var bgclass = $(this).attr('title');
        $('body').removeClass().addClass(bgclass);
        $('#background a').removeClass();
        $(this).addClass('active');
        // set bg in cookie (for 20 years)
        Set_Cookie("myBG", bgclass, (365 * 20), '/', '', '');
    });

    // NAVIGATION DROPDOWN
    $('#nav-nutrition').bind("mouseenter", function() {
        $('#nav-nutrition ul').show();
    });
    $('#nav-nutrition').bind("mouseleave", function() {
        $('#nav-nutrition ul').hide();
    });

    // INPUTS -> CLEAR TEXT ON FOCUS, RESTORE DEFAULT ON BLUR IF EMPTY
    $('input.cleartext').focus(function() {
        if (($(this).val() == this.defaultValue)) {
            if ($(this).val() > 10000) {
                // this is a zip code -> do not clear (locations page)
            } else {
                $(this).val('');
            }
        }
    }).blur(function() {
        if ($(this).val() == '') {
            $(this).val(this.defaultValue);
        }
    });

    // DISABLE ENTER KEY ON INPUTS
    $('input').keypress(function(e) {
        if (e.keyCode == 13) return false;
    });

    $('input.zipcodesearch').keypress(function(e) {
        if (e.keyCode == 13) {
            if ($(this).val() > 10000) {
                searchZip();
                pageTracker._trackEvent('location_page', 'location_search', $(this).attr('id'));
                Lm.pt.gat._trackEvent('location_page', 'location_search', $(this).attr('id'));
            } else {
                $('#locations').html("<p>Please enter a five digit zip code.</p>");
            }
        }
    });

    $('a#btn-find-restaurant').click(function(event) { //locations page
        event.preventDefault();
        if ($('input.zipcodesearch').val() > 10000) {
            searchZip();
            pageTracker._trackEvent('location_page', 'location_search', $(this).attr('id'));
            Lm.pt.gat._trackEvent('location_page', 'location_search', $(this).attr('id'));
        } else {
            $('#locations').html("<p>Please enter a five digit zip code.</p>");
        }
    });

    // COLORBOX POPUP
    $('a.popup').colorbox();

    // FOR SPROUTS ONLY
    $('#btn-play-spudman').click(function(event) {
        event.preventDefault();
        $('#top-left').css({ "padding": "0 42px", "height": "422px", "width": "360px", "background-image": "none" }).flash(
            { src: '../flash/spudman.swf',
                width: 360,
                height: 422
            },
            { expressInstall: true }
        ).focus();
        //$('#top-right').css({ "height": "422px" });
    });

    // TALK TO US FORMS
    $('a.talk-to-us-link').click(function(event) {
        event.preventDefault();
        var clientid = ($(this).attr("id") == "lnk-souplantation") ? "1988" : "1987";
        $('#talk-to-us-form').html('<iframe frameborder="0" height="500" marginwidth="0" marginheight="0" name="specific" scrolling="auto" src="http://www.ServiceCheck.net/forms/irpt_welcome.asp?brandid=155&clientid=' + clientid + '" width="100%"></iframe>"');
    });

    // FIND/TRACK OUTBOUND LINKS
    $("a[href^='http']").click(function(event) {
        var link = $(this).attr('href');
        var pagenameArr = link.split("/", 3);
        pageTracker._trackPageview('/outgoing/links/' + pagenameArr[2]);
    });

    // TRACK SPROUTS DOWNLOAD LINKS
    $("div.sproutscontent a[href!=#]").click(function(event) {
        var link = $(this).attr('href');
        pageTracker._trackPageview('/downloads/sprouts/' + link);
    });

    // SET ACTIVE STATES
    $('body:has(div.funraiserscontent) a.navFun').addClass("active");
    $('body:has(div.careerscontent) a.navCareers').addClass("active");
    $('body:has(div.companycontent) a.navCompany').addClass("active");
    $('body:has(div.presscontent) a.navPress').addClass("active");
    $('body:has(div.talkcontent) a.navTalk').addClass("active");
    $('body:has(div.sproutscontent) a.navSprouts').addClass("active");

    $('body:has(div.locationscontent) li#nav-locations').addClass("active");
    $('body:has(div.nutritioncontent) li#nav-nutrition').addClass("active");
    $('body:has(div.giftcardscontent) li#nav-gift-cards').addClass("active");

});

// DATE PICKER
$(function() {
    $('.date-pick')
        .datePicker({ createButton: false })
        .bind('click', function() {
            // show calendar
            $(this).dpDisplay();
            this.blur();
            return false;
        })
        .bind('dateSelected', function(e, selectedDate, $td) {
            // redirect with new date
            var storeid = $("#ctl00_Body_hdnStoreID").val();
            var newdate = (selectedDate.getMonth()+1) + "/" + selectedDate.getDate() + "/" + selectedDate.getFullYear();
            var newurl = "/locations/restaurant.aspx?store_id=" + storeid + "&dt=" + newdate + "&disp=future#subnav";
            window.location.replace(newurl);
        });
});

function locationSet(location) {
    pageTracker._trackEvent('topnav', 'location_set', location);
    Lm.pt.gat._trackEvent('topnav', 'location_set', location);
}

function SetHeaderPromo(navurl, imagesrc) {
    try
    {
        document.getElementById("ctl00_Body_hplLocalization").href = navurl;
        document.getElementById("ctl00_Body_hplocalizationimage").src = imagesrc;
        window.location.href= window.location.href;
    }
    catch (err)
    {    }
}

// COOKIE HANDLING
function Set_Cookie(name, value, expires, path, domain, secure) {
    // set time, it's in milliseconds
    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 Get_Cookie(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;
    }
}
