﻿

function getModels(forceUpdate){

	if(getModels.lastPostParam=='undefined') getModels.lastPostParam='';	
	var postParam=$('#search_form form').serialize();
	if (forceUpdate || getModels.lastPostParam!=postParam) {
	    debug('stream: '+postParam);
		$('#result_flash_counter').css('color','#dde6f1');
		$.post("stream.php?stream&target=models", postParam,
		  function(data){
			   $('#search_form #result_flash').empty().append(data);		   
			   setModelCount();		   
			   debug('searchform update: ... done.');			   
			   },
		"html");									
		getModels.lastPostParam=postParam;

// aktive felder makieren
		$('#car_data select[id!=cardata_geoDistanceInKm],#equipment input,#equipmentX input,#special_offers input').each(function() {
			var el=$(this);
			el=el.add('label[for='+el.attr('id')+']')
			if ((this.type=='checkbox' && this.checked)||(this.type=='select-one' && this.value)) {
				el.addClass('selected').removeClass('default');
			} else {
				el.removeClass('selected').addClass('default');
			}
		});
		// Umkreissuche speziell behandeln
		var zip=$('#car_data input#cardata_zip');
		var el=$('#car_data input#cardata_zip,#car_data label[for=cardata_zip],'+
				 '#car_data select#cardata_geoDistanceInKm,#car_data label[for=cardata_geoDistanceInKm]');
		if (zip.val() && zip.val()!=zip.classData('default')) {
			el.addClass('selected').removeClass('default');
		} else {
			el.removeClass('selected').addClass('default');
		}
			
											  
	} else {
	    debug('stream: form not changed');
	}
}	


function setModelCount(save){	
	var count=0;
	var data=new Array();
	if (!save) { // gespeicherte Elemte wieder markieren
		data=$('#search_form #result_flash').data('selectedModels');
		if (data && data.length>0) $('#search_form #result_flash option').each(function(){
			if($.inArray($(this).text(),data)>=0) this.selected=true;					
			if($.inArray($(this).attr('value'),data)>=0) { this.selected=true; save=true; }
		});
		data=new Array();
	}
	if($('#search_form #result_flash :selected').size()) { // falls markierung vorhanden, dann diese Zählen
		$('#search_form #result_flash :selected').each(function(){
			count+=parseInt($(this).attr('id'));
			if (save) data.push($(this).text());
		});	
	} else { // sonst alles zählen
	 	$('#search_form #result_flash option').each(function(){
			count+=parseInt($(this).attr('id'));
		});		
	}
	if (save) $('#search_form #result_flash').data('selectedModels',data); // markierte elemente merken

	showModelCount(count);
}

function showModelCount(nr) {	
	var counter=$('#result_flash_counter');
	var maxval=$('#results_flash_panel img').attr('alt');
	if (typeof nr == 'undefined' ) { nr=counter.data('count'); }
	counter.data('count',nr).empty().append('('+(((nr>maxval)&&(!counter.data('all')))?('>'+maxval):nr)+')').css('color','white'); // anzahl ausgeben:
	if (nr==0) { $('#results_flash_panel').addClass('noresults'); } else { $('#results_flash_panel').removeClass('noresults'); }
}

function creditCalcBindChange(){
	
	$("#credit_calculator form").bind("submit",(function() {
		  var sarg='sid='+$.cookie('sid');			  
		  $.post("stream.php?"+sarg+"&stream&target=credit&"+$('#credit_calculator form').attr('action').substring(1), 
				$('#credit_calculator form').serialize()+'&CMD_action_calc=',
			 function(data){
				$('.snapbox').remove();
				$('#credit_calculator').empty().append($(data).contents());
				
				snapboxActivation();
				creditCalcBindChange();
			  }, "html");		   					
		   return false;      
	   }));	 
	
	$("#credit_calculator form input").bind("keyup",(function() {
				
		var id="#"+$(this).attr('id');
		var val=0;
		if(id.search('Percent')>=0)
			$(id.replace(/Percent/g, "")).val(Math.floor($("#vehiclePrice").val()*$(this).val()/100));
		else
			val=$(id+"Percent").val(Math.floor(100*$(this).val()/$("#vehiclePrice").val())+1);		
	
	   return false;      
   }));		  
}


//onload

var flashteasers = {};

$(function() {
		   
	// remove ALT-texts in IE
	if ($.browser.msie) {
		$('img[alt]:not([title])').attr('title','');
	}
	
	// label cursor
	$('label[for]').css({cursor:'pointer'});
	
	//activate tease anim.
	if (jQuery.isFunction($.fn.teaser)){
		$('.teaser').teaser();
	}


	
	
	// activate Tabs
	if (jQuery.isFunction($.fn.tabs))
		$('#tabs').tabs();	

	//monatliche Rate Click
	$('#tabs td.label_rate').click(function() {
		$('#tabs').tabs('select', 1); 
		return false;
	}).css({cursor:'pointer'});


	// bind snapbox hover and moving	
	$('.snapbox').appendTo('body');
	$('.snapbox_hover').hoverIntent(function(e) {
			var hover=$(this);								
			var name=hover.attr('class').match(/snapbox_hover\s(.+?)\b/)[1];
			var snapbox=$('#'+name+'.snapbox');
			if (snapbox.size()>0) {
				var doPos=function(e) {
					var posx=Math.min(e.pageX-15,$(window).width()-snapbox.width()-2); // rechte rand prüfung
					var posy=e.pageY-snapbox.height()-20;
					if (posy<0) { // obere rand prüfung
						posy=e.pageY+30;
						snapbox.addClass('down');
					} else {
						snapbox.removeClass('down');
					}
					snapbox.css({left:posx, top:posy})
					.find('.snapbox_bottom').css({left:e.pageX-15-posx});
				}
				hover.mousemove(doPos);
				doPos(e);
				snapbox.show();
			}
		 }, function() {
			var hover=$(this);								
			var name=hover.attr('class').match(/snapbox_hover\s(.+?)\b/)[1];
			var snapbox=$('#'+name+'.snapbox');
			hover.unbind('mousemove'); 
			snapbox.hide().css({left:-100, top:-300});
		 });
											 
/*	$('.snapbox_hover').mouseenter(function() {
			var hover=$(this);								
			var name=hover.attr('class').match(/snapbox_hover\s(.+?)\b/)[1];
			var snapbox=$('#'+name+'.snapbox');
			if (snapbox.size()>0) {
				hover.mousemove(function(e){
						var posx=Math.min(e.pageX-15,$(window).width()-snapbox.width());
						snapbox.css({left:posx, top:e.pageY-snapbox.height()-22})
						.find('.snapbox_bottom').css({left:e.pageX-15-posx});
					});
				hover.mouseleave(function(){ 
						hover.unbind('mousemove'); 
						snapbox.hide().css({left:-100, top:-300});
					});
				snapbox.show();
			}
		});
*/	
	// Gallery Hover and Activation - its more stable with JS
	$('#gallery a')
		.hover(function() { $(this).addClass('hover'); }, function() { $(this).removeClass('hover'); })
		.click(function() { $('#gallery a.active').not(this).removeClass('active'); $(this).addClass('active'); })
	;
	
	// spotlight Hover/click
	$('div.spotlight')
		.css({cursor:'pointer'})
		.hover(function() { $(this).addClass('hover'); }, function() { $(this).removeClass('hover'); })
		.click(function(event) { 
			location.href=$(this).find('a[href]').attr('href');  
			return false;
		});
	
	// Enter bei Angebotsnummer
	$('input#result_id').keypress(function (e) {
      if (e.which == 13 ) {
		  e.preventDefault();
		  $('input#CMD_action_search_byid').click();
      } 
    });

	// Doppelklick bei Modelliste
	$('#results_flash_panel select').dblclick(function() { $('input#CMD_action_search').click(); });
	$('#results_flash_panel img').click(function(e) {
		if(e.ctrlKey) { 
			with ($('#result_flash_counter')) { data('all',!data('all')); }
			showModelCount();
		}
	});
	
	// activate model counting
	$('#result_flash').change(function(){ setModelCount(true); }).each(function() {
		// höhenanpassung model-panel																				
		var re=$('#results_flash_panel');																		
		var eq=$('#equipment'); // set the panel height equal to equipment
		if (eq.size()>0) {
			var corr=eq.position().top+eq.outerHeight()-re.position().top-re.outerHeight();
			if (corr>-5) { // nicht zu stark verkleinern
				re.height(re.height()+corr);
			}
		}
	});
	
	
	// searchtable: klick auf entire TD
/*	$('#result_table>tbody>tr>td'). css({cursor:'pointer'}). click(function() {
		location.href=$(this).parent().find('a[href]').attr('href');  
		return false;
	});
*/	

	// result page length
	$('#results_page_nav #pagelength')
		.find('input[name=CMD_action_pagesize]').hide()
		.end().find('select').change(function() {
			$(this).closest('form').find('input[name=CMD_action_pagesize]').click();
		});

	// kontaktform: select entire field by focus
	$('#contact_dealer,#sendAFriend_panel,#results_flash_panel #noresults').find('input[type=text],textarea').add('#cardata_zip').each(function() {
		var field=$(this);
		var defaultValue=field.classData('default');
		if (defaultValue) {
			field.focus(function(){ if (field.val()==defaultValue) field.val(''); });
			field.blur(function(){ if (!field.val()) field.val(defaultValue); }) ;
		}
	});
	
	
	// Spotlighthöhe gleichschalten
/*	$('#col2_2a').each(function() {
		with ($(this).find('.spotlight h4')) { height(Math.max.apply(null,map(function() { return $(this).height(); }).get())); }
		with ($(this).find('.spotlight table')) { height(Math.max.apply(null,map(function() { return $(this).height(); }).get())); }
//		with ($(this).find('.spotlight .spot_img')) { height(Math.max.apply(null,map(function() { return $(this).height(); }).get())); }
	});
*/	
	//activate sendAFriend Panel
	var sendAFriendPanelFunction = function() {
			var panel=	$('#sendAFriend_panel');											  
			var op=$(this).position();
			panel.css({left:op.left-panel.outerWidth()+$(this).outerWidth()});
			if (!panel.is(':visible')) {
				if (this.id=='sendAFriend2' ) {
					panel.css({top:'auto', bottom:$(this).offsetParent().height()-op.top+15});			
				} else {
					panel.css({top: op.top+$(this).outerHeight()+5, bottom:'auto'});
				}
			}
			panel.slideToggle().find('#sendAFriend_close').click(
			function(){
			 $(this).parent().slideUp();
			 return false;
			});
			return false;
	}
	$('#sendAFriend1').unbind().click(sendAFriendPanelFunction);
	$('#sendAFriend2').unbind().click(sendAFriendPanelFunction);
	

	//credit calculator
	creditCalcBindChange();
	  
	  
	
	// Lightbox	
	if (jQuery.isFunction($.fn.lightBox ))
		$('#gallery .panel a').lightBox({
		overlayBgColor: '#9090a0',
		overlayOpacity: 0.7,
		imageLoading: '../images/lightbox/lightbox-ico-loading.gif',
		imageBtnClose: '../images/lightbox/lightbox-btn-close.gif',
		imageBtnPrev: '../images/lightbox/lightbox-nav-btn-prevNew.gif',
		imageBtnNext: '../images/lightbox/lightbox-nav-btn-nextNew.gif',
		imageBlank: '../images/lightbox/lightbox-blank.gif',
		containerBorderSize:   10,
		containerResizeSpeed: 400,
		containerResizeSpeed: 350,
		txtImage: 'Bild',
		txtOf: 'von',
		keyToClose: 'c',
		keyToPrev: 'p',
		keyToNext: 'n'
   });
});




