 //add a js class to the top element (<html>) to assist CSS rules and prevent FOUC
document.documentElement.className = 'js'; 

//********************************************************************************************
//** Run on document ready
//********************************************************************************************
$(function () {
  // Pick a sample class of an advert and test if the adblocker has been applied
  if ($('.rightColBanner336x280').height() == 0) {
      // AD BLOCKER IS ON
      setTimeout("DocumentReady();", 1000);
  } else {
      // AD BLOCKER IS OFF
      setTimeout("DocumentReady();", 0);
  }
});

//********************************************************************************************
//** Code that previously resided in the document ready function
//********************************************************************************************
function DocumentReady() {	
	// Pick up extra fields so they can be used in below script
	/* 
	var customField = $("#newsletterDetails .dqslevel1 div");
	var appendFields = "<fieldset class=\"dqs_tree level1 Manual\"><ul>"
	
	i = 0;
	customField.each(function(){
		if((i < customField.length -1) && (i != 0)){
			var label = $(this).find("label");
			var input = $(this).find("input");
	
			input.each(function(){
				inputType = $(this).attr('type');
				if(inputType != "hidden"){
					appendFields += "<li>"				
					inputID = $(this).attr('id');
					appendFields += "<input id=\""+inputID+"\" type=\""+$(this).attr('type')+"\" value=\""+$(this).attr('value')+"\" name=\""+$(this).attr('name')+"\">"
					inputLabel = $(this).parent().find("label");
					inputLabel.each(function(){
						if($(this).attr('for') == inputID){
							appendFields += "<label>"+$(this).html()+"</label>"
						}
					});
					appendFields += "</li>"
				}
			});
		}
		i++;
	});

	appendFields += "</ul></fieldset>"
	$("#newsletterDetails .dqslevel1").find("div:first").append(appendFields);

	// make up for the not so good markup from alchemetrics
	// account details tab

	var b = $('#accountDetails div.formButton');
	b.each(function() {
		var t = $(this);
		t.addClass('actions');
		var i = t.find('input');
		i.wrap('<div class="inline invert"><span></span></div>');
	});
	
	// newsletter tab
	var f = $('#newsletterDetails fieldset.dqs_tree');
	var c = $('#newsletterDetails div.columns');
	var form = $('#newsletterDetails form');
	if (c.length == 0) {
		c = $('<div class="columns"></div>');
	}
	form.append(c);
	
	// var g = $('#newsletterDetails > ul.group_select');
	// if (g.length == 0) {
	// 	g = $('<ul class="group_select">'
	// 			+ '<li><input type="radio" value="select" id="select_all" name="all">'
	// 			+ '<label for="select_all">Select all</label></li>'
	// 			+ '<li><input type="radio" value="deselect" id="deselect_all" name="all">'
	// 			+ '<label for="deselect_all">Deselect all</label></li>'
	// 			+ '</ul>');
	// 	form.append(g);
	// }
	
	var l = $('<div class="leftCol"></div>');
	var r = $('<div class="rightCol"></div>');
	
	var Manual = $('<div class="fullCol"></div>');
	//var rightManual = $('<div class="rightCol"></div>');
	
	var manualCount = 0;
	
	
	var orderLeft = [true, false, false, true];
	f.each(function(cnt) {
		var select = $('<ul class="group_select">'
						+ '<li><input type="radio" value="select" id="select_all_' + cnt + '" name="all' + cnt + '">'
						+ '<label for="select_all_' + cnt + '">Select all</label></li>'
						+ '<li><input type="radio" value="deselect" id="deselect_all_' + cnt + '" name="all' + cnt + '">'
						+ '<label for="deselect_all_' + cnt + '">Deselect all</label></li>'
						+ '</ul>');
		var t = $(this);
		var checkCount = t.find(':checkbox').length;
		
		//alert(checkCount);
		if (checkCount>1){
			t.find('legend').append(select);
		}


		// Added this to keep the Order displaying correctly. 		
		if(cnt>3){
			orderCnt = cnt-4;
		}else{
			orderCnt = cnt;
		}
		
		inputs = t.find("label");
		
		inputs.each(function(){
			returnString = t.children("legend").html() + " - " + $(this).html();
			formatHtml = $(this).html()+"";
			index = t.children("legend").html();
			if(!(index === null)){
				index = index.split("<");
				if(formatHtml == "&nbsp;"+index[0]){
					$(this).parent("li").addClass('topLevel');
				}
			}
		});

		var childFind = t.children("ul").attr('id').indexOf("level2");
		if(childFind < 0){
			t.children("ul").children("li").children("ul").children("li").children("ul").parent("li").addClass('hasChildren');
			childBranch = t.children("ul").children("li").find("ul");
			childBranch.each(function(){
				$(this).addClass("child");
			});
			childCount = t.children("ul").children("li").children("ul");
		}
		var children = $(".child").children("li");
		children.each(function(){
			$(this).children("ul").addClass("child");
		});
		var manualFind = t.attr('class').indexOf("Manual");
		if(manualFind < 0){
			if (orderLeft[orderCnt]) {
				l.append(t);
			} else {
				r.append(t);
			}
		}else{
			Manual.append(t.children('ul'));
			manualCount++;
		}
	});
	c.append(l).append(r);
	if(manualCount != 0){
		var manualSplitter = '<div class="manualSplitter">Supplementary Newsletters<ul class="manual_select">'
						+ '<li><input type="radio" value="select" id="select_all_manual" name="allmanual">'
						+ '<label for="select_all_manual">Select all</label></li>'
						+ '<li><input type="radio" value="deselect" id="deselect_all_manual" name="allmanual">'
						+ '<label for="deselect_all_manual">Deselect all</label></li>'
						+ '</ul></div>';
		c.append(manualSplitter).append(Manual);
		var manualSelect = $(".manual_select").find('input');
		var manualCheck = $(".fullCol").find('input:checkbox');
		manualSelect.each(function(){
			var val = $(this).val();
			$(this).click(function(){
			if(val == "select"){
				manualCheck.each(function(){
					$(this).attr('checked', true);						  
				});
			}else{
				manualCheck.each(function(){
					$(this).attr('checked', false);						  
				});
			}
						   });
		});
	}

	var a = $('#newsletterDetails div.actions');
	a.parent().css({ display: 'none'});
	c.after(a);	
	 */
	
	$("input#location_include").focus(function () { 
  		$(this).val(""); 
  	}).blur(function() { 
		if ($(this).val() == "") { 
			$(this).val($(this)[0].defaultValue); 
		} 
	}); 

	//Carousel functionality begin
	var carousel = $("div.carousel").carousel({
		nextBtnInsert: "appendTo",
		prevBtnInsert: "appendTo",
		nextBtn: "<span>&nbsp;</span>",
		prevBtn: "<span>&nbsp;</span>",
		effect: "fade",
		launchOnLoad: function (o) {$(o).css({'visibility':'visible', 'position':'relative'});}
	});

	//The carousel items are made invisible in a way that their height can be calculated
	//See subsectionteaser.vm
	//Carousel functionality end

	// adds last child to last li in footerlinks to remove last bar on footer links
	$("#footerLinks li:last-child").addClass("last-child"); 

	// resizes editorials image
	jQuery('img.editorialSectionImg').each(function(){
		var image = jQuery(this);
		
		var maxWidth = 595;
		var maxHeight = 422;
		var w = image.width();
		var h = image.height();

		if ((w > h && w <= maxWidth) && h <= maxHeight) {
			return;		//check if the resizing is needed
		}

		var link = jQuery('<a class="imageWrapper" href="#resize-image"><span class="resizeIcon"></span></a>');
		image.before(link);
		
		var expand = function() {
			link.addClass('fullImage');
			image.animate({width: w + 'px', height: h + 'px'}, 'fast');
		};
		
		var collapse = function() {
			link.removeClass('fullImage');
			image.animate({width: w/2 + 'px', height: h/2 + 'px'}, 'fast');	
		};

		link.click(function(e) {
			if (link.hasClass('fullImage')) {
				collapse();
			} else {
				expand();
			}
			e.preventDefault();
		});
		
		link.prepend(image);
		collapse();
	});
			
	// set full display if the rightcolum is empty
	$('.newsSectionRight').each( function() {
	 	if ($(this).children().length == 0) {
			$(this).width('0px');
			$(this).parent().find('.newsSectionLeft').width('97%');
		}
   	});
	
	// set full display if the rightcolum is empty
	$('.editorialSectionRight').each( function() {
	 	if ($(this).children().length == 0) {
			$(this).width('0px');
			$(this).parent().find('.editorialSectionLeft').width('97%');
		}
   	});

	/* Divide up the menu items, and if there are more than 5 align the drop down navigation to the right of the menu item. 
	This will prevent the menu hanging over the right hand side of the site, and potentially going off screen. 
	Steve Judge - 15/02/2011 */ 
	var count = 0; 
	$('ul.primaryNav li').each(function(){
		pClass = $(this).parent().attr("class");
		
		if(pClass=="primaryNav"){
			count++;
			if(count>5){
				$(this).find('div.navContainer').addClass('navContainerRight');	
			}
		}
	});
	//display secondary and tertiary navigation
	$('ul.primaryNav li').hover(function(){
		var colWidth = 161;
		var maxCols = $(this).find('.secondaryNav').length;

		var minWidth = 250;
		var leftpadd = 5;
		var leftpaddTotal = maxCols * leftpadd;

		var numCols = $(this).find('div ul li').length - $(this).find('div ul ul li').length;
		
		if(numCols > maxCols){
			$(this).children('div.navContainer').width(colWidth * maxCols + leftpaddTotal);
			$('ul.secondaryNav').width(colWidth);
		} else {
			$(this).children('div.navContainer').width(colWidth * numCols + leftpaddTotal);
			if($(this).children('div.navContainer').width(colWidth * numCols + leftpaddTotal) < minWidth ){
				$(this).children('div.navContainer').width(minWidth + leftpaddTotal);
			}
		}
		$(this).children('div.navContainer').show();

		/* If the navContainer is aligned right, and has a lot of sections, it can go off the left side of the screen in smaller resolutions. 
		This fix works out how far is spills out, and brings it back inline with the left side of the screen. 
		Steve Judge 12/09/2011 */
		var offset = $(this).children('div.navContainer').offset();
		if(offset.left<-15){
			$(this).children('div.navContainer').css("right", offset.left+"px");
		}
		var maxnavContainerHeight = 0
		$(this).find('ul.secondaryNav').each(function() {
			var thisHeight = $(this).height();
			if (thisHeight > maxnavContainerHeight) {
				maxnavContainerHeight = thisHeight;
			}
		});
		$(this).find('ul.secondaryNav').height(maxnavContainerHeight);
	}, function(){
		$(this).children('div.navContainer').hide();
	});
	
	// Default Search Text
	//var searchText = "Search Site";
	var searchText = getQuerystring("freeTextQuery", "Search Site")
	$("#frm-search-term").val(searchText);
	//var searchText = $("#frm-search-term").val();
	
	$("#frm-search-term").focus(function(){
		$(this).val("");
	});
	
	$("#frm-search-term").blur(function(){
		if($(this).val()!=""){
			searchText = $(this).val();
		}else{
			$(this).val(searchText);
		}
	});	 	  			 
	// hide sponsered pannel onload
	$('.tabPanelSponsor').hide();

	//tabpanel functionality begin
	$('#searchtab2').click(function(){
		$('.tabPanelSponsor').show();
	}); 
	
	// finds the tallest height and returns it in px
	function findHighest(el) {
		var height = 0;
		el.each(function() {
			var h = $(this).height();
			if ( h > height) {
				height = h;
			}
		});
		
		if(height>0){
			el.css("height", height);
		}
		//return height;
	}
	
	function setTabPanelHeight(){
		var heightArg = arguments[1];
		var panels = arguments[0] || $('.tabPanels');
		panels.each(function() {
			var c = $('.tabContent', this);
			if(typeof heightArg !== 'undefined'){
				c.css('height', heightArg);
			}
			else{
				findHighest(c)
				//c.css('height', findHighest(c));
			}
		});
	}
	setTabPanelHeight();
	//tabpanel functionality end
	
	//toggles areas where there is a list of links
	//USAGE: class 'toggle' is added to the parent container for the list of links
	//links are expected to have a bookmark link going to the ID of the element to be shown/hidden
	//e.g. <a href="#foo">Show foo</a> ... <div id="foo">foo</div>
	function getBookmarkedElem(link){
		if(link.href.indexOf('#') === -1){return false;}
		var elem_id = link.href.substring(link.href.indexOf('#')+1);
		return $('#'+elem_id);
	}
	function setupTogglers(){
		var togglers = $('.toggle a');
		togglers.each(function(){
			var toggling = getBookmarkedElem(this);
			if(toggling.hasClass('selected')){return;}
			toggling.hide();
		});
		togglers.click(function(event){
			event.preventDefault();
			var target = $(this);
			var el = this;
			if(target.hasClass('inactive')){return;}
			if(target.parent().hasClass('selected')){return;}
			var allTogglers = target.parents('.toggle').find('a').each(function(){
				if(el === this){return;}
				getBookmarkedElem(this).removeClass('selected').hide();
				$(this).parent().removeClass('selected');
			});
			var toggling = getBookmarkedElem(this);
			toggling.show().addClass('selected');
			target.parent().addClass('selected');
		});
		
		
		var selected = window.location.hash.split("?")[0];
		if (selected) $('.toggle a[href*=' + selected + ']').click();
	};
	setupTogglers();
	//end toggling
	
	//select/deselect all
	//requires 2 radios, 1 with value select, nested in an element with class group_select
	//elements to be checked/unchecked should be nested in the same fieldset
	function setGroupSelection(){
		var triggers = $('.group_select input:radio');
		if(triggers.length === 0){return;}
		triggers.click(function(e){
			var elem = $(this);
			var isCheckAll = (elem.val() === 'select') ? true : false;
			var topLevel = (elem.closest('fieldset').length > 0) ? elem.closest('fieldset') : elem.closest('form');
			var inputs = topLevel.find('input:checkbox');
			if(isCheckAll){
				inputs.attr('checked','checked');
			}
			else{
				inputs.removeAttr('checked');
			}
			//topLevel.find('.group_select input[value='+elem.val()+']').attr('checked','checked');
			topLevel.find('#' + elem.attr('id')).attr('checked','checked');
		});
	}
	setGroupSelection();
	//end select/deselect all
	
	//nested newsletter options
	//where a newsletter checkbox has nested sub-options, these should be checked/unchecked to match the parent
	function newsletterSubs(){
		var allCheckboxes = $('#newsletterDetails input:checkbox');
		if(allCheckboxes.parent().find('ul').length > 0){
			allCheckboxes.click(function(e){
				var isChecked = this.checked;
				$(this).parent().find('ul input:checkbox').attr('checked',isChecked);
			});
		}
	}
	//newsletterSubs();
	//end nested newsletter options
	
	//add in CAPTCHA functionality
	function setupCaptcha(){
		if(typeof Recaptcha === 'undefined'){return false;}
		$('#captcha_getNew').click(function(e){Recaptcha.reload();e.preventDefault();});
		$('#captcha_getAudio').click(function(e){Recaptcha.switch_type('audio');e.preventDefault();})
		$('#captcha_getImage').click(function(e){Recaptcha.switch_type('image');e.preventDefault();});
		$('#captcha_getHelp').click(function(e){Recaptcha.showhelp();e.preventDefault();});
	};	
	setupCaptcha();
	
	function generateUID(jElem){
		var uid_prefix = 'uid_';
		var uid_index = 1;
		var uid = uid_prefix + uid_index;
		while($('#'+uid).length > 0){
			uid_index++;
			uid = uid_prefix + uid_index
		}
		return uid;
	}
	//override tab panel height where there is a twitter feed due to load times
	function setupTwitterFeed(){
		var twitterLink = $('.twitterLink');
		if(twitterLink.length === 0){return;}
		twitterLink.each(function(){
			var jElem = $(this);
			if(jElem.parents('.tabContent').length > 0){
				setTabPanelHeight(jElem.parents('.tabPanels'), 'auto');
			}
		});
		
	};
	setupTwitterFeed();
		
	// Concertina functionality begin
		$.ajax({
		type: "GET",
		url: "/ajax?action=advertisers&siteKey=" + siteKey + "&businessCount=10",
		dataType: "xml",
		success: function(xml) {
			var items = $(xml).find('item');
			var output = '';
			items.each(function(){
				var hdr = $(this).find('title').text();
				var bdy = $(this).find('body').text();
				var lnk = $(this).find('link').text();
				output = output + '<div><h4 style="margin:0px;"><a href="'+lnk+'">'+hdr+'</a></h4><p style="margin:1px 0px 10px;"><a href="'+lnk+'">'+bdy+'</a></p></div>';
			});
			$('#advertisers').append(output);

			var itemsPerPage = 5;
			$('#advertisers div').hide();
			$('#advertisers div').slice(0,itemsPerPage).show();

			if(items.length > itemsPerPage){
				$('#pager').append('<ul></ul>');
				var pages = Math.ceil(items.length/itemsPerPage);
				for(var i=0;i<pages;i++){
					$('#pager ul').append('<li><a href="#"> '+(i+1)+' </a></li>');
				}
				$('#pager ul li a').click(function(){
					$('#pager ul li a').removeClass('active');
					$(this).addClass('active');
					var i = parseInt($(this).html()) - 1;
					$('div#advertisers div').hide();
					$('div#advertisers div').slice(i*itemsPerPage,(i+1)*itemsPerPage).show();
					return false;
				});
				$('#pager ul li:first a').addClass('active');
			}
		},
		error: function(){}
	});

	// Open default concertina
	$('div.concertinaContent:first').slideDown(700);

	// Add dynamic functions to headers
	$('div.concertinaPanel h3.concertinaHeading').click(function(){
		$('.concertinaContent').slideUp(700);
		$(this).next(".concertinaContent").slideDown(700);
	})

	// Ticker functionality begin
	$('#tickerContainer').show();
	var options = {
		newsList: "ul#news",
		startDelay: 10,
		loopDelay: 3000
	}

	// Uncomment the line below if news ticker items are hard coded in HTML
	$().newsTicker(options);

	//read XML News Data begin
	/*$.ajax({
		type: "GET",
		url: "/assets/xml/news.xml",
		dataType: "xml",
		success: function(xml) {

			//$('<ul id="news"></ul>').appendTo('body');
			$('#tickerContainer').append('<ul id="news"></ul>');
			$(xml).find('item').each(function(){
				var desc = $(this).find('title').text();
				var link = $(this).find('link').text();
				$('<li><a href="'+link+'">'+desc+'</a></li>').appendTo('ul#news');
			});
			$().newsTicker(options);
		}
	});*/
	//read XML News Data end
	//ticker functionality end

	// print
    $('#sharePrint').click(function(e) {
		window.print();
		e.preventDefault();
    });

	var q = 'a.report, #showWeather, #shareEmail';
	$(q).click(function(e) {
		var id = $(this).attr('id');
		var c = $(this).attr('class');
		var popUps = {
			showWeather: 'popupWeather',
			shareEmail: 'popupSendToAFriend',
			report: 'popupReportComment'
		};
		if (typeof popUps[id] !== 'undefined') {
			$('div.popup').hide();
			openPopup(popUps[id]);
		} else if (typeof popUps[c] !== 'undefined') {
			openPopup(popUps[c]);
		}
		e.preventDefault();
	});

	//Image gallery functionality
	$('.galleryThumbImg').click(function(){
		var thumbSrc = $(this).attr('src');
		var mainSrc;
		mainSrc = thumbSrc.replace('_135','_578');
		$('#galleryMainImg').attr("src",mainSrc);
	});

	// concertinas
	if ( $("#carSearchFrm").length > 0 ) {
		loadMakes();
		$('#make').change(function(){
			$("#model").empty();
			loadModels($(this).val());
		});
	}
	concertinaShowPropertyPriceRange();
	$("#propertySearchFrm input[name=buyRent]").change(function(){
		concertinaShowPropertyPriceRange();
	});

	$('#localSearchFrm button').click(function(){
		performLocalPagesSearch();
		return false;
	});
	$('#jobSearchFrm button').click(function(){
		performJobSearch();
		return false;
	});
	
	$('#carSearchFrmww button').click(function(){
		performVerticalCarSearch();
		return false;
	});
	
	$('#carSearchFrm button').click(function(){
		performCarSearch();
		return false;
	});
	$('#propertySearchFrm button').click(function(){
		performPropertySearch();
		return false;
	});

	// basic form validation
	$('form button.primaryBtn,form input.primaryBtn,#sendToAFriendFrm button.secondaryBtn, #reportCommentFrm button.secondaryBtn').click( function(){
		var $form = $(this).parents('form');
		if (validateForm($form)) {
			closePopup();
			return true;
		} else return false;
	});

	/*
	Fix styling issued with JavaScript
	*/
	
	// split layout into two columns and paginate when needed
	if (window.noSplit === undefined)
	{
	var sections = jQuery('div.newsSection');
	sections.each(function() {
		var section = jQuery(this);
		var articles = jQuery('div.newsArticle', section);
		
		// check to see if a right column element exists... if it does then don't split
		var newsImageModule = $(this).children(".newsSectionRight").children(".newsImageModule");
		var newsModule = $(this).children(".newsSectionRight").children(".newsModule");
		var newsVid = $(this).children(".video");
		var exists = newsImageModule.length + newsModule.length + newsVid.length;
		
		if((exists != 0) && (articles.length < 6)){
			//don't split
		}else{
			// minimum articles to split into two columns
			var l = articles.length;
			if ( l > 1) {		
				var preserve = 0;		//number of articles to keep as one column
				var sec = $(this).children('div.newsSectionRight');
				// get the element height including the margin
				var h = sec.outerHeight() + parseInt(sec.css('margin-top')) + parseInt(sec.css('margin-bottom'));
				var el = jQuery(articles[0]);
	
				// article section margin
				var offset = parseInt(el.css('margin-top')) + parseInt(el.css('margin-bottom'));
	
				if (h) {
					var headline = jQuery('h1.mainHeadline');
					var ah = (headline.length == 0 )? 0 : headline.outerHeight() + parseInt(headline.css('margin-top')) + parseInt(headline.css('margin-bottom'));
	
					// check article height and determine which ones to preserve
					articles.each(function(cnt) {
						var el = jQuery(this);
						ah += el.outerHeight() + offset;
	
						if ( (ah > h) && (h > 20) && (exists !=0) ) {
							preserve = cnt + 1;
							return false;
						}
					});
				}
				
				//this is to preserve the 1st video before splitting
				var vid = $(this).children(".newsArticle").children(".video");
				if (vid.length != 0){
					preserve = 1;
				}
	
				var articles_count = l-preserve;
				if (articles_count > 40) {
					var pages = parseInt(articles_count/20);
					pages = (articles_count % 20 > 0)? pages + 1: pages; 
					var index_counter = preserve;
					var counter = jQuery('<ul></ul>');
					var pWrapper = jQuery('<div class="paginate"></div>');
					var pageReport = jQuery('<p>Page <span>1</span> of <span>' + pages +  '</span></p>');
					pWrapper.append(pageReport);
					var activePage = 1;
					for (var cnt = 1; cnt <= pages; cnt++) {
						var page_closure = function() {
							var pageid = cnt;
							var lc = jQuery('<div class="leftColumn"></div>');
							var rc = jQuery('<div class="rightColumn"></div>');
							var w = jQuery('<div class="wrapperColumn" id="content-' + cnt + '"></div>').append(lc, rc)
							var chunk = articles.slice(index_counter, index_counter + 20);
							var link = jQuery('<a href="#leftContent">' + cnt + '</a>');
							// var link = jQuery('<a href="#' + ((cnt == 1)? 'leftContent' : 'content-' + cnt) + '"><span>Page</span> ' + cnt + '</a>');
							link.smoothScroll({afterScroll: function() {
								var top_section = jQuery('div.newsSectionLeft div.newsArticle, div.newsSectionRight');
								if (pageid == 1 ){
									top_section.show();
								} else {
									top_section.hide();
								}
								activePage = pageid;
								if(activePage === pages){
									next.hide();
								}
								else{
									next.show();
								}
								if(activePage === 1){
									prev.hide();
								}
								else{
									prev.show();
								}
								pageReport.find('span:eq(0)').text(activePage);
								jQuery('li', counter).removeClass('selected');
								link.parent().addClass('selected');
								jQuery('div.wrapperColumn').hide();
								w.show();
							}});
							
							counter.append(link);
							link.wrap('<li/>');
							chunk.each(function(cnt) {
								if (cnt < 10) {
									lc.append(jQuery(this));
								} else {
									rc.append(jQuery(this));
								}
							});
							index_counter += 20;
							section.append(w);
							var lch = lc.height();
							var rch = rc.height();
							w.css({
								height: ((lch > rch)? lch : rch) + 'px'
							});
							if (cnt !==1) w.css({display: 'none'});
						};
						page_closure();
					}
					section.append(pWrapper.append(counter));
					jQuery('li:first', counter).addClass('selected');
					var prev = jQuery('<li class="previous"><a href="#previous">Previous</a></li>');
					prev.hide();
					var next = jQuery('<li class="next"><a href="#next">Next</a></li>');
					var gotoPage = function(step) {
						if (activePage + step < 1) {
							step = 1;
						} else if (activePage + step > pages ) {
							step = pages;
						} else {
							activePage += step;
						}
						jQuery('li:eq(' + activePage + ') a',counter).trigger('click');
					};
					
					prev.click(function(e) {
						gotoPage(-1);
						e.preventDefault();
					});
					next.click(function(e) {
						gotoPage(1);
						e.preventDefault();
					});
					
					counter.prepend(prev).append(next);
					// articles.hide();
				} else {
					var lc = jQuery('<div class="leftColumn"></div>');
					var rc = jQuery('<div class="rightColumn"></div>');
					var w = jQuery('<div class="wrapperColumn"></div>').append(lc, rc)
					
					var leftCount = Math.round((l-preserve)/2);
					// var rightCount = (l-preserve) - leftCount;
					articles.each(function(cnt) {
						if (cnt < preserve) {
							return;
						}
						if ((cnt - preserve) < leftCount) {
							lc.append(jQuery(this));
						} else {
							rc.append(jQuery(this));
						}
					});
					section.append(w);
					var lch = lc.height();
					var rch = rc.height();
					w.css({
						height: ((lch > rch)? lch : rch) + 'px'
					});
				}
			}
		}
	});
	}
	
	// remove empty paragraphs - it's adding unecessary gap under gallery image
	jQuery('div.newsSectionRight p.newsArticleBobyTxt').each(function() {
		var h = jQuery(this);
		if (typeof h.innerHtml == 'undefined') {
			h.hide();
		}
	});
	
	// This small code snippet runs the annual date change for the copyrite notice in the footer.
	var currentYear = (new Date).getFullYear();	
	$("#copyDate").text( (new Date).getFullYear() );
		
	
	//Tommys Search Results code                
	//Apply slider links
	$(".filterCategories h2, .filterContentType h2, .filterAuthors h2").prepend("<a href='#'>More...</a>");
	
	//Get original ul heights and convert them to ems, then give each a unique id
	var filterHeights = new Array();
	var miniHeights = new Array();
	$(".filterCategories ul, .filterContentType ul, .filterAuthors ul").each(function(i) {
																					  
		//Set the Default height for the desired filters
		var defaultHeight = "auto";
		if( ($(this).find("li").length) > 5 ){
			defaultHeight = "8.3333em";
		}else{
			$(this).prev().find("a").css("display","none");
		}
		var theHeight = $(this).height();
		var FontSize = parseInt($(this).css("font-size"));
		var theHeightEm = (1 / FontSize) * theHeight;
		var roundedHeightEm = parseFloat(theHeightEm).toFixed(4) + "em";
		filterHeights[i] = roundedHeightEm;
		miniHeights[i] = defaultHeight;
		$(this).attr("id",i);
		$(this).css({"height":defaultHeight,"overflow":"hidden"});
	});
	
	//Slide to the original heights and back
	$(".filterCategories h2 a, .filterContentType h2 a, .filterAuthors h2 a").toggle(function(){
		var ulID = $(this).parent().next().attr("id");								 
		$(this).parent().next().animate({
			height: filterHeights[ulID]
		}, 1000, function() {
			// Animation complete.
		});
	},function(){	
		var ulID = $(this).parent().next().attr("id");
		$(this).parent().next().animate({
			height: miniHeights[ulID]
		}, 1000, function() {
			// Animation complete.
		});
	});
};

//********************************************************************************************
//** Loads makes.... presumably
//********************************************************************************************
function loadMakes(){
	$.ajax({
		type: "GET",
		url: "/assets/xml/makes.xml",
		dataType: "xml",
		success: function(xml) {
			$(xml).find('make').each(function(){
				var val = $(this).attr('id');
				var make = $(this).text();
				$('<option value="'+val+'">'+make+'</option>').appendTo('select#make');
				if($(''))
				{
				}
			});
		}
	});
};

//********************************************************************************************
//** Loads models.... presumably
//********************************************************************************************
function loadModels(id){
	$.ajax({
		type: "GET",
		url: "/assets/xml/models.xml",
		dataType: "xml",
		success: function(xml) {
			$('<option value="">Any Model</option>').appendTo('select#model');
			$(xml).find('model').each(function(){
				var val = $(this).attr('id');
				var make = $(this).attr('manufacturerid');
				var model = $(this).text();
				if(val >= 0 && make == id){
					$('<option value="'+val+'">'+model+'</option>').appendTo('select#model');
				}
			});
		}
	});
};

//********************************************************************************************
//** Validates the form on submit ?
//********************************************************************************************
function validateForm ($form) {
	
	$(':input:not(button)', $form).each( function(){
		var valid = false;

		switch(this.id){
			
			case 'password':
			case 'newPassword':
				valid = this.value && this.value != '' && this.value.length > 5;
				break;
			case 'confirm':
				var newPswd = $(':input#password', $form).attr('value');
				if (newPswd && newPswd != '' && newPswd.length > 5) {
					valid = this.value == newPswd;
				}
				break;
			case 'confirmPassword':
				var newPswd = $(':input#newPassword', $form).attr('value');
				if (newPswd && newPswd != '' && newPswd.length > 5) {
					valid = this.value == newPswd;
				}
				break;
			case 'terms':
				valid = this.checked;
				break;
			default:
				valid = this.value && this.value != '';
				
				if ($(this).hasClass('optional') && !valid) {
					valid = true;
				} else if (this.id == 'email' || $(this).hasClass('email')) {
					var regex = /^([a-zA-Z0-9_\-\.\'\!\#\$\%\&\*\+\/\=\?\^\{\|\}\~]+)@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,3})$/;
					valid = regex.test(this.value);
				} else if ($(this).hasClass('postcode')) {
					var regex = /^((([A-PR-UWYZ](\d([A-HJKSTUW]|\d)?|[A-HK-Y]\d([ABEHMNPRVWXY]|\d)?))\s*(\d[ABD-HJLNP-UW-Z]{2})?)|GIR\s*0AA)$/;
					valid = regex.test(this.value.toUpperCase());
				} else if ($(this).hasClass('phone')) {
					var regex = /^(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4})|((\+353\s?\d{2}|\(?0\d{2}\)?)\s?\d{3}\s?\d{4})|((\+353\s?\d{2}|\(?0\d{2}\)?)\s?\d{2}\s?\d{5}))(\s?\#(\d{4}|\d{3}))?$/;
					valid = regex.test(this.value);
				} else if ($(this).hasClass('website')) {
					var regex = new RegExp ('^(http[s]?://|ftp://)?(www\.)?[a-zA-Z0-9-\.]+\.(biz|ca|co|co.uk|com|com.au|edu|eu|gov|ie|info|ltd.uk|me.uk|mil|mobi|name|net|net.uk|org|org.uk|plc.uk|sch.uk|tel|tv)$');
					valid = regex.test(this.value);
				}
			
				break;
		}

		if (this.id != '') {
			$('.'+this.id+'.check', $form).toggleClass('hide', valid==false);
			$(this).toggleClass('error', valid==false);
			$('.'+this.id+'.errorTxt', $form).toggleClass('hide', valid==true);
		}
	});

	if($(':input.error', $form).length == 0){
		return true;
	}
	return false;
}

//********************************************************************************************
//** Resize teh overlay
//********************************************************************************************
function resizeOverlay() {
	overlayHeight = $(document).height();
	overlayWidth = $(window).width();
	// $('#popupOverlay, body').height(overlayHeight);
	// $('#popupOverlay, body').width(overlayWidth);
	$('#popupOverlay').height(overlayHeight);
	$('#popupOverlay').width(overlayWidth);
}

//********************************************************************************************
//** Open popup no block
//********************************************************************************************
function openPopupNoBlock (popupId, top, left) {
	
	var popup = $('div#' + popupId);
	popup.find('a#popupClose').bind('click', function(){
		$(this).unbind('click');
		closePopup();
		return false;
	});
	popup.css({
		position:"absolute",
		top:top,
		left:left
	});
	popup.show();
}

//********************************************************************************************
//** Open pop up
//********************************************************************************************
function openPopup(popupId) {
	var overlayHeight, overlayWidth, mainHeight;
	$('div#popupOverlay').show().css({ width: "100%", height: "100%" });
	overlayHeight = $(window).height();
	overlayWidth = $(window).width();
	// $('#popupOverlay, body').height(overlayHeight);
	// $('#popupOverlay, body').width(overlayWidth);
	$('#popupOverlay').height(overlayHeight);
	$('#popupOverlay').width(overlayWidth);
	$('div#' + popupId).show();
	posPopup(popupId);
}

//********************************************************************************************
//** Position of popup
//********************************************************************************************
function posPopup(id){
	var $popup = $('div#' + id);
	var $height = $('#' + id).height();
	var $width = $('#' + id).width();
	var windowHeight = $(window).height();
	var windowWidth = $(window).width();
	var popUpLeft = ((windowWidth - $width)/2);
	var popUpTop = ((windowHeight - $height)/2) + $(window).scrollTop();
	$popup.css({
		position:"absolute",
		top:popUpTop,
		left:popUpLeft
	});

	resizeOverlay();

	$popup.find('a#popupClose').bind('click', function(){
		$(this).unbind('click');
		closePopup();
		return false;
	});
};

//********************************************************************************************
//** Close popup
//********************************************************************************************
function closePopup()
{
	$('#popupOverlay').hide();
    $('div.popup').hide();
}

//********************************************************************************************
//** Concertina price range
//********************************************************************************************
function concertinaShowPropertyPriceRange() {
	if ( $('#propertySearchFrm input[name=buyRent]:checked').val() == 0) {
		$('#propertySearchFrm #priceFromBuy').show();
		$('#propertySearchFrm #priceToBuy').show();
		$('#propertySearchFrm #priceFromRent').hide();
		$('#propertySearchFrm #priceToRent').hide();
		$('#propertySearchFrm label[for=priceFromBuy]').show();
		$('#propertySearchFrm label[for=priceFromRent]').hide();
		$('#propertySearchFrm label[for=priceToBuy]').show();
		$('#propertySearchFrm label[for=priceToRent]').hide();				
	} else {
		$('#propertySearchFrm #priceFromRent').show();
		$('#propertySearchFrm #priceToRent').show();
		$('#propertySearchFrm #priceFromBuy').hide();
		$('#propertySearchFrm #priceToBuy').hide();
		$('#propertySearchFrm label[for=priceFromRent]').show();
		$('#propertySearchFrm label[for=priceFromBuy]').hide();
		$('#propertySearchFrm label[for=priceToRent]').show();
		$('#propertySearchFrm label[for=priceToBuy]').hide();		
	}
}

//********************************************************************************************
//** Map initialisation
//********************************************************************************************
function gMapInit(div, lat, lng, mapType) {
	if (!mapType) mapType = google.maps.MapTypeId.ROADMAP;
	var mapElement = document.getElementById(div);
	if (mapElement){
	    if (mapElement.style.display == "none"){
	    	mapElement.style.display = "";
	    }
	}
	var markerLatLng;
	if (lat && lng) {
		markerLatLng = new google.maps.LatLng(lat, lng);
	}
	var mapOptions = {
	    zoom: 14,
	    center: markerLatLng,
	    mapTypeId: mapType,
	    mapTypeControl: true,
	    mapTypeControlOptions: {
	        style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
	        position: google.maps.ControlPosition.TOP_RIGHT
	    },
	    navigationControl: true,
	    navigationControlOptions: {
	        style: google.maps.NavigationControlStyle.SMALL,
	        position: google.maps.ControlPosition.TOP_RIGHT
	    },
	    scaleControl: true,
	    scaleControlOptions: {
	        position: google.maps.ControlPosition.TOP_LEFT
	    }
	}
	map = new google.maps.Map(mapElement, mapOptions);
	return map;
}

//********************************************************************************************
//** Map marker
//********************************************************************************************
function gMapMarker (map, index, lat, lng, title, infowWindowHtml ) {
	var shadow;
	var icon;
	if (index > 0 && index < 11) {
		shadow = new google.maps.MarkerImage('http://www.google.com/mapfiles/shadow50.png',
	  		new google.maps.Size(20, 34),
		    new google.maps.Point(0,0),
		    new google.maps.Point(9, 34));
	  	icon = new google.maps.MarkerImage("/media/images/bluemarker_" + index + ".gif",
	 	     new google.maps.Size(20, 34),
	 	     new google.maps.Point(0,0),
	 	     new google.maps.Point(9, 34));
	}
 
	var marker = new google.maps.Marker({
		position: new google.maps.LatLng(lat, lng), 
		icon: icon,
		shadow: shadow,
		map: map, 
		title:title
	});   

	if (infowWindowHtml) {
	    var infowindow = new google.maps.InfoWindow({
		 content: infowWindowHtml,
		 maxWidth: 250
		});
		google.maps.event.addListener(marker, 'click', function() {
				infowindow.open(map,marker);
		});
	}
	return marker;
}

//-----------------------------------------------------------------------
//Eros Fratini - eros@recoding.it
//jqprint 0.3
//
//- 19/06/2009 - some new implementations, added Opera support
//- 11/05/2009 - first sketch
//
//Printing plug-in for jQuery, evolution of jPrintArea: http://plugins.jquery.com/project/jPrintArea
//requires jQuery 1.3.x
//
//Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
//------------------------------------------------------------------------

(function($) {
 var opt;

 $.fn.jqprint = function (options) {
     opt = $.extend({}, $.fn.jqprint.defaults, options);

     var $element = (this instanceof jQuery) ? this : $(this);
     
     if (opt.operaSupport && $.browser.opera) 
     { 
         var tab = window.open("","jqPrint-preview");
         tab.document.open();

         var doc = tab.document;
     }
     else 
     {
         var $iframe = $("<iframe  />");
     
         if (!opt.debug) { $iframe.css({ position: "absolute", width: "0px", height: "0px", left: "-600px", top: "-600px" }); }

         $iframe.appendTo("body");
         var doc = $iframe[0].contentWindow.document;
     }
     
     if (opt.importCSS)
     {
         if ($("link[media=print]").length > 0) 
         {
             $("link[media=print]").each( function() {
                 doc.write("<link type='text/css' rel='stylesheet' href='" + $(this).attr("href") + "' media='print' />");
             });
         }
         else 
         {
             $("link").each( function() {
                 doc.write("<link type='text/css' rel='stylesheet' href='" + $(this).attr("href") + "' />");
             });
         }
     }
     
     for (var s in opt.parentdivs) {
    	 doc.write("<div id='" + opt.parentdivs[0] + "'>");
     }
     if (opt.printContainer) { doc.write($element.outer()); }
     else { $element.each( function() { doc.write($(this).html()); }); }

     for (var s in opt.parentdivs) {
    	 doc.write("</div>");
     }

     doc.close();
     
     (opt.operaSupport && $.browser.opera ? tab : $iframe[0].contentWindow).focus();
     setTimeout( function() { (opt.operaSupport && $.browser.opera ? tab : $iframe[0].contentWindow).print(); if (tab) { tab.close(); } }, 1000);
 }
 
 $.fn.jqprint.defaults = {
		parentdivs: ["localDir"],
		debug: false,
		importCSS: true, 
		printContainer: true,
		operaSupport: true
	};

 // Thanks to 9__, found at http://users.livejournal.com/9__/380664.html
 jQuery.fn.outer = function() {
   return $($('<div></div>').html(this.clone())).html();
 } 
})(jQuery);

(function($) {
// Animated Scrolling for Same-Page Links
// @see http://www.learningjquery.com/2007/10/improved-animated-scrolling-script-for-same-page-links

var version = '1.1';
var locationPath = filterPath(location.pathname);

$.fn.extend({
	smoothScroll: function(options) {

    this.each(function() {
      var opts = $.extend({}, $.fn.smoothScroll.defaults, options);

      $(this).bind('click', function(event) {
        var link = this, $link = $(this),
            hostMatch = ((location.hostname === link.hostname) || !link.hostname),
            pathMatch = opts.scrollTarget || (filterPath(link.pathname) || locationPath) === locationPath,
            thisHash = link.hash && '#' + link.hash.replace('#',''),
            include = true;

        if (!opts.scrollTarget && (!hostMatch || !pathMatch || thisHash.length == 1) ) {
          include = false;
        } else {
          var exclude = opts.exclude, elCounter = 0, el = exclude.length;
          while (include && elCounter < el) {
            if ($link.is(exclude[elCounter++])) {
              include = false;
            }
          }

          var excludeWithin = opts.excludeWithin, ewlCounter = 0, ewl = excludeWithin.length;
          while (include && ewlCounter < ewl) {
            if ($link.parents(excludeWithin[ewlCounter++] + ':first').length) {
              include = false;
            }
          }          
        }

        if (include) {
          opts.scrollTarget = opts.scrollTarget || thisHash;
          opts.link = link;
          event.preventDefault();
          $.smoothScroll(opts);        
        }
      });
    });

    return this;
  }
});

$.smoothScroll = function(options, px) {
  var opts,
      scrollTargetOffset,
      scrollElem = scrollableElement('html', 'body');

  if ( typeof options === 'number') {
    opts = $.fn.smoothScroll.defaults;
    scrollTargetOffset = options;
  } else {
    opts = $.extend({}, $.fn.smoothScroll.defaults, options);
    scrollTargetOffset = px || $(opts.scrollTarget).offset().top;
  }
  opts = $.extend({link: null}, opts);

  $(scrollElem).animate({
    scrollTop: scrollTargetOffset + opts.offset
  }, 
  {
    duration: opts.speed,
    easing: opts.easing, 
    complete: function() {
      if ( opts.afterScroll && $.isFunction(opts.afterScroll) ) {
        opts.afterScroll.call(opts.link, opts);
      }
    }
  });
};

$.smoothScroll.version = version;

// default options
$.fn.smoothScroll.defaults = {
  exclude: [],
  excludeWithin:[],
  offset: 0,
  scrollTarget: null, // only use if you want to override default behavior
  afterScroll: null,   // function to be called after window is scrolled
  easing: 'swing',
  speed: 400
};

// private functions

// don't pass window or document
function scrollableElement(els) {
  for (var i = 0, argLength = arguments.length; i < argLength; i++) {
    var el = arguments[i],
        $scrollElement = $(el);
    if ($scrollElement.scrollTop() > 0) {
      return el;
    } else {
      $scrollElement.scrollTop(1);
      var isScrollable = $scrollElement.scrollTop() > 0;
      $scrollElement.scrollTop(0);
      if (isScrollable) {
        return el;
      }
    }
  }
  return [];
}

function filterPath(string) {
  return string
    .replace(/^\//,'')
    .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
    .replace(/\/$/,'');
}

})(jQuery);

/* SEARCH RESULTS JAVASCRIPT */
// define a custom method on the string class to trim leading and training spaces
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

//********************************************************************************************
//** Integer Test
//********************************************************************************************
function isInteger(s){
	var i;
	for (i = 0; i < s.length; i++){
		// Check that current character is number.
		var c = s.charAt(i);
		if (((c < "0") || (c > "9"))) return false;
	}
	// All characters are numbers.
	return true;
}

//********************************************************************************************
//** Strip characters
//********************************************************************************************
function stripCharsInBag(s, bag){
	var i;
	var returnString = "";
	// Search through string's characters one by one.
	// If character is not in bag, append to returnString.
	for (i = 0; i < s.length; i++){
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}

//********************************************************************************************
//** Number of days in feb (is leap year or not)
//********************************************************************************************
function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
	// EXCEPT for centurial years which are not also divisible by 400.
	return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

//********************************************************************************************
//** Days in month
//********************************************************************************************
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
			if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
			if (i==2) {this[i] = 29}
	}
	return this
}

//********************************************************************************************
//** Checks the key that was pressed
//********************************************************************************************
function checkKeyPress(e,strURL) {
    if (e.keyCode == 13) {
    	filterByDate(strURL)
    }
}

//********************************************************************************************
//** Validates if the value is a date
//********************************************************************************************
function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)

	strYr=strYear

	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)

	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)

	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}

	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)

	if (pos1==-1 || pos2==-1){
		alert("The date format should be : dd/mm/yyyy")
		return false
	}

	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}

	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}

	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}

	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
	return true
}

//********************************************************************************************
//** Filter by date on search
//********************************************************************************************
function filterByDate(urlQueryString){
    var filterPublishedFrom = document.getElementById('filterFrom_Date');
    var filterPublishedTo = document.getElementById('filterTo_Date'); 
    var proceed = true
    
    if (filterPublishedFrom.value == "" && filterPublishedTo.value == ""){
          //Do nothing
          proceed = false
          
    }else if (filterPublishedFrom.value != "" && filterPublishedTo.value == ""){
          //Populate TO date with todays date
          var currentTime = new Date();
          var month = currentTime.getMonth() + 1;
          var day = currentTime.getDate();
          var year = currentTime.getFullYear();
          filterPublishedTo.value = BuildDateFormat(day,month,year)      //(day + "/" + month + "/" + year);
                                              
          if (isDate(filterPublishedFrom.value)==false){
                filterPublishedFrom.focus()
                filterPublishedFrom.style.borderColor = 'red'
                proceed = false
          }
          
    }else if (filterPublishedFrom.value == "" && filterPublishedTo.value != ""){
          //Populate FROM date with todays date minus 1 year
          /*
          var currentTime = new Date();
          var month = currentTime.getMonth() + 1;
          var day = currentTime.getDate();
          var year = currentTime.getFullYear()-1;
          filterPublishedFrom.value = BuildDateFormat(day,month,year)     //(day + "/" + month + "/" + year);
          
          if (isDate(filterPublishedTo.value)==false){
                filterPublishedTo.focus()
                filterPublishedTo.style.borderColor = 'red'
                proceed = false
          }
          */
          
          if (isDate(filterPublishedTo.value)==false){
                filterPublishedTo.focus()
                filterPublishedTo.style.borderColor = 'red'
                proceed = false
          }else{
                var arrDate = filterPublishedTo.value.split("/")
                filterPublishedFrom.value = BuildDateFormat(arrDate[0],arrDate[1],arrDate[2]-1);
          }
          
          
    }else if (filterPublishedFrom.value != "" && filterPublishedTo.value != ""){
          //Perform normal search
          if (isDate(filterPublishedFrom.value)==false){
                filterPublishedFrom.focus()
                filterPublishedFrom.style.borderColor = 'red'
                proceed = false
          }
          
          
          if (isDate(filterPublishedTo.value)==false){
                filterPublishedTo.focus()
                filterPublishedTo.style.borderColor = 'red'
                proceed = false
          }
    }
	if (proceed == true) {

		var arrDateFrom = filterPublishedFrom.value.split("/")
		var dateFrom = new Date(arrDateFrom[2], arrDateFrom[1], arrDateFrom[0]);

		var arrDateTo = filterPublishedTo.value.split("/")
		var dateTo = new Date(arrDateTo[2], arrDateTo[1], arrDateTo[0]);

		if (dateTo < dateFrom) {
			// swap dates and call BuildQueryString
			BuildQueryString(urlQueryString, filterPublishedTo, filterPublishedFrom)

		} else {
			// call BuildQueryString without swapping dates
			BuildQueryString(urlQueryString, filterPublishedFrom, filterPublishedTo)
		}
	}
}

//********************************************************************************************
//** Constructs querystring
//********************************************************************************************
function BuildQueryString(urlQueryString, filterPublishedFrom, filterPublishedTo) {
	if (urlQueryString.lastIndexOf("publishedon=") == -1) {
		urlQueryString = urlQueryString.concat('&publishedon=' + filterPublishedFrom.value);
	} else {
		var endOfSort = urlQueryString.indexOf("&", urlQueryString.lastIndexOf("publishedon="));
		var sortInQuery = urlQueryString.substring(urlQueryString.lastIndexOf("publishedon=") + 12, endOfSort);
		//urlQueryString = urlQueryString.replace(sortInQuery, filterPublishedFrom.value);
        urlQueryString = urlQueryString.replace('publishedon=' + sortInQuery, 'publishedon=' +filterPublishedFrom.value);

	}

	if (urlQueryString.lastIndexOf("publisheduntil=") == -1) {
		urlQueryString = urlQueryString.concat('&publisheduntil=' + filterPublishedTo.value);
	} else {
		var endOfSort = urlQueryString.indexOf("&", urlQueryString.lastIndexOf("publisheduntil="));
		var sortInQuery = urlQueryString.substring(urlQueryString.lastIndexOf("publisheduntil=") + 15, endOfSort);
		//urlQueryString = urlQueryString.replace(sortInQuery, filterPublishedTo.value);
        urlQueryString = urlQueryString.replace('publisheduntil=' + sortInQuery, 'publisheduntil=' + filterPublishedTo.value);
	}

	window.location = urlQueryString
}

//********************************************************************************************
//** Constructs a date format
//********************************************************************************************
function BuildDateFormat(elementDay, elementMonth, elementYear){
	var tmpDay = elementDay + '';
    var tmpMonth = elementMonth + '';
    var tmpYear = elementYear + '';

    if (tmpYear.length == 2){
    	tmpYear = ('20' + tmpYear);
    }
    
    if (tmpMonth.length == 1){;
		tmpMonth = ('0' + tmpMonth);
    };

	if (tmpDay.length == 1){;
		tmpDay = ('0' + tmpDay);
	};

	return tmpDay + '/' + tmpMonth + '/' + tmpYear
}

//********************************************************************************************
//** Retrieves a parameter from the querystring
//********************************************************************************************
function getQuerystring(key, default_){
  if (default_==null) default_=""; 
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
	return unescape(qs[1].replace(/\+/g, " "));
}
/*scotsman nav class change only*/
$(function replaceText() {
    $("ul.primaryNav li a").each(function() { 
		if($(this).children().length==0) { 
			var thisHTML = $(this).html();
			var emarket = thisHTML.indexOf('eMarket');
			if(!(emarket==-1)){
				$(this).html($(this).text().replace('eMarket', 'market'));
				$(this).prepend("<span/>");
				$(this).children("span").css('text-transform','lowercase').html("e");
			}
        } 
    });
});

function postByAjax(field, layout, target, replace, callback) {
	
	var url = $(field).attr('href');
	if(layout!=null) {
		url = url + ((url.indexOf("?")>=0)?"&":"?") + "ot=" + layout;
	}	
	jQuery.get(url, function(result){
			var htmlResult = $(result);
			var html = $(htmlResult).find('#' + target).html();
			if (html==null) {
				html = $(result).html();
			}
			if (replace===true) {
				$('#'+target).html(html);}
			else {
				$('#'+target).append(html);
			}
			if (callback && typeof(callback) === "function") {
			    callback();
			} 
		});
	return false;
}
