﻿/*  
Copyright Eonic.co.uk
Authors: Will Hancock and Perry Harlock 
*/

// Simple .exists() function
jQuery.fn.exists = function () { return jQuery(this).length > 0; }

// new queue manager - to handle the loading ajax of the pages
var ajaxQueueManager = $.manageAjax.create('pageAjaxQueue', {
    queue: true,
    cacheResponse: true,
    maxRequests: 1
});
var currentScrollerBarPosition = 0;
var scrollItemWidth = 928;
var ieVersion = msieversion();
var scrollerTimeout = 0;
var gScrollPosition = 0;
var ScrollerBarPane;
var ScrollerBarPaneAPI;
var ageVerified = false;


$(document).ready(function () {

    /* if from site already authed age */
    if ($("#mainTable").hasClass('avs-true')) {
        // set cookie
        $.cookie('codorniuAVS', null, { expires: 1, path: '/' });
        $.cookie('codorniuAVS', true, { expires: 1, path: '/' });
        ageVerified = true;
        // send back to page
        //window.location = '/';
    }

    //Check for existence of ageCheck Cookie
    var ageCheckCookieValue = '';
    ageCheckCookieValue = $.cookie('codorniuAVS');

    // if codorniuAVS cookie, age is verified
    if (ageCheckCookieValue) {
        ageVerified = true;
    }

    //If not age Verified - give a popup
    if (!ageVerified) {
        //Run the modal pop up 
        $("#simplemodal-container").modal({
            containerCss: { height: 250, width: 923 },
            focus: false,
            overlayClose: false,
            close: false,
            escClose: false,
            position: [210, 0]
        });
    }

});



function initialiseCodorniuSpecifics(div) {

    //equalHeight($(div + " #template_4_Columns .FormattedText p"));

    //    Modal Pop Up for Stockists
    $(div + " .stockists").click(function () {
        var targetId = '.' + $(this).attr('id');
        $(targetId).modal({
            closeHTML: "<a class='stockistClose' href='#'></a>",
            containerCss: { height: 550, width: 340 },
            overlayClose: true,
            escClose: true,
            position: [75, 0]
        });
        return false;
    });

    // jScrollPane
    $(div + " .scrollingInner").jScrollPane({ showArrows: true });
    $(div + " .fixedHeight").jScrollPane({ showArrows: true });

    if (ieVersion != 7) {
        $(div + " #column2Links .listItem").each(function () {
            if ($(this).find(".videoImage").exists()) {
                /*$(this).find("a.vidlink").mouseover(function () {
                $(this).parents(".listItem").find(".videoImage").slideDown('fast');
                }).mouseout(function () {
                $(this).parents(".listItem").find(".videoImage").slideUp('fast');
                });*/

                $(this).find(".vidlink").hover(function () {
                    $(this).find(".videoImage").slideDown(1000);
                }, function () {

                    $(this).find(".videoImage").slideUp(1000);

                });
            }
        });
    }

    // Find a stockist listener
    $(div + " #findStockist #findStockistSubmit").click(function (brap) {
        brap.preventDefault();
        var stockistPostcode = $('#findStockist #stockistPostcode').val();
        if (!stockistPostcode) {
            alert('Please enter a valid UK postcode');
        } else {
            getAndPopulateStockistLongLat(stockistPostcode);


        }
    });


    //---------------------- Datepicker ----------------------------

    if ($(div + ' input.jqDatePicker').exists()) {
        $.datepicker.setDefaults($.datepicker.regional['']);
        // write common css for datepicker
        $("head").prepend('<link rel="stylesheet" type="text/css" href="/ewcommon/js/jquery/datepicker/smoothness/ui.datepicker.css"/>');
        $(div + ' input.jqDatePicker').each(function (i) {

            $(this).datepicker({
                closeAtTop: false,
                closeText: 'Close Calendar',
                clearText: 'Clear Date',
                showOn: "both",
                buttonImage: "/ewcommon/images/icons/calendar.gif",
                buttonImageOnly: true,
                dateFormat: 'd M yy',
                altField: '#' + $(this).attr('id').replace('-alt', ''),
                altFormat: 'yy-mm-dd',
                mandatory: $(this).hasClass('required')
            });
        });
    };

    // change settings for Date picker
    if ($(div + " #mailForm input.jqDatePicker").exists()) {
        $(div + " input.jqDatePicker").datepicker("option", "defaultDate", '-18y');
        $(div + " input.jqDatePicker").datepicker("option", "yearRange", '-120:-18');
        $(div + " input.jqDatePicker").datepicker("option", "changeYear", true);
        $(div + " input.jqDatePicker").datepicker("option", "changeMonth", true);
        $(div + " input.jqDatePicker").datepicker("option", "showMonthAfterYear", true);
        $(div + " input.jqDatePicker").datepicker("option", "stepMonths", true);
    };

    // validation for forms
    $("form.ewXform").each(function () {
        var formId = $(this).attr('id');
        $(this).validate();
        //        $(this).validate({
        //            submitHandler: function () {
        //                //alert('success');
        //                $("#" + formId).find("input[type='submit']").attr('value', 'Please wait...');


        //            }
        //        });
        // bind 'myForm' and provide a simple callback function 
        //        var ajaxSubmitOptions = { 
        //            target: '#mailFormSentMessage',
        //            success: showAjaxFormResponse()
        //        };
        //        $(this).ajaxForm(ajaxSubmitOptions);
        $("#" + formId).ajaxForm(function () {
            if (formId != 'findStockist') {
                $("#" + formId + " fieldset").css('display', 'none');
                $("#" + formId + " .mailFormSentMessage").slideDown('slow');
            }
        });
    });

    // vertical align video links on NOT home.
    $(div + ' .clink').each(function () {
        if (!$(this).parents("#page-1").exists()) {
            var thisHeight = $(this).height();
            var titleHeight = $(this).find('.linkTitle').height();
            if (titleHeight < thisHeight) {
                var topPos = (thisHeight / 2) - (titleHeight / 2);
                $(this).find('.linkTitle').css('padding-top', topPos)
            }
        }
    });


}



function validateAgeCheckForm() {

    //Get the Date of Birth Values from the Inputs
    var ageDay = $("#ageCheckDay").val();
    var ageMonth = $("#ageCheckMonth").val();
    var ageYear = $("#ageCheckYear").val();
    var age = 18;
    var mydate = new Date();
    var validAge;

    //Check to see if date entered makes the user 18+           
    mydate.setFullYear(ageYear, ageMonth - 1, ageDay);
    var currdate = new Date();
    currdate.setFullYear(currdate.getFullYear() - age);
    if ((currdate - mydate) < 0) {
        //If under 18 show an alert
        alert("Sorry, only persons over the age of " + age + " may enter this site");
        validAge = false;
    }
    else {
        validAge = true;   
    }
    // set cookies
    setCookie(ageDay, ageMonth, ageYear, validAge);
    return validAge;
};


function setCookie(ageDay, ageMonth, ageYear, validAge) {

    //set DOB cookie - always for returning people
    var oCheckAge = {
        "ageCheckName": 'codorniuDOB',
        "ageCheckDOB": ageYear + '-'  + ageMonth + '-' + ageDay 
    };
    $.cookie('codorniuDOB', null, { expires: 30, path: '/' });
    $.cookie('codorniuDOB', oCheckAge.ageCheckDOB, { expires: 30, path: '/' });

    // if over 18 set AVS cookie
    if (validAge) {
        $.cookie('codorniuAVS', null, { expires: 1, path: '/' });
        $.cookie('codorniuAVS', true, { expires: 1, path: '/' });
    }
}

function form_checkAge(oForm) {

    var oElem, i, bValid, cCheckRadio, cTestName, oOptions, bSelected, nElemTypeGroup, cId, cName;
    var aRadioCheck = new Array();
    var bHasDisabledButton = false
    bValid = true;



    for (i = 0; i < oForm.length; i++) {
        oElem = oForm.elements[i]

        switch (oElem.type) {
            case "text": nElemTypeGroup = 1; break;
            case "textarea": nElemTypeGroup = 1; break;
            case "checkbox": nElemTypeGroup = 3; break;
            case "radio": nElemTypeGroup = 3; break;
            case "select-one": nElemTypeGroup = 2; break;
            case "select-multiple": nElemTypeGroup = 2; break;
            default: nElemTypeGroup = 0; break;
        }

        // Check if the element is required
        if (oElem.className.toLowerCase().indexOf("required") >= 0) {
            switch (nElemTypeGroup) {

                case 1:
                    if (form_check_value(oElem.value)) {
                        form_alert("required", oElem)
                        bValid = false
                    }
                    break;
                case 2:
                    if (oElem.value == '') {
                        form_alert("required", oElem)
                        bValid = false
                    }
                    if (oElem.selectedIndex < 0) {
                        form_alert("required", oElem)
                        bValid = false
                    }
                    else if (form_check_value(oElem.options[oElem.selectedIndex].text)) {
                        form_alert("required", oElem)
                        bValid = false
                    }
                    break;
                case 3:
                    // Check if the checkbox group has already been checked through
                    cCheckRadio = "," + aRadioCheck.join(",") + ","
                    cTestName = "," + oElem.name + ","
                    if (cCheckRadio.indexOf(cTestName) < 0) {

                        // Not found - let's do the checks
                        aRadioCheck.push(oElem.name)
                        oOptions = document.getElementsByName(oElem.name)
                        bSelected = false;
                        if (oOptions.length > 1) {
                            for (i = 0; i < oOptions.length; i++) { if (oOptions[i].checked) { bSelected = true; break } }
                        }
                        if (!bSelected && oOptions.length > 1) {
                            form_alert("required", oElem)
                            bValid = false
                        }
                    }
                    break;
            }
            if (!bValid) { break }
        }
    }

    if (bValid) {
        for (i = 0; i < oForm.length; i++) {
            oElem = oForm.elements[i]
            if (oElem.type == 'text' || oElem.type == 'textarea') {
                if (form_check_value(oElem.value)) { oElem.value = ''; }
            }
        }
    }

    if (bValid) {
        ageVerified = validateAgeCheckForm();

        /* if of age, destroy the modal */
        if (ageVerified) {
            $.modal.close();
        }
        /*  always bValid = false, we don't need to submit the form.
            in fact we don't want to submit it as it will refresh the page 
            and we will be ajaxing in ALL the pages a 2nd time. */
        bValid = false;
    }


    if (bValid) {
        // Check for Disabled Buttons
        for (i = 0; i < oForm.length; i++) {
            oElem = oForm.elements[i];
            if (oElem.type == "hidden" && oElem.id.indexOf("ewSubmitClone_") == 0) {
                cId = oElem.id.replace(/ewSubmitClone_/, "")
                cName = oElem.name.replace(/ewSubmitClone_/, "")
                form_disable_button(oForm, cId, cName)
                oElem.id = cId
                oElem.name = cName
                bHasDisabledButton = true;
            }
        }

        if (bHasDisabledButton) {
            for (i = 0; i < oForm.length; i++) {
                oElem = oForm.elements[i];
                if (oElem.type == "submit" || oElem.type == "button") { oElem.disabled = true; }
            }
        }

        // If other country - send to .com
        if ($("#ageCheck #ageCheckCountry").val() == 2) {
            $("#ageCheck").attr('action','http://www.codorniu.com/');    
        }
    }

    return bValid;
}

function equalHeight(group) {
    var tallest = 0;
    group.each(function () {
        var thisHeight = $(this).height();
        if (thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}

//    Modal Pop Up for Video Content
function vidclick(vidId) {
    $("#" + vidId).modal({
        containerCss: { height: 404, width: 610 },
        opacity: 50,
        overlayCss: { backgroundColor: "#fff" },
        overlayClose: true
    });
    return false;
}


function letsScrollThis() {

    // initialise Main Scroll Pane
    initialiseMainScroller();

    // Load in Initial pages in sequence
    s_loadingInitialPages();

    // Listeners for MenuItem Clicks
    var navAreas = ["#mainMenu a", "a[name^='contentLink']", "#footerMenu a"];
    s_listenerForNavClicks(navAreas);

    // If we have navigated to not home
    if (currentWindowPos > 1) {
        var pageName = $("#page-" + currentWindowPos).attr('name');
        var pageId = pageName.substring(6);
        //alert(pageId)
        navigateToPage(pageId, pageName);
    }
}
function scrollerArrowListeners() {
    // Next button
    $(".scrollRight").click(function (clicky) {
        clicky.preventDefault();
        if (currentWindowPos < oLoadingList.MenuItems.MenuItem.length) {
            var nextWindowPos = Number(currentWindowPos) + 1;
            var pageName = $("#page-" + nextWindowPos).attr('name');
            var pageId = pageName.substring(6);
            navigateToPage(pageId, pageName);
        }
    });
    // Previous button
    $(".scrollLeft").click(function (clicky) {
        clicky.preventDefault();
        if (currentWindowPos > 1) {
            var prevWindowPos = currentWindowPos - 1;
            var pageName = $("#page-" + prevWindowPos).attr('name');
            var pageId = pageName.substring(6);
            navigateToPage(pageId, pageName);
        }
    });
}
function s_loadingInitialPages() {

    // This is where we use the JSON Object populated by XSLT.
    // Go in order of Priorities
    var highestPriorityNumber = getHighestPriorityNumber();
    // for each priority starting at 1
    for (p = 1; p <= highestPriorityNumber; p++) {

        // for each MenuItem
        for (i = 0; i < oLoadingList.MenuItems.MenuItem.length; i++) {

            // If current priority
            if (oLoadingList.MenuItems.MenuItem[i].priority == p) {

                //only AJAX if not loaded
                var pageId = oLoadingList.MenuItems.MenuItem[i].id;
                if ($(".pageID" + pageId + " .loading").exists()) {

                    // Make the AJAX Call
                    ajaxCallPage(oLoadingList.MenuItems.MenuItem[i].url + '?ajaxPageContent=');
                }
            }
        }
    }
}

// LISTENRS FOR NAV CLICKS
function s_listenerForNavClicks(navAreas) {

    for (i = 0; i < navAreas.length; i++) {
        var thisArea = navAreas[i];
        $(thisArea).click(function (clicky) {
            clicky.preventDefault();

            var subMenuClick = $(this).parents(".subMenu").exists();
            // active/inactive - Don't bother if Submenu clicked
            if (!subMenuClick) {

                $("a.active").each(function () {
                    if (!$(this).parents(".subMenu").exists()) {
                        $(this).removeClass('active');
                    }
                });
                if (!$(this).parents(".subMenu").exists()) {
                    $(this).addClass('active');
                }
            }
            // get page id
            var clickyID = $(this).attr('name');
            var hyphenPos = clickyID.indexOf('-');
            var pageId = clickyID.substring(hyphenPos + 1);
            var pageName = 'pageID' + pageId;

            navigateToPage(pageId, pageName);
            makeParentActive(pageId);
            //if content click, make any menuItems active if exist
            if (clickyID.substring(0, hyphenPos) == 'contentLink') {
                $("a[name='menuitem-" + pageId + "']").addClass('active');
            }

        });
    }
}

function manageNavigationActiveClasses(pageId) {
    $("a.active").each(function () {
        if (!$(this).parents(".subMenu").exists()) {
            $(this).removeClass('active');
        }
    });

    $("#mainMenu a[name='menuitem-" + pageId + "']").addClass('active');
    $("#footerMenu a[name='menuitem-" + pageId + "']").addClass('active');

    // If This page don't exist in main menu' makes their parents children.
    if (!($("#mainMenu a[name='menuitem-" + pageId + "']").exists() || $("#footerMenu a[name='menuitem-" + pageId + "']").exists())) {
        makeParentActive(pageId);
    }


}

function makeParentActive(pageId) {
    for (mi = 0; mi < oLoadingList.MenuItems.MenuItem.length; mi++) {
        if (oLoadingList.MenuItems.MenuItem[mi].id == pageId) {
            var parentId = oLoadingList.MenuItems.MenuItem[mi].childOf;
            if (parentId == 0) {
                break;
            } else {
                manageNavigationActiveClasses(parentId);
            }
        }

    }
}

function navigateToPage(pageId, pageName, scrollerNav) {

    // Check page loaded; and re-prioritise ajaxing in of pages.
    rePrioritiseAjaxQueue(pageId, pageName);

    // scroll to page - rely upon scrollbar behavior to move scrollArea.
    setScrollBarElement('scroller' + pageName);

    // change currentWindow position
    var pagePos = $("div[name='" + pageName + "']").attr('id');
    currentWindowPos = pagePos.substring(5);

    // Push google page tracking here.
    var newPageURL = $("div[name='" + pageName + "']").attr('rel');
    _gaq.push(['_trackPageview', newPageURL]);

    //    // change navigation active classes
    //    if (scrollerNav) {
    //        
    //    }
}

function navigateToNearestPage(xPos) {

    var scrollCount = Math.round((Math.round(xPos) + scrollItemWidth) / scrollItemWidth)
    var targetPos = (scrollCount * scrollItemWidth) - scrollItemWidth
    //    if (gScrollPosition == 0) {
    //        gScrollPosition = xPos;
    //    }
    var pageName = $("div[id='page-" + scrollCount + "']").attr('name');
    var pageId = pageName.substring(6);
    manageNavigationActiveClasses(pageId);
    if (!(targetPos - xPos < 30 && targetPos - xPos > -30)) {
        navigateToPage(pageId, pageName, true);
    }
    //    gScrollPosition = xPos;

}


// upon user navigation, reprioritise ajax loading of pages to this and children.
function rePrioritiseAjaxQueue(pageId, pageName) {
    var anyLoadingToDo = $(".scrollItem .loading").exists();

    // if any loading to do
    if (anyLoadingToDo) {
        var thisNeedsLoading = $("." + pageName + " .loading").exists();

        //if this needs loading
        if (thisNeedsLoading) {
            // clear ajaxQueue and send this
            $.manageAjax.clear('pageAjaxQueue', { shouldAbort: false });
            var requestURL = getURLfromId(pageId) + '?ajaxPageContent=';
            ajaxCallPage(requestURL);
        }

        // Run through menu items, for this' children, and que them up
        var MIsLength = oLoadingList.MenuItems.MenuItem.length;
        // using c here as using i seems to break?!?!?!
        for (c = 0; c < MIsLength; c++) {

            // if MenuItem is a child of current clicked
            if (oLoadingList.MenuItems.MenuItem[c].childOf == pageId) {

                var childPageId = oLoadingList.MenuItems.MenuItem[c].id;

                if ($(".pageID" + childPageId + " .loading").exists()) {
                    var cRequestURL = getURLfromId(childPageId) + '?ajaxPageContent=';
                    ajaxCallPage(cRequestURL);
                }
            }
        }

        // Run through all again 
        // - don't worry this checks to see if loaded before ajaxing in.
        // - The manager also has a setting to not do duplicates in queue.
        s_loadingInitialPages();

    }
}
// send to AJAX queue manager
function ajaxCallPage(ajaxURL) {
    $.manageAjax.add('pageAjaxQueue', {
        url: ajaxURL,
        success: function (html) {
            // write to pending div
            $('#ajaxPendingPlacement').html(html);
            initialiseAjaxedPage();
        }

    });
}

// Initialise and Scroller Options
function initialiseMainScroller() {

    // if not home, scroll bar to that page
    var scrollBarOffset = $("#scrollerpage-" + currentWindowPos).position().left;
    //api.scrollToX(parseInt(scrollBarOffset));
    setScrollBar(scrollBarOffset);
    // set or reset listeners for Arrow clicks
    scrollerArrowListeners();

}

function setScrollBar(xPos) {
    ScrollerBarPane = $("#scrollerDiv");
    ScrollerBarPane.jScrollPane({
        showArrows: false,
        animateScroll: true,
        animateDuration: 1500
    });
    ScrollerBarPaneAPI = ScrollerBarPane.data('jsp');
    ScrollerBarPaneAPI.scrollToX(parseInt(xPos));
    ScrollerBarPane.bind('jsp-scroll-x', function (event, scrollPositionX, isAtLeft, isAtRight) {
        var PosX = Math.round(scrollPositionX)
        //move the top panel
        $(".scrollArea").scrollTo(PosX);

        if (scrollerTimeout != 0) {
            clearTimeout(scrollerTimeout);
        };
        scrollerTimeout = setTimeout('navigateToNearestPage(' + scrollPositionX + ')', 300);
    });
}

function setScrollBarElement(elemName) {
    ScrollerBarPaneAPI.scrollToElement($("div[name='" + elemName + "']"), true);
}


function initialiseAjaxedPage() {
    var pageId = $("#ajaxPendingPlacement .ajaxcontainer").attr('rel');
    var pageContent = $("#ajaxPendingPlacement").html();
    // write to correct div
    $(".pageID" + pageId).html(pageContent);

    // as we have ajaxed pages in, we need to re-initialise the normal common guff for THAT div.
    var navAreas = [".pageID" + pageId + " .subMenu a", ".pageID" + pageId + " a[name^='contentLink-']"];
    s_listenerForNavClicks(navAreas);
    reAutoAdjustFloatingColumns('.pageID' + pageId);
    initialiseCodorniuSpecifics('.pageID' + pageId);
    reInitialiseLightBox('.pageID' + pageId);
    if (ieVersion == '6') {
        rePNGFix();
    }
    // reset pending div, to try and reduce DOM Elements.
    $("#ajaxPendingPlacement").html('');
}
function reAutoAdjustFloatingColumns(div) {
    $(div + " .cols2").each(function () {
        matchHeightCol($(this).find(".listItem"), '2');
    });
    $(div + " .cols3").each(function () {
        matchHeightCol($(this).find(".listItem"), '3');
    });
    $(div + " .cols4").each(function () {
        matchHeightCol($(this).find(".listItem"), '4');
    });
    $(div + " .cols5").each(function () {
        matchHeightCol($(this).find(".listItem"), '5');
    });
}
function reInitialiseLightBox(div) {
    if ($(div + ' a.lightbox').exists()) {
        $(div + ' a.lightbox').lightBox();
    }
}
function rePNGFix() {
    var arVersion = navigator.appVersion.split("MSIE");
    var version = parseFloat(arVersion[1]);
    if ((version >= 5.5) && (document.body.filters)) {
        for (var i = 0; i < document.images.length; i++) {
            var img = document.images[i];
            var imgName = img.src.toUpperCase();
            if (imgName.substring(imgName.length - 3, imgName.length) == "PNG") {
                var imgID = (img.id) ? "id='" + img.id + "' " : "";
                var imgClass = (img.className) ? "class='" + img.className + "' " : "";
                var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
                var imgStyle = "zoom:100%;" + img.style.cssText;
                if (img.align == "left") imgStyle = "float:left;" + imgStyle
                if (img.align == "right") imgStyle = "float:right;" + imgStyle
                if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
                var strNewHTML = "<span " + imgID + imgClass + imgTitle
         + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
         + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
         + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
                img.outerHTML = strNewHTML
                i = i - 1
            }
        }
    }
}
// Runs through the MenuStructure calculating the max priority
function getHighestPriorityNumber() {
    var length = oLoadingList.MenuItems.MenuItem.length;
    var maxPriority = 0;
    for (i = 0; i < length; i++) {
        var pri = oLoadingList.MenuItems.MenuItem[i].priority;
        if (pri > maxPriority) {
            maxPriority = pri;
        }
    }
    return maxPriority;
}
// Returns a URL from a page Id
function getURLfromId(pageId) {
    var length = oLoadingList.MenuItems.MenuItem.length;
    var url = '';
    for (i = 0; i < length; i++) {
        if (oLoadingList.MenuItems.MenuItem[i].id == pageId) {
            url = oLoadingList.MenuItems.MenuItem[i].url;
        }
    }
    return url;
}
function bChildrenNeedLoding(pageId) {
    var length = oLoadingList.MenuItems.MenuItem.length;
    var bChildren = false;

    for (i = 0; i < length; i++) {
        if (oLoadingList.MenuItems.MenuItem[i].childOf == pageId) {
            var childPageId = oLoadingList.MenuItems.MenuItem[i].id;
            var childPageName = '.pageID' + childPageId;
            bChildNeedsLoading = $(childPageName + " .loading").exists();
            if (bNeedsLoading) {
                bChildren = bNeedsLoading;
            }
        }
    }
    return bChildren;
}

function msieversion() {
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0)      // If Internet Explorer, return version number
        return parseInt(ua.substring(msie + 5, ua.indexOf(".", msie)));
    else                 // If another browser, return 0
        return 0;

}


/* == Stockist and Location / Google Maps geocoder / Address finder stuff ======================= */


// triggered by admin calculate coords button 
function locationCoordPopulator() {

    $(".getGeocodeFromAddress").click(function (click) {
        click.preventDefault();
        var findAddress = {
            "No": $("#cContentLocationNo").val(),
            "Street": $("#cContentLocationStreet").val(),
            "Town": $("#cContentLocationTown").val(),
            "Region": $("#cContentLocationRegion").val(),
            "PostCode": $("#cContentLocationPostCode").val()
        }
        // If no Postcode insist on the rest of address being filled.
        if (!findAddress.PostCode && (!findAddress.Street || !findAddress.Town || !findAddress.Region)) {
            alert('Without a Post code, ensure that Street, Town, and County are populated');
        } else {
            // we gonna go get the Lat and Long from Google.
            getLatandLongFromAddress(findAddress);
        }

    });

}

function getLatandLongFromAddress(address) {

    var addressString = '';
    if (address.No) {
        addressString = address.No + ', ';
    }
    if (address.Street) {
        addressString = addressString + address.Street + ', ';
    }
    if (address.Town) {
        addressString = addressString + address.Town + ', ';
    }
    if (address.Region) {
        addressString = addressString + address.Region + ', ';
    }
    if (address.PostCode) {
        addressString = addressString + address.PostCode + ', ';
    }
    var geocoder = new google.maps.Geocoder();

    // get address, and callback function
    geocoder.geocode({ 'address': addressString }, function (results, status) {

        if (status == google.maps.GeocoderStatus.OK) {
            var addLat = results[0].geometry.location.lat();
            var addLng = results[0].geometry.location.lng();
            // write coords to inputs
            $("#cContentLocationLat").val(addLat);
            $("#cContentLocationLong").val(addLng);

        } else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
            $("#cContentLocationLat").val('');
            $("#cContentLocationLong").val('');
            alert('NO ADDRESS FOUND \n \n This could be due to; \n - Invalid Address entered, \n - Google does not recognise this address, \n - Google Geo location services are suffering interuptions. \n \n Please check your address and try again.');
        }
    });

}

function getAndPopulateStockistLongLat(postcode) {

    var geocoder = new google.maps.Geocoder();

    // get address, and callback function
    geocoder.geocode({ 'address': postcode }, function (results, status) {

        if (status == google.maps.GeocoderStatus.OK) {

            var addLat = results[0].geometry.location.lat();
            var addLng = results[0].geometry.location.lng();

            // write coords to inputs
            $("#stockistLatitude").val(addLat);
            $("#stockistLongitude").val(addLng);

            ajaxResultsPage();

        } else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
            $("#stockistLatitude").val('');
            $("#stockistLongitude").val('');
            alert('Postcode not recognised. Please re-enter and try again.');
        }
    });
}

function ajaxResultsPage() {
    // SUBMIT FORM, WELL AJAX THE GET ANYWAY.

    // get values to AJAX
    var productSelection = $('#findStockist #wineList').val();
    var stockistPostcode = $('#findStockist #stockistPostcode').val();
    stockistPostcode = stockistPostcode.replace(' ', '+');
    var stockistLatitude = $('#findStockist #stockistLatitude').val();
    var stockistLongitude = $('#findStockist #stockistLongitude').val();
    var distance = $('#findStockist #stockistDistance').val();
    var sTop = $('#findStockist #stockistTop').val();
    var ewSubmitClone_findStockist = 'Find';
    var currentPageURL = getCurrentPageURL();

    // indicate Loading
    $(".stockistContent img.image").css('opacity', '0.3');
    $(".stockistContent img.image").css('filter', 'alpha(opacity=30)');



    $(".stockistContent").append('<img src="/images/layout/loading.gif" width="150" height="150" class="stockistsLoading"/>');
    $(".stockistContent").css('position', 'relative');

    // AJAX URL
    var ajaxURL = currentPageURL + '?productSelection=' + productSelection + '&stockistPostcode=' + stockistPostcode + '&stockistLatitude=' + stockistLatitude + '&stockistLongitude=' + stockistLongitude + '&distance=' + distance + '&ewSubmitClone_findStockist=' + ewSubmitClone_findStockist + '&getStockistSearchResults=true' + '&top=' + sTop;
    $(".stockistContent").load(ajaxURL, function () {

        // re initialise stuff
        reAutoAdjustFloatingColumns('.stockistContent');
        initialiseCodorniuSpecifics('.stockistContent');
        reInitialiseLightBox('.stockistContent');
        if (ieVersion == '6') {
            rePNGFix();
        }

    });
}

function getCurrentPageURL() {
    var url = '';
    if (currentWindowPos == 'manual') {
        url = window.location;
    } else {
        url = $('div#page-' + currentWindowPos).attr('rel');
    }
    return url;
}
