var lastMake = [-1,-1,-1];
var lastModel = [-1,-1,-1];

var animateForm;
var preselectChannel;

var mmv = [null,null,null];

function PreSelect()
{
	if (preselectChannel && mmv[0] && mmv[1] && mmv[2])
	{
		jQuery.each($(".finder-tabs li a:eq("+(preselectChannel-1)+")"),tabsClick)		
		$(".finder-tabs li a:eq("+(preselectChannel-1)+")").parent().addClass('active');
	}

}

function ToggleSection(i, toggle)
{
	if (toggle)
	{
		$("#"+i+" :input").attr("disabled","");
		if (preselectChannel)
			$("#"+i).show();
		else
			$("#"+i).fadeIn();
		if (i=="row_typekeyword")
		{
			if (preselectChannel)
				$("#row_typekeyword_type").show();
			else	
				$("#row_typekeyword_type").fadeIn();
		}
	}
	else
	{
		$("#"+i+" :input").attr("disabled","disabled");
		$("#"+i).hide();
		if (i=="row_typekeyword")
			$("#row_typekeyword_type").hide();	
	}	
}

var TabClicked = false;
var mmvReady = false;


function tabsClick()
{

		if (!TabClicked)
		{
			TabClicked = true;
			$("#search-start").hide();
			$("#search-form-cnt").show();
		}
		
		var channel = this.id.replace("tab-","");

		document.mainform.channel.value = channel.toUpperCase();
		
		ToggleSection("row_makemodel",0);
		ToggleSection("row_body",0);
		ToggleSection("row_typekeyword",0);
		ToggleSection("row_year",0);
		ToggleSection("row_price",0);
		ToggleSection("row_price",1);
		
		if (channel=="cars" || channel=="bikes" || channel=="commercials")
		{
			ToggleSection("row_makemodel",1);
			ToggleSection("row_year",1);
			
			if (channel=="cars")
			{
				ToggleSection("row_body",1);
				FillMakes(0);
			}
			else if (channel=="bikes")
			{
				FillMakes(1);
			}
			else if (channel=="commercials")
			{
				FillMakes(2);
			}
		}
		else
		{
			ToggleSection("row_typekeyword",1);
			if (channel!="leisure")
				ToggleSection("row_typekeyword_type",0);
		}
		return false;
}

// TABS VEHICLE FINDER
$(document).ready(function(){

	
	
	$("a[bookmark]").click(function() {
      if ($.browser.webkit)
		{alert("Press CTRL+D to bookmark this page");return false;}
	  else if (window.sidebar) { // Mozilla Firefox Bookmark
        window.sidebar.addPanel("Autotrader.ie",location.href,"");
		return false;
      } else if(window.external) { // IE Favorite
        window.external.AddFavorite(location.href,"Autotrader.ie"); }
      else if(window.opera && window.print) { // Opera Hotlist
        this.title="Autotrader.ie";
        return true;
  		}
	
		});
	
	$(".tab:not(:first)").hide();
	
	if (!preselectChannel)
	{
		$(".tab:first").show();
		$(".finder-tabs a").click(tabsClick);

		//ACTIVE LINKS ON TABS
		$('.finder-tabs li a').click(function()
		{
			$('.finder-tabs li').removeClass('active');
			$(this).parent().addClass('active');
			
		});
	}
	else
	{
		$(".tab:first").hide();
	}
	
	
	
	
	
	//Sell Box Expand 
	$("#login-box-expand-content").hide();
	$("#login-box-heading").click(function(){
	$(this).next("#login-box-expand-content").slideToggle(200);
	});


	//Sell Box Expand on subpage
	$("#login-box-expand-content").hide();
	$("#login-box-heading-sub").click(function(){
	$(this).next("#login-box-expand-content").slideToggle(200);
	});


   /* $("#Logotype-carousel").jCarouselLite({
        btnNext: ".jcarousel-button-next",
        btnPrev: ".jcarousel-button-prev",
		visible:8

    });*/
	$("#News-carousel").jCarouselLite({
        btnNext: ".jcarousel1-button-next",
        btnPrev: ".jcarousel1-button-prev",
		visible:3

    });
	$("#dealers-carousel").jCarouselLite({
        btnNext: ".jcarousel2-button-next",
        btnPrev: ".jcarousel2-button-prev",
		visible:1

    });
	
	$(".car-right-selling").jCarouselLite({
        auto: 1000,
		interval:10000,
		speed:1500,
 		//duration:10000,
		//easing:'easeInOutSine',
		visible:1

    });
	
		

	var nimgs
	if (document.getElementById("News-carousel") && (nimgs=document.getElementById("News-carousel").getElementsByTagName("img")))
	{
		for (var a=0;a<nimgs.length;a++)
		{
   		 	if ($.browser.webkit)
				nimgs[a].onload=function() {if (this.height>100) this.style.marginTop = -parseInt((this.height-100)/2)+"px"; this.onload=null}
			else if (nimgs[a].height>100) nimgs[a].style.marginTop = -parseInt((nimgs[a].height-100)/2)+"px";
		}
	}
	if (animateForm)
	{
		animateForm=setTimeout("doAnimateForm(0)",10000);
		$('#Finder').mousemove(function() {stopAnimatingForm();});
	}
});

function doAnimateForm(a)
{
	$('#'+document.getElementById("Finder").getElementsByTagName("a")[a].id).trigger('click');
	animateForm=setTimeout("doAnimateForm("+((a+1) % $("#Finder a").length)+")",10000);
}
function stopAnimatingForm()
{
	clearTimeout(animateForm);
	$('.finder-tabs li').removeClass('active');
	TabClicked = false;
	$("#search-form-cnt").hide();
	$("#search-start").show();
	$('#Finder').unbind('mousemove');
}

function FillMakes(channel)
{
	var f
	if (!(f=document.mainform) || !mmv[channel]) return; 

	$("#mainform").attr("ch",channel);
	ClearSelect(f.make);
	
	for (var a=0;a<mmv[channel].length;a++)
	{
		//if (mmv[channel][a].name!="{Make unknown}")
		//{
			var op=new Option();
			op.text=mmv[channel][a].name;
			op.value=mmv[channel][a].name;
			op.setAttribute("i",a)
			if (lastMake[channel]==a)
				op.selected = true;
			f.make.options[f.make.options.length]=op
		//}
	}
	f.make.disabled=false;
	FillModels(f.make);
}


function FillModels(o)
{
	var f=o.form;
	var mid = o.selectedIndex;
	ClearSelect(f.model)
	var	channel = $("#mainform").attr("ch");
	
	if (mid==0) return

	for (var a=0;a<mmv[channel][mid-1].models.length;a++)
	{
		var model = mmv[channel][mid-1].models[a].name;
		//if (model!="{Model unknown}")
		//{
			var op=new Option()
			op.text=model;
			op.value=model;
			if (lastModel[channel]==f.model.options.length)
				op.selected=true;
			f.model.options[f.model.options.length]=op
		//}
	}
	
	f.model.disabled=false
}

function ClearSelect(o,a)
{
	for (a=o.options.length-1;a>0;a--)
		o.options[a]=null
}
function Remember(o)
{
	var f = o.form;
	var channel = $("#mainform").attr("ch");
	if (o.name=="model")
		lastModel[channel] = o.selectedIndex;
	else
	{
		lastMake[channel] = parseInt(o.options[o.selectedIndex].getAttribute("i"));
		lastModel[channel] = -1;
	}
}

function SubmitForm(searchForm)
{
    var queryString = "";
    var makeModel;
    if (searchForm.make && searchForm.make.value != "" && !searchForm.make.disabled)
    {
        makeModel = searchForm.make.value;
    }
    if (searchForm.model && searchForm.model.value != "" && !searchForm.model.disabled)
    {
        makeModel += "|" + searchForm.model.value;
    }
    if (makeModel)
    {
        queryString += "&make_model=" + encodeURIComponent(makeModel);
    }
    if ( (searchForm.min_price.selectedIndex > 0 || (searchForm.max_price.selectedIndex != 0 && searchForm.max_price.selectedIndex != searchForm.max_price.options.length - 1)) && !searchForm.min_price.disabled)
    {
        if (document.cookie.indexOf("Currency=GBP") >= 0)
        {
            queryString += "&min_price_gbp=" + searchForm.min_price.value +
                "&max_price_gbp=" + searchForm.max_price.value + "&currency=GBP";
        }
        else
        {
            queryString += "&min_price_euro=" + searchForm.min_price.value +
                "&max_price_euro=" + searchForm.max_price.value + "&currency=EUROS";
        }
    }
    if ( ( (searchForm.year_min && searchForm.year_min.selectedIndex > 0) || (searchForm.year_max && searchForm.year_max.selectedIndex != 0 && searchForm.year_max.selectedIndex != searchForm.year_max.options.length - 1)) && !searchForm.year_min.disabled)
    {
        queryString += "&year_min=" + searchForm.year_min.value +
            "&year_max=" + searchForm.year_max.value;
    }
    if (searchForm.body && !searchForm.body.disabled && searchForm.body.value != "")
    {
        queryString += "&body=" + encodeURIComponent(searchForm.body.value);
    }
    if (searchForm.vehicletype && !searchForm.vehicletype.disabled && searchForm.vehicletype.value != "")
    {
        queryString += "&vehicletype=" + encodeURIComponent(searchForm.vehicletype.value);
    }
    if (searchForm.keywords && !searchForm.keywords.disabled && searchForm.keywords.value != "")
    {
        queryString += "&keywords=" + encodeURIComponent(searchForm.keywords.value);
    }
	var randomNumber = new Date().getTime() + "" + Math.floor(Math.random() * 1000);
    var searchResultsUrl = "http://www.autotrader.ie/search/results?" +
        "searchsource=quick&channel=" + searchForm.channel.value + "&cacheBuster=" + randomNumber;
    if (queryString.length > 0)
    {
        searchResultsUrl += queryString + "&legacy_url=y";
    }
	window.location = searchResultsUrl;
	return false;
}

function ShowEm(str)
{
	$('span[str]').each(function(){
		var e2="",e,b,a;
		e = $(this).attr("str");
		{
			for (b=0;b<e.length;b++) e2+=String.fromCharCode(e.charCodeAt(b)-1);
			this.innerHTML = "E-mail: ";
			a = document.createElement("a");
			a.href = "mailto:"+e2+"&subject=Enquiry sent from Autotrader.ie website";
			a.innerHTML = e2;
			$(this).after(a);
			$(this).removeAttr("str")
			$(this).removeAttr("id")
		}
	})
}

function regFrmSubmit(o,rv)
{
	o = $("#regNo");
	rv = jQuery.trim(o.attr("value"));
	if (rv!="" && rv!=o.attr("initialValue"))
	{
		window.location="http://www.autotrader.ie/ie-ola/lookupVRM.action?directEntry=true&accountType=P&regNo="+encodeURIComponent(rv)+"&channel=0";
		return false
	}
	else
		return true;
}
