﻿/*
Edited: 01 July 2009 ((A Keats @ 14:14)
Website: http://leisure.ordnancesurvey.co.uk/leisure/
Created: 22 February 2008
Author: Henry Tapia

*/


/*Window size function*/
window.size = function()
	{
	var w = 0;
	var h = 0;

	//IE
	if(!window.innerWidth)
		{
		//strict mode
		if(!(document.documentElement.clientWidth == 0))
		{
			w = document.documentElement.clientWidth;
			h = document.documentElement.clientHeight;
		}
		//quirks mode
		else
		{
			w = document.body.clientWidth;
			h = document.body.clientHeight;
		}
	}
	//w3c
	else
		{
			w = window.innerWidth;
			h = window.innerHeight;
		}
	return {width:w,height:h};
}

/*
NOTE: These scripts are based on jQuery 1.2.3
*/
$(document).ready(function(){
	function setTextFields(elementToSet, changeElement) {
		elementToSet = $(elementToSet);
		changeElement = $(changeElement);
		if (elementToSet.length) {
			var fieldText = elementToSet.val();
			elementToSet.focus(function(){
 				if (elementToSet.val()==fieldText ) elementToSet.val('');
				if (changeElement) { (changeElement).addClass('active'); }
			});
			elementToSet.blur(function(){
				if (!elementToSet.val()) { elementToSet.val(fieldText); }
				if (changeElement) { changeElement.removeClass('active'); }
			});
		}
	}
	setTextFields('#map-search .textfield:not(".no-change")','#map-search');	// 1st value is a CSS selector for the input field, 2nd is an element to toggle an "over" class on
	setTextFields('#map-search-super .textfield:not(".no-change")','#map-search');	// 1st value is a CSS selector for the input field, 2nd is an element to toggle an "over" class on
	setTextFields('#header-search .textfield:not(".no-change")','#header-search');
	
	setTextFields('#os-select-search .textfield:not(".no-change")','#os-select-search');
	
});

// Add .first and .last to list items
$(document).ready(function(){
	$("li:first-child").addClass("first");
	$("li:last-child").addClass("last");
});

//remove bottom bit of basket rounded box if the basket is hidden
$(document).ready(function(){
    var hideBasket = false;
    if(location.pathname.length < 9)
    {
        // don't want to cause an error here by getting a substring of something not long enough.
        return;
    }
    if(location.pathname.substring(0, 9).toLowerCase() == "/checkout")
    {
        hideBasket = true;
    }
    if(location.pathname.length >= 18)
    {
        if(location.pathname.substring(0, 18).toLowerCase() == "/checkout/register")
        {
            hideBasket = false;
        }
    }
});

// make the whole basket clickable
$(document).ready(function(){
	
	function makeBasketClickable(basket) {
		var basketLink = $(basket).find("dt a").attr("href");
		var basketTitle = $(basket).find("dt a").attr("title");
		$(basket).css("cursor","pointer");
		$(basket).attr("title", basketTitle);
		$(basket).click(function() {
			window.location = basketLink;
		});
	}

	makeBasketClickable("#shopping-basket");	// a CSS selector for the basket element
});


// turn buttons with class "linkbutton" into a text link
$(document).ready(function(){
 
	$(".linkbutton").each(function() {
		var btn = this;
		$("<a></a>").attr("href","#").attr("title",btn.title).attr("class","").append(this.value).css("display","inline").bind("click", function() {
			btn.click() 
		}).insertBefore(this)
		$(this).hide();             
	});

});

// Create zebra (stripey) tables, unordered lists and definition lists
$(document).ready(function(){
	$("table.zebra tr:even").addClass("alt");
	$("ul.zebra>li:even").addClass("alt");
	$("dl.zebra dt:even").addClass("alt");
	$("dl.zebra dd:even").addClass("alt");
});

// turn a UL grid into a series of self-clearing ULs that behave like table rows
/*
Requires:
- ul.row style defined in CSS if borders are required
- "clearfix"
- you may need to add some styles for ".gridRow", "ul.gridRow" and "ul.gridRow li"

Just put in a selector and the number of columns in the "makeGridList" call at the end.
*/
$(document).ready(function() {

	function makeGridList(element, numCols) {
		if (!$(element).length) {
			return;
		}
		$("<div class='gridRowHolder'></div>").insertAfter(element); 	// a container for the new ULs

		$(element).children("li").each(function(i) {

			$(this).css("min-height", "0"); 	// get rid of min-height
			if (i % numCols == 0) {
				$("<ul class='clearfix gridRow'></ul>").appendTo($(this).parents().find("div.gridRowHolder")[0]);
			}
			$(this).clone().appendTo($(this).parents().find("div.gridRowHolder > ul:last")[0]);

		});
		$(element).remove(); // remove the original UL
		$("ul.gridRow li:last-child").css("margin-right", "0"); // gets rid of any right margin on the last item of each row
	}

	makeGridList(".results ul.gridList", 2); // 1st argument is a selector for the original UL, the 2nd is the number of columns in the grid
	makeGridList(".results ul.gridList2", 2);
	makeGridList(".sitemap ul.sm-products", 5);

});

// split a UL with class="cols" into multiple 
/*
Requires:
- "clearfix"
- "col" style defined in CSS with width, float, etc

Just put in a selector and the number of columns in the "multiColList" call at the end.
Each separate list needs its own function call with a unique selector
*/
$(document).ready(function(){

	function multiColList(element, numCols) {

		var colItems = Math.ceil($(element).find("li").length / numCols);

		$("<ul class='col'></ul>").insertAfter(element);		// new UL

		$(element).children("li").each(function(i) {

			$(this).clone().appendTo($(element).parent().children("ul.col:last"));
			if (i == colItems - 1) {
				$("<ul class='col'></ul>").insertAfter($(element).parent().children("ul.col:last"));
			}
		});
		$(element).remove();	// remove the original UL
	}

	multiColList("#shop-footer ul.cols", 2);	// 1st argument is a selector for the original UL, the 2nd is the number of columns
	//multiColList("#browse-products ul.cols", 2); // no longer needed

});

// options panel show/hide
$(document).ready(function(){

	$(".paging a.view-options").click(function(){
	  $(this).parents(".paging").contents(".options").slideToggle("normal");
	  $(this).toggleClass("active");
	  if ($(this).text() == "View options") {
		$(this).text("Hide options");
	  } else {
		$(this).text("View options");
	  }
	  return false;
	});

	// Create close button
	$(".paging .options").append('<p class="close"><a title="Close options panel" href="#">Close</a></p>');
	$('.close', '.paging .options').click(function(){
		$(this).parents(".paging").contents().find("a.view-options").toggleClass("active").text("View options");
		$(this).parents(".paging").contents(".options").slideUp("normal");
		return false;
	});

});

// dynamically load jquery.idTabs.pack.js then set up idTabs for product list page
$(document).ready(function(){

	if ( $(".browse-products").not("#shop-footer .browse-products").length > 0 ) {
		//$.getScript("/Assets/Global/Scripts/jquery.idTabs.min.js", function(){
            $(".browse-products").idTabs(function(id,list,set){
				$(".product-list-paging a",set).removeClass("active") 
				.filter("[@href='"+id+"']",set).addClass("active"); 
				for(i in list) 
					$(list[i]).hide(); 
				$(id).slideDown("fast"); 
				return false;
			}); 
        //});
    }

});
// invoke idTabs functionality from links inside another tab
$(document).ready(function(){
	if( $('.os-select').length ){
		$('.os-select div#preview div.container a[@href^="#map"]').click(function(){
			$('ul.tabs a[@href='+ $(this).attr('href') +']').click();
			return false;
		});
	};
});
// create map reference overlays that appear when search results are moused over 
$(document).ready(function(){
	// create overlay element
	$("<div id='map-overlay'></div>").insertAfter("#mapbutton");

	// assign hover behaviours and positions
	$("#main a[@rel^='map-hover']").each(function(i) {

		// get the x and y values from the rel string
		var overlayX = $(this).attr("rel").substring(10, $(this).attr("rel").length).replace(/^x(\d+)y\d+$/ig,"$1");
		var overlayY = $(this).attr("rel").substring(10, $(this).attr("rel").length).replace(/^x\d+y(\d+)$/ig,"$1");

		// add the hover behaviours and reference number
		$(this).hover(function() {
			$("#map-overlay").css({ 
				"display":"block", 
				"left":(overlayX - 10)+"px", 
				"top":(overlayY - 10)+"px"
			});
			$("#map-overlay").text(i+1);
		}, function() {
			// $("#map-overlay").css("display","none");
		});
	});
});

// dynamically load jquery.highlightFade.js then apply yellow fade to alerts
function alertHighlight(element) {
	if ( $(".alert").length > 0 ) {
		//$.getScript("/Assets/Global/Scripts/jquery.color.js", function(){
			//setTimeout(function(){
				$(".alert").animate({backgroundColor:"#FAF8E2"}, 1000);
			//}, 2000);
		//});
    }
}

function ApplicationLoadHandler() {
		Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded);
}

function pageLoaded(sender, args) {
	alertHighlight(".alert");
}

$(document).ready(function(){
	 alertHighlight(".alert");
	 try {
		Sys.Application.add_load(ApplicationLoadHandler);	// Animate alerts generated by .NET partial page reloads
	} catch (e){}

});

// show/hide options in the checkout
$(document).ready(function(){

	$("#stored-addresses p.change").wrapInner("<a href='#'></a>");		// turn the heading into a link
	$("#stored-addresses p.change a").click(function() {
		$("#stored-addresses .address-book").slideToggle("fast");		// create the toggle behaviour
		return false;
	});

	$("#payment-details .card-type").change(function(){
		if (($("#payment-details select.card-type option:selected").text() == "Maestro") || ($("#payment-details select.card-type option:selected").text() == "Switch") || ($("#payment-details select.card-type option:selected").text() == "Solo")) {
			$("#payment-details #card-options").slideToggle("fast");
		} else {
			$("#payment-details #card-options").hide();
		}
	});
});

//injecting default text into the textarea on delivery page
$(document).ready(function() {
	var detailsExample = $('p', '#additional-details');
	var detailsEntryArea = $('textarea', '#additional-details');
	//if (detailsExample.length && (detailsExample.text().length > -1) && detailsEntryArea.length) 
	detailsEntryArea.val(detailsExample.text());
	detailsExample.hide();
	//}
});
// show/hide selector for alternative billing addresses in payment page
$(document).ready(function(){

$(".stored-billing-addresses p.change").wrapInner("<a href='#'></a>");
 	// hide the div intitally
 	$(".stored-billing-addresses .billing-addresses").hide();
 	// turn the heading into a link
 	$(".stored-billing-addresses p.change a").click(function() {
		$(".stored-billing-addresses .billing-addresses").slideToggle("fast");		// create the toggle behaviour
		return false;
	});
});

// apply "ifixpng" PNG transparency fix for IE6
$(document).ready(function(){
//#sidebar.category, .js-enabled #super-nav #super-nav-head, .js-enabled #super-nav #super-nav-content, .js-enabled #gazetteerresults .summary p.summary, .js-enabled #gazetteerresults div.list , /*.js-enabled #super-nav #super-nav-content*/
	$.ifixpng('/Assets/OrdnanceSurvey/Images/pixel.gif');
	$('img[@src$=.png], input[@src$=.png], #map-overlay, .js-enabled #super-nav #super-nav-content, .js-enabled #gazetteerresults div.list').ifixpng();

});

// password fields disallow whitespaces
$(document).ready(function(){
	$(".textfield[@type=password]").keypress(function(e) {
	    var charCode = e.charCode || e.keyCode; //fixed browser incompatability issue
      	    if(charCode==32){ // if key pressed is spacebar      	         
                 return false;
      	    }
	});
});

// OS Select behaviours
$(document).ready(function(){

	// set up idTabs
	if ( $(".os-select #preview").length > 0 ) {
		$(".os-select #preview ul.tabs").idTabs({
			click: function(id, panels, tabs) {
				$("li.active", tabs).removeClass("active");
				$("li:has(a[@href=" + id + "])", tabs).addClass("active");
				return true;
			} 
		}); 
    }

	// make the "personalise" button work in OS Select
	$(".os-select #options .continue a").click(function(){
		$(".os-select #preview .tabs a[@href='#map-cover']").click();
		return false;
	}); 

	// show "personalise" options when cover editor is open
	$(".os-select #preview .tabs li a").click(function(){
		if ($(this).attr("href") == '#map-cover') {
			$(".os-select #options .map-options").hide();
			$(".os-select #options .map-cover").css("position", "static");
		} else {
			$(".os-select #options .map-options").show();
			$(".os-select #options .map-cover").css("position", "absolute");
		}
	});

	// Set cover image background colour
	if ($(".os-select #options select.map-type option:selected").text().indexOf("Explorer") != -1) {
		$(".os-select #cover").addClass("explorer");
	}
	if ($(".os-select #options select.map-type option:selected").text().indexOf("Landranger") != -1) {
		$(".os-select #cover").addClass("landranger");
	}
	
	// Cover image selector
	$(".os-select #preview .cover-images li input[@checked]").parent("li").find("label").addClass("active");		// apply "active" class to selected option

	$(".os-select #preview .cover-images li").css("height","67px");	// lock vertical height on the list items
	$(".os-select #preview .cover-images li input").hide();		// hide labels
	$(".os-select #preview .cover-images li label").prepend("<span></span>");		// add span in each label with background image set to the same as the image element

	var unselectedLabelTitle = $(".os-select #preview .cover-images li label[@title!='This is the image you have selected']").attr("title");		// get the default title for the labels

	$(".os-select #preview .cover-images li label").click(function(){
		$(this).parent().eq(0).siblings().children("label").attr("title", unselectedLabelTitle).removeClass("active");		// reset titles and classes on all labels
		$(this).attr("title","This is the image you have selected").addClass("active");		// change title and add "active" class
	});
	
	// this addresses the IE bug where images within labels do not trigger a click on their associated form inputs.
	$(".os-select #preview .cover-images li img").click(function(){
		$(this).parent().eq(0).siblings("input").attr("checked","checked");
	});
	

	// Cover image selector live preview
	$(".no-JS").hide(); // hide no JavaScript message

    //
    // update title on preview
    //
	$(".os-select #options .title").keyup(function () {		// .title keystroke listener
		var value = $(this).val();
		if(titleRegexValidation(value)) // only update if valid characters
		{
    		$("#cover .titles h2").text(value);
    	}
	}).keyup();
	
	$(".os-select #options .title").change(function () {		// .title keystroke listener
		var value = $(this).val();
		if(titleRegexValidation(value)) // only update if valid characters
		{
    		$("#cover .titles h2").text(value);
    	}
    	else
		{
    		$("#cover .titles h2").text(""); //blank the text if invalid
    	}
	}).change();
	

    //
    //update sub-title on preview
    //
	$(".os-select #options .subtitle").keyup(function () {		// .subtitle keystroke listener
		var value = $(this).val();
		if(titleRegexValidation(value)) // only update if valid characters
		{
		    $("#cover .titles h3").text(value);
		}
	}).keyup();

	$(".os-select #options .subtitle").change(function () {		// .subtitle keystroke listener
		var value = $(this).val();
		if(titleRegexValidation(value)) // only update if valid characters
		{
		    $("#cover .titles h3").text(value);
		}
		else
		{
		    $("#cover .titles h3").text("");
		}
	}).change();
		
	
    //
	// Validation for title and sub-title boxes.  Uses regex to test if valid on keyup.
	//
	$(".map-cover input.title, input.subtitle").keyup(function(e) {
	    var charCode = e.charCode || e.keyCode; //fixed browser incompatability issue
	    if(charCode!=13)
	    { // if key pressed is not enter
	        var enteredText = $(this).val();
	        if(!titleRegexValidation(enteredText))
	        {
                 $(this).nextAll().filter('.errMsg').eq(0).slideDown("fast"); //show error message
                 $(".map-cover .continue input.button-strong").attr("disabled", "disabled"); //disable add to basket button
                 e.preventDefault();
                 return false;
	        }
	        else
	        {
	            $(this).nextAll().filter('.errMsg').eq(0).slideUp("fast"); //hide error message
	            $(".map-cover .continue input.button-strong").removeAttr("disabled"); //enable add to basket button
	        }
	    }
	    else
	    {
            // if enter is pressed scroll error message up if down else do nothing.
            $(this).nextAll().filter('.errMsg').eq(0).slideUp("fast"); //hide error message
            e.preventDefault();
            return false;
	    }
	
	});
	

	$(".map-cover input.title, input.subtitle").change(function(e) {
        var enteredText = $(this).val();
        if(!titleRegexValidation(enteredText))
        {
             $(this).nextAll().filter('.errMsg').eq(0).slideDown("fast"); //show error message
             $(".map-cover .continue input.button-strong").attr("disabled", "disabled"); //disable add to basket button
             e.preventDefault();
             return false;
        }
        else
        {
            $(this).nextAll().filter('.errMsg').eq(0).slideUp("fast"); //hide error message
            $(".map-cover .continue input.button-strong").removeAttr("disabled"); //enable add to basket button
        }
	});

	
	// for IE to scroll up error message when delete is pressed
	$(".map-cover input.title, input.subtitle").keydown(function(e) {
	    if(e.keyCode == 8) $(this).nextAll().filter('.errMsg').eq(0).slideUp("fast"); //hide error message
	});
});


function titleRegexValidation(inputString) {
    return new RegExp("^([a-z]|[A-Z]|[0-9]|[ÀàÁáÂâÃãÄäÇçÈèÉéÊêËëÌìÍíÎîÏïÑñÒòÓóÔôÕõÖöŠšÚùÛúÜûÙüÝýŸÿŽž; ,}:_={+'\.\"-]|[)(]|[\\[\\]])*$").test(inputString);
}


// show dynamic elements - corresponding with items in hide.css
$(document).ready(function(){
	$('#main .browse-products').css('display', 'block');
	$('.os-select #preview #map-centre').css('visibility', 'visible');
});

//pop up
$(document).ready(function(){
	function popThisLink(link, winWidth, winHeight){
		if ($(link).length) {
			$(link).each( function() {
				leftPos = (screen.width) ? (screen.width-winWidth)/2 : 0;
				topPos = (screen.height) ? (screen.height-winHeight)/2 : 0;
				dimensionDetails = 'width='+winWidth+',height='+winHeight+',left='+leftPos+',top='+topPos;
				function popUp(){
				popUpWindow = window.open(linkHref,'popup',dimensionDetails);
				return false;
				};
				$(this).click( function() {
					linkHref = $(this).attr('href');
					popUp();
					return false;
				});
			});
		};
	};
	popThisLink('a.zoom', '640','660');
});

// pop up close window button
$(document).ready(function(){
	function closeAndRefocus (elementToClick) {
		if ($(elementToClick).length){
			if (window.opener){// checks for existance of a previous window that has opened the current window
				$(elementToClick).click( function (){
					self.close();
					//window.opener.focus();
					return false;
				});
			};
		};
	};
	closeAndRefocus('input#return');
});


//refactor the following two into a function later

$(document).ready(function() {
	// custom drop down
	var gazArea = $('#gazetteerresults');
	var gazResults = gazArea.find('ol');
	if (gazResults.length) {
		$('.summary p.summary', '#gazetteerresults').click(
			function(e) {
				$('.summary p.summary', '#gazetteerresults').toggleClass('active');
				$('.list', '#gazetteerresults').toggleClass('active');
				e.stopPropagation();
				$('body').click(
					function() {
						$('.summary p.summary', '#gazetteerresults').removeClass('active');
						$('.list', '#gazetteerresults').removeClass('active');
						$('body').unbind('click');
				});
			}
		);
	}

});


//tabbed pagination on shop by location - this is in an update panel, so slightly more complicated!
jQuery(function() { 
	if ($.browser.msie) {
		$('.star-rating.interactive').each(function() {
			new StarRating(this);
		});
		$('input.textfield', '.mapproduct .add-to-basket, .snowandrockproduct .add-to-basket').each( function() {
			$(this).numericUpDown();
		});
		emailAFriendTrigger();
		initTabs();
		initReport();
	}
	Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(partialPostback);
});

//Bind tell a friend anchor to button
function emailAFriendTrigger() {
	var triggerButton = $('.email', '#right');
	var targetButton = $('.link-button', '#right');
	if (triggerButton.length && targetButton.length) {
		triggerButton.click(function() {
			targetButton.click();
		});
	}
}

//tell friend overlay
function tellFriendCloseOverlay() {
	var tellFriendOverlay = $('#tell-a-friend.overlay');
	if (!tellFriendOverlay.length){return;}
	$('#tell-a-friend a.close').click(function() {
		$.browser.msie ? tellFriendOverlay.css('display', 'none') : tellFriendOverlay.fadeOut(800);
		return false;
	});
}

// Star Rating
function StarRating(element, selectElement) { // used for Write a Review

  var elementW    = jQuery(element).width(),            // star-rating element
    offsetLeft    = jQuery(element).offset().left;
    ratingElement = jQuery('.rating', element).eq(0),       // empty stars element
    dropdown      = selectElement || jQuery(element).siblings().find('select'),
    currentStep   = 0,
	starWidth	  = 22,
    selectedStep  = jQuery('option:selected', dropdown).val() || 0,
    setDisplayedStarRating = function(rating) {
		jQuery(ratingElement).attr('class', 'rating is-' + rating );
    };
    
  if (dropdown.length == 0) { // don't continue if the select element is not present
    return false;
  };

  jQuery(element).hover(function() {
  
  }, function() {
    //jQuery(ratingElement).attr('class', 'rating is-' + selectedStep );
    setDisplayedStarRating(selectedStep);
  });

  jQuery(element).click(function() { 
    selectedStep = currentStep; // store the rating the user selects
    jQuery('option', dropdown).eq( selectedStep ).attr('selected', 'selected'); // set the dropdown so the rating will be posted back to the server
  }).css('cursor', 'pointer'); 

  jQuery(element).mousemove(function(e) {
    var pos = e.clientX - offsetLeft + (starWidth / 2);

    currentStep = Math.round( (pos / elementW) * 100 / 20 );  // calculate number of stars out of 5
    jQuery(ratingElement).attr('class', 'rating').addClass('is-' + currentStep); // set the class to show the number of stars
	setDisplayedStarRating(currentStep);
  });
  
  setDisplayedStarRating(selectedStep);

  return element;
}

// initiate tabs on product details page
function initTabs() {
	if ( $("ul.tabs", "#content.product-details").length) {
		function runTabs(){
			$(".preview").idTabs(function(id,list,set){
				$(".tabs a",set).removeClass("active").filter("[@href='"+id+"']",set).addClass("active"); 
				for(i in list) 
					$(list[i]).hide(); 
				$(id).fadeIn("fast"); 
				return false;
			});
				
			function linkToTabBinder(link, tabsContainer, scrollContext) {
				linkObj = $(link);
				if (!linkObj.length){
					return false;
				}
				var hashLocation = linkObj.attr('href').indexOf('#');
				linkObj.hrefAfterHashStr = linkObj.attr('href').substring(hashLocation);
				var targetLinkObj = $('a[href="' + linkObj.hrefAfterHashStr + '"]', tabsContainer);
				scrollContext = scrollContext || null;
				if (targetLinkObj.length) {
					linkObj.click( function(){
						targetLinkObj.click();
						if (scrollContext) {
							var scrollContextObj = $(scrollContext);
							var scrollVal = scrollContextObj.offset().top;
							$('html,body').animate({scrollTop: (scrollVal - 40)}, 500);
							return false;
						} else {
							return false;
						}
					});
				}
			}
			
			linkToTabBinder('#right .reviews a','.tabs ','#main .preview');
			linkToTabBinder('#right a.size-guide-link','.tabs ','#main .preview');
			linkToTabBinder('#target-links li:first-child a','.tabs ','#main .preview');
			linkToTabBinder('#target-links li:last-child a','.tabs ','#main .preview');
				
			/*if ($('a','#right .reviews').length && $('a[href="#reviews-faq"]','.tabs ').length) {
				//var reviewsLink = $('a','#right .reviews');
				var hashLocation = reviewsLink.attr('href').indexOf('#');
				var reviewsLink.hrefAfterHashStr = reviewsLink.attr('href').substring(hashLocation);
				var scrollVal = $('.preview', '#main').offset().top;
				reviewsLink.click( function(){
					$('a[href="#reviews-faq"]','.tabs ').click();
					//window.scrollTo(0, (scrollVal - 40));
					$('html,body').animate({scrollTop: (scrollVal - 40)}, 500);
					return false;
				});
			}*/
		}
		
		//if ($.fn.idTabs) {
			runTabs();
		//} else {
			// get the scripts and then invoke the function using the callback
			//$.getScript("/Assets/Global/Scripts/jquery.idTabs.min.js", runTabs);
		//}
	}
}

//binding the submit button to an ajax post to submit the report
function initReport() {
	var initReportLink = $('a.report-a-review', '#reviews');
	var reportOverlayEl = $('#report-a-review.overlay');
	$('#report-a-review.overlay .inner a.close').removeData('events');
	if (!initReportLink.length) {return;}
	//initReportLink.reportReview({overlay: reportOverlayEl});
	initReportLink.reportReview({overlay: reportOverlayEl});
	//unbind the idTabs from the close button in overlay;
	$('a.close','#report-a-review.overlay').click( function(){
		$('#report-a-review.overlay').hide();
		return false;
	});
}

function partialPostback(event, args) {
	$('.star-rating.interactive').each(function() {
		new StarRating(this);
	});
	$('input.textfield', '.mapproduct .add-to-basket, .snowandrockproduct .add-to-basket').each( function() {
		$(this).numericUpDown();
	});
	emailAFriendTrigger();
	initTabs();
	initReport();
	function hitReviewsTab() {
		$('.tabs li a[@href="#reviews-faq"]', '#main .preview').click();
	}
	if ((event._postBackSettings != null) && (event._postBackSettings.sourceElement.value == "Write a review")){ 
		setTimeout(hitReviewsTab, 500);
	}
	// Add .first and .last to list items
	$("li:first-child").addClass("first");
	$("li:last-child").addClass("last");
	if (args._panelsUpdated.length > 0 && (typeof(addthis) != "undefined")){
		//reinitialise the AddThis buttons
		addthis.toolbox(".addthis_toolbox");
	}
	if (args._panelsUpdated.length > 0){
		tellFriendCloseOverlay();
	}
};


//the super nav
$(document).ready(function() {
	if ($('#super-nav-head', '#super-nav').length) {
		if ($.browser.msie && (parseInt($.browser.version, 10) < 7)) {
			function ie6ResetPreRender() {
				$('#super-nav-content', '#super-nav').css('visibility', 'visible').removeClass('active');
			}
			$('#super-nav-content', '#super-nav').css('visibility', 'hidden').addClass('active');
			setTimeout(ie6ResetPreRender, 300);
		}
		$('#super-nav-head', '#super-nav').click(
   			function() {
   				$(this).toggleClass('active');
   				if ($('.cb', '#super-nav').length) {
   					$('.cb', '#super-nav').toggleClass('active');
   				}
   				$('#super-nav-content', '#super-nav').toggleClass('active');
   			}
   		);
	}
});

// retrieving static content from the basket page
$(document).ready(function() {
	if ($('.delivery a', '.checkout #main ').length) {
		var xmlCollected = false;
		var overlay = $('<div/>'); //
		var closeLink = $('<a class="close" href="#"/>');
		closeLink.text('Close');
		overlay.attr('id', 'overlay');
		overlay.append(closeLink);
		overlay.append('<div/>');
		overlay.children('div').addClass('inner');
		overlay.appendTo('#content.checkout');
		closeLink.click(function() {
			$.browser.msie ? overlay.css('display', 'none') : overlay.fadeOut(800);
			return false;
		});
		$('.delivery a', '.checkout #main ').click(function() {
			if (!xmlCollected) {
				$.ajax({
					type: "GET",
					url: "/Content/Interwoven/OrdnanceSurvey/en/help/delivery.xml",
					dataType: "xml",
					success: function(xml) {
						$(xml).find('contentArea[name!="Sidebar"]').each(function() {
							var content_text = $(this).text();
							overlay.children('div.inner').append(content_text);
							xmlCollected = true;
						});
					},
					error: function() {
						window.location = $('.delivery a', '.checkout #main ').attr('href');
					}
				});
			}
			$.browser.msie ? overlay.css('display', 'block') : overlay.fadeIn(800);
			return false;
		});
	}
});

//getting the category highlighting to work for ie6
$(function() {
	if ($.browser.msie & $.browser.version < 7 ) {
	var categories = ['home', 'paper-maps','digital-maps','navigation-and-gps','road-and-street-atlases','leisure-guide-books','wall-maps','historical-maps'];
	var currentTopLevel = $('#category-navigation').attr('class');
	var position = $.inArray(currentTopLevel, categories);
	$('#category-navigation li').eq(position).addClass('current');
	}
});

//mirroring checkbox ticking on Checkout/Review.aspx

$(document).ready(function() {
    var checkboxes = $("input[type=\"checkbox\"][name=\"terms\"]");
    checkboxes.click(function() {
        var errorSummary = $("#ctl00_MainContent_ErrorAndValidationSummary");
        if ($(this).is(":checked")) {
            checkboxes.attr("checked", "checked");
            errorSummary.hide();
        }
        else {
            checkboxes.removeAttr("checked");
            errorSummary.show();
        }
    });
});



/*
$(function() {

});
*/
