﻿var ie6Below = $.browser.msie && parseFloat($.browser.version) <= 6;
var ie7Below = $.browser.msie && parseFloat($.browser.version) <= 7;

/***
* jQuery.matchColumns - make bottoms of column match 
* four object parameters at the moment
* children : (optional, string) children are the nodes within the container that the height is to be added to
* position : (optional, string - default bottom) position is where you where you want the extra height to be added
* restart :  (optional, integer) if you want to reset the height at the start of each row, give the column number
* style :    (optional,string [padding,margin] ) which style attribute the height is to be added to
* imageWait : (optional, boolean) Waits until all of the images in the columns are loaded before performing the function */

(function(jQuery) {
    jQuery.fn.matchColumns = function(obj) {

        if (!obj) obj = {};

        if (!this.length) return;

        var columns = this;

        var children = obj.children || null;
        var position = obj.position || "bottom";
        var restart = obj.restart || null;
        var style = obj.style || "margin";

        function setColumns() {
            var lowest = 0;
            var lowList = [];
            columns.each(
            function(i) {
                if (restart && i % restart == 0) {
                    lowList[lowList.length] = 0; lowest = 0;
                    if (jQuery.browser.msie) // if rows are floated and not cleared there are problems in IE. Don't know which browser is rendering correctly but assume it is not IE. This is only a problem if the bottom is being found, not the height.
                    {
                        jQuery(this).before('<div class="REMOVED_AFTER_FOUND_BOTTOM" style="clear:both;font-size:0;height:0;width:100%;"/>');
                    }
                }

                var bottom = jQuery(this).offset().top + this.offsetHeight;
                this.currentBottom = bottom;
                if (bottom > lowest) { lowest = bottom; }
                if (restart) { lowList[lowList.length - 1] = lowest; }
            })
        .css("height", "auto")
        .siblings(".REMOVED_AFTER_FOUND_BOTTOM").remove().end()
        .each(
          function(i) {
              if (lowList.length) {
                  lowest = lowList[Math.ceil((i + 1) / (restart)) - 1];
              }
              var el = this;
              var diff = lowest - this.currentBottom;
              var endHeight = this.offsetHeight + diff;
              if (diff > 0) {
                  if (children) {
                      var tries = 0;
                      jQuery(el).find(children).each(function() {
                          while (el.offsetHeight < endHeight && tries < 6) // if it can't get it in 4 tries then something if wrong
                          {
                              var exist = jQuery(this).css(style + "-" + position).replace(/px/, "") * 1;
                              if (isNaN(exist)) exist = 0;
                              jQuery(this).css(style + "-" + position, endHeight - el.offsetHeight + exist);
                              tries++;
                          }
                      });
                  }
                  else {
                      jQuery(this).css("padding-" + position, diff + jQuery(this).css("padding-" + position).replace("px", "") * 1);
                  }
              }
          }
        );
        }; // end function setColumns

        if (obj.imageWait) {
            var totalToLoad = 0;

            function finishedLoad() {
                totalToLoad--;
                if (!totalToLoad) setColumns();
            }

            columns.find("img").each(function(i) {
                if (!this.complete) {
                    // IE doesn't return complete for failed images so check to see if it currently loading
                    if (jQuery.browser.msie && this.readyState != "loading") return;
                    totalToLoad++;
                    this.onload = finishedLoad;
                }
            });
            if (!totalToLoad) setColumns();
        }
        else {
            setColumns();
        }

    }
})(jQuery);

/***********************************
Main page load script
************************************/


$(function() {


    $("#footer .newsletterSignup input[type=text]").each(function() {
        var labelVal = $("#footer .newsletterSignup label").text();

        $(this).each(function() {
            createText(labelVal, $(this));
        });
        // Removal of text on user-focus
        $(this).focus(function() {
            removeText(labelVal, $(this));
        });
        // Restoration of default text on input blur, if no user input.
        $(this).blur(function() {
            restoreText(labelVal, $(this));
        });
    });

    $("#forwardToWorldPay").each(function() {
        try {
            var cookieData = pageTracker._getLinkerUrl(location.href).match(/[^\?](\?.+)/)[1];
            $(this).append('<input type="hidden" name="GoogleCookieData" value="' + cookieData + '"/>');
        }
        catch (e) {
        }
    });

    $(".register.group,.login.group")
        .matchColumns({ children: ".button", style: "margin", position: "top" });

    $(".productRow").each(function() {
        $(".productItem", this)
            .matchColumns({ children: ".action", style: "margin", position: "top" });
    });

    $(".ajax-link").live('click', showAjaxContent);

});

// Create default text for text field on page load
function createText(defVal, thisObj) {
    var inpType = thisObj.attr("type");
    if (inpType != "submit") {

        if (thisObj.attr("value") == defVal || thisObj.attr("value").length == 0) {

            thisObj.attr("value", defVal);
            thisObj.addClass("empty");
        }
    }
}

// Remove default text on focus. Ignore user-inserted text
function removeText(defVal, thisObj) {
    var inpType = thisObj.attr("type");
    if (inpType != "submit") {
        var currVal = thisObj.attr("value");
        if (currVal == defVal) {
            thisObj.attr("value", "");
            thisObj.removeClass("empty")
        }
    }
}

// Restore default text on focus. Ignore user-inserted text
function restoreText(defVal, thisObj) {
    var inpType = thisObj.attr("type");
    if (inpType != "submit") {
        var currVal = thisObj.attr("value");
        if (currVal != undefined && currVal != '') {
            thisObj.attr("value", currVal);
        }
        else if (currVal == undefined || currVal == '') {
            thisObj.attr("value", defVal);
            thisObj.addClass("empty");
        }
    }
}

/* .NET validator functions */
// checkbox for the over 18 and terms validator
function validateTerms(sender, args) {
    args.IsValid = $("[id*='cbTerms']").attr("checked");
}

/* show on page content in popups */

function showAjaxContent() {

    var anchor = this;
    var ajaxPopup = null;

    $.ajax({
        url: anchor.href,
        cache: true,
        dataType: "html",
        success: function(html) {
            var strContent = html.match(/<!--CONTENTSTART-->([.\s\S]*)<!--CONTENTEND-->/i);
            if (!strContent || !strContent[1]) {
                location.href = anchor.href;
                return false;
            }
            var content = $("<div/>").append(strContent[1]).html();

            displayPanel(content);
        },
        error: function() {
            location.href = anchor.href;
        }
    });

    function removePopup() {
        ajaxPopup.fadeOut("slow", function() { $(this).add(".popFrame").remove(); });
        $(window).unbind("scroll");
        return false;
    }

    function displayPanel(html) {

        ajaxPopup = $('<div class="popup"></div><div class="ajaxContent"></div>').css("visibility", "hidden");
        var popupUnderlay = ajaxPopup.eq(0);
        var popupContainer = ajaxPopup.eq(1);
        popupUnderlay.css("opacity", "0.4").click(removePopup);
        var close = $('<a class="topClose" title="Close window" href="#">x close</a>').click(removePopup)

        popupContainer.append(html, close);

        $("body").append(ajaxPopup);

        var popupTop = popupContainer.offset().top;
        //var popupPaddingTop = ajaxPopup.eq(1).css("padding-top");
        var popupPaddingBottom = popupContainer.css("padding-bottom").replace("px", "");
        var popupHeight = $(window).height() - 80;
        //        ajaxPopup.eq(1).find(".contentGroup").height($(window).height() - 80); //.css("overflow", "auto");
        popupContainer.height(popupHeight); //.css("overflow", "auto");

        var popupContentContainer =  popupContainer.find(".contentGroup");
        
        if (popupContentContainer.outerHeight() > popupHeight) {
            popupContentContainer.css({ height: popupHeight, overflow: "auto" });
            popupContainer.css("padding-right",0);
        }

        ajaxPopup
            .hide()
            .css("visibility", "visible")
            .fadeIn();

        if (ie6Below) {
            popupUnderlay.css({ height: document.body.scrollHeight, position: "absolute" });
            popupContainer.css({ top: (getScrollXY()[1] + 30), position: "absolute" });
            $(window).bind("scroll", function() {
                popupContainer.stop().animate({ top: getScrollXY()[1] + 20 }, 500);
            });

            $("body").append('<iframe class="popFrame" style="position:absolute;top:0;left:0;width:100%;height:' + document.body.scrollHeight + 'px" frameborder="0" src="javascript:false;"></iframe>').find(":last").css("opacity", 0);

        }
        else {
            popupContainer.css("top", 20);
        }

    }

    return false;
}


//Jscript to generate window height
function getWindowSize() {
    var myWidth = 0, myHeight = 0;
    if (typeof (window.innerWidth) == 'number') {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    return [myWidth, myHeight];
}

function getScrollXY() {
    var scrOfX = 0, scrOfY = 0;
    if (typeof (window.pageYOffset) == 'number') {
        //Netscape compliant
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
    } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
        //DOM compliant
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
    } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
    }
    return [scrOfX, scrOfY];
}

/***
* jQuery.matchColumns - make bottoms of column match 
* four object parameters at the moment
* children : (optional, string) children are the nodes within the container that the height is to be added to
* position : (optional, string - default bottom) position is where you where you want the extra height to be added
* restart :  (optional, integer) if you want to reset the height at the start of each row, give the column number
* style :    (optional,string [padding,margin] ) which style attribute the height is to be added to
* imageWait : (optional, boolean) Waits until all of the images in the columns are loaded before performing the function */

(function(jQuery) {
    jQuery.fn.matchColumns = function(obj) {

        if (!obj) obj = {};

        if (!this.length) return;

        var columns = this;

        var children = obj.children || null;
        var position = obj.position || "bottom";
        var restart = obj.restart || null;
        var style = obj.style || "margin";

        function setColumns() {
            var lowest = 0;
            var lowList = [];
            columns.each(
            function(i) {
                if (restart && i % restart == 0) {
                    lowList[lowList.length] = 0; lowest = 0;
                    if (jQuery.browser.msie) // if rows are floated and not cleared there are problems in IE. Don't know which browser is rendering correctly but assume it is not IE. This is only a problem if the bottom is being found, not the height.
                    {
                        jQuery(this).before('<div class="REMOVED_AFTER_FOUND_BOTTOM" style="clear:both;font-size:0;height:0;width:100%;"/>');
                    }
                }

                var bottom = jQuery(this).offset().top + this.offsetHeight;
                this.currentBottom = bottom;
                if (bottom > lowest) { lowest = bottom; }
                if (restart) { lowList[lowList.length - 1] = lowest; }
            })
        .css("height", "auto")
        .siblings(".REMOVED_AFTER_FOUND_BOTTOM").remove().end()
        .each(
          function(i) {
              if (lowList.length) {
                  lowest = lowList[Math.ceil((i + 1) / (restart)) - 1];
              }
              var el = this;
              var diff = lowest - this.currentBottom;
              var endHeight = this.offsetHeight + diff;
              if (diff > 0) {
                  if (children) {
                      var tries = 0;
                      jQuery(el).find(children).each(function() {
                          while (el.offsetHeight < endHeight && tries < 6) // if it can't get it in 4 tries then something if wrong
                          {
                              var exist = jQuery(this).css(style + "-" + position).replace(/px/, "") * 1;
                              if (isNaN(exist)) exist = 0;
                              jQuery(this).css(style + "-" + position, endHeight - el.offsetHeight + exist);
                              tries++;
                          }
                      });
                  }
                  else {
                      jQuery(this).css("padding-" + position, diff + jQuery(this).css("padding-" + position).replace("px", "") * 1);
                  }
              }
          }
        );
        }; // end function setColumns

        if (obj.imageWait) {
            var totalToLoad = 0;

            function finishedLoad() {
                totalToLoad--;
                if (!totalToLoad) setColumns();
            }

            columns.find("img").each(function(i) {
                if (!this.complete) {
                    // IE doesn't return complete for failed images so check to see if it currently loading
                    if (jQuery.browser.msie && this.readyState != "loading") return;
                    totalToLoad++;
                    this.onload = finishedLoad;
                }
            });
            if (!totalToLoad) setColumns();
        }
        else {
            setColumns();
        }

    }
})(jQuery);
