/* Case Correction needed for some string comparisons */
function CorrectCase(input) {
    output = '';
    words = input.toLowerCase().split(' ');
    for (var i in words) {
        word = words[i];
        if (word.length > 2) {
            firstLetter = word.substring(0, 1).toUpperCase();
            word = firstLetter + word.substring(1);
        } //end if (word.length > 2)
        output += word + ' ';
    } //end for (var i in words)
    return output.replace(/^\s+|\s+$/g, '');
} //end function CorrectCase(input)

/* Page Size & Scroll - needed to resize overlays */
function ___getPageSize() {
    var xScroll, yScroll;
    if (window.innerHeight && window.scrollMaxY) {
        xScroll = window.innerWidth + window.scrollMaxX;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }
    var windowWidth, windowHeight;
    if (self.innerHeight) {    // all except Explorer
        if (document.documentElement.clientWidth) {
            windowWidth = document.documentElement.clientWidth;
        } else {
            windowWidth = self.innerWidth;
        }
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }
    // for small pages with total height less then height of the viewport
    if (yScroll < windowHeight) {
        pageHeight = windowHeight;
    } else {
        pageHeight = yScroll;
    }
    // for small pages with total width less then width of the viewport
    if (xScroll < windowWidth) {
        pageWidth = xScroll;
    } else {
        pageWidth = windowWidth;
    }
    arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight);
    return arrayPageSize;
};

function ___getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
        yScroll = self.pageYOffset;
        xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {     // Explorer 6 Strict
        yScroll = document.documentElement.scrollTop;
        xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
        yScroll = document.body.scrollTop;
        xScroll = document.body.scrollLeft;
    }
    arrayPageScroll = new Array(xScroll, yScroll);
    return arrayPageScroll;
};

/* Transparent Overlay for helper forms */
function hideOverlay() {
    $('#overlayBackground').hide();
    $('#overlayPanel').hide();
    //re-enable buttons
    enableOverlayShowButtons();
    return false;
} //end function hideOverlay()

function showOverlay() {
    //disable buttons to prevent double submission
    disableOverlayShowButtons();

    //set up the background
    var arrPageSizes = ___getPageSize();

    $('#overlayBackground').css({
        backgroundColor: "#000",
        opacity: "0.5",
        width: arrPageSizes[0],
        height: arrPageSizes[1]
    }).fadeIn();

    //set up the panel
    var arrPageSizes = ___getPageSize();
    var arrPageScroll = ___getPageScroll();
    $('#overlayPanel').css({
        //top: arrPageScroll[1] + 50, //was (arrPageSizes[3] / 20)
        top: ((arrPageSizes[3] - $('#overlayPanel').outerHeight()) / 2),
        left: ((arrPageSizes[2] - $('#overlayPanel').outerWidth()) / 2)
    });

    $('#overlayPanel').show();
    //reposition panel when the window resizes
    $(window).resize(function () {
        // Get page sizes
        var arrPageSizes = ___getPageSize();
        // Style overlay and show it
        $('#overlayBackground').css({
            width: arrPageSizes[0],
            height: arrPageSizes[1]
        });
        // Get page scroll
        var arrPageScroll = ___getPageScroll();
        // Calculate top and left offset for the jquery-lightbox div object and show it
        $('#overlayPanel').css({
            //top: arrPageScroll[1] + 50, //was (arrPageSizes[3] / 20)
            top: ((arrPageSizes[3] - $('#overlayPanel').outerHeight()) / 2),
            left: ((arrPageSizes[2] - $('#overlayPanel').outerWidth()) / 2)
        });
    });

    /*//reposition panel when the window scrolls
    $(window).scroll(function () {
    var arrPageScroll = ___getPageScroll();
    // Calculate top and left offset for the jquery-lightbox div object and show it
    $('#overlayPanel').css({
    top: arrPageScroll[1] + 50, //was (arrPageSizes[3] / 20)
    left: ((arrPageSizes[2] - $('#overlayPanel').outerWidth()) / 2)
    });
    });*/

    //apply hover effects to images inside the panel
    $("#overlayPanelInner img.hover").hover(
        function () { $(this).attr('src', $(this).attr('src').replace("_off", "_on")); },
        function () { $(this).attr('src', $(this).attr('src').replace("_on", "_off")); }
    );
    return false;
} //end function showOverlay()

function setUpOverlay() {
    $('body').append('<div id="overlayBackground"></div><div id="overlayPanel"><a href="#" id="closeOverlayPanel"><img src="/images/AbsoluteSnow/Buttons/closeoverlayBTN_off.png" class="hover" alt="Close Panel" /></a><div id="overlayPanelInner"></div></div>');
    $('#overlayBackground').click(function () { return hideOverlay(); });
    $('#closeOverlayPanel').click(function () { return hideOverlay(); });
    $("#closeOverlayPanel img.hover").hover(
        function () { $(this).attr('src', $(this).attr('src').replace("_off", "_on")); },
        function () { $(this).attr('src', $(this).attr('src').replace("_on", "_off")); }
    );
} //end function setUpOverlay()

function enableOverlayShowButtons() { //edit this in the future to re-enable all buttons and links which pop up the overlay
    $('a[rel="postcodeLookup"]').click(function () {
        return postcodeLookupPanel($(this).attr('id').replace("postcodeLookup", ""));
    });
} //function enableOverlayShowButtons()

function disableOverlayShowButtons() {
    $('a[rel="showOverlay"]').click(function () { return false; })
} //function disableOverlayShowButtons()

/* Create 'select address' panel */
function setUpPostcodeLookupAndStateDropdown(prefix, disablePostcodeLookup) {
    $('#' + prefix + 'StateCode').hide();
    if ($('input#' + prefix + 'Postcode').length) {
        if (!disablePostcodeLookup) { $('input#' + prefix + 'Postcode').after('<a href="#" id="' + prefix + 'postcodeLookup" rel="postcodeLookup" class="postcodeLookup"><img src="/images/AbsoluteSnow/Buttons/findaddressBTN_off.png" class="hover" alt="Find Address" /></a>'); }
        $('#' + prefix + 'postcodeLookup img.hover').hover(
            function () { $(this).attr('src', $(this).attr('src').replace("_off", "_on")); },
            function () { $(this).attr('src', $(this).attr('src').replace("_on", "_off")); }
        );
        $('#' + prefix + 'postcodeLookup').hide();
        $('#' + prefix + 'StateCode').hide();

        //On page load, check if the postcode lookup form needs enabling
        if ($('#' + prefix + 'Country').val() == 1 && !disablePostcodeLookup) {
            $('#' + prefix + 'postcodeLookup').show();
        } else {
            $('#' + prefix + 'postcodeLookup').hide();
        } //end if ($(this).val() == 1)

        //On page load, check if we need to hide the Postcode field
        if ($('#' + prefix + 'Country option:selected').text().toUpperCase() == "EIRE" || $('#' + prefix + 'Country option:selected').text() == "Ireland") {
            $('#' + prefix + 'Postcode').val('1');
            $('#' + prefix + 'Postcode').parent().hide();
        }

        //On page load, check if the state dropdown needs enabling
        if ($('#' + prefix + 'Country option:selected').text() == "USA") {
            $('#' + prefix + 'StateCode').show();
            $('#' + prefix + 'StateCode').val(CorrectCase($('#' + prefix + 'County').val()));
            $('#' + prefix + 'County').hide();
            $('#' + prefix + 'County').val($('#' + prefix + 'StateCode').val());
        } else {
            $('#' + prefix + 'StateCode').hide();
            $('#' + prefix + 'County').show();
        } //end if ($('#' + prefix + 'Country option:selected').text() == "USA")

        //attach actions for when the Country dropdown changes
        if (disablePostcodeLookup) {
            $('#' + prefix + 'Country').change(function () {
                if ($('#' + prefix + 'Country option:selected').text().toUpperCase() == "EIRE" || $('#' + prefix + 'Country option:selected').text() == "Ireland") {
                    $('#' + prefix + 'Postcode').val('1');
                    $('#' + prefix + 'Postcode').parent().hide();
                } else {
                    if ($('#' + prefix + 'Postcode').val() == '1') {
                        $('#' + prefix + 'Postcode').val('');
                    } //end if ($('#' + prefix + 'Postcode').val() == '1')
                    $('#' + prefix + 'Postcode').parent().show();
                } //end if ($('#' + prefix + 'Country option:selected').text() == "EIRE" || $('#' + prefix + 'Country option:selected').text() == "Ireland")

                if ($('#' + prefix + 'Country option:selected').text() == "USA") {
                    $('#' + prefix + 'StateCode').show();
                    $('#' + prefix + 'StateCode').val(CorrectCase($('#' + prefix + 'County').val()));
                    $('#' + prefix + 'County').hide();
                    $('#' + prefix + 'County').val($('#' + prefix + 'StateCode').val());
                } else {
                    $('#' + prefix + 'StateCode').hide();
                    $('#' + prefix + 'County').show();
                } //end if ($('#' + prefix + 'Country option:selected').text() == "USA")
            });
        } else {
        $('#' + prefix + 'Country').change(function () {
            //alert(prefix + "Country Changed to " + $('#' + prefix + 'Country option:selected').text() + " " + $('#' + prefix + 'Country').val());
            if ($('#' + prefix + 'Country option:selected').text().toUpperCase() == "EIRE" || $('#' + prefix + 'Country option:selected').text() == "Ireland") {
                $('#' + prefix + 'Postcode').val('1');
                $('#' + prefix + 'Postcode').parent().hide();
                //alert("Hide the postcode field");
            } else {
                if ($('#' + prefix + 'Postcode').val() == '1') {
                    $('#' + prefix + 'Postcode').val('');
                    //alert("Empty the postcode field");
                } //end if ($('#' + prefix + 'Postcode').val() == '1')
                $('#' + prefix + 'Postcode').parent().show();
                //alert("Show the postcode field");
            } //end if ($('#' + prefix + 'Country option:selected').text() == "EIRE" || $('#' + prefix + 'Country option:selected').text() == "Ireland")

            if ($(this).val() == 1) {
                $('#' + prefix + 'postcodeLookup').show();
                //alert("Show the address lookup button");
            } else {
                $('#' + prefix + 'postcodeLookup').hide();
                //alert("Hide the address lookup button");
            } //end if ($(this).val() == 1)

            if ($('#' + prefix + 'Country option:selected').text() == "USA") {
                $('#' + prefix + 'StateCode').show();
                $('#' + prefix + 'StateCode').val(CorrectCase($('#' + prefix + 'County').val()));
                $('#' + prefix + 'County').hide();
                $('#' + prefix + 'County').val($('#' + prefix + 'StateCode').val());
                //alert("Show the State dropdown");
            } else {
                $('#' + prefix + 'StateCode').hide();
                $('#' + prefix + 'County').show();
                //alert("Hide the State dropdown");
            } //end if ($('#' + prefix + 'Country option:selected').text() == "USA")
        });
        } //end if (disablePostcodeLookup)
        $('#' + prefix + 'StateCode').change(function () {
            $('#' + prefix + 'County').val($('#' + prefix + 'StateCode').val());
        });
    }
}


function postcodeLookupPanel(prefix) {
    $('#overlayPanelInner').html('');
    postcodeToLookup = $('#' + prefix + 'Postcode').val();

    $.ajax({
        url: '/WebServices/Postcode/',
        dataType: 'json',
        data: { postcode: postcodeToLookup },
        success: function (result) {
            if (result.Success) {
                if (result.Data.length > 0) {
                    even = false;
                    $('#overlayPanelInner').html('<h2>Select an Address:</h2>');
                    for (var i in result.Data) {
                        address = result.Data[i];
                        $('#overlayPanelInner').append('<address' + (even ? ' class="even"' : '') + '></address>');
                        $('#overlayPanelInner address:last').append('<a href="#" rel="useAddress" class="right"><img src="/images/AbsoluteSnow/Buttons/useaddressBTN_off.png" alt="Use This Address" class="hover" /></a>');
                        if (address.Company) { $('#overlayPanelInner address:last').append('<strong class="company">' + address.Company + '</strong><br />'); }
                        if (address.Address1) { $('#overlayPanelInner address:last').append('<span class="addressLine1">' + address.Address1 + '</span>'); }
                        if (address.Address2) { $('#overlayPanelInner address:last').append(', <span class="addressLine2">' + address.Address2 + '</span>'); }
                        if (address.Town) { $('#overlayPanelInner address:last').append('<br /><span class="town">' + address.Town + '</span>'); }
                        if (address.County) { $('#overlayPanelInner address:last').append(', <span class="county">' + address.County + '</span>'); }
                        if (address.Postcode) { $('#overlayPanelInner address:last').append(', <span class="postcode">' + address.Postcode + '</span>'); }
                        even = !even;
                    }
                    $('#overlayPanelInner address a[rel="useAddress"]').click(function () { return overlaySelectAddress($(this).parent(), prefix); });
                    $('#overlayPanelInner').append('<p><a href="#" id="overlayPanelCancel"><img src="/images/AbsoluteSnow/Buttons/cancelBTN_off.png" alt="Cancel" class="hover" /></a></p>');
                    $('#overlayPanelCancel').click(function () { return hideOverlay(); });
                } else {
                    $('#overlayPanelInner').html('<h2>No Results Found</h2>');
                    $('#overlayPanelInner').append('<p>No addresses were found for the entered postcode, <em>' + postcodeToLookup + '</em></p>');
                }
            } else {
                $('#overlayPanelInner').html('<h2>An error occurred</h2>');
                $('#overlayPanelInner').append('<p class="Error">' + result.Message + '</p>');
            }
            return showOverlay();
        },
        error: function () {
            $('#overlayPanelInner').html('<h2>An error occurred</h2>');
            $('#overlayPanelInner').append('<p class="Error">No response from postcode lookup server</p>');
            return showOverlay();
        }
    });
    return false;
} //end function postcodeLookupPanel()

function overlaySelectAddress(addressToSelect, prefix) {
    $('#Company').val((addressToSelect.children(".company").length ? addressToSelect.children(".company").text() : ''));
    $('#' + prefix + 'Address1').val((addressToSelect.children(".addressLine1").length ? addressToSelect.children(".addressLine1").text() : ''));
    $('#' + prefix + 'Address2').val((addressToSelect.children(".addressLine2").length ? addressToSelect.children(".addressLine2").text() : ''));
    $('#' + prefix + 'Town').val((addressToSelect.children(".town").length ? addressToSelect.children(".town").text() : ''));
    $('#' + prefix + 'County').val((addressToSelect.children(".county").length ? addressToSelect.children(".county").text() : ''));
    $('#' + prefix + 'Postcode').val((addressToSelect.children(".postcode").length ? addressToSelect.children(".postcode").text() : ''));
    return hideOverlay();
} //end overlaySelectAddress(addressToSelect)

function setUpImageMouseOverChangeSRC() {
    $('img[src*="_off"]').hover(
            function () { $(this).attr('src', $(this).attr('src').replace("_off", "_on")); },
            function () { $(this).attr('src', $(this).attr('src').replace("_on", "_off")); }
        );
    $('input[type=image][src*="_off"]').hover(
            function () { $(this).attr('src', $(this).attr('src').replace("_off", "_on")); },
            function () { $(this).attr('src', $(this).attr('src').replace("_on", "_off")); }
        );
} //end setUpImageMouseOverChangeSRC()

//Product Image Swapping Func
(function ($) {
    $.fn.vAlign = function () {
        return this.each(function (i) {
            var ah = $(this).height();
            var ph = $(this).parent().height();
            var mh = (ph - ah) / 2;
            $(this).css('margin-top', mh);
        });
    };
})(jQuery);

//Form Hints
(function ($) {

    $.fn.hint = function (blurClass) {
        if (!blurClass) {
            blurClass = 'blur';
        }

        return this.each(function () {
            // get jQuery version of 'this'
            var $input = $(this),

            // capture the rest of the variable to allow for reuse
      title = $input.attr('title'),
      $form = $(this.form),
      $win = $(window);

            function remove() {
                if ($input.val() === title && $input.hasClass(blurClass)) {
                    $input.val('').removeClass(blurClass);
                }
            }

            // only apply logic if the element has the attribute
            if (title) {
                // on blur, set value to title attr if text is blank
                $input.blur(function () {
                    if (this.value === '') {
                        $input.val(title).addClass(blurClass);
                    }
                }).focus(remove).blur(); // now change all inputs to title

                // clear the pre-defined text when form is submitted
                $form.submit(remove);
                $win.unload(remove); // handles Firefox's autocomplete
            }
        });
    };

})(jQuery);

// Image Preloading func
(function($) {
    var cache = [];
    // Arguments are image paths relative to the current page.
    $.preLoadImages = function() {
        var args_len = arguments.length;
        for (var i = args_len; i--; ) {
            var cacheImage = document.createElement('img');
            cacheImage.src = arguments[i];
            cache.push(cacheImage);
        }
    }
})(jQuery)

/* When document is ready, do stuff */
$(document).ready(function () {
    $('a[rel*=facebox]').facebox({});
    //Show/Hide text over 130 characters for descriptive text boxes
    var trim_length = 200;
    if ($('#descriptive_text').length && $('#descriptive_text').html().length > trim_length) {
        var first_description = $('#descriptive_text').html().substring(0, trim_length);
        var second_description = $('#descriptive_text').html().substring(trim_length);
        $('#descriptive_text').html(first_description);
        $('#descriptive_text').after('<span id="extra_descriptive_text" style="display: none;">' + second_description + '</span>');
        $('#descriptive_text').after('<span id="descriptive_text_ellipsis">...</span>');
        $('#extra_descriptive_text').after(' <a id="read_more_descriptive_text" href="#">Read More</a>');
        $('#read_more_descriptive_text').click(function () {
            if ($('#extra_descriptive_text').css('display') == 'none') {
                $('#read_more_descriptive_text').html('Read Less');
                $('#descriptive_text_ellipsis').css('display', 'none');
                $('#extra_descriptive_text').css('display', 'inline');
            } else {
                $('#read_more_descriptive_text').html('Read More');
                $('#descriptive_text_ellipsis').css('display', 'inline');
                $('#extra_descriptive_text').css('display', 'none');
            }
            return false;
        });
    } //end if ($('#descriptive_text').length && $('#descriptive_text').html().length>trim_length)
    //Fix main menu for IE 6
    $('ul#departments li').hover(function () {
        $(this).find('ul.columns').css('display', 'block');
    }, function () {
        $(this).find('ul.columns').css('display', 'none');
    });
    //Brand accordian menus
    $('a.brand_header').click(function () {
        //$('ul.brands').slideUp('normal');
        //$(this).next().slideDown('normal').css("overflow", "auto");
        $('ul.brands').hide();
        $(this).next().show();
        return false;
    });

    //Set up overlay panel and assorted buttons
    setUpOverlay();
    setUpPostcodeLookupAndStateDropdown('', false);
    setUpPostcodeLookupAndStateDropdown('Delivery', false);
    setUpPostcodeLookupAndStateDropdown('Billing', true);
    enableOverlayShowButtons();

    //Set up image hover functions
    setUpImageMouseOverChangeSRC();

    //Set up footer pop up menus
    $(" #pullup ul ").css({display: "none"}); // Opera Fix
    $(" #pullup li ").hover(function(){
		$(this).find('ul:first:hidden').css({visibility: "visible",display: "none"}).fadeIn(400);
		},function(){
		$(this).find('ul:first').css({visibility: "hidden",display: "none"});
    });
    $("a.footer_nonlink").click(function() { return false; });
    $("#tmBrandLink").click(function () { return false; });

    //Set up expanding brands in a menu???
    /*$(".listCol dd").hide();
    $(".listCol dt.brand a").click(function () {
        //$(".listCol dd:visible").slideUp("normal");
        //$(this).parent().next().slideDown("normal");
        $(".listCol dd:visible").hide();
        $(this).parent().next().hide();
        return false;
    });*/

    //Set up Tabs on Product Pages
    //When page loads...
    $(".tab_content").hide(); //Hide all content
    $("ul.tabs li.tab:first").addClass("active").show(); //Activate first tab
    $(".tab_content:first").show(); //Show first tab content

    //On Click Event
    $("ul.tabs li.tab").click(function () {

        $("ul.tabs li.tab").removeClass("active"); //Remove any "active" class
        $(this).addClass("active"); //Add "active" class to selected tab
        $(".tab_content").hide(); //Hide all tab content

        var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
        $(activeTab).fadeIn(); //Fade in the active ID content
        return false;
    });

    //Image and Video swapping on Product Pages
    $('div#productcolumn01 div#smallImages ul.small_product_images a').click(function () {

        var x = $('div#productcolumn01 div#productimagecontainer img.product_image').attr('src');

        var y = $(this).children('img').attr('src').replace('/Medium/', '/Larger/').replace('width=80&maxHeight=85', 'width=340&maxHeight=350')

        $(this).children('img').attr('src', x.replace('/Larger/', '/Medium/').replace('width=340&maxHeight=350', 'width=80&maxHeight=85'));
        $('div#productcolumn01 div#productimagecontainer img.product_image').attr('src', y);

        return false;
    });

    $('div#productcolumn01 div#YouTubeVideoImages ul.small_product_images a').click(function () {
        $(this).parents('ul').children('li').removeClass('hidden');
        $(this).parents('li').addClass('hidden');

        var imgId = $(this).parents('li').attr('id').substring(10, 12);

        var youTubeVideoWrapper = $('div#productcolumn01 div#youtubevideo div.videowrapper');
        youTubeVideoWrapper.addClass('hidden');

        var youTubeCurrentVideoWrapper = $('div#productcolumn01 div#youtubevideo div#video' + imgId);

        youTubeCurrentVideoWrapper.removeClass('hidden');

        var p = $('div#productcolumn01 div#youtubevideoscontainer p');
        var s = $('div#productcolumn01 div#YouTubeVideoImages li#videoImage' + imgId + ' img');
        p.html(s.attr('alt'));

        return false;
    });

    //Apply form hints
    // find all the input elements with title attributes
    $('input[title!=""]').hint();
});

//Attach Preloader
jQuery.preLoadImages("/images/snowBTN_on.jpg", "/images/surfBTN_on.jpg", "/images/skateBTN_on.jpg", "/images/streetBTN_on.jpg", "/images/skyBTN_on.jpg", "/images/brandsBTN_on.jpg", "/images/homeBTN_on.jpg", "/images/absolutesnow/snowBTN_on.jpg", "/images/absolutesnow/surfBTN_on.jpg", "/images/absolutesnow/skateBTN_on.jpg", "/images/absolutesnow/streetBTN_on.jpg", "/images/absolutesnow/skyBTN_on.jpg", "/images/absolutesnow/brandsBTN_on.jpg", "/images/absolutesnow/homeBTN_on.jpg");
