var chooseText = '';
var makeText = '';
var modelText = '';
var bodyTypeText = '';
var engineText = '';
var driveText = '';
var partCategoryText = '';
var widthRimText = '';
var partText = '';
var openExtendedSearchText = '';
var closeExtendedSearchText = '';
var nextText = '';
var backText = '';
var addpartText = '';
var addpartsText = '';

/* IE6 flicker fix
-------------------------------------------------- */
try {
	document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}

/* Dialog
-------------------------------------------------- */
var openModalContent = null;

function showModal(target){
	if ($("#overlay").length == 0) {
		$("#wrap").after("<div id='overlay'></div>");
	}
	if (openModalContent != null){
		$("#" + openModalContent).hide();
	}
	openModalContent = target;

	$("#overlay").show();
	$("#modalwrap").fadeIn(150);
	$("#" + target).fadeIn(150);

	if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
		$("html").css("overflow","hidden");
		$("body").css("height","100%");
	} else {
		$("#modalwrap").css("margin-top","-" + $("#modalwrap").height() / 2 + "px");//1440-450
		//$("#modalwrap").css("left", "" + (($(window).width() / 2) - 125) + "px");
	}

	$("#overlay").bgiframe({ src: "javascript:'<html></html>';" });

	escape();
	return false;
}

function hideModal(){
	if (openModalContent != null){
		$("#" + openModalContent).fadeOut(150);
	}
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("html").css("overflow","");
		$("body").css("height","");
	}
	$("#overlay").hide();
	$("#modalwrap").fadeOut(150);

	return false;
}

function escape(){
	document.onkeyup = function(e) {
		var code;
		if (!e) var e = window.event;
		if (e.keyCode) code = e.keyCode;
		else if (e.which) code = e.which;
		if (code == 27){
			hideModal();
		}
	}
}

/* jQuery
-------------------------------------------------- */
var toggleH2boxes = {
	init : function(){
		$("h2.toggle a, h3.toggle a").click(this.clickIt);
	},
	clickIt : function(){
		$(this).parent().toggleClass("toggle-open");
		$(this).parent().next("div.toggle-wrap:first").slideToggle("fast");
		return false;
	}
};

/* data tables */

function dataHover() {
	$("table.data tbody:not(.form) tr").hover(
		function(){
			$(this).addClass("hover");
		},
		function(){
			$(this).removeClass("hover");
		}
	);
}
var toggleSubrow = {
	init : function(){
		$("table.data tbody a.toggle-subrow").click(this.clickIt);
	},
	clickIt : function(){
		if($(this).parents("tr").next("tr.subrow").css("display") == "none") {
			$(this).parents("tr").addClass("toggler");
			$(this).parents("tr").next("tr.subrow").css("display","");
		} else {
			$(this).parents("tr").removeClass("toggler");
			$(this).parents("tr").removeClass("marked");
			$(this).parents("tr").next("tr.subrow").css("display","none");
		}
		return false;
	}
};
var toggleSubrow2 = {
	init : function(){
		$("table.data tbody.subrows tr.toggle-level a.toggle-subrows").click(this.clickIt);
	},
	clickIt : function(){
		if($(this).parents("tr").nextAll("tr").css("display") == "none") {
			$(this).addClass("toggle-open");
			$(this).parents("tr").nextAll("tr").css("display","");
		} else {
			$(this).removeClass("toggle-open");
			$(this).parents("tr").removeClass("marked");
			$(this).parents("tr").nextAll("tr").css("display","none");
		}
		return false;
	}
};
function fixIEoverflow() {
	if (!/*@cc_on!@*/0) return;

	var all = document.getElementsByTagName('*'), i = all.length;
	while (i--) {
		// adding a class match just to show the difference
		if (all[i].className.match(/scroll/) && all[i].scrollWidth > all[i].offsetWidth) {
			all[i].style['overflowY'] = 'hidden';
			all[i].style['paddingBottom'] = '17px';
		}
	}
}
var headingSort = {
	init : function(){
		$("table.data thead th.sort a").click(this.clickIt);
	},
	clickIt : function(){
		if($(this).parent().is(".ascending")) {
			$(this).parents("thead").find("th").removeClass("ascending");
			$(this).parents("thead").find("th").removeClass("descending");
			$(this).parent().removeClass("ascending");
			$(this).parent().addClass("descending");
		}
		else if ($(this).parent().is(".descending")) {
			$(this).parents("thead").find("th").removeClass("ascending");
			$(this).parents("thead").find("th").removeClass("descending");
			$(this).parent().removeClass("descending");
			$(this).parent().addClass("ascending");
		}
		else {
			$(this).parents("thead").find("th").removeClass("ascending");
			$(this).parents("thead").find("th").removeClass("descending");
			$(this).parent().addClass("ascending");
		}
		return false;
	}
};

/* radio, checkbox */

var markRows = {
	init : function(){
		$("table.data tbody:not(.form) tr").dblclick(this.clickIt);
	},
	clickIt : function(){
		$(this).toggleClass("marked");
	}
};
var markAllCheck = {
	init : function(){
		$("div.sub-action a.mark-all").click(this.clickIt);
	},
	clickIt : function(){
		$(this).parents("div.sub-action").nextAll("table.data:first").find("tbody tr td.check input:checkbox").attr("checked","checked");
		$(this).parents("div.sub-action").nextAll("table.data:first").find("tbody tr td.check input:checked").parents("tr").addClass("checked");
		return false;
	}
};
var markNoneCheck = {
	init : function(){
		$("div.sub-action a.mark-none").click(this.clickIt);
	},
	clickIt : function(){
		$(this).parents("div.sub-action").nextAll("table.data:first").find("tbody tr td.check input:checkbox").removeAttr("checked");
		$(this).parents("div.sub-action").nextAll("table.data:first").find("tbody tr td.check input").not(":checked").parents("tr").removeClass("checked");
		return false;
	}
};
var setCheckbox = {
	init : function(){
		$("table.data tr td.check input:checkbox").click(this.clickIt);
	},
	clickIt : function(){
		if($(this).is(":checked")) {
			$(this).parents("tr").addClass("checked");
		} else {
			$(this).parents("tr").removeClass("checked");
		}
	}
};
var setRadio = {
	init : function(){
		$("table.data tr td.check input:radio").click(this.clickIt);
	},
	clickIt : function(){
		$(this).parents("table").find("tr.checked").removeClass("checked");
		$(this).parents("tr").addClass("checked");
	}
};
var setRadioDatasp = {
	init : function(){
		$("table.data-sp tr td.price input:radio").click(this.clickIt);
	},
	clickIt : function(){
		$("table.data-sp tr td.price input:radio").next("label").css("font-weight","normal");
		$("table.data-sp tr td.price input:radio:checked").next("label").css("font-weight","bold");
	}
};
function controlCheckbox() {
	$("table.data tbody tr td.check input:checkbox:checked").parents("tr").addClass("checked");
}
function controlRadio() {
	$("table.data tbody tr td.check input:radio:checked").parents("tr").addClass("checked");
}

function tooltip() {
	$(".tooltip2").change( function() {
		model = this.options[this.selectedIndex].value;
		var element = $(this);
		$.ajax({
			url: '/car/show-picture/model/' + model + '/check/1',
			success: function(response) {
				if (response.length > 0) {
					$("div.tooltip").css("display","block").css("left", element.position().left + element.width()).css("top", element.position().top + element.height() - 90);

					if($.browser.msie && ($.browser.version < 7) ){
						$(".tooltip").bgiframe({ src: "javascript:'<html></html>';" });
						element.parent().next().css("left", element.position().left + element.width() + 5);
					}
					
					$.getJSON('/car/get-car-tooltip/model/' + model, function(json){
						var endDate = json.production_end_date;
						if (endDate == 0) {
							endDate = '...';
						}
						$('#tooltipMake').html(json.make);
						$('#tooltipModel').html(json.model);
						$('#tooltipImg').html('<img src="/car/show-picture/model/' + model + '" alt="" />');
					});
				} else {
					$("div.tooltip").css("display","none");
				}
			}
		});



	}).blur(function(){
		$("div.tooltip").css("display","none");
	});
}

function tabs () {
	$("#sidebar ul.tabs li a").click(this.clickIt);

	$("#spare-part div.action p.secondary span.back a").click(function () {

		$("div.more-spare-parts").slideToggle();
		$(this).toggleClass("opened");

		if ($(this).hasClass("opened")) {
			$("#spare-part div.action p.secondary span.back a").text(closeExtendedSearchText);
			$("#extendedSearch").val(1);
		}
		else {
			$("#spare-part div.action p.secondary span.back a").text(openExtendedSearchText);
			$("#extendedSearch").val(0);

		}
		return false;
	});
	$("li.spare-part a").click(function () {
		$("#sidebar ul.tabs li").removeClass("active");
		$("#spare-part").show();
		$("#calculator").hide();
		$(this).parent().addClass("active");
		return false;
	});
	$("li.calculator a").click(function () {
		$("#sidebar ul.tabs li").removeClass("active");
		$("#calculator").show();
		$("#spare-part").hide();
		$(this).parent().addClass("active");
		return false;
	});
};

var tabsRadio  = {
	init : function(){
		$("#calculator p.radio input, #sidebar ul.tabs li.calculator").click(this.clickIt);
	},
	clickIt : function(){
		if($("#calculator p.radio #i01, #calculator p.radio #i02").is(":checked")) {
			$("div.i01").slideDown();
			$("div.i02, div.i03").slideUp();
		}
		else if($("#calculator p.radio #i03, #calculator p.radio #i04, #calculator p.radio #i05, #calculator p.radio #i06").is(":checked")) {
			$("div.i02").slideDown();
			$("div.i01, div.i03").slideUp();
		}
		else if($("#calculator p.radio #i07").is(":checked")) {
			$("div.i03").slideDown();
			$("div.i01, div.i02").slideUp();
		}
		else {
			$("div.i01, div.i02, div.i03").slideUp();
		}
	}
};

function toggleHelp() {
	$("img.help-toggle").click(function(){
		var target = $(this).next("div.help");
		var target2 = $(this).parent().next("div.help");
		var offset = $(this).offset();
		var scroll = $(document).scrollLeft();

		if(target.is(":visible")){
			target.css("display","none");
		}
		else if (target.is(":hidden")){
			$("div.help:visible").css("display","none");
			target.css({
				display: "block",
				top: offset.top + "px",
				left: $(this).width() + offset.left + "px",
				right: "auto"
			})
			.bgiframe({ src: "javascript:'<html></html>';" });
			if( offset.left - scroll + target.width() > $(window).width() ){
				target.css({
					left: "auto",
					top: offset.top + 32 + "px", // default row height is 32px, adjust if necessary
					right: 0 - scroll + "px"
				})
			}
		}

		else if (target2.is(":visible")){
			target2.css("display","none");
		}
		else if (target2.is(":hidden")){
			$("div.help:visible").css("display","none");
			target2.css({
				display: "block",
				top: offset.top + "px",
				left: $(this).width() + offset.left + "px",
				right: "auto"
			})
			.bgiframe({ src: "javascript:'<html></html>';" });
			if( offset.left - scroll + target2.width() > $(window).width() ){
				target2.css({
					left: "auto",
					top: offset.top + 32 + "px", // default row height is 32px, adjust if necessary
					right: 0 - scroll + "px"
				})
			}
		}
	});
	$("div.help p.close a").click(function(){
		$("div.help:visible").css("display","none");
		return false;
	});
}

function toggleActions() {
		if( $("ul.menu").length > 0 ) {
		$("table.data tbody td.actions ul.menu > li").hover(
			function(){
				$(this).children("div").css("display", "block");
					$(this).children("div").css("margin-left", $(this).children("span").width() - $(this).children("div").width() + 79);
				if($.browser.msie && ($.browser.version < 8) ){
					$(this).children("div").css("margin-left", - $(this).children("div").width() - 2);
				}
				$(this).children("a").addClass("open");
			},
			function(){
				$(this).children("div").css("display","none");
				$(this).children("a").removeClass("open");
			}
		);
	}
}

var setUsername = {
	init : function(){
		$("input:text.username-input").blur(this.blurIt);
	},
	blurIt : function(){
		var value = $(this).val();
		$("table.form td.username-output strong").text(value);

		return false;
	}
};

/* disable popup fields */

function enableShoplist() {
	$("table.shoplist-save input.text, table.shoplist-save select").focus(function(){
		$(this).parent().parent().children().children("input:radio").attr("checked","checked");
	});
}

function disableShoplist() {

}

var territory = {
	get: function(select) {
		var id = select.options[select.selectedIndex].value;
	 	$.getJSON('/territory/get-territory/id/' + id, function(data){
	 		var options = '';
	 		$.each(data, function(id, item){
	 			 options += '<option value="' + id + '">' + item + '</option>';
	 		});

	 		$("select#city").html(options);
	 	});
	}
}

var AddressTerritory = {
	get: function (object, key) {
		var countyId = $(object).val();

	 	$.getJSON('/territory/get-territory/id/' + countyId, function (data) {
	 		var options = '<option value="" class="label">- ' + chooseText + ' -</option>';
	 		$.each(data, function(id, item){
	 			 options += '<option value="' + id + '">' + item + '</option>';
	 		});

	 		$('select#city-' + key).html(options);
	 	});
	}
};

var Car = {
	year: null,
	make: null,
	model: null,
	bodyType: null,
	power: null,
	fuel: null,
	drive: null,

	getMakesByYear: function(select) {
		if (select != null) {
			this.year = select.options[select.selectedIndex].value;
			this.make = null;
			this.model = null;
			this.bodyType = null;
			this.power = null;
			this.fuel = null;
			this.drive = null;
		}
		$.getJSON('/car/get-makes-by-year/year/' + this.year, function(data) {
	 		var options = '';
	 		options += '<option value="" class="label">- ' + chooseText + ' -</option>';
	 		$("select#model").html(options);
	 		$.each(data, function(id, item) {
	 			options += '<option id="' + id + '" value="' + id + '">' + item + '</option>';
	 		});
	 		$("select#make").html(options);
	 		
	 		
	 		
	 		$("#" + Car.make).attr('selected', true); 		
	 	});
		
	},

	getModelsByMakeAndYear: function(select) {
		if (select != null) {
			Car.make = select.options[select.selectedIndex].value;
			this.model = null;
			this.bodyType = null;
			this.power = null;
			this.fuel = null;
			this.drive = null;
		}

	 	$.getJSON('/car/get-models-by-make-and-year/make/' + Car.make + '/year/' + this.year, function(data) {
	 		var options = '';
	 		options += '<option class="label" value="">- ' + chooseText + ' -</option>';
	 		$.each(data, function(id, item) {
	 			options += '<option id="' + id + '" value="' + id + '">' + item + '</option>';
	 		});

	 		$("select#model").html(options);
	 		$("#" + Car.model).attr('selected', true);
	 	});
	},

	getBodyTypesByMakeAndModelAndYear: function(select) {
		if (select != null) {
			Car.model = select.options[select.selectedIndex].value;
			this.bodyType = null;
			this.power = null;
			this.fuel = null;
			this.drive = null;
		}

	 	$.getJSON('/car/get-body-types-by-make-and-model-and-year/make/' + Car.make + '/model/' + Car.model + '/year/' + Car.year, function(data) {
	 		var options = '';
	 		options += '<option value="" class="label">- ' + chooseText + ' -</option>';
	 		$.each(data, function(id, item) {
	 			options += '<option id="' + id + '" value="' + id + '">' + item + '</option>';
	 		});

	 		$("select#bodyType").html(options);
	 		$("#" + Car.bodyType).attr('selected', true);
	 	});
	},

	getFuelsByMakeAndModelAndBodyTypeAndYear: function(select) {
		if (select != null) {
			this.bodyType = select.options[select.selectedIndex].value;
			this.power = null;
			this.drive = null;
			this.fuel = null;
		}
		$('[name="fuel"]').attr('disabled', true);
	 	$.getJSON('/car/get-fuels-by-make-and-model-and-body-type-and-year/make/' + this.make + '/model/' + this.model + '/bodyType/' + this.bodyType + '/year/' + this.year, function(data) {
	 		var first = true;
	 		$.each(data, function(id, item) {
	 			if (first) {
	 				first = false;
	 				Car.fuel = id;
	 			}
	 			$('#radioFuel' + id).attr('disabled', false);
	 		});
	 		//Car.getPowersByMakeAndModelAndFuelAndBodyTypeAndYear(null);
	 	});

	},

	getPowersByMakeAndModelAndFuelAndBodyTypeAndYear: function(select) {
		if (select != null) {
			this.fuel = select.value;
			this.drive = null;
		}
	 	$.getJSON('/car/get-powers-by-make-and-model-and-fuel-and-body-type-and-year/make/' + this.make + '/model/' + this.model + '/fuel/' + this.fuel + '/bodyType/' + Car.bodyType + '/year/' + Car.year, function(data) {
	 		var options = '';
	 		options += '<option value="" class="label">- ' + chooseText + ' -</option>';
	 		$.each(data, function(id, item) {
	 			options += '<option id="' + id + '" value="' + id + '">' + item + 'kW</option>';
	 		});
	 		$("select#power").html(options);

	 	});
	},



	getDrivesByMakeAndModel: function(select) {
		if (select != null) {
			this.drive = select.options[select.selectedIndex].value;
		}
		$('[name="drive"]').attr('disabled', true);
	 	$.getJSON('/car/get-drives-by-make-and-model/make/' + this.make + '/model/' + this.model, function(data) {
	 		$.each(data, function(id, item) {
	 			$('#radioDrive' + id).attr('disabled', false);
	 		});

	 	});
	}
}

var Part = {

	mainCategory: null,
	subCategory: null,
	part: null,
	swappedSelects: false,
	widthRimValue : '',


	getSubCategories: function(select, fromAdding) {
		if (select != null) {
			this.mainCategory = select.options[select.selectedIndex].value;
		}
		$.getJSON('/part/get-sub-categories/mainCategory/' + this.mainCategory, function(data) {
	 		var options = '';
	 		if (fromAdding) {
	 			var adding = '- ' + chooseText + ' - ';
	 		} else {
	 			var adding = '- ' + partCategoryText + ' -';
	 		}
	 		options += '<option class="label" value="">' + adding + '</option>';
	 		$.each(data, function(id, item) {
	 			options += '<option id="' + id + '" value="' + id + '" title="' + item + '">' + item + '</option>';
	 		});
	 		$("select#subCategory").html(options);
	 	});
	},

	init: function (subCategory) {
		var withRim;
		var diameter;
		
		if (this.swappedSelects) {
			withRim = $('#diameterParent').html();
			diameter = $('#widthRimParent').html();
			$('#widthRimParent').html(withRim);
			$('#diameterParent').html(diameter);
			
			if (withRim == null || diameter == null) {
				withRim = $('#diameter').html();
				diameter = $('#widthRim').html();
				$('#widthRim').html(withRim);
				$('#diameter').html(diameter);
			}
			this.swappedSelects = false;
		}
		
		if (subCategory == 'SC_REH') {
			$('#diameter').show();
			$('#widthRim').show();
			$('#widthRimSelect').show();
			$.getJSON('/domain-value/get-width-rims/', function(data) {
				if (Part.fromAdding) {
		 			var adding = '- ' + chooseText + ' - ';
		 		} else {
		 			var adding = '- ' + widthRimText + ' -';
		 		}
				
				var options = '<option class="label" value="">' + adding +'</option>';
		 		$.each(data, function(id, item) {
		 			options += '<option id="widthRimValue_' + item + '" value="' + item + '">' + item + '</option>';
		 		});
		 		$("select#widthRimSelect").html(options);
		 		$("#widthRimValue_" + Part.widthRimValue).attr('selected', true);
		 		$("input#widthRimType").val('SC_REH');
		 	});
			
			
			$('#profile').show();
			$('#boltPattern').hide();
		} else if (subCategory == 'SC_VEL') {
			if (!this.swappedSelects) {
				withRim = $('#widthRimParent').html();
				diameter = $('#diameterParent').html();
				$('#widthRimParent').html(diameter);
				$('#diameterParent').html(withRim);

				if (withRim == null || diameter == null) {
					withRim = $('#widthRim').html();
					diameter = $('#diameter').html();
					$('#widthRim').html(diameter);
					$('#diameter').html(withRim);
				}

				this.swappedSelects = true;
			}
			
			$('#diameter').show();
			$('#widthRim').show();
			$('#widthRimSelect').show();
			$.getJSON('/domain-value/get-width-rims-wheel/', function(data) {
				if (Part.fromAdding) {
		 			var adding = '- ' + chooseText + ' - ';
		 		} else {
		 			var adding = '- ' + widthRimText + ' -';
		 		}
				
				var options = '<option class="label" value="">' + adding +'</option>';
		 		$.each(data, function(id, item) {
		 			options += '<option id="widthRimValue_' + ((item/0.5) % 2 == 0 ? item : (item-0.5) + '_') + '" value="' + item + '">' + ((item/0.5) % 2 == 0 ? item + '.0' : item) + '"</option>';
		 		});

		 		$("select#widthRimSelect").html(options);
		 		$("#widthRimValue_" + ((Part.widthRimValue/0.5) % 2 == 0 ? Part.widthRimValue : (Part.widthRimValue-0.5) + '_')).attr('selected', true); 
		 		$("input#widthRimType").val('SC_VEL');
		 	});
			
			$('#profile').hide();
			$('#boltPattern').show();
		} else if (subCategory == 'SC_ILU') {
			$('#diameter').show();
			$('#widthRim').hide();
			$('#widthRimSelect').hide();
			$('#profile').hide();
			$('#boltPattern').hide();
		} else {
			$('#diameter').hide();
			$('#widthRim').hide();
			$('#widthRimSelect').hide();
			$('#profile').hide();
			$('#boltPattern').hide();
			
		}
	},

	getParts: function(select, fromAdding) {
		if (select != null) {
			this.subCategory = select.options[select.selectedIndex].value;
			Part.init(this.subCategory);
		}
		
		

		$.getJSON('/part/get-parts/subCategory/' + this.subCategory, function(data) {
	 		var options = '';
	 		if (fromAdding) {
	 			var adding = '- ' + chooseText + ' - ';
	 		} else {
	 			var adding = '- ' + partText + ' -';
	 		}
	 		options += '<option  class="label" value="">' + adding + '</option>';
	 		$.each(data, function(id, item) {
	 			options += '<option id="' + id + '" value="' + id + '" title="' + item + '">' + item + '</option>';
	 		});
	 		$("select#part").html(options);
	 	});
	}
};

var SearchForm = {

	year: null,
	make: null,
	model: null,

	init: function() {
		$('#diameter').hide();
		$('#widthRim').hide();
		$('#boltPattern').hide();
		$('#profile').hide();
	},

	getMakesByYear: function(select) {
		if (select != null) {
			this.year = select.options[select.selectedIndex].value;
			this.make = null;
			this.model = null;
		}
		$.getJSON('/car/get-makes-by-year/year/' + this.year, function(data) {
	 		var options = '';
	 		var first = false;
	 		options += '<option class="label" value="">* - ' + makeText + ' -</option>';
	 		$.each(data, function(id, item) {
	 			options += '<option id="' + id + '" value="' + id + '">' + item + '</option>';
	 		});
	 		$("select#make").html(options);
	 		$("select#calculatorMake").html(options);
	 		$("#" + SearchForm.make).attr('selected', true);
	 		
	 		$("select#model").html('<option class="label" value="">* - ' + modelText +' -</option>');
	 		$("select#calculatorModel").html('<option class="label" value="">* - Mudel -</option>');

	 		var yearSearch = $('select#year');
	 		var yearCalc = $('select#calculatorYear');
			yearSearch[0].selectedIndex = select.selectedIndex
			yearCalc[0].selectedIndex = select.selectedIndex

		});
	},

	getModelsByMakeAndYear: function(select) {
		if (select != null) {
			SearchForm.make = select.options[select.selectedIndex].value;
			this.model = null;
		}

	 	$.getJSON('/car/get-models-by-make-and-year/make/' + SearchForm.make + '/year/' + this.year, function(data) {
	 		var options = '';
	 		var first = false;
	 		options += '<option class="label" value="">* - ' + modelText +' -</option>';
	 		$.each(data, function(id, item) {
	 			options += '<option id="' + id + '" value="' + id + '">' + item + '</option>';
	 		});

	 		$("select#model").html(options);
	 		$("select#calculatorModel").html(options);
	 		$("#" + SearchForm.model).attr('selected', true);

	 		var makeSearch = $('select#make');
	 		var makeCalc = $('select#calculatorMake');
			makeSearch[0].selectedIndex = select.selectedIndex
			makeCalc[0].selectedIndex = select.selectedIndex
	 	});
	},

	getBodyTypesByMakeAndModelAndYear: function(select) {
		if (select != null) {
			SearchForm.model = select.options[select.selectedIndex].value;
			this.bodyType = null;
		}

	 	$.getJSON('/car/get-body-types-by-make-and-model-and-year/make/' + SearchForm.make + '/model/' + SearchForm.model + '/year/' + SearchForm.year, function(data) {
	 		var options = '';
	 		options += '<option value="" class="label">- ' + bodyTypeText +' -</option>';
	 		$.each(data, function(id, item) {
	 			options += '<option id="' + id + '" value="' + id + '">' + item + '</option>';
	 		});

	 		$("select#bodyType").html(options);
	 		$("select#calculatorBodyType").html(options);
	 		$("select#calculatorBodyType2").html(options);
	 		$("#" + SearchForm.bodyType).attr('selected', true);

	 		var modelSearch = $('select#model');
	 		var modelCalc = $('select#calculatorModel');
			modelSearch[0].selectedIndex = select.selectedIndex
			modelCalc[0].selectedIndex = select.selectedIndex
	 	});

	},

	getPowersByMakeAndModelAndYear: function(select) {
		if (select != null) {
			this.bodyType = select.options[select.selectedIndex].value;
			this.drive = null;
		}

	 	$.getJSON('/car/get-powers-by-make-and-model-and-year/make/' + this.make + '/model/' + this.model + '/year/' + SearchForm.year, function(data) {
	 		var options = '';
	 		options += '<option value="" class="label">- ' + engineText +' -</option>';
	 		$.each(data, function(id, item) {
	 			options += '<option id="' + id + '" value="' + id + '">' + item + 'kW</option>';
	 		});
	 		$("select#power").html(options);
	 		$("select#calculatorPower1").html(options);
	 		$("select#calculatorPower3").html(options);
	 	});

	},

	getDrivesByMakeAndModel: function(select) {
		if (select != null) {
			this.drive = select.options[select.selectedIndex].value;
		}
	 	$.getJSON('/car/get-drives-by-make-and-model/make/' + this.make + '/model/' + this.model, function(data) {
	 		var options = '';
	 		options += '<option value="" class="label">- ' + driveText +' -</option>';
	 		$.each(data, function(id, item) {
	 			options += '<option id="' + id + '" value="' + id + '">' + item + '</option>';
	 		});
	 		$("select#drive").html(options);
	 		$("select#calculatorDrive1").html(options);
	 	});
	},

	changeTooltip: function(model) {
		$('#tooltipImg').html('<img src="/car/show-picture/model/' + model + '" alt="" />');
	},

	changeValue: function(select, element) {
		selectValue = select.options[select.selectedIndex].value;
		$('#' + element).val(selectValue);
	}

};

var Product = {
	init: function() {
		$('#radio02b1').click(function() {
			Product.enableCarStep();
			$('span#partText').text(addpartText);
		});

		$('#radio02b2').click(function() {
			Product.enableCarStep();
			$('span#partText').text(addpartsText);
		});
		$('#radio02b3').click(function() {
			Product.disableCarStep();
			$('span#partText').text(addpartText);
		});
	},

	disableCarStep: function() {
		$('li#car').addClass('disabled');
	},

	enableCarStep: function() {
		$('li#car').removeClass('disabled');
	},

	showParts: function(mainCategory) {
		if ($('#data-' + mainCategory).html() == 0) {
			$.ajax({
				url: '/product/show-car-parts/mainCategory/' + mainCategory,
				type: 'POST',
				success: function(html) {
					$('#data-' + mainCategory).html(html);
				}
			});
		}
	},

	deleteImage: function(image) {
		$('#img-' + image).hide();
		$('#txt-' + image).hide();
		$('#deleted' + image).val('1');
	}
};

var ShoppingList = {

	add: function(id, carId) {
		$.post('/shopping-list/add', {
			'advertisementId': id,
			'amount': 1,
			'carId': carId
		}, function () {
			if ($('#shopping-list-count').html() == null) {
				$('#shopping-list-element').html('<a href="/shopping-list/list">Ostukorv (<span id="shopping-list-count">0</span>)</a>');
			}
			
			$('#shopping-list-count').html(parseInt($('#shopping-list-count').html()) + 1);
			$('#amount-' + id).html(parseInt($('#amount-' + id).html()) + 1);
			
			$('#sum-' + id).html(Math.round(parseInt($('#amount-' + id).html()) * (parseFloat($('#price-' + id).html())) * 100) / 100);
			$('#total').html(Math.round((parseFloat($('#total').html()) + parseFloat($('#price-' + id).html())) * 100) / 100);
			
			setTimeout(function() {
				$('#shopping-list-element').addClass('active');
				setTimeout(function() {
					$('#shopping-list-element').removeClass('active');
					setTimeout(function() {
						$('#shopping-list-element').addClass('active');
						setTimeout(function() {
							$('#shopping-list-element').removeClass('active');
							setTimeout(function() {
								$('#shopping-list-element').addClass('active');
								setTimeout(function() {
									$('#shopping-list-element').removeClass('active');
							   	}, 500);
						   	}, 500);
					   	}, 500);
				   	}, 500);
			   	}, 500);
		   	}, 500);
			
			
			$('#popup-added').show(); 
		   	
		   	setTimeout(function() {
		   			$('#popup-added').fadeOut('slow'); 
		   	}, 2500);
		});
	},
	
	removeOne: function(id) {
		$.post('/shopping-list/remove-one', {
			'advertisementId': id,
			'amount': 1
		}, function () {
			if (parseInt($('#amount-' + id).html()) > 1) {
				$('#shopping-list-count').html(parseInt($('#shopping-list-count').html()) - 1);
				$('#amount-' + id).html(parseInt($('#amount-' + id).html()) - 1);
				$('#sum-' + id).html(Math.round(parseInt($('#amount-' + id).html()) * (parseFloat($('#price-' + id).html())) * 100) / 100);
				$('#total').html(Math.round((parseFloat($('#total').html()) - parseFloat($('#price-' + id).html())) * 100) / 100);
			} else {
				if (confirm('Kustutada toode?')) {
					ShoppingList.remove(id);
				}
			}
		});
	},
	
	remove: function(id) {
		$.post('/shopping-list/remove', {
			'advertisementId': id
		}, function () {
			$('#shopping-list-count').html(parseInt($('#shopping-list-count').html()) - 1);
			window.location.href = '';
		});
	},
	editableAddress: function() {
		$('#firstNameSpan').html('<input type="text" name="firstName" class="text" value="' + $('#firstName').val() + '" />');
		$('#firstName').remove();
		
		$('#lastNameSpan').html('<input type="text" name="lastName" class="text" value="' + $('#lastName').val() + '" />');
		$('#lastName').remove();
		
		$('#companySpan').html('<input type="text" name="company" class="text" value="' + $('#company').val() + '" />');
		$('#company').remove();
		
		$('#countySpan').html('<input type="text" name="county_name" class="text" value="' + $('#county').val() + '" />');
		$('#county').remove();
		
		$('#citySpan').html('<input type="text" name="city_name" class="text" value="' + $('#city').val() + '" />');
		$('#city').remove();
		
		$('#addressSpan').html('<input type="text" name="address" class="text" value="' + $('#address').val() + '" />');
		$('#address').remove();
		
		$('#indexSpan').html('<input type="text" name="index" class="text" value="' + $('#index').val() + '" />');
		$('#index').remove();
		
		$('#phoneSpan').html('<input type="text" name="phone" class="text" value="' + $('#phone').val() + '" />');
		$('#phone').remove();
		
		$('#button-change').remove();
	}
	
};

var Util = {

	findId: function(string) {
		var id = /\-(\d+)/.exec(string);
		if (
			(id != null)
			&& (id[1] != undefined)
		) {
			return id[1];
		} else {
			return null;
		}
	},

	setLoading: function(fieldObject) {
		$(fieldObject).text('');
		$(fieldObject).append('<div class="ajax-loading"><img src="/gfx/ico_loading.gif" width="16" height="16" alt="" /></div>');
	}

}

var toggleAddresses = {
	toggle: function(object) {
		if ($(object).attr('checked')) {
			$('#address-wrapper').show();
		} else {
			$('#address-wrapper').hide();
		}
	}
};

var Maps = {
	addressString: null,
	map: null,
	init: function() {
	
		geocoder = new google.maps.Geocoder();
	    var myOptions = {
	      zoom: 13,
	      mapTypeId: google.maps.MapTypeId.ROADMAP
	    };
	    if (document.getElementById("map_canvas") != undefined) {
	    	Maps.map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	    	
	    }
	},
	
	address: function() {
	    var address = Maps.addressString;
	    if (geocoder) {
	      geocoder.geocode( { 'address': address}, function(results, status) {
	        if (status == google.maps.GeocoderStatus.OK) {
	          Maps.map.setCenter(results[0].geometry.location);
	          
	          var marker = new google.maps.Marker({
	              map: Maps.map, 
	              position: results[0].geometry.location
	          });
	          
	        } else {
	        	alert("Geocode was not successful for the following reason: " + status);
	        }
	      });
	    }
	}
};

function filter_check(id){
	if($('#' + id).is(':checked')){
		$('#' + id + "-sub").show('fast');
	}
	else {
		$('#' + id + "-sub").hide('fast');
	}
}

var Filter = {
	partsTree: null,
	mainCategories: new Object(),
	make: null,
	model: null,
	currentPage: 1,
	results: null,
	resultsToPage: 40,
	sortOrder: 'desc',
	sortBy: '',
	bodyTypes: new Object(),
	partTypes: new Object(),
	advertisementTypes: new Object(),
	colors: new Object(),
	powers: new Object(),
	gearboxes: new Object(),
	drives: new Object(),
	counties: new Object(),
		
	init: function (make, model) {
		Filter.make = make;
		Filter.model = model;
		
		$('#toggler INPUT:checked').each(function() {
			var func = $(this).attr('onclick');
			func();
		});
		
		Filter.reload(true);
	},
	
	initSort: function (order) {
		$('#sort-now').click(function(){
			Filter.reload();
		});
		$('#sort-ads #' + order).attr('selected', 'selected');
		$('#sort-ads').change(function() {
			Filter.sortOrder = $(this).val();
			Filter.sortBy = 'id';
			//Filter.reload();
		});
		
		
		$('#part').click(function(){
			if (Filter.sortOrder == 'desc') {
				Filter.sortOrder = 'asc';
			} else {
				Filter.sortOrder = 'desc';
			}
			Filter.sortBy = 'part';
			Filter.reload();
		});
		
		$('#seller').click(function(){
			if (Filter.sortOrder == 'desc') {
				Filter.sortOrder = 'asc';
			} else {
				Filter.sortOrder = 'desc';
			}
			Filter.sortBy = 'seller';
			Filter.reload();
		});
		
		$('#price').click(function(){
			if (Filter.sortOrder == 'desc') {
				Filter.sortOrder = 'asc';
			} else {
				Filter.sortOrder = 'desc';
			}
			Filter.sortBy = 'price';
			Filter.reload();
		});
		
		if (Filter.sortOrder == 'desc') {
			$(this).parents("thead").find("th").removeClass("ascending");
			$(this).parents("thead").find("th").removeClass("descending");
			$('#' + Filter.sortBy).parent().addClass('ascending');
		} else {
			$(this).parents("thead").find("th").removeClass("ascending");
			$(this).parents("thead").find("th").removeClass("descending");
			$('#' + Filter.sortBy).parent().addClass('descending');
		}
		
	},
	
	initPaginator: function (results) {
		Filter.results = results;
		Filter.drawPages();
		jQuery(window).hashchange( function(e) {
			Filter.currentPage = location.hash.substring(1);
			Filter.reload();
		});
		
		$('#pages .pagenr').click(function() {
			Filter.currentPage = parseInt($(this).html());
			window.location.hash = Filter.currentPage;
			
			Filter.reload();
		});
		$('#pages .next').click(function() {
			Filter.currentPage++;
			Filter.reload();
		});
		$('#pages .last').click(function() {
			Filter.currentPage = Math.ceil(Filter.results/40);
			Filter.reload();
		});
		$('#pages .first').click(function() {
			Filter.currentPage = 1;
			Filter.reload();
		});
		$('#pages .back').click(function() {
			Filter.currentPage--;
			Filter.reload();
		});
		var showing = Filter.currentPage * Filter.resultsToPage;
		$('#showing').html((showing - Filter.resultsToPage + 1) + '-' + (showing));
		
	},
	
	drawPages: function() {
		var pagesNr = Math.ceil(Filter.results/Filter.resultsToPage);
		if (Filter.currentPage == 1) {
			var html = '<li class="first"><span>&lt;&lt;</span></li><li class="back"><span>&lt;</span></li>';
		} else {
			var html = '<li class="first"><a href="javascript:;">&lt;&lt;</a></li><li class="back"><a href="javascript:;">&lt;</a></li>';
		}
		
		var start = Filter.currentPage - 4 <= 0 ? 1 : Filter.currentPage - 4;
		var end = Filter.currentPage + 4 >= pagesNr ? pagesNr : Filter.currentPage + 4;
		
		for (i = start; i <= end; i++) {
			if (Filter.currentPage == i) {
				html += '<li class="active"><strong>' + i + '</strong></li>';
			} else {
				html += '<li><a href="javascript:;" class="pagenr">' + i + '</a></li>';
			}
		}
		if (Filter.currentPage == pagesNr) {
			html += '<li class="next"><span>&gt;</span></li><li class="last"><span>&gt;&gt;</span></li>';
		} else {
			html += '<li class="next"><a href="javascript:;">&gt;</a></li><li class="last"><a href="javascript:;">&gt;&gt;</a></li>';
		}
		$('#pages').html(html);
	},
	
	reload: function (init) {
		
		
		
		if (!init && $('#results').length == 0) {
			$('#main-content').html('<div id="results"></div>');
		}
		$('#results').html('<img src="/gfx/ico_loading.gif">');
		$.ajax({
		   type: "POST",
		   url: "/car/search-part/",
		   data: "make=" + Filter.make + "&model=" + Filter.model + "&partTree=" + JSON.stringify(Filter.mainCategories) + '&currentPage=' + Filter.currentPage + '&sortOrder=' + Filter.sortOrder + '&sortBy=' + Filter.sortBy + '&bodyTypes=' + JSON.stringify(Filter.bodyTypes) + '&colors=' + JSON.stringify(Filter.colors) + '&powers=' + JSON.stringify(Filter.powers) + '&gearboxes=' + JSON.stringify(Filter.gearboxes) + '&drives=' + JSON.stringify(Filter.drives) + '&counties=' + JSON.stringify(Filter.counties) + '&partTypes=' + JSON.stringify(Filter.partTypes) + '&advertisementTypes=' + JSON.stringify(Filter.advertisementTypes),
		   success: function(data){
				$('#results').html(data);
				
		   }
		 });
		
	},
	
	addMainCategory: function(mainCategory, reload) {
		if (Filter.mainCategories[mainCategory] == undefined) {
			Filter.mainCategories[mainCategory] = new Object();
		} else {
			delete Filter.mainCategories[mainCategory];
		}
		Filter.currentPage = 1;
		if (!reload) {
			Filter.reload();
		}
	}, 
	
	addSubCategory: function(mainCategory, subCategory, reload) {
		if (Filter.mainCategories[mainCategory][subCategory] == undefined) {
			Filter.mainCategories[mainCategory][subCategory] = new Object();
		} else {
			delete Filter.mainCategories[mainCategory][subCategory];
		}
		Filter.currentPage = 1;
		if (!reload) {
			Filter.reload();
		}
	},
	
	addPart: function(mainCategory, subCategory, partId, reload) {
		if (Filter.mainCategories[mainCategory][subCategory][partId] == undefined) {
			Filter.mainCategories[mainCategory][subCategory][partId] = partId;
		} else {
			delete Filter.mainCategories[mainCategory][subCategory][partId];
		}
		Filter.currentPage = 1;
		if (!reload) {
			Filter.reload();
		}
	},
	
	addBodyType: function(bodyType) {
		if (Filter.bodyTypes[bodyType] == undefined) {
			Filter.bodyTypes[bodyType] = bodyType;
		} else {
			delete Filter.bodyTypes[bodyType];
		}
		Filter.currentPage = 1;
		Filter.reload();
	},
	
	addPartType: function(partType) {
		if (Filter.partTypes[partType] == undefined) {
			if (partType == 1) {
				Filter.partTypes[2] = 2;
			}
			Filter.partTypes[partType] = partType;
		} else {
			if (partType == 1) {
				delete Filter.partTypes[2];
			}
			delete Filter.partTypes[partType];
		}
		Filter.currentPage = 1;
		Filter.reload();
	},
	
	addAdvertisementType: function() {
		if (Filter.advertisementTypes[2] == undefined && Filter.advertisementTypes[4] == undefined) {
			Filter.advertisementTypes[2] = 2;
			Filter.advertisementTypes[4] = 4;
		} else {
			delete Filter.advertisementTypes[2];
			delete Filter.advertisementTypes[4];
		}
		Filter.currentPage = 1;
		Filter.reload();
	},
	
	addColorCar: function(color) {
		if (Filter.colors[color] == undefined) {
			Filter.colors[color] = colors;
		} else {
			delete Filter.colors[color];
		}
		Filter.currentPage = 1;
		Filter.reload();
	},
	
	addPower: function (engine, engine_kw) {
		if (Filter.powers[engine + "-" + engine_kw] == undefined) {
			Filter.powers[engine + "-" + engine_kw] = engine + "-" + engine_kw;
		} else {
			delete Filter.powers[engine + "-" + engine_kw];
		}
		Filter.currentPage = 1;
		Filter.reload();
	},
	
	addGearbox: function(gearbox) {
		if (Filter.gearboxes[gearbox] == undefined) {
			Filter.gearboxes[gearbox] = gearbox;
		} else {
			delete Filter.gearboxes[gearbox];
		}
		Filter.currentPage = 1;
		Filter.reload();
	},
	
	addDrive: function(drive) {
		if (Filter.drives[drive] == undefined) {
			Filter.drives[drive] = drive;
		} else {
			delete Filter.drives[drive];
		}
		Filter.currentPage = 1;
		Filter.reload();
	},
	
	addCounty: function(id) {
		if (Filter.counties[id] == undefined) {
			Filter.counties[id] = id;
		} else {
			delete Filter.counties[id];
		}
		Filter.currentPage = 1;
		Filter.reload();
	}
};

var MostSearched = {
		partsTree: null,
		currentPage: 1,
		results: null,
		resultsToPage: 40,
		sortOrder: 'desc',
		sortBy: 'id',
		parts: new Object(),
		counties: new Object(),
		profiles: new Object(),
		widths: new Object(),
		diameters: new Object(),
		bolts: new Object(),
		part: null,
		
		init: function (part) {
			MostSearched.part = part;
			$('#toggler INPUT:checked').each(function() {
				var func = $(this).attr('onclick');
				func();
			});
			MostSearched.reload();
		},
		
		initSort: function (order) {
			$('#sort-now').click(function(){
				MostSearched.reload();
			});
			$('#sort-ads #' + order).attr('selected', 'selected');
			$('#sort-ads').change(function() {
				MostSearched.sortOrder = $(this).val();
				//MostSearched.reload();
			});
			
			$('#part').click(function(){
				if (MostSearched.sortOrder == 'desc') {
					MostSearched.sortOrder = 'asc';
				} else {
					MostSearched.sortOrder = 'desc';
				}
				MostSearched.sortBy = 'part';
				MostSearched.reload();
			});
			
			$('#seller').click(function(){
				if (MostSearched.sortOrder == 'desc') {
					MostSearched.sortOrder = 'asc';
				} else {
					MostSearched.sortOrder = 'desc';
				}
				MostSearched.sortBy = 'seller';
				MostSearched.reload();
			});
			
			$('#price').click(function(){
				if (MostSearched.sortOrder == 'desc') {
					MostSearched.sortOrder = 'asc';
				} else {
					MostSearched.sortOrder = 'desc';
				}
				MostSearched.sortBy = 'price';
				MostSearched.reload();
			});
			
			if (MostSearched.sortOrder == 'desc') {
				$(this).parents("thead").find("th").removeClass("ascending");
				$(this).parents("thead").find("th").removeClass("descending");
				$('#' + MostSearched.sortBy).parent().addClass('ascending');
			} else {
				$(this).parents("thead").find("th").removeClass("ascending");
				$(this).parents("thead").find("th").removeClass("descending");
				$('#' + MostSearched.sortBy).parent().addClass('descending');
			}
		},
		
		initPaginator: function (results) {
			MostSearched.results = results;
			MostSearched.drawPages();
			
			$('#pages .pagenr').click(function() {
				MostSearched.currentPage = parseInt($(this).html());
				MostSearched.reload();
			});
			$('#pages .next').click(function() {
				MostSearched.currentPage++;
				MostSearched.reload();
			});
			$('#pages .last').click(function() {
				MostSearched.currentPage = Math.ceil(MostSearched.results/40);
				MostSearched.reload();
			});
			$('#pages .first').click(function() {
				MostSearched.currentPage = 1;
				MostSearched.reload();
			});
			$('#pages .back').click(function() {
				MostSearched.currentPage--;
				MostSearched.reload();
			});
			var showing = MostSearched.currentPage * MostSearched.resultsToPage;
			$('#showing').html((showing - MostSearched.resultsToPage + 1) + '-' + (showing));
		},
		
		drawPages: function() {
			var pagesNr = Math.ceil(MostSearched.results/MostSearched.resultsToPage);
			if (MostSearched.currentPage == 1) {
				var html = '<li class="first"><span>&lt;&lt;</span></li><li class="back"><span>&lt;</span></li>';
			} else {
				var html = '<li class="first"><a href="javascript:;">&lt;&lt;</a></li><li class="back"><a href="javascript:;">&lt;</a></li>';
			}
			
			var start = MostSearched.currentPage - 4 <= 0 ? 1 : MostSearched.currentPage - 4;
			var end = MostSearched.currentPage + 4 >= pagesNr ? pagesNr : MostSearched.currentPage + 4;
			
			for (i = start; i <= end; i++) {
				if (MostSearched.currentPage == i) {
					html += '<li class="active"><strong>' + i + '</strong></li>';
				} else {
					html += '<li><a href="javascript:;" class="pagenr">' + i + '</a></li>';
				}
			}
			if (MostSearched.currentPage == pagesNr) {
				html += '<li class="next"><span>&gt;</span></li><li class="last"><span>&gt;&gt;</span></li>';
			} else {
				html += '<li class="next"><a href="javascript:;">&gt;</a></li><li class="last"><a href="javascript:;">&gt;&gt;</a></li>';
			}
			$('#pages').html(html);
		},
		
		reload: function () {
			$('#results').html('<img src="/gfx/ico_loading.gif">');
			$.ajax({
			   type: "POST",
			   url: "/car/search-part/mostSearched/1",
			   data: "&subCategory=" + MostSearched.part + "&parts=" + JSON.stringify(MostSearched.parts) + '&currentPage=' + MostSearched.currentPage + '&sortOrder=' + MostSearched.sortOrder + '&sortBy=' + MostSearched.sortBy + '&counties=' + JSON.stringify(MostSearched.counties) + '&profiles=' + JSON.stringify(MostSearched.profiles) + '&widths=' + JSON.stringify(MostSearched.widths) + '&diameters=' + JSON.stringify(MostSearched.diameters) + '&bolts=' + JSON.stringify(MostSearched.bolts),
			   success: function(data){
					$('#results').html(data);
			   }
			 });
		},
		
		addPart: function(partId) {
			if (MostSearched.parts[partId] == undefined) {
				MostSearched.parts[partId] = partId;
			} else {
				delete MostSearched.parts[partId];
			}
			MostSearched.currentPage = 1;
			MostSearched.reload();
		},
		
		addWidth: function(width) {
			if (MostSearched.widths[width] == undefined) {
				MostSearched.widths[width] = width;
			} else {
				delete MostSearched.widths[width];
			}
			MostSearched.currentPage = 1;
			MostSearched.reload();
		},
		
		addBolt: function(bolt) {
			if (MostSearched.bolts[bolt] == undefined) {
				MostSearched.bolts[bolt] = bolt;
			} else {
				delete MostSearched.bolts[bolt];
			}
			MostSearched.currentPage = 1;
			MostSearched.reload();
		},
		
		addDiameter: function(diameter) {
			if (MostSearched.diameters[diameter] == undefined) {
				MostSearched.diameters[diameter] = diameter;
			} else {
				delete MostSearched.diameters[diameter];
			}
			MostSearched.currentPage = 1;
			MostSearched.reload();
		},
		
		addProfile: function(profile) {
			if (MostSearched.profiles[profile] == undefined) {
				MostSearched.profiles[profile] = profile;
			} else {
				delete MostSearched.profiles[profile];
			}
			MostSearched.currentPage = 1;
			MostSearched.reload();
		},
		
		
		addCounty: function(id) {
			if (MostSearched.counties[id] == undefined) {
				MostSearched.counties[id] = id;
			} else {
				delete MostSearched.counties[id];
			}
			MostSearched.currentPage = 1;
			MostSearched.reload();
		}
	};

var Clicks = {
		
	show: function (a, id, type) {
		if (type == undefined) {
			type = 'day';
		}
		var response = $.ajax({
		   type: "GET",
		   async: false,
		   url: "/user/advertisement-clicks/advertisementId/" + id + '/type/' + type,
		   	success: function(data){
				
		   }
		 }).responseText;
		$('#graph-'+a+'-'+ + id).html(response);
		
		$('.day').css('color', '');
		$('.week').css('color', '');
		$('.month').css('color', '');
		$('.' + type).css('color', 'black');
		return false;
	}
};

var Tags = {
		init: function () {
			$("#tag").autocomplete(
				"/blog/autocomplete", {
					delay:10,
					minChars:1,
					matchContains:1,
					cacheLength:10,
					autoFill:false
				}
			);
		}
	};
/* document ready */

var Importer = {
	model: null,
		
	loadModels: function (make, model, relationModel) {
		$.getJSON('/importer/get-models/make/' + make, function(data) {
	 		var options = '';
	 		var selected = '';
	 		var isSelected = false;
	 		var selectedId = null;
	 		/*$.each(data, function(id, item) {
	 			if (item.toLowerCase() == model.toLowerCase() && isSelected == false) {
	 				selected = 'selected="selected"';
	 				isSelected = true;
	 				selectedId = id;
	 			}
	 		});*/
	 		$.each(data, function(id, item) {
	 			if (item.substring(0, 5).toLowerCase() == model.substring(0, 5).toLowerCase() || id == relationModel) {
	 				isSelected = true;
	 				selectedId = id;
	 			}
	 			
	 			if (id == relationModel) {
	 				return false;
	 			}
	 		});
	 		
	 		if (isSelected == false) {
		 		$.each(data, function(id, item) {
		 			if (item.substring(0, 3) == model.substring(0, 3)) {
		 				isSelected = true;
		 				selectedId = id;
		 			}
		 		});
	 		}
	 		
	 		$.each(data, function(id, item) {
	 			options += '<option id="id-' + id + '" value="' + id + '">' + item + '</option>';
	 			selected = '';
	 		});
	 		$("select#model").html(options);
	 		$("#id-" + selectedId).attr('selected', 'selected');
	 	});
	}
};

var Edit = {
		
	addRows: function() {
		var html = '<tr><td><select name="fuel[]"><option value="F_B">bensiin</option><option value="F_D">diisel</option><option value="F_H">hübriid</option></select></td><td><input type="text" autocomplete="off" name="engine[]" value="" /></td><td><input type="text" autocomplete="off" name="power[]" value="" /></td></tr>';
		$('#edit').append(html);
	}
};

var Repair = {
		rows: 4,
		
		addParts: function () {
			for (var i = 0; i < 4; i++) {
				this.rows++;
				$('#partsForm2').append('<tr><td style="text-align: left;width: 10px;">' + this.rows + ':</td><td style="text-align: left;"><input type="text" autocomplete="off" onKeyPress="return disableEnterKey(event)" name="partNames[]" style="width:464px;;" value="" class="text" /></td><td style="text-align: left;"><input type="text" onKeyPress="return disableEnterKey(event)" autocomplete="off" name="partCodes[]" value="" class="text" /></td></tr>');
			}
		}
};

function disableEnterKey(e)
{
     var key;
     if(window.event)
          key = window.event.keyCode;     //IE
     else
          key = e.which;     //firefox
     if(key == 13)
          return false;
     else
          return true;
}

$(document).ready(function(){

	toggleActions();

	toggleHelp();

	markRows.init();
	markAllCheck.init();
	markNoneCheck.init();
	controlRadio();
	controlCheckbox();
	setCheckbox.init();
	setRadio.init();
	setRadioDatasp.init();
	headingSort.init();
	setUsername.init();

	tooltip();

	tabs();
	tabsRadio.init();

	$("table.data tr.subrow, #calculator, div.more-spare-parts, div.i01, div.i02, div.i03").css("display","none");
	toggleSubrow.init();
	toggleSubrow2.init();
	$("table.data tbody.subrows tr").css("display","none");
	$("table.data tbody.subrows tr.toggle-level").css("display","");

	toggleH2boxes.init();
	$("div.toggle-wrap").css("display","none");
	$("div.first").css("display","");
	$("ul.check-sub").hide();
	$("ul.check-sub-sub").hide();
	
	
	$("#slider").easySlider({
		prevText:'<a href="javascript:void(0)" id="newer">' + nextText + '</a>',
		nextText:'<a href="javascript:void(0)" id="older">' + backText + '</a>',
		orientation:'horizontal'
	});
	
	$("#sliderBlog").easySlider({
		prevText:'<a href="javascript:void(0)" id="newer">' + nextText + '</a>',
		nextText:'<a href="javascript:void(0)" id="older">' + backText + '</a>',
		orientation:'horizontal'
	});
	
	$("ul.tabs").prev("h1").addClass("type1");
	$("ul.tabs").prev("p.heading-action").prev("h1").addClass("type1");
	$("ul.tabs").parent().prev("div.heading").addClass("heading-type1");
	$("p.heading-action").prev("h1").addClass("type1");
	$("ul.tabs").prev("div.heading").addClass("heading-type1");


	$("table.data-sp tr td.price input:radio:checked").next("label").css("font-weight","bold");

	fixIEoverflow();

	/* IE */
	if($.browser.msie){
	}

	/* IE6 */
	if($.browser.msie && ($.browser.version < 7) ){
		dataHover();
	}

	Product.init();
	SearchForm.init();
	
	$("input.date").datepicker();

	$("input.date").datepicker();
	$("img.help").tooltip();
	$("*[title].tooltip").tooltip();
	$("input[title]").example(function() {
		return $(this).attr('title');
	});
	
	Tags.init();

});

