jQuery(document).ready(function($){
	/* ********************
	 * DIRECTSEARCH RESULTS
	 * ********************/
	//$('.expandedlist TR').each(function(){
	var initQtips = function(list) {
		if(list.attr('qtipped'))
			return;
		start = new Date().getTime();
		log(' IMG.added_options qtip');
		$(list).find('IMG.added_options').each(function(){
			$(this).qtip({
				content: $(this).next('.tooltip').html(),
				show: { 
					delay: 0,
					when: { 
						event: 'mouseover' 
					}
				},
				hide: { 
					delay: 0,
					when: { 
						event: 'mouseout'
					} 
				},
				position: {
					corner: {
						target: 'bottomRight',
						tooltip: 'topRight'
					}
				},
				style: {
					width: 300,
					padding: 10,
					background: '#2fa3f8',
					color: '#ffffff',
					textAlign: 'left',
					border: {
						width: 3,
						radius: 5,
						color: '#2fa3f8'
					},
					tip: 'topRight'
				}
			});
		});
		list.attr('qtipped', true);
		log(' IMG.added_options qtip done');
	}
	var rowHover = function(list) {
		if(list.attr('hovered'))
			return; 
		$(list).find('TABLE TBODY TR').hover(
			function() {
				$(this).stop(true,true).addClass('active');
			},
			function() {  
				$(this).stop(true,true).removeClass('active');
			}		
		);
		list.attr('hovered', true); 
	}
	log('expandedlist hover done');
	
	var addModelDropdown = function(makeId) {
		var makeDiv = $('DIV#make_'+makeId);
		var template = $('#models_'+makeId+'_template').find("DIV#models_" + makeId);
		var modelDiv = template.clone();
		var modelCheckbox = modelDiv.children("INPUT");
		modelCheckbox.attr('checked', 'checked');
		var modelSelect = modelDiv.children("SELECT");
		modelCheckbox.click(function() {
			checkModel($(this));
		});
		modelSelect.change(function() {
			selectModel($(this).attr("makeId"), $(this).attr("makeName"));
		});
		removeAlreadySelected(makeDiv, modelSelect);
		$('DIV.#addlink_'+makeId).before(modelDiv);
		modelDiv.show();
	}
	var removeAlreadySelected = function(makeDiv, modelSelect){
		var alreadySelected = makeDiv.find('DIV.models>select>option:selected');
		alreadySelected.each(function(){
			var value = $(this).attr('value');
			log('selected: '+value);
			var temp = modelSelect.find('option[value='+value+']');
			temp.remove();
		});
		if(alreadySelected.length > 0) {
			modelSelect.find('option[name="make"]').remove();
			modelSelect.prepend('<option>selecteer een model</option>');
			modelSelect.find('option:first').attr('selected', true);
		}
	}
	
	var expandTypeResults = function (resultdiv) {
		var expandedlist = resultdiv.find(".expandedlist");
		start = new Date().getTime();
		resultdiv.find('.expand').slideToggle("slow,");
		expandedlist.slideToggle("slow,");
		rowHover(expandedlist);
		initQtips(expandedlist);
	};
	var singleModelResults = function () {
		log('Single **************************');
		var rowlist = $("#search_results");
		start = new Date().getTime();
		rowHover(rowlist);
		initQtips(rowlist);
	};
	
	var checkContractKilometers = function() {
		var duration = $("#duration").attr("value");
		var yearlyKm = $("#yearlyKm").attr("value");
		var contractKm = (duration * yearlyKm) / 12;
		var disableDiesel = contractKm > 180000;
		var disableOthers = contractKm > 150000;
		var fuelDiv = $("#ds_fuel"); 
		var fuelLu = fuelDiv.children("#fuel");
		var fuelitems = fuelLu.children('li[class!= more][class!=less]');
		fuelitems.each(function() {
			if ($(this).hasClass("D"))
				disable = disableDiesel;
			else
				disable = disableOthers; 
			$(this).children("label").each(function() {
				if ($(this).hasClass("enabledFuel")) {
					if(disable) {
						$(this).hide();
						$(this).parent().removeClass("active");
					}
					else
						$(this).show();
				}
				else if ($(this).hasClass("disabledFuel")) { 
					if(disable) {
						$(this).show();
						$(this).parent().removeClass("active");
					}
					else
						$(this).hide();
				}
			});
		});
	};
	
	var initSearchResultsDiv = function() {
		start = new Date().getTime();
		
		$('.result').hover(
			function() {  $(this).addClass('active');  },
			function() {  $(this).removeClass('active'); }
		);
		log('.result hover');
		/* toggle the next expandedlist, and toggle the clicked expand */
		$(".result .expand div").click(function(){
			var resultdiv = $(this).parents('.result');
			expandTypeResults(resultdiv);
			return false;
		});
		/* mijn progsel */
		//log('.result hover ********************aaa******');
		singleModelResults();

		log('.result .expand div click done');
		$(".result IMG.expand_list").click(function(){
			var resultdiv = $(this).parents('.result');
			expandTypeResults(resultdiv);
			return false;
		});
		log('.result IMG.expand_list');
		$(".result>a>IMG").click(function(){
			var resultdiv = $(this).parents('.result');
			expandTypeResults(resultdiv);
			return false;
		});
		log('.result>a>IMG").click');
		$(".result h3>a").click(function(){
			var resultdiv = $(this).parents('.result');
			expandTypeResults(resultdiv);
			return false;
		});
		log('.result h3>a").click');
		/* toggle the clicked expand, and toggle the next expandedlist */
		$(".collapse").click(function(){
		    $(this).parent(".expandedlist").prev(".expand").slideToggle("slow,");
			$(this).parent(".expandedlist").slideToggle("slow,");
			return false;
		});
		log('.collapse click');
		$("A.modelNameCollapse").click(function(){
		    $(this).parents('.result').find(".expandedlist").prev(".expand").slideToggle("slow,");
			$(this).parents('.result').find(".expandedlist").slideToggle("slow,");
			return false;
		});
		log('A.modelNameCollapse .click(function()');
		$("INPUT.select_models").click(function() {
			checkModel($(this));
		});
		log('INPUT.select_models');
		$("SELECT.modelselect").change(function() {
			selectModel($(this).attr("makeId"), $(this).attr("makeName"));
		});
		log('SELECT.modelselect .change');
		$("DIV.pagination A").each(function() {
			$(this).click(function() {
				$("INPUT#currentPage").attr("value", $(this).attr("value"));
				var update = $("INPUT#updatePage")
				update.attr('value' , 'true');
				updateSearch();
			});
		});
		$("DIV#sorting A").each(function() {
			$(this).click(function() {
				$("INPUT#sortField").attr("value", $(this).attr("field"));
				var direction = $("INPUT#sortDirection")
				direction.attr('value' , $(this).attr("dir"));
				updateSearch();
			});
		});
		log('DIV.pagination A');
		$("label.enabledFuel").each(function() {
			$(this).show();
		});
		$("label.disabledFuel").each(function() {
			$(this).hide();
		});
		checkContractKilometers();
		$("DIV.processingdiv").hide();
	};
	
	var showUpdatedSearch = function(data) {
		var searchhtml = data.components.searchresult.html;
		start = new Date().getTime();
		var resultdiv = $("#search_results_main");
		resultdiv.html(searchhtml);
		log('resultdiv.replaceWith(html)');
		var searchfiltersdiv = $("#search_filters");
		var update = $("INPUT#updatePage")
		update.attr('value' , 'false');
		updateDirectSearchResults();
		log('updateDirectSearchResults()');
		var feedbacks = data.components.feedback;
		for(key in feedbacks) {
			if (key == "equipment") {
				var equipmentMap = feedbacks[key];
				for(equipmentName in equipmentMap) {
					var equipmentValue = equipmentMap[equipmentName];
					var feedbackSpan = $("#" + equipmentName);
					feedbackSpan.html("(" + equipmentValue + ")");
				}
			} else {
				var componentDiv = $('#ds_'+key);
				var values = feedbacks[key];
				componentDiv.find('input').each(function(){
					var feedbackSpan = $(this).next().find('.feedback');
					var value = $(this).attr('value');
					if(values[value]) {
						feedbackSpan.html('('+values[value]+')');
					} else {
						feedbackSpan.html('(0)');
					}
				});
			}
		}
		$("DIV.processingdiv").hide();
		log('feedbacks');
	};
	
	var updateDirectSearchResults = function() {
		$('UL.selectCB INPUT:checked').parent().addClass('active').removeClass('inactive');
		$('UL.select INPUT:checked').parent().addClass('active').removeClass('inactive');
		initSearchResultsDiv();
	}
	
	var updateSearch = function () {
		$("DIV.processingdiv").show();
		checkContractKilometers();
		$('UL.selectCB LI.active').each(function() {
			var checkBox = $(this).children('INPUT');
			checkBox.attr('checked' , 'checked');
		});
		$('UL.select LI.active').each(function() {
			var checkBox = $(this).children('INPUT');
			checkBox.attr('checked' , 'checked');
		});

		var data = $("#ds_update_form").serialize();
		
		var selectedModels = $(".selectMM LI");
		for (var count = 0; count < selectedModels.length; count++) {
			var selectedMakeModel = $(selectedModels[count]);
			data += '&model='+selectedMakeModel.attr('data-value');
		}
		var url = $("#ds_search_link").attr("href");
		log("updateSearch");
		$.ajaxSetup({ cache: false });
		$.ajax( {
			type : 'GET',
			url : url,
			data: encodeURI(data),
			dataType : 'json',
			success : showUpdatedSearch,
			timeout : 100000,
			error : function(jqXHR, textStatus, errorThrown) {
				console.log(jqXHR, textStatus, errorThrown);
				alert("error");
				$("DIV.processingdiv").hide();
			}
		});
		if (window.Cobrowser){
		   window.Cobrowser._ajaxRefresh();
		}
	}
	
	var toggleMakeModel = function () {
		$("#search_results_main").slideToggle();
		$("#select_makemodel").slideToggle();
		return false;
	};
	
	var setMakeModel = function() {
		toggleMakeModel();
		updateSearch();
	};
	
	var switchModelSelect = function(makeId) {
		addModelDropdown(makeId);
		var titleDiv = $("#title_" + makeId);
		titleDiv.hide();
		updateSelectedMakeModels();
	}
	
	var checkModel = function (checkBox) {
		var parentDiv = checkBox.parent();
		var makeDiv = parentDiv.parent();
		var makeId = checkBox.attr("makeId");
		var siblings = makeDiv.children("DIV#make_"+makeId+">DIV#models_" + makeId);
		if (siblings.length == 1) {
			parentDiv.hide();
			siblings.remove();
			var linkDiv = $('#addlink_' + makeId);
			linkDiv.hide();
			var titleDiv = $("#title_" + makeId);
			var makeCheckbox = titleDiv.children("INPUT");
			makeCheckbox.attr('checked', '');
			titleDiv.show();
		}
		else {
			parentDiv.remove();
		}
		updateSelectedMakeModels();
	}
	
	var selectModel = function (makeId, makeName) {
		$('#addlink_' + makeId).show();
		updateSelectedMakeModels();
	}
	
	var updateSelectedMakeModels = function() {
		var makeModelList = '';
		$('input.select_models').each(function(){
			if(this.checked) {
				var selectBox = $(this).next();
				var type = selectBox[0].nodeName;
				while (type != "SELECT") {
					selectBox = selectBox.next();
					type = selectBox[0].nodeName;
				}
				var selected = selectBox.find(":selected");
				var dataValue = selected.attr('data-value');
				var dataLabel = selected.attr('data-label');
				makeModelList += '<li data-value="'+dataValue+'">'+dataLabel+'</li>';
			}
				
		});
		$('ul#selectMM').html(makeModelList);
	}
	
	var initSearchResultPage = function () {
		$("#select_makemodel").hide();
		$("#search_results_main").show();
		$("#search_models").hide();
		
		var switchmodels = $("INPUT.switch_models[selected=false]");
		switchmodels.each( function() {
			if (this.checked) {
				this.checked=false;
			}
		});
		
		$('A.searchresult_makemodel').click(toggleMakeModel);
		$('a#searchresult_makemodel_submit').click(function(){
			setMakeModel();
			return false;
		});
		$('.addlink').click( function() {
			addModelDropdown($(this).attr('makeId'));
		});
		
		$('DIV.models').each(function() {
			$(this).hide();
		});
		
		$('INPUT.switch_models').each(function() {
			$(this).click(function() {
				switchModelSelect($(this).attr('makeId'));
			});
			var selected = $(this).attr('selected');
			if (selected == "true") {
				switchModelSelect($(this).attr('makeId'));
			}
		});
		
		$('INPUT.switch_models').each(function(){
			$(this).click(function() {
				var parent = $(this).parent();
				var models = parent.children(".models");
				for (var count=0; count<models.length; count++) {
					var mdl = $(models[count]);
					mdl.slideToggle();
					$(this).slideToggle();
				}
				var id = $(this).attr('value');
			});
		});
		
	//	$('UL.selectCB LI').each(function() {
	//		if ($(this).hasClass('active')) {
	//			$(this).addClass('tempClass');
	//		}
	//	});
		
		$('SPAN#compare_package').each(function(){
			$(this).click(function() {
				$("#select_makemodel").show();
				return false;
			});
		});
	//	$('UL.selectCB LI').each(function() {
	//		if ($(this).hasClass('active')) {
	//			$(this).addClass('tempClass');
	//		}
	//	});
		$('#directsearch_criteria INPUT[type="checkbox"]').hide();
		$('INPUT#searchfuelprice').show();
		$('INPUT#searchco2price').show();
		$('INPUT#searchfuelprice').bind(($.browser.msie ? "click" : "change"), function(){
			updateSearch();
		});
		$('INPUT#searchco2price').bind(($.browser.msie ? "click" : "change"), function(){
			updateSearch();
		});
		
	//	$('UL.selectCB LI').each(function() {
	//		if ($(this).hasClass('tempClass')) {
	//			$(this).addClass('active');
	//		}
	//	});
		
		$('UL.select').each(function() {
			var selectitems = $(this).children('li[class!= more][class!=less]');
			var select = $(this);
			selectitems.click(function(){
				// Deselect if already active and reset to the default value
				if ($(this).hasClass('active')) {
					$(this).addClass('inactive');
					$(this).removeClass('active');
					var checkBox = $(this).children('INPUT');
					checkBox.attr('checked' , '');
					updateSearch();
					return false;
				}
				// Otherwise, activate the new value and inactivate others
				else {
					var selectId = select.attr('id');
					$("input[name=" + select.attr('id') + "]").attr('value', $(this).children('A').attr('id'));
					$(this).addClass('active');
					$(this).removeClass('inactive');
					/* het hele punt van "faceted" search is dat er met meerdere zoekcriteria kan worden gespeeld. dus niet andere cirteria op inactief zetten */
					$(this).siblings('li[class!=more]').each(function() {
						$(this).removeClass('active');
						$(this).addClass('inactive');
						var checkBox = $(this).children('INPUT');
						checkBox.attr('checked' , '');
					});
					//$(this).siblings('li[class!=more]').removeClass('active').addClass('inactive');
					updateSearch();
					return false;
				}
			});
			var val = $("input[name=" + select.attr('id') + "]").attr('value');
			if (val)
				selectitems.children('#'+val).parent().addClass('active');
		});
		
		$('UL.selectCB').each(function() {
			var selectitems = $(this).children('li[class!=more][class!=less]');
			var select = $(this);
			if ($(this).hasClass('active')) {
				$(this).addClass('active');
			}
			selectitems.click(function(){
				// Deselect if already active and reset to the default value
				if ($(this).hasClass('active')) {
					$(this).addClass('inactive');
					$(this).removeClass('active');
					var ul = $(this).parent();
					// The id of this select
					var thisId = ul.attr('id');
					// Find the appropriate span, which contains the <input> we're looking for
					var span = ul.parent().children('span[id=' + thisId + "]");
					var inputObj = span.children('input');
					// Set the default value for this select type
					var defaultVal = inputObj.attr('defVal');
					$(this).children('input').attr('checked', false);
//					$("input[name=" + select.attr('id') + "]").attr('value', defaultVal);
					updateSearch();
					return false;
				}
				// Otherwise, activate the new value and inactivate others
				else {
					$("input[name=" + select.attr('id') + "]").attr('value', $(this).children('A').attr('id'));
					$(this).addClass('active');
					$(this).removeClass('inactive');
					/* het hele punt van "faceted" search is dat er met meerdere zoekcriteria kan worden gespeeld. dus niet andere cirteria op inactief zetten */
					//$(this).siblings('li[class!=more]').removeClass('active').addClass('inactive');
					updateSearch();
					return false;
				}
			});
			var val = $("input[name=" + select.attr('id') + "]").attr('value');
			if (val)
				selectitems.children('#'+val).parent().addClass('active');
		});
		
		$('UL.selectCB INPUT:checked').parent().addClass('active').removeClass('inactive');
		$('UL.select INPUT:checked').parent().addClass('active').removeClass('inactive');
		
		if( $('#ds_amount').length ) {			
			var priceRangeMinimum = parseInt($("#priceRangeMinimum").attr('value'));
			var priceRangeMinimum = 150;
			var priceRangeMaximum = parseInt($("#priceRangeMaximum").attr('value'));			
			var priceRangeMaximum =   1990;
			$("#slider-range").slider({
				range: true,
				min: priceRangeMinimum,
				max: priceRangeMaximum,
				values: [$("#minLeasePrice").attr('value'), $("#maxLeasePrice").attr('value')],
				step: 25,
				slide: function(event, ui){
					$("#minSliderPrice").text('€ ' + $("#slider-range").slider("values", 0));
					$("#maxSliderPrice").text('€ ' + $("#slider-range").slider("values", 1));
					$("#minLeasePrice").val(ui.values[0]);
					$("#maxLeasePrice").val(ui.values[1]);
				},
				change: function(event, ui){
					updateSearch();
				}
			});
			$("#minSliderPrice").text('€ ' + $("#slider-range").slider("values", 0));
			$("#maxSliderPrice").text('€ ' + $("#slider-range").slider("values", 1));
			$("#minLeasePrice").val($("#slider-range").slider("values", 0));
			$("#maxLeasePricev").val($("#slider-range").slider("values", 1));			
		}
	    
		/* *** DIRECTSEARCH SLIDER YEARLYKM *** */
		if( $('#ds_yearlyKm').length ) {
			$("#slider-simple-yearlykm").slider({
				range: 'min',
				min: 15000,
				max: 70000,
				value: $("#yearlyKm").attr('value'),
				step: 5000,
				change: function(event, ui){
					updateSearch();
				},
				slide: function(event, ui){
					$("#currentYearlyKm").text(ui.value);
					$("#yearlyKm").val(ui.value);
				}
			});
			$("#currentYearlyKm").text($("#slider-simple-yearlykm").slider("values", 0));
			$("#yearlyKm").val($("#slider-simple-yearlykm").slider("values", 0));
		}
	
		/* *** DIRECTSEARCH SLIDER CATALOGUS *** */
		if ( $("#slider-range-catalogue").length ) {
			$("#slider-range-catalogue").slider({
				range: true,
				min: 5000,
				max: 200000,
				values: [$("#mincostexvat").attr('value'), $("#maxcostexvat").attr('value')],
				step: 5000,
				slide: function(event, ui){
					$("#minCostexvatText").text('€ ' + ui.values[0]);
					$("#maxCostexvatText").text('€ ' + ui.values[1]);
					$("#mincostexvat").val(ui.values[0]);
					$("#maxcostexvat").val(ui.values[1]);
				},
				change: function(event, ui){
					updateSearch();
				}
			});
			$("#minCostexvatText").text('€ ' + $("#slider-range-catalogue").slider("values", 0));
			$("#maxCostexvatText").text('€ ' + $("#slider-range-catalogue").slider("values", 1));
			$("#mincostexvat").val($("#slider-range-catalogue").slider("values", 0));
			$("#maxcostexvat").val($("#slider-range-catalogue").slider("values", 1));
		}
	
		/* *** DIRECTSEARCH SLIDER LOOPTIJD *** */
		if( $("#slider-simple-duration").length ) {
			$("#slider-simple-duration").slider({
				range: 'min',
				min: 24,
				max: 60,
				step: 3,
				value: $("#duration").attr('value'),
				change: function(event, ui) {
					updateSearch();
				},
				slide: function(event, ui) {
					$("#currentDurationYears").text( (ui.value - (ui.value % 12)) / 12);
					if ( (ui.value % 12) == 0) {
						$("#ds_duration_month").show().hide();
						$("#currentDurationMonths").text('');
					}
					else {
						$("#ds_duration_month").show(); 
						$("#currentDurationMonths").text(ui.value % 12);
					}
					$("#duration").val(ui.value);
				}
			});
			
			var value = $("#slider-simple-duration").slider("values", 0);
			$("#currentDurationYears").text( (value - (value % 12)) / 12);		
			if ( (value % 12) == 0) {
				$("#ds_duration_month").show().hide();
				$("#currentDurationMonths").text('');
			}
			else {
				$("#ds_duration_month").show(); 
				$("#currentDurationMonths").text(value % 12);
			}
			$("#duration").val($("#slider-simple-duration").slider("values", 0));
		}
		
	
		/* *** DIRECTSEARCH SLIDER FISCALE PKS *** */
		if ($("#slider-simple-fiscalHP").length) {
			$("#slider-simple-fiscalHP").slider({
				range: 'min',
				min: 4,
				max: 20,
				step: 1,
				value: $("#maxFiscalHP").attr('value'),
				slide: function(event, ui) {
					$("#currentFiscalHP").text(ui.value);
					$("#maxFiscalHP").val(ui.value);
				},
				change: function(event, ui){
					updateSearch();
				}
			});
			$("#currentFiscalHP").text( $("#slider-simple-fiscalHP").slider("values", 0) );
			$("#maxFiscalHP").val($("#slider-simple-fiscalHP").slider("values", 0));
		}
		
		$("INPUT.fuelLeaseCostVatType").each(function() {
			$(this).bind(($.browser.msie ? "click" : "change"), function(){
				updateSearch();
	        });
		});
	
	//	$('UL.selectCB LABEL').click(function(event) {
	//		event.stopPropagation();
	//		var parent = $(this).parent();
	//		var checkBox = parent.children('INPUT');
	//		var newValue = !checkBox.attr('checked');
	//		checkBox.attr('checked', newValue)
	//		parent.toggleClass('active', newValue);
	//		//parent.toggleClass('inactive', !newValue);
	//		updateSearch()
	//		return false;
	//	});
	//	$('UL.selectCB INPUT:checked').parent().addClass('active').removeClass('inactive');
		//$('#make').change(updateCount);
	
	
		function moreLessSearch(){ // toggle full search/ simple search
			//initializeSearch();
			if ( $('.home_directsearch').hasClass("open") ){
				$('.home_directsearch').removeClass("open");
			} else {
				$('.home_directsearch').addClass("open");
			}
			
			$('#ds_catalogue').slideToggle("slow,");
			$('#makeSelect').slideToggle("slow,");
			if($('#fiscalHPSlider').length) {
				$('#fiscalHPSlider').slideToggle("slow,");
			}
			$('DIV.vslider').slideToggle("slow,");
			$('LI.secondary').slideToggle("slow,");
			$('P#searchless').slideToggle("slow,");
	
			$('LI.more').slideToggle("slow,");
			$('LI.less').slideToggle("slow,");
			$('P#searchmore').slideToggle("slow,");
			
			return false;
		}
		//allow certain buttons to expand the form
		$('P#searchless').click(moreLessSearch);
		$('P#searchmore').click(moreLessSearch);
		$('LI.more').click(moreLessSearch);
		$('LI.less').click(moreLessSearch);
		
		$('OPTION.selectedModel').each(function() {
			var selected = $(this)[0].getAttribute('selected');
			if (selected == "true") {
				var makeId = $(this).attr('makeId');
				var makeName = $(this).attr('makeName');
				switchModelSelect(makeId);
				selectModel(makeId, makeName);
				var select = $(this).parent();
				select.val($(this).attr('value'));
			}
		});
	}
	
	/*function checkModel() {
		var models = $("#ds_update_form")[0].elements.model;
		if (models != null && models.checked != null && models.checked){
			$("#searchresult_makemodel").hide();
			$("#ds_bodytype").hide();
		}
	}*/

	log(' DirectSearch result page Site Specific');
	
	/* ****************************************
	 * DirectSearch result page Site Specific *
	 * ***************************************/	
		
	if ($('#directsearch_resultpage').length) {
		initSearchResultPage();	
	}

	log(' DirectSearch result page Site Specific done');
	initSearchResultsDiv();
});

