﻿// ON DOCUMENT READY
$(document).ready(function () {
    // 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'));
            } 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();
        } else {
            $('#locations').html("<p>Please enter a five digit zip code.</p>");
        }
        pageTracker._trackEvent('findstore', 'find', 'menupage');
    });

    // 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");

    // EVENT TRACKING
    $('#ctl00_ctl09_btnJoinEmail').click(function () {
        pageTracker._trackEvent('clubveg', 'go', 'topnav');
    });
    $('#ctl00_Body_hplClubVeg').click(function () {
        pageTracker._trackEvent('clubveg', 'join', 'carousel');
    });
    $('#ctl00_Body_btnFindRestaurant').click(function () {
        pageTracker._trackEvent('findstore', 'go', 'carousel');
    });

    // PASSPORT PROMOTION
    var postcardmaxlength = 220;
    $('#ctl00_Body_postcardTextarea')
        .focus(function () {
            $(this).css('background', 'none');
        })
        .blur(function () {
            if ($(this)[0].value == '') { $(this).css("background", "url(../images/passport/postcard-bg.gif)") }
        })
        .keyup(function () {
            $(this).val($(this).val().substring(0, postcardmaxlength));
        });
    $('a.region-link').click(function (evt) {
        evt.preventDefault();
        var region = $(this).attr('id').substring(7);
        $('#ctl00_Body_hdnRegion').val(region);
        //Swap Postcard Background
        switch (region) {
            case "2":
                $('#postcard-content').css('background', 'url(../images/passport/create-asia.jpg)');
                break;
            case "3":
                $('#postcard-content').css('background', 'url(../images/passport/create-greece.jpg)');
                break;
            case "4":
                $('#postcard-content').css('background', 'url(../images/passport/create-mexico.jpg)');
                break;
            default:
                $('#postcard-content').css('background', 'url(../images/passport/create-italy.jpg)');
        }
    });
    //send another
    $('#bonvoyage-content a.pbtn-send-another').click(function () {
        pageTracker._trackEvent('passport', 'sendanother');
    });
    //jet off
    $('#bonvoyage-content a.pbtn-jet').click(function () {
        pageTracker._trackEvent('passport', 'passportpage2');
    });
    //join club veg
    $('#bonvoyage-content a.pbtn-join-club-veg').click(function () {
        pageTracker._trackEvent('passport', 'clubvegsignup');
    });
    // passport landing page pdf downloads
    $("#regions .region a").click(function () {
        var link = $(this).attr('href');
        pageTracker._trackPageview('/download/passport/' + link);
    });

});

$(function () {
    var $ready = null;
    function addHandler() {
        if ($ready) $ready.unbind('ready');
        $ready = $('#ctl00_Body_postcardTextarea').ready(function (evt) {
            $(this).css("background","none");
        });
    }
    Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(addHandler);
    addHandler();
});

// TRACK SWEETIE'S ROADTRIP
function sweetiesRoadtrip() {
    pageTracker._trackEvent('sweetiepromo', 'learnmore');
    window.location = '/roadtrip/';
}

// 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);
}

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;
    }
}


// MOBILE STATS
$(function() {
    var $click = null;
    function addHandler() {
        if ($click) $click.unbind('click');
        $click = $('.showCharts').click(function(e) {
            e.preventDefault();
            displayCharts();
        });
    }
    Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(addHandler);
    addHandler();
});
var myStates = new Array();
var myPages = new Array();
var myDevices = new Array();
var colors = ['#A51C18', '#4286BD', '#71D743', '#FDCB3F', '#9900ff', '#FA5E1F', '#AB7B55', '#B381C9', '#5a0000',
                '#22273A', '#336633', '#E5D48F', '#375E27', '#FFCC33', '#4286BD', ];
function displayChart(container, data, title) {
    $('#' + container).empty();
    var myColors = new Array();
    for (i = 0; i < data.length; i++) {
        myColors.push(colors[i]);
    }
    var myChart = new JSChart(container, 'bar');
    myChart.setDataArray(data);
    myChart.colorizeBars(myColors);
    myChart.setBarOpacity(0.8);
    myChart.setBarBorderWidth(0);
    myChart.setBarValues(true);
    myChart.setTitle(title);
    myChart.setAxisNameX('');
    myChart.setAxisNameY('');
    if (data.length > 5) {
        myChart.setSize(570, 300);
    } else {
        myChart.setSize(280, 300);
    }
    myChart.setTitleColor('#333333');
    myChart.setAxisColor('#555555');
    myChart.setAxisValuesColor('#000000');
    myChart.draw();
}

function displayCharts() {
    // STATES
    myStates = [];
    $('.statestats').each(function (i, e) {
        var thisVal = parseInt($(this).val());
        var thisName = $(this).attr('name');
        myStates.push([thisName, thisVal]);
    });
    displayChart('chartStates', myStates, 'States');

    // PAGE HITS
    myPages = [];
    $('.pagehitsstats').each(function (i, e) {
        var thisVal = parseInt($(this).val());
        var thisName = $(this).attr('name');
        myPages.push([thisName, thisVal]);
    });
    displayChart('chartHits', myPages, 'Page Hits');

    // DEVICES
    var iphone = parseInt($('#iphonestats').val());
    var bb = parseInt($('#bbstats').val());
    var android = parseInt($('#androidstats').val());
    var windows = parseInt($('#windowsstats').val());
    myDevices = [];
    myDevices.push(['iPhone', iphone]);
    myDevices.push(['Blackberry', bb]);
    myDevices.push(['Android', android]);
    myDevices.push(['Win. Mob.', windows]);
    displayChart('chartDevices', myDevices, 'Devices');
}