//add a js class to the top element (<html>) to assist CSS rules and prevent FOUC
document.documentElement.className = 'js';

$(function(){
	
	// make up for the not so good markup from alchemetrics
	// acount 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 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);
		t.find('legend').after(select);
		if (orderLeft[cnt]) {
			l.append(t);
		} else {
			r.append(t);
		}
	});
	c.append(l).append(r);
	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
	$("div.carousel").carousel({
		nextBtnInsert: "appendTo",
		prevBtnInsert: "appendTo",
		nextBtn: "<span>&nbsp;</span>",
		prevBtn: "<span>&nbsp;</span>",
		effect: "fade"
	});
	//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%');
		}
   	});


	// set full display if the rightcolum is empty
	$('.editorialSection').each( function() {
	 	if ($(this).find('.editorialSponLogo span').length == 0) {
			$(this).find('.editorialSponLogo').width('0px');
			$(this).find('h1.mainHeadline').width('97%');
		}
   	});


	//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();

		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();

	});

	// 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;
			}
		});
		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{
				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');
		});
		
		//select relevant tab
		var selected = location.href.substring(location.href.indexOf('#')+1);
		$('.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();
	
	
	//CHANGING EMAIL via ACCOUNT DETAILS
	
	function ajaxSpinner(parent){
		var spinner = $('#spinner');
		if(spinner.length < 1){
			var div = document.createElement('div');
			div.id = 'spinner';
			spinner = div;
		}
		spinner.style.width = parent.width() + 'px';
		spinner.style.height = parent.height() + 'px';
		spinner.style.top = (parent.height() * -1) + 'px';
		parent.append(spinner);
		return spinner;
	}
	
	//second state of changing email
	function authenticate(){
		var authform = $('#userauthenticate');
		authform.submit(function(event){
			event.preventDefault();
			authform.fadeTo('fast',0.5);
			var spinner = ajaxSpinner(authform);
			$.ajax({
				type:'post',
				data: 'password=' + $('#password_confirm').val(),
				url:'/ajax?action=accountUpdateAuth',
				success:function(html){
					authform.replaceWith(html);
					if(html.indexOf('userauthenticate') !== -1){
						authenticate();
					} else {
						change_email();
					}
				},
				error:function(){
					authform.fadeTo('fast',1);
					$(spinner).remove();
				}
			});
		});
		authform.find('button[type=reset]').click(function(){
			authform.fadeTo('fast',0.5);
			var spinner = ajaxSpinner(authform);												   
			$.ajax({
			   type:'post',
				url:'/ajax?action=accountUpdateStart',
				success:function(html){
					authform.replaceWith(html);
					edit_email();
				},
				error:function(){
					authform.fadeTo('fast',1);
					$(spinner).remove();
				}
			});
		});
	}
	//third state of changing email
	function change_email(){
		var useremail = $('#useremail');
		useremail.submit(function(event){
			event.preventDefault();
			useremail.fadeTo('fast',0.5);
			var spinner = ajaxSpinner(useremail);
			$.ajax({
			   type:'post',
				data:{
						'email': $('#email').val(),
						'username':$('#username').val(),
						'password':$('#password').val(),
						'password_confirm':$('#password_confirm').val()
					},
				url: '/ajax?action=accountUpdateForm',
				success:function(html){
					useremail.replaceWith(html);
					if(html.indexOf('userlogin') !== -1){
						edit_email();
					}
					else{
						change_email();
					}
				},
				error:function(){
					useremail.fadeTo('fast',1);
					$(spinner).remove();
				}		
			});
		});
		useremail.find('button[type=reset]').click(function(){
			useremail.fadeTo('fast',0.5);
			var spinner = ajaxSpinner(useremail);
			$.ajax({
				url:'/ajax?action=accountUpdateStart',
				type:'post',
				success:function(html){
					useremail.replaceWith(html);
					edit_email();
				},
				error:function(){
					useremail.fadeTo('fast',1);
					$(spinner).remove();
				}
			});
		});
	}
	
	//initial state of changing email
	function edit_email(){
		var startform = $('#userlogin');
		startform.submit(function(event){

			event.preventDefault();
			startform.fadeTo('fast',0.5);
			var spinner = ajaxSpinner(startform);
			$.ajax({
				type:'post',
				url:'/ajax?action=accountUpdateEdit',
				success:function(html){
					startform.replaceWith(html);
					authenticate();
				},
				error:function(){
					startform.fadeTo('fast',1);
					$(spinner).remove();
				}
			});
		});
	}
	edit_email();
	
	// 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, #sendToAFriendFrm button.secondaryBtn, #reportCommentFrm button.secondaryBtn').click( function(){
		var $form = $(this).parents('form');
		$(':input:not(button)', $form).each( function(){
			var valid = false;

			switch(this.id){
				case '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);
					break;
				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:
					if ($(this).hasClass('optional') ) {
						valid = true;
					} else {
						valid = this.value && this.value != '';
					}
					break;
			}

			// useful for debugging
			// alert('field ' + this.id + ' value = ' + this.value + ', valid = ' + valid);

			$('.'+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){
			closePopup();
			return true;
//			$form.submit( function(){
//				if($form.parents('div.popup').length > 0){
//					closePopup();
//				}
//			});
		}
		return false;
	});

	/*
	Fix styling issued with JavaScript
	*/
	
	// split layout into two columns and paginate when needed
	var sections = jQuery('div.newsSection');
	sections.each(function() {
		var section = jQuery(this);
		var articles = jQuery('div.newsArticle', section);
		// minimum articles to split into two columns
		var l = articles.length;
		if ( l > 5) {		
			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) ) {
						preserve = cnt + 1;
						return false;
					}
				});
			}

			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();
		}
	});


	// fix right column height issue
	var lc = jQuery('#leftContent').height();
	var rc = jQuery('#rightContent').height();

	// if statement edited to fix Right Column resize issue. Due to recommended partners being pulled in after the below if statement is called, if the left column is less than 2300, then the height will be determined by CSS as everything is floated correctly. However, if the left columns height is less than 2300, we need javascript to adjust the height to fit. This will allow for 8 recommended partners. 
	if ((lc > rc ) && (lc > 2160)){
		jQuery('#rightContent').css({ height: lc + 'px' });
		}

});

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($(''))
				{
				}
			});
		}
	});
};

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');
				}
			});
		}
	});
};

function resizeOverlay() {
	overlayHeight = $(document).height();
	overlayWidth = $(window).width();
	// $('#popupOverlay, body').height(overlayHeight);
	// $('#popupOverlay, body').width(overlayWidth);
	$('#popupOverlay').height(overlayHeight);
	$('#popupOverlay').width(overlayWidth);
}

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);
}
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;
	});
};
function closePopup()
{
	$('#popupOverlay').hide();
    $('div.popup').hide();
}

function concertinaShowPropertyPriceRange() {
	if ( $('#propertySearchFrm input[name=buyRent]:checked').val() == 0) {
		$('#propertySearchFrm #priceFromBuy').show();
		$('#propertySearchFrm #priceToBuy').show();
		$('#propertySearchFrm #priceFromRent').hide();
		$('#propertySearchFrm #priceToRent').hide();
	} else {
		$('#propertySearchFrm #priceFromRent').show();
		$('#propertySearchFrm #priceToRent').show();
		$('#propertySearchFrm #priceFromBuy').hide();
		$('#propertySearchFrm #priceToBuy').hide();
	}
}

function googleMapInit(lat, lng) {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("mapCanvas"));
		var point = new GLatLng(lat, lng);

		map.setCenter(point, 13);
		map.setUIToDefault();
		map.addOverlay(new GMarker(point));
	}
}


(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);
