/**
 * @author Javelin Group
 * @version 1.0
 */


/*
CSS Browser Selector v0.4.0 (Nov 02, 2010)
Rafael Lima (http://rafael.adm.br)
http://rafael.adm.br/css_browser_selector
License: http://creativecommons.org/licenses/by/2.5/
Contributors: http://rafael.adm.br/css_browser_selector#contributors
*/
function css_browser_selector(u){var ua=u.toLowerCase(),is=function(t){return ua.indexOf(t)>-1},g='gecko',w='webkit',s='safari',o='opera',m='mobile',h=document.documentElement,b=[(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?g+' ff2':is('firefox/3.5')?g+' ff3 ff3_5':is('firefox/3.6')?g+' ff3 ff3_6':is('firefox/3')?g+' ff3':is('gecko/')?g:is('opera')?o+(/version\/(\d+)/.test(ua)?' '+o+RegExp.$1:(/opera(\s|\/)(\d+)/.test(ua)?' '+o+RegExp.$2:'')):is('konqueror')?'konqueror':is('blackberry')?m+' blackberry':is('android')?m+' android':is('chrome')?w+' chrome':is('iron')?w+' iron':is('applewebkit/')?w+' '+s+(/version\/(\d+)/.test(ua)?' '+s+RegExp.$1:''):is('mozilla/')?g:'',is('j2me')?m+' j2me':is('iphone')?m+' iphone':is('ipod')?m+' ipod':is('ipad')?m+' ipad':is('mac')?'mac':is('darwin')?'mac':is('webtv')?'webtv':is('win')?'win'+(is('windows nt 6.0')?' vista':''):is('freebsd')?'freebsd':(is('x11')||is('linux'))?'linux':'','js']; c = b.join(' '); h.className += ' '+c; return c;}; css_browser_selector(navigator.userAgent);


/* Cam object to hold functions */
var cam = {

    // Text resources set in resources.jsp
    resources:{},

    // Carousels
    carousels:[],

    // Videos
    video: {},

	// 360 rotating image
	rotate: {}

};


/**
 * @info Generic object to hold all carousel settings.
 *       cam.carousels is populated with the camCarousel from two files:
 *          VerticalProductCarousel and HorizontalProductCarousel
 *       camCarousel.options is passed directly to jcarousel, through camCarousel.init().
 *       Methods within this object refer to both settings for the jcarousel (carousel.options.<param>) instance,
 *       and those stored against the jcarousel list, using the data object (list.data(<param>)).
 */
var camCarousels = {

    /**
     * @info Carousel call back function called from jcarousel. Specified in carousel.options
     * @param carousel: The instance of jcarousel
     */
    carouselCallback: function(carousel) {

        // The original DOM carousel element reference
        // We use this to store data against
        var domCarousel = jQuery(carousel.list);

        // carousel.options are passed to jcarousel
        var options = carousel.options;

        // Auto is not an option for horizontal carousels
        var auto = options.auto || domCarousel.data('auto');

        // Vertical flag, not present for horizontal carousels
        var vertical = options.vertical || false;

        // For vertical carousels, set the height of the mask / clip element to the stored data value
        // We do this within the callback otherwise the scrolling won't function properly
        if(vertical) jQuery(carousel.clip).css('height', domCarousel.data('carouselClipHeight'));

        // Get scrolling flags
        var scrollStarted = domCarousel.data('scrollStarted');
        var scrollDisabled = domCarousel.data('scrollDisabled');

        // Determine if we need to show the controls from the stored data value
        if(domCarousel.data('carouselControls')) {

            // Disable autoscrolling if the user clicks the prev or next button.
            carousel.buttonNext.bind('click', function() { carousel.startAuto(0); domCarousel.data('scrollDisabled', true); });
            carousel.buttonPrev.bind('click', function() { carousel.startAuto(0); domCarousel.data('scrollDisabled', true); });

            // Pause autoscrolling if the user moves with the cursor over the clip.
            carousel.clip.hover(
                function() { carousel.stopAuto(); },
                function() { carousel.startAuto(); }
            );

            // Init auto scrolling if carousel is in viewport
            if(camCarousels.carouselAutoEnabled(carousel)) {
                carousel.startAuto(auto);
            }

            /**
             * Determine if we start the auto scroll if carousel is inviewport.
             * Removed for performance & overhead
             */
            /*if(!camCarousels.carouselAutoEnabled(carousel)) {
                // Add event handler to start when it's scrolled into view
                jQuery(window).scroll(function(){
                    // Start the scroll if the carousel is scrolled into view
                    //if(camCarousels.carouselAutoEnabled(carousel) && !camCarousels.scrollDisabled && !camCarousels.scrollStarted) {
                    if(camCarousels.carouselAutoEnabled(carousel) && !scrollDisabled && !scrollStarted) {
                        carousel.startAuto(auto);
                        //camCarousels.scrollStarted = true;
                        //domCarousel.data('scrollStarted', true);
                        scrollStarted = true;
                    }
                });
            }
            else {
                // Carousel is in view, therefore start auto scroll
                carousel.startAuto(auto);
            };*/
        };
    },


    /*
     * @info Utility method to determine if the carousel can be automatically scrolled
     *       Returns true when the carousel is in the browser viewport
     */
    carouselAutoEnabled: function(carousel) {

        var winH = jQuery(window).height();                         // Height of viewport
        var winScrollY = jQuery(window).scrollTop();                // Amount window is scrolled by
        var carouselY = jQuery(carousel.container).offset().top;    // Top left position of carousel relative to document
        var carouselH = jQuery(carousel.container).height();        // Height of carousel

        // We can enable auto scrolling if all of carousel is within viewport
        var result = ((carouselY - winScrollY) + carouselH <= winH) ? false : true;
        return result;
    },


    /*
     * @info camCarousel initialisation function
     *       Called from domready, it is used to:
     *       1. Make the height of each item in vertical carousels equal.
     *          This enables correct scrolling of products with different attributes, e.g. variants, different length of descriptions
     *       2. Set the relevant data to the DOM carousel list, for retreval later
     *       3. Call the jcarousel function
     */
    init : function(){
        jQuery.each(cam.carousels, function(index, carousel){

            var maxHeight = 0;
            var vertExtras = 0;
            var jc = jQuery('#' + carousel.id);

            if(carousel.options.vertical) {
                // Vertical

                jc.find('li .situpProduct').each(function(){
                    var outerHeight = jQuery(this).outerHeight();
                    // Set height to the maximum found
                    maxHeight = outerHeight > maxHeight ? outerHeight : maxHeight;
                });
                // Set height of each LI to maxHeight
                jc.children('li').css('height', maxHeight);

                // Get extra padding etc
                vertExtras = (jc.children('li').outerHeight() - maxHeight);

                // Store height data to be used in callback
                // Height of carousel mask is (num items shows * (height of items + padding etc of LI))
                jc.data('carouselClipHeight', carousel.slotsToShow * (maxHeight + vertExtras));
            }
            else {
                // Horizontal
                // Auto option is set by camCarousel auto param, not via the options for jcaoursel, ie. carousel.options.auto
                // Auto is only applied to horizontal carousels when in viewport
                jc.data('auto', carousel.auto);
            }
            // Store control data to the DOM carousel, for use in callback
            jc.data('carouselControls', carousel.showControls);

            // Set scrolling flags
            jc.data('scrollStarted', carousel.scrollStarted);
            jc.data('scrollDisabled', carousel.scrollDisabled);

            // Create the carousel
            jc.jcarousel(carousel.options);
        });
    }
};


/**
 * =x: Form field manipulation
 */
function formDisable(formId) {
    $("#" + formId + " input, #" + formId + " select").each(function(i) { this.disabled = "disabled"; });
}

function formEnable(formId) {
    $("#" + formId + " input, #" + formId + " select").each(function(i) { $(this).removeAttr("disabled"); });
}

function setPayment(paymentMethod) {
    switch (paymentMethod) {
        case "paypal":
            formDisable("payDets");
            formDisable("savedCard");
            break;
        case "savedCard":
            formDisable("payDets");
            formEnable("savedCard");
            break;
        case "newCard":
            formDisable("savedCard");
            formEnable("payDets");
            break;
        default:
            return;
    }
}

/* blocks multiple clicks on forms */
function blockMultipleClicks(form) {
    if (form.getAttribute('submitted')) { return false; }
    form.setAttribute('submitted','true');
}

/* removes values from search boxes on click *if* it is the default text */
function inputTextRemove() {
    $('#freeText').val(cam.resources["FREE_TEXT_SEARCH_HINT"]);
    $("#freeText").focus(function() { if (this.value == cam.resources["FREE_TEXT_SEARCH_HINT"]) { this.value = ""; } }).blur(function() { if (this.value == "") { this.value = cam.resources["FREE_TEXT_SEARCH_HINT"]; } });
    $("#emailAddress").focus(function() { if (this.value == cam.resources["NEWSLETTER_SIGNUP_HINT"]) { this.value = ""; } }).blur(function() { if (this.value == "") { this.value = cam.resources["NEWSLETTER_SIGNUP_HINT"]; } });
    $("#queryField").focus(function() { if (this.value == cam.resources["STORE_LOCATOR_HINT"]) { this.value = ""; } }).blur(function() { if (this.value == "") { this.value = cam.resources["STORE_LOCATOR_HINT"]; } });
}

/* merch list (de)select all */
function merchSelectToggle() {
    $(".selectAllLink").css("display", "block");
    $("#selectAll").toggle(
        function() {
            $(".productList input[type='checkbox']").each(function() { $(this).attr("checked", "checked"); });
            $("#selectAll").attr("title", cam.resources["MERCHANDISEDLIST_DESELECTALL"]).html(cam.resources["MERCHANDISEDLIST_DESELECTALL"]);
        },
        function() {
            $(".productList input[type='checkbox']").each(function() { $(this).attr("checked", ""); });
            $("#selectAll").attr("title", cam.resources["MERCHANDISEDLIST_SELECTALL"]).html(cam.resources["MERCHANDISEDLIST_SELECTALL"]);
        }
    );
}

/**
 * =x: Password Strength Indicator
 */
function passwordTest() {
    if (passwordInput = document.getElementById("password").value) {
        passwordMsg = document.getElementById("passwordStrength");

        // reset variables
        lengthScore = 0;
        typeScore = 0;

        // test for length
        if (passwordInput.length < 6) { lengthScore = 0; }
        else if (passwordInput.length < 8) {lengthScore = 1; }
        else if (passwordInput.length > 7) { lengthScore = 2; }

        // test for content
        if (passwordInput.match(/[a-z]/)) { typeScore += 1; }
        if (passwordInput.match(/[A-Z]/)) { typeScore += 1; }
        if (passwordInput.match(/\d+/)) { typeScore += 1; }
        if (passwordInput.match(/.[!,@,#,$,%,^,&,*,?,_,~]/)) { typeScore += 1; }

        // set classes/text from score
        switch (lengthScore) {
            case 0:
                break;
            case 1:
                if (typeScore > 1) { passwordMsg.className = "strength2"; }
                else { passwordMsg.className = "strength1"; }
                break;
            case 2:
                if (typeScore > 2) { passwordMsg.className = "strength3"; }
                else if (typeScore > 1) { passwordMsg.className = "strength2"; }
                break;
            default:
                passwordMsg.className = "strength1";
        }

        // if the field has been cleared then reset indicator
        if (passwordInput.length < 2) { passwordMsg.className = ""; }
    }
}


/**
 * =x: Auto Submit Dropdowns
 */
function dropdownSubmit() {
    $("#productFm select").change(function() { $("#productFm").submit(); });
    $("#ResultSort select").change(function() { $("#ResultSort").submit(); });
    $("#CategoryResultSort select").change(function() { $("#CategoryResultSort").submit(); });
    $("#BrandResultSort select").change(function() { $("#BrandResultSort").submit(); });
    $("#TabbedResultSort select").change(function() { $("#TabbedResultSort").submit(); });
}
/** Filter search results per page. Show and hide "showall" option */
function filterResults(selectComp, productCountStr, allResultsLimit, showAllLink, formComp){
    showAllLink.click(
            function(){
                selectComp.selectOptions(productCountStr);
                formComp.submit();
                return false;
            ;}
    );

    var productCount = parseInt(productCountStr);

    switch(productCount){
    case 50:
        selectComp.removeOption(2);
        break;
    case 20:
        selectComp.removeOption(1);
        break;
    case 10:
        selectComp.removeOption(0);
        break;
    }

    if(productCount < 50)
    {
        selectComp.removeOption("50");
    }
    if(productCount < 20)
    {
        selectComp.removeOption("20");
    }
    if(productCount < 10)
    {
        selectComp.removeOption(productCountStr);
        showAllLink.hide();
    } else {
        showAllLink.show();
    }
    if(productCount > allResultsLimit){
        showAllLink.hide();
        selectComp.removeOption(productCountStr);
    }

}

/**
 * =x: Animated basket with AJAX data load
 */
var ajaxBasket = false;
var itemsHeight = 0;

// if js is on, add ajax basket link
function addBasketLink() {
    $("<a href='#' class='toggle-basket'>" + cam.resources["BASKET_EXPAND"] + "</a>").toggle(
        function() {
            // create basket id not created already
            if (!ajaxBasket) { initBasket(); }
            else {
                $("#basket-contents").animate({top: "0"}, 1000);
                $(".toggle-basket").html(cam.resources["BASKET_HIDE"]).css("background", "url(/images/icons/link-bullet-up.gif) 0 6px no-repeat");
            }
        },
        function() {
            $("#basket-contents").animate({top: -(itemsHeight-4) + "px"}, 1000);
            $(".toggle-basket").html(cam.resources["BASKET_EXPAND"]).css("background", "url(/images/icons/link-bullet.gif) left no-repeat");
        }
    ).insertBefore(".basket-links a");
}

// set up contents of basket
function initBasket() {

    if(window.parent.document.location.protocol == 'https:'){
        basketAction = globalURLPrefix + "SecBasketAjax.action"
    }else{
        basketAction = globalURLPrefix + "BasketAjax.action"
    }
    $.getJSON(basketAction,
        function(data){
	    	prodList = $("<ul></ul>");

	        if ((data.entries).length > 0) {
	            for (i=0; i<(data.entries).length; i++) {
	                if (data.entries[i].quantity != "") {
	                	prodList.append( $("<li><span class='grey_qty'>" + data.entries[i].quantity + " x&nbsp;</span>" + "<span class='bold'>" +  data.entries[i].productName + "</span>" + " <span class='red bold'>" + data.entries[i].totalPrice + "</span>" + "</li>") );
	                }
	            }
	            //prodList.append( $("<li class='fs11 normal vdb'><a href='/Basket.action'>" + cam.resources["VIEW_BASKET"] + "</a></li>") );
	        }

	        else { prodList.append( $("<li class='li-empty-basket'>" + cam.resources["BASKET_EMPTY"] + "</li>") ); }

	        prodList.insertBefore(".basket-links");

	        itemsHeight = $("#basket-contents").height() - 14;
	        $("#basket-contents").css("top", -itemsHeight + "px");

	        $("#basket-contents").animate({top: "0"}, 1000);
	        $(".toggle-basket").html(cam.resources["BASKET_HIDE"]).css("background", "url(/images/icons/link-bullet-up.gif) 0 6px no-repeat");

	        ajaxBasket = true;
        });
}

/**
 * =x; Tooltips
 */
function initTooltips() {
    $("a.tooltip:not(a.link)").click(function() { return false; });
    $("a.tooltip.link").click(function() { return true; })
    $("a.tooltip").attr("title", "").mouseover(function(e) {
        tooltip = $(this).parent().next();
        tooltip.css({
            left: ($(this).position().left + ($(this).width() / 2)) - (tooltip.width() / 2) + "px",
            top: ($(this).position().top - (tooltip.height() + 10)) + "px"
        })
    }).mouseout(function(e) { tooltip.css("left", "-1000em"); });

    $("a.tooltip.help").attr("title", "").mouseover(function(e) {
        tooltip = $(this).parent().next();
        tooltip.css({
            left: ($(this).position().left + ($(this).width() * 6.5)) - (tooltip.width()) + "px",
            top: ($(this).position().top + 3) + "px"
        })
    }).mouseout(function(e) { tooltip.css("left", "-1000em"); });

}


var ytPlayer;  		// playerapiid
var ytPlayerState; 	// playerstate
function onYouTubePlayerReady (playerId) {
	ytPlayer = document.getElementById("media-video");
	ytPlayer.addEventListener("onStateChange", function(state){
		ytPlayerState = state;
	});
}

/**
 * =x: Product Image Switcher
 */
var pos = 0; // tracks which image is shown - for prod zoom viewer
function prodImgSwitch() {
    $("#related-images a:not('.watch-video, .rotate-360')").click(function() {
        $("#primary-image").attr("src", this.href);
        pos = $(this).parent().prevAll().length;

		// stop video
		if(ytPlayerState == 1) ytPlayer.stopVideo();

		// hide video and 360, show image
		$(".product-video, .product-360").hide();
		$(".product-image").show();
        return false;
    });

    if($(".watch-video").length > 0) {
		// Set the params and embed the video
		var fparams = {allowScriptAccess: 'always'};
		var fvars = {};
		var fattributes = {id: 'media-video'};
    	swfobject.embedSWF(cam.video.url, "media-video", "300", "255", "8", null, fvars, fparams, fattributes);

		// Append the correct instructions
		$(".product-video").append("<p>" + cam.resources.VIDEO_CONTROLS + "</p>");

		$(".watch-video").click(function() {
			// If already playing, don't do anything
			if(ytPlayerState == 1) return false;

			// Hide the product image and 360, show video
			$(".product-image, .product-360").hide();
			$(".product-video").show();
			return false;
		});
    };

    if($(".rotate-360").length > 0) {
    	// Set the params and embed the 360 image
		var fparams = {wmode: 'transparent'};
		var fvars = {};
		var fattributes = {id: 'media-rotate'};
    	swfobject.embedSWF(cam.rotate.url, "media-rotate", "300", "300", "8", null, fvars, fparams, fattributes);

		// Append the correct instructions
		$(".product-360").append("<p>" + cam.resources.ROTATE_360_CONTROLS + "</p>");

		$(".rotate-360").click(function(){
			// If already playing, stop video
			if(ytPlayerState == 1) ytPlayer.stopVideo();

			// Hide the product image, video and show 360
			$(".product-image, .product-video").hide();
			$(".product-360").show();
			return false;
		});
    };
}


/**
 * =x: Product Zoom
 */
function initProductZoom() {
    if($(".product-image").length > 0) {
        $(".product-image").append('<p class="image-zoom"><a href="Javascript:void(0)">' + cam.resources["PRODUCT_DETAIL_ZOOM"] + '</a></p>');
		$(".product-image .image-zoom a").click(function(){launchZoom();updatePrevNextDisplay(); return false;});
		//$(".product-image .image-zoom a").colorbox({width: "500px", height: "500px", inline:true, href:"#nisbets-zoom"});

        $(document.body).append( $("<div class='image-zoom-overlay' style='display: none; width: " + $(document).width() + "px; height: " + $(document).height() + "px;'> </div>"
			+ "<div class='image-zoom-window' id='nisbets-zoom'><p class='close-button'><a href='javascript:void(0);'>" + cam.resources["PRODUCT_DETAIL_ZOOM_CLOSE"] + "</a></p>"
			+ "<div class='zoomed-image'><img src='#' alt='' />"
			+ "<div class='prev-zoomed'><a href='javascript:void(0);'>Previous image</a></div><div class='next-zoomed'><a href='javascript:void(0);'>Next image</a></div></div>"
			+ "</div>")
		);

		$(".image-zoom-window .close-button a").click(function(){hideZoom(); return false;});

        // set alt images if applicable
        relImages = $("#related-images").clone().attr("id", "zoom-related-images");
        $(".image-zoom-window").append(relImages);

		// Remove the video and 360 from the zoom viewer
		$("#zoom-related-images .watch-video, #zoom-related-images .rotate-360").each(function(){
			$(this).parent().remove();
		});

        $("#zoom-related-images a").each(function(i) {
            this.href = imageLinks[i];
        });

		// Bind prev/next buttons
		$(".prev-zoomed a").click(function(){
			pos --;
			$(".zoomed-image img").attr("src", imageLinks[pos]);
			updatePrevNextDisplay();
		});

		$(".next-zoomed a").click(function(){
			pos ++;
			$(".zoomed-image img").attr("src", imageLinks[pos]);
			updatePrevNextDisplay();
		});

        swapZoomedImage();

		$(".image-zoom-overlay, .image-zoom-window").css("opacity", "0");
    }
}

function launchZoom() {
    $(".image-zoom-overlay").css("display", "block").fadeTo("def", 0.6);
    $(".image-zoom-window").css("display", "block").fadeTo("def", 1);

	$(".image-zoom-window").css(
		"top", (($(window).height() - $(".image-zoom-window").outerHeight() ) / 2) + $(window).scrollTop()
	);

    $(".zoomed-image img").attr("src", imageLinks[pos]).css("width", $(".zoomed-image").width());

    // set offsets to work out the 0,0 of the container
    leftOffset = $(".image-zoom-window").position().left - ($(".image-zoom-window").width() / 2);
    topOffset = $(".image-zoom-window").position().top + $(".zoomed-image").position().top;

    // set offset level relative to hmc defined zoom level
    if (zoomLevel == null || zoomLevel < 2) { zoomLevel = 2; }
    var offsetLevel = zoomLevel - 1;

    $(".zoomed-image").mousemove(function(e) {
        // mouse pos and img pos debug
        // $("#status").html("x: " + (e.pageX - leftOffset) + ", y: " + (e.pageY - topOffset) + ", top: " +
        // $(".zoomedImage img").css("top") + ", left: " + $(".zoomedImage img").css("left"));

        // set position of larger image in .zoomedImage using the x/y points and -ive abs. pos.
        // offset level req'd for hmc configured zoom level
        $(".zoomed-image img").css({
            "top": -(e.pageY - topOffset) * offsetLevel,
            "left": -(e.pageX - leftOffset) * offsetLevel
        });
		// Reset when hovered over the prev/ next buttons
		var parent = $(e.target).parent();
		if(parent.hasClass('next-zoomed') || parent.hasClass('prev-zoomed')) {
			$(".zoomed-image img").css({
				"top": "0",
				"left": "0",
				"width": $(".zoomed-image").width()
			});
		}

    }).mouseover(function() {
        // show larger image in place of small
        $(".zoomed-image img").css("width", $(".zoomed-image").width() * zoomLevel);
    }).mouseout(function() {
        // change image back to normal size on mouseout
        // need to change position to be top left again
        $(".zoomed-image img").css({
            "top": "0",
            "left": "0",
            "width": $(".zoomed-image").width()
        });
    });
}

function hideZoom() {
    $(".image-zoom-overlay, .image-zoom-window").fadeTo("def", 0, function() {
        $(".image-zoom-overlay, .image-zoom-window").css("display", "none");
    });
}

function swapZoomedImage() {
    $("#zoom-related-images a").click(function() {
        $(".zoomed-image img").attr("src", this.href);
		pos = $(this).parent().prevAll().length;

		// Set display of prev/nex buttons
		updatePrevNextDisplay();
        return false;
    });
}

/* Update the display of prev/next buttons based on pos */
function updatePrevNextDisplay() {
	if(pos == 0) {
		// Hide prev, show next
		$(".prev-zoomed").fadeOut();
	}
	else if(pos == imageLinks.length -1) {
		// Hide next, show prev
		$(".next-zoomed").fadeOut();
	}
	else {
		// Show both
		$(".prev-zoomed").fadeIn();
		$(".next-zoomed").fadeIn();
	}
}


/**
 * =x: Auto-completion of input fields
 */
function initAutoCompleteSearch() {
    // alert('globalAutoCompleteEnabled: [' + globalAutoCompleteEnabled + ']');
    // Check if the feature is enabled and exit if not
    if (!globalAutoCompleteEnabled)
    {
        return;
    }

    $("#freeText").autocomplete( globalURLPrefix + "AutoCompleteProductSearch.action", {
        width: 260,
        minChars: 3,
        delay: 300,
        max: 100,
        selectFirst: false
    });

    $("#freeText").result(function(event, data, formatted) {
        if (data) {
            location.href = globalURLPrefix + "RedirectAutoCompleteSearch.action?value=" + data[0] + "&id=" + data[1];
        }
    });
}

jQuery.fn.justifyMinHeight=function() {
  var maxHeight=0;
  this.each(function(){
	// console.log(this.className + " " + this.offsetHeight + " maxh:" + maxHeight);
    if (this.offsetHeight>maxHeight) {maxHeight=this.offsetHeight;}
  });
  this.each(function(){
    jQuery(this).css('min-height',(maxHeight + "px"));
    jQuery(this).css('height','auto !important');
    jQuery(this).css('height',(maxHeight + "px"));

    if (this.offsetHeight>maxHeight) {
      jQuery(this).css('min-height',((maxHeight-(this.offsetHeight-maxHeight))+"px"));
      jQuery(this).css('height','auto !important');
      jQuery(this).css('height',((maxHeight-(this.offsetHeight-maxHeight))+"px"));
    }
  });
};

function justifyHeights() {
	$('.address-field-group ul li').justifyMinHeight();
	$('.delivery-row .panel-box .panel').justifyMinHeight();
	$('.payment-row .panel-box .panel').justifyMinHeight();
};

// Perform functions for checkout summary page
function initCheckoutSummary() {
	if(jQuery('body').hasClass('checkout-summary')) {

		// Clone ts & cs boxes - change labels / id's so they link
		var submitClone = $(".checkout-submit").clone().addClass('submit-top');
		submitClone.find('label').attr('for','agree_terms_top');
		submitClone.find('input[type=checkbox]').attr('id','agree_terms_top');
		submitClone.prependTo('#PlaceOrder');

		// Bind input boxes, so both de/select each other
		jQuery('input[type=checkbox]').bind('click',function(){
			// Get checked value (true / false)
			var checked = this.checked ? true : false;
			var orginator = this;

			// Loop over the checkboxes, set checked val to each other one
			jQuery('input[type=checkbox]').each(function(index,checkbox){
				if(orginator != checkbox) jQuery(checkbox).attr('checked', checked);
			});
		});
	}
}

function associateOtherOptionWithOtherField(otherCode, source, target) {

  if ($(source).val() == otherCode){
      $(target).css("margin-top","9px");
      $(target).css("margin-left","210px");
      $(target).show();
  }
  else
    $(target).hide();

  $(source).change(function() {
	if ($(source).val() == otherCode){
	    $(target).css("margin-top","9px");
	    $(target).css("margin-left","210px");
	    $(target).show();
	}
    else
	  $(target).hide();
  });

}

function padding_left(s, c, n) {
    if (! s || ! c || s.length >= n) {
        return s;
    }

    var max = (n - s.length)/c.length;
    for (var i = 0; i < max; i++) {
        s = c + s;
    }

    return s;
}


/**
 * =x: Functions to perform on DOM load
 */
jQuery(document).ready(function() {
    // functions
    camCarousels.init();
    addBasketLink();
    inputTextRemove();
    prodImgSwitch();
    dropdownSubmit();
    initTooltips();
    merchSelectToggle();
    initProductZoom();
    initAutoCompleteSearch();
    justifyHeights();
    initCheckoutSummary();

    // Add generic body class for JS users
    jQuery('body').addClass('has-js');

    /* Block multiple clicks on all forms */
    jQuery("form").submit(function(){
        if(jQuery(this).attr('className') != 'allowmultipleclick')
        {
            if(!jQuery(this).data('submitted')){
                // Set data as not present and return true
                jQuery(this).data('submitted',true);
                return true;
            }
            return false;
        }
        return true;
    });

    // Handle homepage price rollovers
    jQuery(".reduced-price").hover(
    	function () { jQuery(this).addClass('popup');}
    );
    jQuery(".reduced-price").mouseleave(
    	function () { jQuery(this).removeClass('popup');}
    );

    // achieving better look of paging
    jQuery('#listItem').wrap('<div class="white-rounded" />');
    jQuery('.white-rounded').wrap('<div class="light-blue-bgr" />');
    jQuery('.order-det-paging:last').wrap('<div class="border-radius" />');
    jQuery('.pagebanner:last').wrap('<div class="hide" />');

    // Bind colorbox
	jQuery('.panel-box.login .field-note a').colorbox({iframe:true, width: 650, height:450});
	jQuery('a.email-a-friend').colorbox({iframe:true, width: 550, height:650});
	jQuery('.query-link a').colorbox({iframe:true, width: 550, height:650});
	jQuery('.query-link-simple a').colorbox({iframe:true, width: 550, height:650});
	jQuery('.whats-this a').colorbox({iframe:true, width: 550, height:650});
	jQuery('.pop-up-link').colorbox({iframe:true, width: 550, height:650});
	jQuery('.errorMessage a').colorbox({iframe:true, width: 650, height:450});


    // turn on password strength indicator
	jQuery("#pwordStrengthIndicator").css("display", "block");

    // Bind external links
    jQuery('a[rel=external]').attr('target','_blank').attr('title',cam.resources.OPENS_NEW_WINDOW);

    // Bind quickshop table striping
    jQuery(".quickshopTable tr").mouseover(function() {
        jQuery(this).addClass("over");
	}).mouseout(function() {
	    jQuery(this).removeClass("over");
	});

	// Bind inline radio / text field selection for product enquiry form
    jQuery('.inline-radio-text input[type=text]').bind('focus', function(){
        jQuery(this).prev().click();
	});
});
