/// <reference path="jquery-1.4.4-vsdoc.js" />
// CONTENTS ====================================================================
/*
1.0 Utilities
	
2.0 Frontend
2.1 Frontend.Default
2.2 Frontend.PNGFix
2.3 Frontend.LightBox
2.4 Frontend.Carousel
2.5 Frontend.LocationMap
2.6 Flash
2.7 CollapseList (FAQ Collapse)
2.8 Contour Functions
2.9 Store Navigation
2.10 Rotator
2.11 Header
2.12 Speechbox
2.13 Store disclaimer dynamic placement
2.14 Rate recipe hover and click actions

	
3.0 Tracking
3.1 Google Analytics
*/

// 1.0 Utilities ======================================================================


// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function () {
    log.history = log.history || [];   // store logs to an array for reference
    log.history.push(arguments);
    if (this.console) {
        console.log(Array.prototype.slice.call(arguments));
    }
};

// 2.0 Frontend ======================================================================
var Frontend = {

    // 2.1 Frontend.Default ======================================================
    Default: (function () {

        //This Init function is called on every page on the site.
        function init() {

            //Place general init functions here or else add to DocReadyMgr using Header.DocReadyMgr.AddFunction("functionName(params)")
            Header.DocReadyMgr.Run();
            Frontend.Header.Init();
            Frontend.Utility.init();
            Frontend.FAQ.init();
            Frontend.LightBox.Init();
            Frontend.Contour.Init();
            Frontend.Speechbox.Init();
            Frontend.LicensingTrustLaws.Init();
            Frontend.EmailSliderSubscription.Init();
        }

        //This init function is called only on the homepage
        function homepageInit() {

        }

        return {
            init: init,
            homepageInit: homepageInit
        }

    })(),

    Utility: (function () {
        function init() {
            $('.con-store-nav-toggle').click(function () {
                $('html').animate({ scrollTop: 0 }, 'slow', function () {
                    $('.store-nav-toggle').trigger('click');
                });

            });
        }
        return {
            init: init
        }
    })(),

    FAQ: (function () {
        function init() {

            //Open first answer if more than one question listed
            $('.questions li:first .answer').slideDown(100);

            //Set expand/collapse links
            $('.questions li').each(function (i) {
                if (i != 0)
                    $(this).find('h2').find('.q').wrap('<a href="#"/>');
                var classList = "ind ", html = "";
                classList += i == 0 ? "arrow-up" : "arrow-down";
                html += i == 0 ? "Hide answer" : "Show answer";
                $(this).prepend('<p class="right"><a href="#" class="' + classList + '">' + html + '</a></p>');
            });
            //SlideUp/SlideDown triggers
            $('.questions li h2 a').live('click', function () {
                $(this).parents('li').find('.ind').trigger('click');
                return false;
            });
            $('.questions li .ind').click(function () {
                var $li = $(this).parents('li:first');
                var $ind = $li.find('.ind');
                var $heading = $li.find('h2');

                if ($ind.hasClass('arrow-down')) {
                    $ind.html("Hide answer");
                    $li.find('.answer').slideDown(100);
                    $heading.html('<span class="marker">' + $heading.find('.marker').html() + '</span>' + $heading.find('a').html());
                }
                else {
                    $ind.html("Show answer");
                    $li.find('.answer').slideUp(100);
                    $heading.find('.q').wrap('<a href="#"/>');
                }
                $ind.toggleClass('arrow-up arrow-down');
                return false;
            });

            if (location.hash) {
                $(location.hash + ' a').trigger('click');
            }

        }
        return {
            init: init
        }
    })(),

    // 2.2 Frontend.PNGFix ======================================================
    // IE6 PNG Transparency Fix
    PNGFix: (function () {

        function Fix() {
            DD_belatedPNG.fix('.test');
        }

        return {
            Fix: Fix
        }

    })(),


    // 2.3 Frontend.LightBox ======================================================
    LightBox: (function () {

        var $cbox;

        function Init() {
            $cbox = $('#colorbox');

            $("a[rel='lightbox']").each(
				function () {
				    $(this).colorbox({
				        initialWidth: 1,
				        initialHeight: 1,
				        transition: "elastic",
				        title: function () {
				            return $(this).attr('title');
				            //return "test title";
				        },
				        onComplete: function () {
				            SetDescriptionAndHeight($(this));

				        },
				        onCleanup: function () {

				        }
				    });
				}
			);

            $("a[rel='lightbox-content']:not(#colorbox a[rel='lightbox-content'])").live('click', function () {
                $.colorbox({
                    href: $(this).attr('href'),
                    innerWidth: 630,
                    innerHeight: 400,
                    title: $(this).attr('title'),
                    onComplete: function () {
                        $cbox.find('.offscreen').removeClass('offscreen').addClass('onscreen');
                        SetDescriptionAndHeight($(this));
                    },
                    onCleanup: function () {
                        $cbox.find('.onscreen').removeClass('onscreen').addClass('offscreen');
                    }
                });
                return false;
            });

            $("a > span[class='lightbox-content']:not(#colorbox a > span[class='lightbox-content'])").live('click', function () {
                $.colorbox({
                    href: $(this).parent().attr('href'),
                    innerWidth: 630,
                    innerHeight: 400,
                    title: $(this).parent().attr('title'),
                    onComplete: function () {
                        $cbox.find('.offscreen').removeClass('offscreen').addClass('onscreen');
                        SetDescriptionAndHeight($(this));
                    },
                    onCleanup: function () {
                        $cbox.find('.onscreen').removeClass('onscreen').addClass('offscreen');
                    }
                });
                return false;
            });

        }

        function SetDescriptionAndHeight(elm) {
            var description = elm.parent().find('p:first').text();
            $("#cboxDescription").remove();
            var $content;
            if (description != '') {
                $("#cboxLoadedContent").after('<div id="cboxDescription">' + description + '</div>');
                var heightIncrease = $("#cboxTitle").height() > 39 ? ($("#cboxTitle").height() - 39) : 0;
                if (heightIncrease != 0) {
                    $("#cboxLoadedContent").css({ 'margin-top': 20 + heightIncrease });
                }
                heightIncrease += $('#cboxDescription').height();
                $content = $('#cboxContent');
                $content.height($content.height() + heightIncrease);

                $cbox.css({ 'top': ($cbox.css('top').replace('px', '') - (heightIncrease / 2)) + 'px' });
                $('#cboxWrapper').height($('#cboxWrapper').height() + heightIncrease);
                $('#colorbox').height($('#colorbox').height() + heightIncrease);
            } else {
                var heightIncrease = $("#cboxTitle").height() > 39 ? ($("#cboxTitle").height() - 39) : 0;
                if (heightIncrease != 0) {
                    $("#cboxLoadedContent").css({ 'margin-top': 20 + heightIncrease });
                    $content = $('#cboxContent');
                    $content.height($content.height() + heightIncrease);
                    $cbox.css({ 'top': ($cbox.css('top').replace('px', '') - (heightIncrease / 2)) + 'px' });
                    $('#cboxWrapper').height($('#cboxWrapper').height() + heightIncrease);
                    $('#colorbox').height($('#colorbox').height() + heightIncrease);
                }
            }
        }

        return {
            Init: Init
        }
    })(),


    // 2.4 Frontend.Carousel ======================================================
    Carousel: (function () {

        function Init() {
            $('#gallery-navigation').terousel({
                ajaxPage: true
            });
            $('#gallery-navigation li').tooltip();
        }

        return {
            Init: Init
        }
    })(),

    // 2.5 Frontend.LocationMap ===================================================
    LocationMap: (function () {

        function Init($map, latitude, longitude, zoom, storeDetails, directionsLink) {

            //MAP
            var latlng = new google.maps.LatLng(latitude, longitude);
            var myOptions = {
                zoom: parseInt(zoom),
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var map = new google.maps.Map(document.getElementById("store-location"), myOptions);
            //MARKER
            var storeMarker = new google.maps.Marker({
                position: latlng,
                map: map,
                title: "Four Square",
                icon: '/images/ico-googlemap-marker.png'
            });
            //POPUP Info Pane
            storeDetails = '<div class="map-info">' + storeDetails + '</div>';
            storeDetails += '<a target="_blank" class="directions" href="' + directionsLink + '">Get Directions</a>';

            var infowindow = new google.maps.InfoWindow({
                content: storeDetails
            });

            var $gmap = $('#store-location');
            var orig_width = $gmap.width();
            var orig_height = $gmap.height();

            $('.gmap-toggle').click(function () {
                var $this = $(this);
                if ($this.text() === 'Enlarge Map') {
                    $this.html('Shrink map');
                    $gmap.animate({ 'width': 580, 'height': 580 }, 500, function () {
                        google.maps.event.trigger(map, 'resize');
                        map.panTo(latlng);
                    });
                } else {
                    $this.text('Enlarge Map');
                    $gmap.animate({ 'width': orig_width, 'height': orig_height }, 500, function () {
                        google.maps.event.trigger(map, 'resize');
                        map.panTo(latlng);
                    });
                }

                return false;
            });

            if (location.hash) {
                $('.gmap-toggle').trigger('click');
            }

            /*
            infowindow.open(map, storeMarker);
            google.maps.event.addListener(storeMarker, 'mousedown', function () {
            infowindow.open(map, storeMarker);
            });
            */
        }

        return { Init: Init }
    })(),

    // 2.6 Flash =====================================================================
    Flash: (function () {

        function Embed(target, src, width, height) {
            var vars = {};
            var params = { 'wmode': 'transparent' };
            swfobject.embedSWF(src, target, width, height, "9.0.0", "/scripts/expressInstall.swf", vars, params);
        }

        return { Embed: Embed }

    })(),

    // 2.7 FAQ Collapse ==============================================================
    CollapseList: (function () {

        function Init(elms) {

            elms.each(function () {
                var $this = $(this);
                var $toggler = $this.find('h2').css({ 'cursor': 'pointer' });
                var $info = $this.find('div');
                $toggler.toggle(function () { $info.show(); }, function () { $info.hide(); });
            });

            if (location.hash) {
                $(location.hash).trigger("click");
            }
        }

        return { Init: Init }

    })(),

    // 2.8 Contour form ==============================================================
    Contour: (function () {

        function Init() {
            Fileupload();
            Docket();
            ButtonStyle();
        }

        function Fileupload() {

            $("input.styledfileupload").attr('size', '40');

            $('fieldset').delegate("input.styledfileupload", "change", function () {
                changeCallback($(this));
            });
        }

        function changeCallback(uploader) {
            var file = $(uploader)[0].value;
            uploader.parents('div.contourField').find('.faux-upload input')[0].value = file;
        }

        function Docket() {

            var $selector = $('.storeselectfield select');
            var $input = $('.docketnumber input.docket-number');
            var region;

            if ($input.length > 0 && $selector.length > 0) {
                $('body').append('<div class="docket-info hidden abs">Locate docket number <img src="/images/placeholder/docket.png" alt="" width="185" height="110" /></div>');

                var $info = $('.docket-info');

                var offset = $input.offset();
                $info.css({ 'top': offset.top, 'left': offset.left + 372, 'display': 'none' }).removeClass('hidden');

                $selector.change(function () {
                    var $currentOption = $(this).find('option:selected');
                    if ($currentOption.attr('data-region')) {
                        region = $currentOption.attr('data-region');
                        $info.find('img').attr('src', '/images/interface/ind/ind-docket-' + region.replace(/ /ig, '-') + '.png');
                    } else {
                        region = '';
                    }
                });

                $selector.trigger('change');

                $input.focus(function () {
                    if (region != '')
                        $info.show();
                });
                $input.blur(function () {
                    $info.hide();
                });
            }
        }

        function ButtonStyle() {
            $('.contourButton').addClass('btn-link').addClass('btn-black');
        }

        return {
            Init: Init
        }

    })(),

    // 2.9 Sub Region and Store Navigaiton ==========================================================
    SubRegionLocations: (function () {
        function Init() {
            var buttons = $('.store-nav-toggle, #stores-nav .close');
            var target = $('#stores-nav .holder');
            buttons.each(function () {
                $this = $(this);
                $this.click(function () {
                    target.slideToggle();
                    targetOnScreen(target);
                    return false;
                });
            });
        }

        function targetOnScreen(target) {
            var offset = $('#header').height();
            var fromtop = $('html, body').scrollTop();
            if (fromtop > offset) { $('html, body').animate({ scrollTop: offset }, 150); }
        }


        return { Init: Init }
    })(),


    // 2.9(a) Regional Navigation Top Banner ====================================================
    LoadStores: (function () {
        function Init() {
            var buttons = $('.regionSelect');
            var storeList = $('#storeListing')

            buttons.each(function () {
                $this = $(this);
                $this.click(function () {
                    storeList.slideToggle('fast');
                    var target = $(this).attr("target");
                    $(target).empty();
                    $(target).load("/Base/restExt/subRegionStoreHTMLOutput//" + $(this).attr("rel") + ".aspx"); //delete previously loaded data
                    storeList.slideToggle('fast');
                    return false;
                });
            });
        }

        return { Init: Init }
    })(),

    // 2.9(a) Regional Navigation Top Banner ====================================================
    FindYourLocal: (function () {
        function Init() {
            var buttons = $('.findYourLocal');
            var storeList = $('#storeListing')

            buttons.each(function () {
                $this = $(this);
                $this.click(function () {
                    storeList.slideToggle('fast');
                    var target = $(this).attr("target");
                    $(target).empty();
                    $(target).load("/Base/restExt/subRegionStoreHTMLOutputFYL/" + $(this).attr("rel") + ".aspx"); //delete previously loaded data
                    storeList.slideToggle('fast');
                    return false;
                });
            });
        }

        return { Init: Init }
    })(),



    // 2.10 Rotator ==================================================================
    Rotator: (function () {
        var current_index = 0;
        var interval = '';
        var delay_sec = 8;
        var interval_sec = 5;
        var $items;
        var numItems;

        function Init() {
            $('.rotator').each(function () {
                var $rotator = $(this);
                numItems = $rotator.find('li').length;
                if (numItems > 1) {
                    $rotator.find('ul').css({ 'width': $rotator.width(), 'position': 'relative', 'overflow': 'hidden', 'top': '0', 'left': '0' });

                    $items = $rotator.find('.items li');
                    $items.css({ 'width': $rotator.width(), 'height': $rotator.height(), 'position': 'absolute' });

                    $rotator.append('<div class="rotator-nav"><ul class="box bg-yello text-center pages"></ul></div>');
                    var $controls = $rotator.find('.rotator-nav');
                    for (var i = 0; i < numItems; i++) {
                        $controls.find('.pages').append('<li class="page-num"><a class="btn btn-black item-index" href="#" rel="' + i + '">' + (i + 1) + '</a> </li>');
                    }
                    $rotator.find('ul.pages').width(numItems * (5 + $rotator.find('li.page-num:first').width()));

                    $(".rotator-nav").append('<a class="ir abs btn btn-black prev" href="#">Previous</a><a class="ir abs btn btn-black next" href="#">Next</a>');
                    BindControls($items, $controls);
                }
            });

            if (numItems > 1) SetTimer();
        }
        function BindControls($items, $controls) {
            var $itembuttons = $controls.find('.item-index');
            var $next = $controls.find('.next');
            var $prev = $controls.find('.prev');

            $itembuttons.each(function () {
                var $this = $(this);
                $this.click(function () {
                    var index = $this.attr('rel');
                    ShowItemAt(index, 0);
                    DelayTimer();
                    return false;
                });
            });
            $next.click(function () {
                moveNext();
                DelayTimer();
                return false;
            });
            $prev.click(function () {
                var index = parseInt(current_index) - 1;
                if (current_index <= 0)
                    index = $items.length - 1;
                ShowItemAt(index, 'left');
                DelayTimer();
                return false;
            });
        }

        function ShowItemAt(index, dir) {

            if (current_index != index) {

                var $currentItem = $items.eq(current_index); //.filter(':visible');
                var $nextItem = $items.eq(index);

                var endpos = (dir === 'left') ? '100%' : '-100%';

                if (dir === 0) {
                    endpos = current_index > index ? '100%' : '-100%';
                }

                current_index = index;

                $nextItem.stop().css({ 'left': '0', 'z-index': '1' });
                $currentItem.css({ 'left': '0', 'z-index': '20' });

                $nextItem.show();
                $currentItem.animate({ 'left': endpos }, 500, function () {
                    $currentItem.hide();
                });

                //$items.hide();
                //$items.eq(index).show();
            }
        }


        function moveNext() {
            var index = parseInt(current_index) + 1;
            if (current_index >= $items.length - 1)
                index = 0;
            ShowItemAt(index, 'right');
        }

        function DelayTimer() {
            window.clearInterval(interval);
            var restart = window.setTimeout('Frontend.Rotator.StartAuto();', delay_sec * 1000);
        }

        function SetTimer() {
            window.clearInterval(interval);
            interval = window.setInterval('Frontend.Rotator.Rotate();', interval_sec * 1000);
        }

        return { Init: Init, Rotate: moveNext, StartAuto: SetTimer }
    })(),

    // 2.10b Image gallery ===========================================================

    ImageGallery: (function () {
        var current_index = 0;
        var interval = '';
        var delay_sec = 8;
        var interval_sec = 5;
        var $items;
        var numItems;

        function Init() {

            $('.image-gallery').each(function () {
                var $rotator = $(this);
                numItems = $rotator.find('.set').length;

                $rotator.find('ul').css({ 'height': $rotator.find('li:first img').height(), 'position': 'relative', 'overflow': 'hidden', 'top': '0', 'left': '0' });
                if (numItems > 1) {

                    $items = $rotator.find('.items .set');
                    $items.addClass('no-bottom-margin');

                    $rotator.append('<ul class="list-inline divide-top text-center pages rel"></ul>');
                    var $controls = $rotator.find('.pages');
                    $controls.append('<li><a class="action brd4px curved10 abs prev" href="#">&laquo;</a></li>');
                    for (var i = 0; i < numItems; i++) {
                        $controls.append('<li class="page-num"><a class="btn btn-black item-index" href="#" rel="' + i + '">' + (i + 1) + '</a> </li>');
                    }
                    $controls.append('<li><a class="action brd4px curved10 abs next" href="#">&raquo;</a></li>');

                    BindControls($items, $controls);
                } else {
                    $rotator.addClass('mar-bot-30');
                }
            });
        }
        function BindControls($items, $controls) {
            var $itembuttons = $controls.find('.item-index');
            var $next = $controls.find('.next');
            var $prev = $controls.find('.prev');

            $itembuttons.each(function () {
                var $this = $(this);
                $this.click(function () {
                    var index = $this.attr('rel');
                    ShowItemAt(index, 0);
                    return false;
                });
            });
            $next.click(function () {
                moveNext();
                return false;
            });
            $prev.click(function () {
                var index = parseInt(current_index) - 1;
                if (current_index <= 0)
                    index = $items.length - 1;
                ShowItemAt(index, 'left');
                return false;
            });
        }

        function ShowItemAt(index, dir) {

            if (current_index != index) {

                var $currentItem = $items.eq(current_index); //.filter(':visible');
                var $nextItem = $items.eq(index);

                var endpos = (dir === 'left') ? '100%' : '-100%';

                if (dir === 0) {
                    endpos = current_index > index ? '100%' : '-100%';
                }

                current_index = index;

                $nextItem.stop().css({ 'left': '20px', 'z-index': '1' });
                $currentItem.css({ 'left': '20px', 'z-index': '20' });

                $nextItem.show();
                $currentItem.animate({ 'left': endpos }, 500, function () {
                    $currentItem.hide();
                });
            }
        }

        function moveNext() {
            var index = parseInt(current_index) + 1;
            if (current_index >= $items.length - 1)
                index = 0;
            ShowItemAt(index, 'right');
        }

        return { Init: Init }
    })(),

    // 2.11 Header ===================================================================

    Header: (function () {
        function Init() {
            Frontend.SubRegionLocations.Init();
            Frontend.LoadStores.Init();
            InitLogin();

            $.reject({
                reject: { msie5: true, msie6: true} // Reject all renderers for demo 
            });

        }

        function InitLogin() {

            var close_html = '<a href="#" class="abs hidden btn btn-black" style="display:none;" id="close-login-box">X</a>';
            $('#header .holder').append(close_html);

            var $close = $('#close-login-box');
            var $loginbox = $('#header-login');

            $('#my-account .btn-login').click(function () {
                $loginbox.css({ 'top': '-' + $loginbox.height() + 'px' }).show().animate({ 'top': '0' }, 300, function () {
                    $close.show();
                    $("#header-login input:first").focus();
                });

                return false;
            });

            $close.click(function () {
                $close.hide();
                $loginbox.animate({ 'top': '-' + $loginbox.height() + 'px' }, 300);
                return false;
            });

            $loginbox.find("input[type=text], input[type=password]").keydown(function (ev) {
                if (ev.keyCode == 13) {
                    ev.preventDefault();
                    ev.stopPropagation();
                    $loginbox.find('input[type=submit]').click();
                    return false;
                }
            });

            // IE to respect placeholder
            FauxPlaceholder();
        }

        function FauxPlaceholder() {
            if (!ElementSupportAttribute('input', 'placeholder')) {
                $("input[placeholder]").each(function () {
                    var $input = $(this);
                    $input.after('<input id="' + $input.attr('id') + '-faux" style="display:none;" type="text" value="' + $input.attr('placeholder') + '" />');
                    var $faux = $('#' + $input.attr('id') + '-faux');

                    $faux.show().attr('class', $input.attr('class')).attr('style', $input.attr('style'));
                    $input.hide();

                    $faux.focus(function () {
                        $faux.hide();
                        $input.show().focus();
                    });

                    $input.blur(function () {
                        if ($input.val() === '') {
                            $input.hide();
                            $faux.show();
                        }
                    });
                });
            }
        }

        function ElementSupportAttribute(elm, attr) {
            var test = document.createElement(elm);
            return attr in test;
        }

        return { Init: Init }
    })(),

    // 2.12 Speechbox ================================================================

    Speechbox: (function () {
        function Init() {
            $('.left-column.module-container, .right-column.module-container, .fullwidth-column.module-container').each(function () {
                var $speech = $(this).find('.speech');
                for (var i = 0; i < $speech.length; i++) {
                    if (i % 2 == 1) { $speech.eq(i).removeClass('bot-left').addClass('bot-right'); }
                }
            });
        }

        return { Init: Init }
    })(),

    // 2.13 Disclaimer dynamic placement ============================================================
    LicensingTrustLaws: (function () {
        function Init() {
            var trustLaws = $('.licensing-trust-laws');
            var backToTop = $('#back-to-top-container');
            if (trustLaws != null && !trustLaws.hasClass('homepage')) {
                backToTop.find('.divide-top').removeClass('divide-top');
                trustLaws.addClass('divide-top');
                backToTop.prepend(trustLaws);
            }
        }
        return {
            Init: Init
        }
    })(),

    // 2.14 Rate Recipe functionality ============================================================
    RateRecipe: (function () {
        function Init() {

            var buttons = $('.sprStarRating.star');

            buttons.each(function () {
                $(this).hover(function () {
                    $(this).prevAll().addClass('active');
                }, function () {
                    $(this).prevAll().removeClass('active');
                });

                $(this).click(function () {
                    var starClicked = $(this).attr("rel");
                    var url = "/Base/restExt/AddRating/" + starClicked + ".aspx";
                    $.get(url, function (data) {
                        if (data > 0) {
                            $("div.starRatingRated").css('width', data + '%');
                        }
                    });
                    var splitStarArray = starClicked.split("/");
                    var percentage = splitStarArray[1] / 5 * 100;
                    //add overlay of star rating
                    $('<div style="width:' + percentage + '%;height:25px;" class="sprStarRating abs"></div>').appendTo($(this).parent(".sprStarRating"));

                    $(this).parents("div.starRatingBase").children(".rating").text("Your rating");

                    //remove all stars
                    buttons.each(function () {
                        $(this).remove();
                    });
                });

            });

        }
        return {
            Init: Init
        }
    })(),

    // 2.14 Wine Club Checker Registration ============================================================
    HasWineClubRegister: (function () {



        function Init(joinWineClubCheckBox, storeSelectList) {

            $(document).ready(function () {
                showWineClubRegister(storeSelectList);
                if ($("#" + joinWineClubCheckBox).attr("checked")) {
                    $("#wineClubDetails").show();
                }
            });

            $("#" + storeSelectList).change(function () {
                showWineClubRegister(storeSelectList);
            });

            $("#" + joinWineClubCheckBox).click(function () {
                if ($(this).attr("checked")) {
                    $("#wineClubDetails").show();
                } else {
                    clearFields();
                }
            });
        }

        function showWineClubRegister(selectedStore) {
            var url = "/Base/restExt/GetPropertyAsBool/" + $("#" + selectedStore).val() + "/" + "hasWineClub.aspx";
            $.get(url, function (data) {
                if (data.toLowerCase() == "true") {
                    $("#subs span.wineClub").show();
                    $("#wineClubForm").show();
                } else {
                    clearFields();
                    $("#wineClubForm").hide();
                    $("#subs span.wineClub input").removeAttr("checked");
                    $("#subs span.wineClub").hide();
                }
            });
        }

        function clearFields() {
            $("#wineClubDetails").hide();
            $("#wineClubDetails input").each(function () {
                switch ($(this).attr("type").toLowerCase()) {
                    case "text":
                        $(this).val("");
                        break;
                    case "checkbox":
                        $(this).removeAttr("checked");
                        break;
                    case "radio":
                        $(this).removeAttr("checked");
                        break;
                }
            });
            $("#wineClubDetails select").each(function () {
                $(this).val("0");
            });
        }

        return {
            Init: Init
        }

    })(),

    // 2.14a Wine Club Checker Update ============================================================
    HasWineClubUpdate: (function () {

        function Init(checkBox, storeSelectList) {

            $("#" + checkBox).click(function () {
                showFormUpdate(checkBox);
            });
            $("#" + storeSelectList).change(function () {
                showWineClubUpdate(storeSelectList);
            });
            $(document).ready(function () {
                showFormUpdate(checkBox);
                showWineClubUpdate(storeSelectList);
            });
        }


        function showWineClubUpdate(selectedStore) {
            var url = "/Base/restExt/GetPropertyAsBool/" + $("#" + selectedStore).val() + "/" + "hasWineClub.aspx";
            $.get(url, function (data) {
                if (data.toLowerCase() == "true") {
                    $("#wineClubForm").show();
                } else {
                    clearFields();
                    $("#wineClubSub input:first").removeAttr("checked");
                    $("#wineClubForm").hide();
                }
            });
        }

        function showFormUpdate(checkBox) {
            if ($("#" + checkBox).attr("checked")) {
                $("#wineClubFormDetails").show();
            } else {
                clearFields();
            }

        }

        function clearFields() {
            $("#wineClubFormDetails").hide();
            $("#wineClubFormDetails input").each(function () {
                switch ($(this).attr("type").toLowerCase()) {
                    case "text":
                        $(this).val("");
                        break;
                    case "checkbox":
                        $(this).removeAttr("checked");
                        break;
                    case "radio":
                        $(this).removeAttr("checked");
                        break;
                }
            });
            $("#wineClubFormDetails select").each(function () {
                $(this).val("0");
            });
        }

        return {
            Init: Init
        }

    })(),

    // 2.15 Email Subscription Slider ============================================================
    EmailSliderSubscription: (function () {

        function Init() {
            var buttons = $('#btnEmailSub, .emailSubscription .emailSubScribeSlider');
            var target = $('.emailSubscription');
            buttons.each(function () {
                $this = $(this);
                $this.click(function (e) {
                    e.preventDefault();
                    target.slideToggle();
                    return false;
                });
            });
            $("#subSubmit").click(function () {
                subscribeUser();
                return false;
            });
        }

        function subscribeUser() {
            var formCheck = true;
            if ($("#subName").val().length == 0) {
                $("#subName").css('backgroundColor', 'pink');
                formCheck = false;
            }
            if ($("#subEmail").val().length == 0) {
                $("#subEmail").css('backgroundColor', 'pink');
                formCheck = false;
            }
            if ($("#subStore").val() == '0') {
                $("#subStore").css('backgroundColor', 'pink');
                formCheck = false;
            }
            if (formCheck) {
                var url = "/Base/restExt/SimpleEmailSubscription/" + $("#subName").val() + "/" + $("#subEmail").val() + "/" + $("#subStore").val() + ".aspx";
                $.get(url, function (data) {
                    if (data.toLowerCase()) {
                        $(".emailSubscription .list-hori").hide();
                        $(".emailSubscription .signUpSuccess").show();
                    } else {
                        $(".emailSubscription .list-hori").hide();
                        $(".emailSubscription .signUpFail").show();
                    }
                });
            }
            return false;
        }

        return {
            Init: Init
        }

    })()

};

// 3.0 Tracking ======================================================================
Tracking = {

    // 3.1 Tracking.GoogleAnalytics ======================================================
    GoogleAnalytics: (function () {
        function TrackAsPageView(path) {
            if (typeof _gaq != 'undefined') {
                _gaq.push(['_trackPageview', path]);
            }
        }

        function TrackAsEvent(category, action, label) {
            if (typeof _gaq != 'undefined') {
                _gaq.push(['_trackEvent', category, action, label]);
            }
        }

        function Download(target) {
            target.find('a[href$=.zip],a[href$=.pdf],a[href$=.doc],a[href$=.docx],a[href$=.xls],a[href$=.xlsx],a[href$=.ppt],a[href$=.pptx]').click(
				function () {
				    var path = $(this).attr('href');
				    var type = 'File';
				    TrackAsEvent('Download', type, path);
				}
			);
        }

        function External(target) {
            target.find('a[href^=http],a[href^=https],a[href^=mailto]').click(
				function () {
				    var path = $(this).attr('href');
				    if (path.indexOf('mailto') == 0) {
				        TrackAsEvent('External', 'Email', path);
				    } else if (path.indexOf(window.location.hostname) == -1) {
				        TrackAsEvent('External', 'Site', path);
				    }
				}
			);
        }

        return {
            TrackAsPageView: TrackAsPageView,
            TrackAsEvent: TrackAsEvent,
            Download: Download,
            External: External
        }
    })()
}

jQuery(document).ready(function () {
    Frontend.Default.init();
});

//Extra common funcs:
function Equalise(elms) {
    var highest = 0;
    for (i = 0; i < elms.length; i++) { if ($(elms[i]).height() > highest) highest = $(elms[i]).height(); }
    for (i = 0; i < elms.length; i++) { if ($(elms[i]).height() < highest) $(elms[i]).height(highest); }
}

function EqRow(elms) {
    // EQ's height per row in a list of items (rather than EQing over the entire collection). 'elms' is a jQuery object.
    var inRow = Math.floor($(elms).width() / $(elms).children("li:first").width());
    var i = 0;
    var items = $(elms).children("li");
    for (i = 0; i < (items.length / inRow); i++) {
        var max = 0;
        var start = (i * inRow);
        for (var j = start; j < start + inRow; j++) {
            if (items[j]) {
                if ($($(items)[j]).height() > max) max = $($(items)[j]).height();
            }
        };
        for (var k = start; k < start + inRow; k++) {
            if (items[k]) {
                $($(items)[k]).height(max);
            }
        };
    };
}
