if( location.search.match(/googleCookie/i) )
{
	alert( "found cookie" );
}


var ie6Below = $.browser.msie && parseFloat($.browser.version) <= 6;

$(function() {
	
	$(".product[href]").click( function() {
		var href = $(this).attr("href");
		location.href = href;
		return false;
	});
	
//	$(".subContent h3 a").each( function(){
	
//		this.href = pageTracker._getLinkerUrl(this.href);
	
//	});
	
	$(".mainContent").find(".newProducts,.bestSellers").each( setupScroller );
	
	$("#searchTerms").focus();
	
    $(".singleProduct .productImage a").click( openImagePopup );
	
	$(".shoppingCartActions :image:not([src*='disabled'])").hover(function() {
		this.src = this.src.replace('_button','_hover');
	},function(){
		this.src = this.src.replace('_hover','_button');
	});
	
	var contactData = {
		Name : {
			required : "Please enter a name"
		},
		Subject : {
			required : "Please enter a subject"
		},
		EmailAddress : {
			required : "Please enter an email",
			regexp : [ /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/,"Please enter a valid email"]
		},
		Message : {
			required : "Please enter a message"
		}
	}
	$("form.contactUs").data("validation",contactData).submit(validationForm);
	
	$(".singleProduct").each(function() {
		$(".description",this).each(renderListItem);
		$('<a href="#back" class="buttonNonAction productBackButton">&lt; Back</a>').click( function() {
			history.back();
			return false;
		}).insertBefore("h1");
	});
	
	
	generatePagination();

	var maxHeight = 0;
	$(".subContent").each( function() {
		if( $(this).innerHeight() > maxHeight )
		{
			maxHeight = $(this).innerHeight();
		}
	}).each( function() {
		$(this).css("padding-bottom", maxHeight - $(this).innerHeight() );
	});
	


	$(".singleProduct .button").click( doAddToCartAjax );

//	$(".breadCrumbs:first").each( setNavFromBreadcrumb );
	$(".subNav .current").parents("li").addClass("current");
	$(".subNav .current > ul").show();

	$(".termsCell").each( setTermsDropDown );

	/* add styles to button that are difficult to get to */
	
	$(".bounceMessage table input,.retrieveConfirm :submit").addClass("button");
	
});

function setTermsDropDown()
{
	var termsDropdown = $(".termsAndConditions" , this );
	$(".mainContent").css("height","auto");
	$(".termsLink span" , this ).replaceWith('<a href="#terms">Terms and conditions</a>');
	$(".termsLink a" , this ).toggle( function() {
		termsDropdown.slideDown();
	},function() {
		termsDropdown.slideUp();
	});
}

function setNavFromBreadcrumb()
{
	var list = $(".subNav > li");
	function setCurrent()
	{
		var text = $.trim($(this).text().replace(/\W*>$/,""));
		$(list).each(function() {
			if( $.trim($("> a",this).text()) == text )
			{
				$(this).addClass("current");
				list = $("> ul > li",this);
				return false;
			}
		});
	}
	$(".link_breadcrumbs" , this).each(setCurrent);
	
}

function doAddToCartAjax()
{
	//return true;
	
	var form = $(this.form);
	$(".validationError" , form).remove();
	var errorPlacement = $(this).parent();
//	form.submit( function() {return false;} );
/*	<span class="actregular">We are sorry, the combination you selected is unavailable at present due to Style_200118 being out of stock.</span>*/
	$.ajax({
		type:"POST",
		data: form.serialize(),
		url: form.attr("action"),
		success:function(html) {
			html = html.match(/<body>([.\s\S]*)<\/body>/i)[0].replace(/(<\/)?script/gi , "$1bogus");
			var errors = $("<div/>").append(html).find(".product .actrequiredcolor,.actregular").filter(":first");
			if( !errors.length )
			{
				location.href = $("#cartLink").val();
			}
			else
			{
				$('<p class="validationError"/>').append(errors).insertBefore( errorPlacement );
			}
		},
		error:function() {
			form.submit();
		}
	});
	return false;
}

function renderListItem()
{
	var el = $(this);
	var html = el.html();
	var list;
	if( list = html.match(/[\*\#][^\*\#]+/g) )
	{
		this.innerHTML = this.innerHTML.replace(/[\*\#][^\*\#]+/g , "");
		list = ('<ul class="description"><li>' + list.join('</li><li>') + '</li></ul>').replace(/[\*\#] ?/g , "");
		el.after( list );
		if( !el.html() ) el.remove();
	}
}

function validationForm()
{
	var valid = true;
	var validation = $(this).data("validation");
	if( !validation ) return true;
	
	$(".validationError" , this).remove();

	for( var v in validation )
	{
		var el = $(this[ v ]);
		var val = $.trim(el.val());
		var message = "";
		
		var errorCheck = validation[v];
		for( var e in errorCheck )
		{
			switch( e )
			{
				case "required" :
					if( !val )
						message = errorCheck[e];
				break;
				case "regexp" :
					if( !errorCheck[e][0].test( val ) )
					{
						message = errorCheck[e][1];
					}
				break;
			}
			
			if( message )
			{
				el.closest(".formRow").before('<p class="validationError">' + message + '</p>');
				if( valid )
				{
					valid = false;
					el.focus();
				}
				break;
			}
		}
	}
	
	return valid;
}

function setupScroller()
{
	var itemsPerPage = 3;
	var scrollContainer = $(this);
	//$(".schoolsGuide").addClass("scroller");

	// Size of visible panel
	var visWidth = $(this).innerWidth();
	
	// Size of school panel (+ margin)
	var items = $("li",this);
	var imgNum = items.length;
	var imgWidth = items.eq(0).outerWidth(true);
	// Set width of schools ul based on number of schools
	var scrollerWidth = imgWidth * imgNum;
	$("ul",this).css("width", scrollerWidth);
	var pageNum = Math.ceil(imgNum / itemsPerPage);

	// Setup Scroller Controls

	var pageNumbering = $('<div class="pageNumbers">Showing <span class="low">1</span> - <span class="high">' + ( imgNum > itemsPerPage ? itemsPerPage : imgNum ) + '</span> of ' + imgNum + '</div>');
	scrollContainer.append(pageNumbering);

	if( pageNum > 1 )
	{
		var blankGifPath = '/acatalog/blank.gif';$("#blankGif").attr("src");
		var leftBut = $('<a href="#previous" class="leftBut lEnd"><img src="' + blankGifPath + '" alt="previous" /></a>');
		var rightBut = $('<a href="#next" class="rightBut"><img src="' + blankGifPath + '" alt="next" /></a>');
		$('<div class="scroller"/>').append( scrollContainer.find("ul") ).appendTo( scrollContainer );
		scrollContainer.append(leftBut, rightBut);

		var currPage = 1;

		leftBut.add(rightBut).click(function(evt) {

			if (this.className.match(/.End/)) return false;

			var direction = (!this.className.match(/rightBut/)) * 2;

			scroll(currPage - direction);
			return false;
		});
		
		function scroll(clickIndex)
		{
			var margin = itemsPerPage * imgWidth * clickIndex;
			
			var low = (itemsPerPage * clickIndex) + 1;
			var	high = itemsPerPage * (clickIndex + 1);
			
			if( clickIndex == 0 ) {
				leftBut.addClass("lEnd");
				rightBut.removeClass("rEnd");
			}
			else if( clickIndex == (pageNum - 1) ) {
				rightBut.addClass("rEnd");
				leftBut.removeClass("lEnd");
				high = imgNum;
			}
			else {
				leftBut.removeClass("lEnd");
				rightBut.removeClass("rEnd");
			}

			scrollContainer.find("ul").animate({ marginLeft: -margin }, 500);
			currPage = clickIndex + 1;
			$(".low",scrollContainer ).text(low);
			$(".high",scrollContainer ).text(high);
			
		}
		
	}
	
}

function openImagePopup()
{
    var el = this;
    
    var img = new Image();
    
    img.onload = function() {
        
        var winHeight = $(window).height() * 0.8; // 2/3 height
        var winWidth = $(window).width() * 0.8;// 2/3 width.
        var imgHeight = img.height;
        var imgWidth = img.width;
        
        if( imgWidth > winWidth )
        {
            img.width = winWidth;
            img.height = img.width*imgHeight/imgWidth;

            imgHeight = img.height;
            imgWidth = img.width;
        }
        
        if( imgHeight > winHeight )
        {
            img.height = winHeight;//abitrary height.
            img.width = img.height*imgWidth/imgHeight;
        }
        
        showOverlay( $('<div class="imageFrame"/>').append(img) );
    };
    
    img.onerror = function() {
           
    };  
    
    img.src = el.href;
    return false; 
    
}

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 ];
}

function showOverlay( html , keepContentWhenRemove ) {

    var popup = null;

    if( keepContentWhenRemove && showOverlay.html )
    {
        html = showOverlay.html;
    }

    displayPanel(html);

    function removePopup() {
        popup.fadeOut("slow", function() { $(this).add(".popFrame").remove(); });
        $(window).unbind("scroll");
        return false;
    }

    function displayPanel(html) {
        popup = $('<div id="overlayPopup" class="popup"></div><div class="overlay"><a class="popupClose" title="Close window" href="#"><span>Close window</span></a><div class="popupContent" /></div>').hide().css("display", "none");
        popup.filter(".popup").css("opacity", "0.5").click( removePopup );
        var popupContent = popup.find(".popupContent").append(html);
        
        showOverlay.html = popupContent.html();

        $("body").append(popup);

        popup.eq(1).width( popup.eq(1).width() );

        popup.eq(1)
            .css("margin-left" , -popup.eq(1).width()/2 )
            .find(".popupClose")
            .css("float","right")
            .click( removePopup );

        popup.fadeIn();

        var offsetTop = ($(window).height() - popup.eq(1).height())/2;
        
        if (ie6Below) {

            popup.css("position","absolute").eq(1).css({ top: (getScrollXY()[1] + offsetTop)}).end().eq(0).height(document.body.scrollHeight);
            $(window).bind("scroll", function() {
                popup.eq(1).stop().animate({ top: getScrollXY()[1] + offsetTop }, 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 {
            popup.get(1).style.top = offsetTop + "px";
        }
    }

    return false;
}

function generatePagination()
{
    var RESULTSPERPAGE = 5; // constant for results on a page
	var PAGINATIONSHOWN = 3; // MAKE ODD NUMBER. constant for how many pages to show in the control panel
	var paginationMiddle = Math.ceil(PAGINATIONSHOWN/2);
    /* get all result divs and store in a var */
    /* Need to hide the results but not the page. Can't have a fixed height on the scroller as it can change size */
    var container = $(".products");
	var results = $(".product",container);

    var totalResults = results.length; // var to hold integer for all results
    
    /* if there are more results than should be on the page AND there already isn't pagination (booking engine and site search) then start the process */
    if( !(totalResults > RESULTSPERPAGE && !$(".pagination").length) ) {container.find("ul").show();return false;}

//	results.filter(":gt(" + RESULTSPERPAGE + ")").
	var hash = location.hash.match(/#page-([0-9]+)$/);
	var currentPage = hash ? hash[1]*1 : 0;

    /* Set the total pages needed based on the total results and the results per page */
    var totalPages = Math.ceil(totalResults / RESULTSPERPAGE );
    
    /* create the page holder and page scroller, add to page and set to local variable */
    container.append('<div class="searchPages"/>');

    var width = container.width(); // width is based on the available space in the tabBox div. Better than hard-coding
	
    var scroller = $('<div class="searchPageScroller"/>');
    
    /* set the scroller width */
    scroller.width(width*totalPages);
    scroller.css("margin-left",-currentPage*width);
    /* create the container pages that the results will be appended to, then append the results to the correct page */
    var pages = [];
    for( var p=0;p<totalPages;p++)
    {
        pages[pages.length] = $('<ul class="searchPage" id="page' + p + '"/>').width(width-10).appendTo(scroller);
    }        
    
    results.each( function(i) {
        var currPage = Math.floor(i/RESULTSPERPAGE);
		if( currPage != currentPage )
		{
			$(this).hide();
		}
		
		pages[currPage].append(this);
        // .append( results.filter(":gt(" + (p*RESULTSPERPAGE-1) + "):lt(" + ((p+1)*RESULTSPERPAGE) + ")"))
    });
    pages = null;       

	container.find("ul").remove();
	
    $(".searchPages").append(scroller);
    /* closure (internal function) for generating the HTML for the pagination controls */
    function getPaginationHTML()
    {
        var page = []; // array to hold the string parts
        
        /* Previous page control */
        if( currentPage == 0 )
        {
//            page[page.length] = '<span class="pageNav">&#171; first</span>';
            page[page.length] = '<span class="pageNav pagePrevious">&#171; previous</span>';
        }
        else
        {
//            page[page.length] = '<a page="0" href="#" class="pageNav">&#171; first</a>';
            page[page.length] = '<a page="' + (currentPage-1) + '" href="#" class="pageNav pagePrevious">&#171; previous</a>';
        }
        
        /* Text that says 'Page' */
        page[page.length] = '<span class="pageText">Page</span>';
        
        /* Control for each page */

		function drawPageNumber(i)
		{
			if( currentPage == i )
            {
                page[page.length] = '<span class="pageNumber">' + (i+1) + '</span>';
            }
            else
            {
                page[page.length] = '<a page="' + i + '" href="#" class="pageNumber">' + (i+1) + '</a>';
            }
		}

		drawPageNumber(0);

		var startPagination = currentPage >= paginationMiddle && totalPages > PAGINATIONSHOWN + 2 ? (totalPages - 1 - paginationMiddle <= currentPage ? totalPages - 1 - PAGINATIONSHOWN : currentPage - paginationMiddle + 1 ) : 1;
		var endPagination = totalPages > PAGINATIONSHOWN + 2 ? startPagination + PAGINATIONSHOWN : totalPages - 1;
		
		if( startPagination > 1 && totalPages > PAGINATIONSHOWN + 2 )
		{
			page[page.length] = '<span class="pageText">...</span>';
		}
		
        for( var x = startPagination;x<endPagination;x++)
        {
			drawPageNumber(x);
        }

		if( endPagination < totalPages - 1 && totalPages > PAGINATIONSHOWN + 2 )
		{
			page[page.length] = '<span class="pageText">...</span>';
		}
		
		drawPageNumber( totalPages - 1 );
		
//        page[page.length] = '<span class="pageText">of ' + totalPages + '</span>';
        
        /* Next page control */
        if( currentPage == totalPages-1 )
        {
            page[page.length] = '<span class="pageNav pageNext">next &#187;</span>';
//            page[page.length] = '<span class="pageNav">last &#187;</span>';
        }
        else
        {
            page[page.length] = '<a page="' + (currentPage+1) + '" href="#" class="pageNav pageNext">next &#187;</a>';
//            page[page.length] = '<a page="' + (totalPages-1) + '" href="#" class="pageNav">last &#187;</a>';
        }

        return page.join(""); // join the string and return it
    }

    /* create the page controls and the holder for the controls, then set the click event
       If the target of the click is a page control then scroll to the appropriate page
       and regenerate the page controls. Not sure whether there is more of a hit creating the HTML
       or with setting the page control logic */


	$('<p class="pagination">' + getPaginationHTML() + '</p>')
		.click( function(e) {
		if( $(".searchPageScroller:animated").length ) return false; // don't do anything if animation has already started
		var el = e.target; // who clicked me?
		
		/* if there is a page attribute then scroll to the new page */
		if( $(el).attr("page") ) 
		{
			scroller
				.height($("#page"+currentPage).outerHeight(true)) // set the height for the duration of the scroll
				.find(".searchPage .product").show(); // show all of the previously hidden results

			currentPage =  $(el).attr("page")*1; // get the new page
					$(".pagination").html(getPaginationHTML()); // regenerate the pagination
			
//                if( !ie6Below ) {scroller.animate({opacity:0.5},{ queue:false, duration:200 });} // Fadeout the pages (visual touch) but don't let ie6 do the fadeout
			scroller.animate({marginLeft:-currentPage*width,height:$("#page"+currentPage).outerHeight(true)},800,function(){ // scroll to the current page, setting the height
					$(this) // when finished :
						.find(".searchPage[id!='page" + currentPage + "'] .product").hide() // - find and hide the results not showing
						.end().height(""); // go back to the scroller and remove the height
				});
//                if( !ie6Below ) {scroller.animate({opacity:1},200,function(){$(this).css("opacity","");});} // Fade the pages back in, but not ie6
			location.hash = "#page-"+currentPage;
		}
		return false;
	}).insertBefore(container).clone(true).insertAfter(container);
		
}

function setGoogleCookieData( inputElement , googleCookie )
{
	
//	alert(googleCookie);

//	alert(googleCookie);
	
	var val = inputElement.value.replace(/&$/,"");
	inputElement.value = val + ( val.match(/\?/) ? "&" : "?" ) + googleCookie;
	
}
	
function setWorldPayGoogleValues()
{
	if( window.isPSPBounce ) // This is set on the psp buonce page. the one before the rbs worldpay pages
//	if( document.forms["formOCC"] )
	{
//		var form = document.forms["formOCC"];
//		var googleCookie = pageTracker._getLinkerUrl("FAKEURL").replace("FAKEURL?" , "");
		//googleCookie = escape(googleCookie.replace(/&/gi , "AMPERSAND").replace(/=/gi,"EQUALS")).replace(/AMPERSAND/gi,"&").replace(/EQUALS/gi , "=");
//		googleCookie = "googleCookie=" + escape(googleCookie);
//		setGoogleCookieData( form["CALLBACKURLAUTH"]  , googleCookie);
//		setGoogleCookieData( form["CALLBACKURLBACK"]  , googleCookie );
//		setGoogleCookieData( form["CALLBACKURLUSER"]  , googleCookie );
//		var input = document.createElement("input");
//		input.type = "hidden";
//		input.name = "MC_gacookie";
//		input.value = pageTracker._getLinkerUrl("FAKEURL").replace("FAKEURL?" , "");
//		form.appendChild( input );
		
//		form["USERDEFINED"] = input.value;
		
		$(document.forms["formOCC"]).submit(function(){
			pageTracker._trackPageview('/shopping/psp site');
		});
		
	}
}

