// this sets the number of filters that are shown for each filter type. eg BRAND:10 will mean 10 filters are shown before 'choose more' link is shown.
//If the type is not included then with scoreRating simply 1 means show, and 0 means hide.
var catBehaviour_FiltersShown = {'BRAND':10,'RANGE':10,'MODEL':10,'BODYSTYLE':10};
var vsearch = {map:null}

$(document).ready(function() {
	vsearch.hideShowFiltersInit();
	vsearch.pulsateChosenFilters();
	vsearch.searchResultsDisplayed();
	vsearch.showFiltersTooltip();
	billboard.init();
	//vsearch.tagDraggonInit();
	vsearch.resultsMouseOverInit();
	$.smoothAnchors(1300, "swing", false); 
	$('#searchPostCode').change(function(){
		this.value = this.value.toUpperCase();
	});
	vsearch.mapInit();
	
	//$("div#filters,.topContent").expose({opacity:0.9});
});

var billboard = {};

billboard.init = function(){
	if( $("div.scrollable div div").size()>1 ){ //just check there are items to scroll through
		var sc = $("div.scrollable").scrollable({circular:true,speed:1600,onBeforeSeek:billboard.scrollseek}).autoscroll({ autoplay: true,interval:8000,autopause:true }).navigator();	
	}
}

billboard.scrollseek = function(e,v){
	var s = e.currentTarget.getSize();
	var f = e.currentTarget.getConf();;
	var t = $.tools.scrollable.autoscroll 
	var d = v * ((723-90-15)/s)+5;
	$("div.scrollcar").show().animate({left:d},1600,function(){
			$("div.scrollcar").show();
		});
	$("#notspinning").hide();
}


vsearch.resultsMouseOverInit = function(){
	$('table.results').delegate("tr", "mouseenter", function(){
						$(this).addClass("mousedOver");
					}).delegate("tr", "mouseleave", function(){
						$(this).removeClass("mousedOver");
					}).delegate("td[class!=compare][class!=finalRow]", "click", 
						vsearch.resultsClicked
					);
}

vsearch.resultsClicked = function(event){
	var src = (event.target)?event.target:event.srcElement;
	var a = $(this.parentNode).find('A')[0];
	if(src.nodeName !="A" && typeof(a.target) == "string" && a.target.length>0){
		var f = document.getElementById('openResultsInNewWindow');
		if(!f){
			$('body').append('<form id="openResultsInNewWindow" name="openResultsInNewWindow" method="get" action="' + a.href + '" target="' + a.target + '"></form>');
			param.addPartnerKeyToForms();
		}
		$('#openResultsInNewWindow').attr('action',a.href).submit();
	}else if(src.nodeName !="A"){
		$(a).triggerHandler('click');
		window.location = a.href;
	}
}

/*
vsearch.overlayInit = function(){
	
	var ar = $(".results a[rel]");
	ar.click(function(){
		var tr = $(this).closest("tr");
		var sp = tr.next().find('.spacerRow');
		sp.html("<div>hello</div>");
		sp.find("div").show('blind',{},400,
			function(){
				$(this).expose({
					onClose: function() {
						var v = this.getExposed()
						$(v).hide('blind',{},400);
					}
			})
		});
	});
	
	return;
	ar.each(function(){
		if( $(this.rel).length==0 ){
			$("body").append('<div id="' + this.rel.replace("#","") + '" class="defOverly w750"><div class="contentWrap">LOADING.. please wait</div></div>');	
			$(this).overlay({
					//top: '',
					mask: {
						color: '#000',
						loadSpeed: 200,
						opacity: 0.5
					},
					onBeforeLoad: function() {
						var wrap = this.getOverlay().find(".contentWrap");
						if (wrap.is(":contains('LOADING')")) {
							wrap.load(this.getTrigger().attr("href")+"?display=deals");
						}
					},
			//		onLoad:overlay.onLoad,
			//		onBeforeClose:overlay.onBeforeClose,
					//closeOnClick: false,
					fixed:false,
					effect: 'apple'
				});
		}
	});			
}


vsearch.tagDraggonInit = function(){
	var ajaxurl = $("#tagbox").attr('class');
	$("#tagCategoryId").val("");
	$('#tagbox').tagdragon({'field':'searchQuery','url':ajaxurl,'max':99,onSelectItem: function(val){$("#tagCategoryId").val(val.id);$('.topTextSearch form').submit(); } });
}
*/
vsearch.showFiltersTooltip = function(){
	$("div.tooltipInfo").prev().tooltip({
		position: 'center right',
		relative:true
	}).dynamic();
}

vsearch.pulsateChosenFilters = function(){
	$('ul.chosen li.fFilters li').effect('pulsate');
}

vsearch.hideShowFiltersInit = function(){
	var behav, num, head
	$('li.fHeading a').click(vsearch.featureHeadingClicked);
	//iterate each filter set and choose appropiate show hide rules
	$('li.fFilters').each(function(){
			behav="";num=null;
			if(this.className != null){
				behav = this.className.split(" ")[1];
				if(behav != null && behav.length>0)num = eval("catBehaviour_FiltersShown."+behav);
			}
			if(typeof(num)=="number"){
				// run if filter behaviour contained in catBehaviour_FiltersShown
				vsearch.hideFiltersWithLowScore(this,num);
			}else{
				//rs0 is hide, rs1 is show
				head = $(this).prev();
				if(head.hasClass('rs0')){
					//head is rs0 so hide all filters
					vsearch.filtersOpenOrClose(
							head.find('a').addClass('fClosed')
							,true);
				}else{
					//head is rs1 leave open check if choosemore required	
					vsearch.hideFiltersWithRs0(this)
				}
			}
	});
}

vsearch.hideFiltersWithRs0 = function(fFilters){
	var rs0 = $(fFilters).find('li.rs0');
	var rs1 = $(fFilters).find('li.rs1');
	//if both filters shown and hidden are present then hide rs0
	if(typeof(rs0[0])!="undefined" && typeof(rs1[0])!="undefined"){
		rs0.hide();
		vsearch.chooseMoreAddLink(fFilters);
	}
}

vsearch.hideFiltersWithLowScore = function(fFilters,num){
	var d;
	var arr = [];
	var addmore = false;
	//iterate each filter and get the maxRatingScore into an array
	$(fFilters).find('li').each(function(){
		d =	this.className.split(" ")[0];		
		if(d.indexOf("rs")==0){
			arr.push(d.substr(2));
		}										 
	});
	//following line does numerical sort, highest first
	arr.sort(function(a,b){return b-a}); 
	//after (value of num) filters hide them, but only if rating is less than the highest score
	//OR hide if not for sale (score < 0), but only if there is atleast one that is for sale (>=0)
	for(i=0;i<arr.length;i++){
			if( (i>=num && arr[i]!=arr[0]) || (arr[0]>=0 && arr[i]<0) ){
				$(fFilters).find('li.rs'+arr[i]).hide();
				addmore = true;
			}
		}
	if(addmore) vsearch.chooseMoreAddLink(fFilters);
}

vsearch.chooseMoreAddLink = function(fFilters){
	$(fFilters).find('ul').append("<li class='chooseMore'><a href='#' onclick='return vsearch.chooseMoreClicked(this)'>SHOW MORE</a></li>");
}

vsearch.chooseMoreClicked = function(obj){
	$(obj).closest('ul').find("li:hidden").show('blind',{},400);
	$(obj).closest('li').hide();
	return false;
}

vsearch.featureHeadingClicked = function(){
	$(this).toggleClass('fClosed');
	vsearch.filtersOpenOrClose(this,false);
	return false;
}

vsearch.filtersOpenOrClose = function(featureLink,noAnimation){
	var qa = $(featureLink);
	var hide = qa.hasClass('fClosed');
	var li = qa.closest("li").next("li.fFilters");
	if(hide && noAnimation){
		li.hide();
	}else if(hide){
		li.hide('blind',{},400);
	}else{
		li.find("li:hidden").show();
		li.find("li.chooseMore").hide();
		li.show('blind',{},400);
	}
}



vsearch.searchResultsDisplayed = function(){
	var url
	//when more results clicked, do ajax call to get next page
	$('#moreResultsTR a.moreResults').click(function(){
			$(this).replaceWith("<strong>MORE RESULTS LOADING..</strong>");
			url = this.href.toString();
			url = url.replace("about:","").replace("blank",""); //msie adds these values
			try{
				$.ajax({
				  url: url,
				  cache: false,
				  success: vsearch.searchResultsReturned
				});
			}catch(e){
				//default if ajax throws error
				url = url.replace("more_","");
				location=url;
			}
			return false;
	});
}

vsearch.searchResultsReturned = function(data){
	$('#moreResultsTR').replaceWith(data);
	vsearch.searchResultsDisplayed();
	vsearch.mapUpdate();
}



function comparecars(obj){
	//obj.openLeft = 40;
	//obj.winwidth = 700
	//obj.winheight = 552
	var chkd=0
	var compareboxs = document.getElementsByName('prodDataId')
	var compareURL = "/CompareVehicles.jhtml?";
	if(window.location.toString().indexOf('/buyacar/')>-1)compareURL = "/buyacar/CompareVehicles.jhtml?";
	for(i=0;i<compareboxs.length;i++){
		if(compareboxs[i].checked){chkd++;compareURL=compareURL + "prodDataId=" + compareboxs[i].value + "&";}
	}
	if(chkd<2){
		//if(window.event)event.returnValue = false;
		alert('Please select at least two cars to compare by ticking their check boxes');
		return false;
	}else{
		obj.href=compareURL+"&compare=Compare+..";
		overlay.setURL(obj.href,null,true);
		return false;
		//return defaultFrame.open(obj,'A');
	}
}

vsearch.mapInit = function(){
	var latlng, LL;
	var latMX, latMN, lngMX, lngMN;
	m = document.getElementById("map_canvas");
	if(m==null)return;
	$('.latLng').each(function(){
		latlng = $(this).html();
		if(latlng != null){
			LL = latlng.split(",");
			LL[0] = parseFloat(LL[0]);LL[1] = parseFloat(LL[1]);
			if(!isNaN(LL[0]) && (LL[0] > latMX || latMX ==null))latMX = LL[0]
			if(!isNaN(LL[0]) && (LL[0] < latMN || latMN ==null))latMN = LL[0];
			if(!isNaN(LL[0]) && (LL[1] > lngMX || lngMX ==null))lngMX = LL[1];
			if(!isNaN(LL[0]) && (LL[1] < lngMN || lngMN ==null))lngMN = LL[1];
		}
	});
	if(isNaN(latMX) || isNaN(lngMN))return;

	//find zoom
	var maxDis = latMX - latMN;
	if((lngMX - lngMN) > maxDis) maxDis = (lngMX - lngMN);
	var zm = Math.round(maxDis*-1 + 10);
	if(isNaN(zm) || zm>15 || zm<5)zm=5;
	//find centre
	var offset = zm*-0.226 + 2.33
	var centerLatlng = new google.maps.LatLng( (latMX+latMN)/2 + offset, (lngMX+lngMN)/2);
	
	//init
	var myOptions = {
      zoom: zm,
      center: centerLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    vsearch.map = new google.maps.Map(m, myOptions);
	
	vsearch.mapUpdate();
}

vsearch.mapUpdate = function(){
	var LL,dn,im,ad,contentString,m,lk;
	var markers = new Array();
	var infowindow = new Array();
	var trs = $('.results tr,.dealerDir');
	var count = (trs.length-1);
	trs.each(function(i){
		dn = $(this).find(".description a,h3").html();
		im = $(this).find(".logo").html();
		ad = $(this).find("address").html();
		lk = $(this).find("a").attr("href");
		latlng = $(this).find(".latLng").html();
		if(i > (trs.length - 22) && dn !=null && im !=null && ad !=null && lk !=null && latlng !=null){
			LL = latlng.split(",");
			LL[0] = parseFloat(LL[0]);LL[1] = parseFloat(LL[1]);
			markers[i] = new google.maps.Marker({
			  position:  new google.maps.LatLng(LL[0],LL[1]), 
			  map: vsearch.map, 
			  title:dn
			  //,icon: "<%=request.getContextPath()%>/images/logo/${imgFile}50.jpg"
			}); 
			
			contentString =
				"<div class='mapMarker'>"
				+ im
				+ "<a href='" + lk + "' class='btn bt1'>View Details</a>"
				+ "<b>" + dn +"</b>"
				+ "<address>" + ad + "</address>"
				+ "</div>";
			
			infowindow[i] = new google.maps.InfoWindow({
				content: contentString
			});
			
			google.maps.event.addListener(markers[i], 'click', function() {
			  infowindow[i].open(vsearch.map,markers[i]);
			});
		
		}
	});
}


