var path_assoluto, co_id=1, tmp;
function fn_ani_1(a1,b1){
					var r={a:a1,b:b1};
					r.a+=1;
					alert(r.a);
					return r;
				}
function init(){
	// assegno alla variabile co_id il valore assegnato nella querysrting
/*
	$('.wizard').animate(
				fn_ani_1(0,100),
			4000);
	*/
	
	
	
	tell2afriend();
	doLoginAfterSubscribe();
	tmp = location.search.toLowerCase().match(/co_id=(\d+)\D*/);
	if (tmp && tmp.length>0){co_id=tmp[1]}
	$('.fancybox').fancybox();
	//DiBa
	$('.start_gallery').each(function(){
			if( $($(this).attr('href') + ' a.fancybox').size() == 0 ){
				$(this).parent('li').hide();
			}
			$(this).click(function(){$($(this).attr('href') + ' a.fancybox:eq(0)').click();return false;});																	
		});

	$('a.toggle_map').click(show_google_maps);
	$('#gmap_7').each(function(){show_google_maps_7();});
//	show_google_maps();
	// campo Calendario	
		if($.datepicker){
			$.datepicker.regional['it'] = {
				closeText: 'Chiudi',
				prevText: '&#x3c;Prec',
				nextText: 'Succ&#x3e;',
				currentText: 'Oggi',
				monthNames: ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno',
				'Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'],
				monthNamesShort: ['Gen','Feb','Mar','Apr','Mag','Giu',
				'Lug','Ago','Set','Ott','Nov','Dic'],
				dayNames: ['Domenica','Luned&#236','Marted&#236','Mercoled&#236','Gioved&#236','Venerd&#236','Sabato'],
				dayNamesShort: ['Dom','Lun','Mar','Mer','Gio','Ven','Sab'],
				dayNamesMin: ['Do','Lu','Ma','Me','Gio','Ve','Sa'],
				dateFormat: 'dd/mm/yy', firstDay: 1,
				isRTL: false};
			$.datepicker.setDefaults($.extend({showMonthAfterYear: false}, $.datepicker.regional['it']));
			$('.calendarButton').datepicker({showOn: 'both', 
					buttonImage: '/bom/images/calendar.gif',
					yearRange: String((new Date()).getFullYear()) +  ':' + String((new Date()).getFullYear() + 1),
					buttonImageOnly: true, 
					dateFormat: 'dd/mm/yy',
					changeMonth: true,
					changeYear: true,
					showButtonPanel: true
				});
			}
	// form di creazione di un account
	 togglePrivatoAzienda();
	 nlt_togglePrivatoAzienda();
	 $('.ws_register_user #ut_state').change(function(){
			// Nasconde e disattiva la select delle province in caso lo stato sia diverso dall'italia
			if($(this).val().toUpperCase()=='IT'){
				$('#ut_provincia').removeAttr('disabled').focus().parent().removeClass('hidden'); //.show('fast');
			}else{
				$('#ut_provincia').attr('disabled','disabled').parent().addClass('hidden'); //.hide('fast')
			}
		});
	PulisciInput("input:password.autoclear, input:text.autoclear ");
	$('form:not(.ncs)').append('<input type="hidden" name="can_submit" value="'+Math.random()+'" />');
	// Convalida delle FORM
	$("form").not('.ws_user_form').submit(function (){return get_form_validation(this);});
	$('form.ws_user_form').submit(function (){return ws_user_form_validation(this);});
	// per il layout dei campi di tipo FILE
	layout_input_file();
	// per il layout dei campi di tipo RADIO CHECKBOX
	layout_input_checked();
	// ACCORDION
	my_accordion();
	// MENU Javascript 
	menu('#menu_vert_3lev');
	
	wizard('.wizard:eq(0)');
	tabs_hp();
	
	diba_scrollable();
	
	diba_paginatore();
	// recents_scrollable_hp();
	diba_reload_modelli();
	diba_reload_concessionarie();
	diba_reload_officine_concessionarie();
	diba_ricerca_x_riferimento();
	try{
		$(".player").jfe({ver:"10,0,0", display:"alternate", noflash:false});
		}
		catch(e){
			
			}
	
}

function diba_scrollable (){
	$("#zoom img").click(function(){
				$.fancybox({href:$(this).attr("src")});				  
			});			  
	$(".scrollable").scrollable({ vertical: true, mousewheel: true, items: 'ul.items', item: '.item' });
	$(".scrollable a").click(function() {
			$("#zoom img").css({'background-image': 'url(' + $("#zoom img:eq(0)").attr("src") + ')'});
			$("#zoom img").attr("src",$(this).attr('href'));							  
			return false;
		});
	$("a.prev, a.next").click(function() {
	return false;
	
	});
	}
function diba_paginatore(){
		$('select.RecordsPerPagina').change(function(){
			$('#RecordsPerPagina').val($(this).val());
			$('#frm_ricerca_usato').submit();
			return false;
		});
		$('.ru_paginatore a').click(function(){
			$('#risultato_pag').val($(this).attr('rel'));
			$('#RecordsPerPagina').val($('select.RecordsPerPagina:eq(0)').val());
			$('#frm_ricerca_usato').submit();
			return false;
		});
	}
function recents_scrollable_hp(){
	if($('#blocchi_home').size()>0){
		$("#blocchi_home div.scrollable").scrollable({vertical:true, loop:true, size:1, speed:900}).circular().autoscroll({autoplay: true});;
	}
}

function layout_input_file(){
	$('.input_file_wrapper input:file').change(function(){
			if($(this).prev('.file_fake').size()==0){
				$(this).before('<span class="file_fake"></span>')
				//style="float:left; padding:0 4px; width:250px; overflow:hidden;"
			}
			try{
				$(this).prev('.file_fake').html($(this).val().match(/[^\/\\]+$/)[0]);
			}
			catch(e){
				
			}
		});
}
function layout_input_checked(){
	$("ul.input_group").children('li').each(
			function(){
				if($(this).children(':checked').size()==0){
					$(this).removeClass("checked");
				}else{
					$(this).addClass("checked");
				}
			});
	
	$('.input_group input:checkbox, .input_group input:radio').click(function(){
				try{
				$(this).parents("ul.input_group").children('li').each(function(){
						if($(this).children(':checked').size()==0){
							$(this).removeClass("checked");
						}else{
							$(this).addClass("checked");
						}
						
					});
				}
				catch(e){
					alert(e);
					}
			});
}
function tell2afriend(){
	$('#dillo').append('<div id="tell_to_friend"><div id="tell2friend"><a href="#" title="close" class="tell2friend_close">chiudi</a><div id="tell2friend_form"></div></div></div>');
	$("a.pulsamico").click(function(){
				$.ajax({url:"frm_dilloaunamico.asp", success: function(data){
						$("#tell2friend_form").append(data); 
						$("form#frm_tell2friend").append("<input type=\"hidden\"  name=\"can_submit\"  value=\"" + (Math.random()*10000) + "\" />");
						$("form#frm_tell2friend").submit(function (){
											var ret;
											ret = get_form_validation(this);
											try{
												if(ret){
													pageTracker._trackPageview ('/invia_a_un_amico');
												}
											} 
											catch(e){
											}
											return ret;
										});
						ws_json_form.init("form#frm_tell2friend");
						$("#tell2friend").hide();
						$("#tell2friend").animate({bottom:0,left:'-300px'},function(){$("#tell2friend").slideDown("normal");});
					}});
				$(".tell2friend_close").click(function(){$("#tell2friend").slideUp("normal", function(){$("#tell2friend_form").empty();});  return false;});
			return false;
		});
}

/* Funzione per Menù 
- - - - - - - - - - - - - - - - - - - - */
function menu(div){
	$(div + " a.active").parent().parent().addClass("on");
	$(div + " ul li ul").not(".on").hide();
	$(div + " ul li a").click(function(){
		if($(this).attr("href")=="#"){
			if ($(this).next().attr("class") == "on") {
//				$(this).next().removeClass("on").slideUp("fast");
				// scriverlo due volte per trovare gli elementi successivi con classe .on
				$(this).parent().children().not("a").removeClass("on").slideUp("fast"); 
			} else {
				$(this).parent().parent().find("ul.on").removeClass("on").slideUp("fast");
				$(this).parent().children().not("a").addClass("on").slideDown("normal");
//				$(this).next().addClass("on").slideDown("fast");
//				$(this).next().next().addClass("on").slideDown("fast"); // serve per aprire l'UL fratello
			}
			return false;
		}
	});
	apriMenu(div);
	//$("img[src='']").src='/img/trasp.gif';

	
}
function apriMenu(div){
	$(div + " a.on").each(function(){
		var el=this;
		var conta=0;
		while(el !== null && conta<30){
			el=$(el).parent();
			if(el[0].tagName=="UL"){
//				$(el).show();
//				$(el).addClass("on");
				$(el).parent().children().not("a").show();
				$(el).parent().children().addClass("on");
				
			}else if (el[0].tagName=="LI"){
				conta++;
			}else if (el[0].tagName=="DIV"){
				el=null;
			}else{
				conta++;
			}
		}
	});
}

function wizard(div){
	var ul_counter = 0;
	var sum_visible_ul_height = 0;
	$(div + " a[href^='#']").each(function(){if($(this).next('ul').size()==0){$(this).parent('li').addClass('disabled');}});
	$(div + ' ul').each(function(){
		$(this).attr('id','ul_id_' + ul_counter++);
		$(this).children('li:even').addClass('even');
		
	});
	$(div + ' ul li ul').hide();
	$(div + ' ul li.disabled a').click(function(){return false;});
	$(div + ' ul li:not(.disabled) a').click(function(){
									  var me = this;
									  if( $(this).attr('href') == '#' ){
											$(this).parent('li').siblings('li').find('ul.on').slideToggle().toggleClass('on');
											$(this).parent('li').toggleClass('on');
											$(this).parent('li').siblings('li.on').toggleClass('on').find('li.on').toggleClass('on');
											$(this).parent('li').siblings('li').find('a.on').toggleClass('on');
											$(this).toggleClass('on');
											$(this).next('ul').css({ 
													top: (0 + $(this).parent().parent('ul').height()) + 'px'
												}).slideToggle('normal',function(){
														var aul;		
														aul = $(div + ' ul:visible');
														sum_visible_ul_height = 0;
														$(aul).each(function(){sum_visible_ul_height += ($(this).height() + parseInt($(this).css('marginTop')));});
														$(div).animate({height:sum_visible_ul_height + 40 + 'px'},800);
														if($(me).next('ul').size()>0){
															$("html:not(:animated), body:not(:animated)").animate({scrollTop:$(me).next('ul').offset().top},1600);
														}
													}).toggleClass('on'); 
												
											if($(me).next('ul').size()==0){
												$("html:not(:animated), body:not(:animated)").animate({scrollTop: $(me).offset().top},1600);
											}
											return false;
									   }else{
										   return true;
									   }
									});
	
}
function active_gallery(){
	if (!$("#TB_Window").length && typeof(tb_init)=='function'){
//		imgLoader = new Image();// preload image
		//imgLoader.src = "/img/trasp.gif";
//		imgLoader.src = tb_pathToImage;
		tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
//		$("#TB_Image").load(function(){ $("#TB_Load").hide();alert("caricata"); });
		
	}
}

function my_accordion(){
	$("h2 a[rel='accordion']").click(function(){
		var thed=$(this).parent().next();
		$(".hidden:visible").not($(thed)).slideUp("fast");
		$(this).parent().next().slideDown("fast");
		return false;
	});
}

/* VIRTUAL EXPLORE */

if(typeof(Array.indexof)!=="function"){
	Array.prototype.indexOf = function(f, s) {
		if (typeof s == 'undefined') s = 0;
		for (var i = s; i < this.length; i++) {
			if (f === this[i]) return i;
		}
		return -1;
	}	
}

/* LANCIA INIT */
if(typeof($)=="function"){
	path_assoluto = location.href;
	$(document).ready (init);

}

/* CONVALIDA FORM
-------------------------------------------*/
function ws_validate(){}
ws_validate.prototype.isEmail = function (what)
{
   var i=new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,6}|[0-9]{1,3})(\\]?)$");
   if(!i.test(what)) { return false}   
   return true;
}
ws_validate.prototype.isDate = function (what)
{
   var i=new RegExp("^([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})$");
   if(i.test(what))
   {
	datePart=what.split("/");
	giorno=(datePart[0]>=1) && (datePart[0]<=31);
	mese=(datePart[1]>=1) && (datePart[1]<=12);
	anno=(datePart[2]>=1900) && (datePart[2]<=9999);
	if(!giorno || !mese || !anno) { return false; }
   }else{
	return false;
   }
   return true;
}

ws_validate.prototype.isTelFax = function(what)
{
//   var i=new RegExp("([0-9]{2,})\/([0-9]{5,})");
   var i=new RegExp("([0-9]{5,})");
   if(!i.test(what)) { return false;}   
   return true;
}

ws_validate.prototype.notZero = function(what)
{
   if(what=="0") { return false;}   	
   return true;
}
ws_validate.prototype.field = function (what, type){
	try{
		if($(what).size()==0){return true;}
		if($(what+":disabled").size()>0){return true;}
		//if($(what).data('exclude')){return true;}
		switch (type) {
		  case "isEmail":
			return this.isEmail($(what).val());
			break; 
		  case "isDate":
			return this.isDate($(what).val());
			break; 
		  case "isTelFax":
			return this.isTelFax($(what).val());
			break; 
		  case "isChecked":
		  	return $(what).is(":checked");
			break; 
		  case "notZero":
			return this.notZero($(what).val());
			break; 
		  case "isText":
			return ($.trim($(what).val()).length>0);
			break; 
		  case "isNumeric":
			return (!isNaN($(what).val()) && ($.trim($(what).val()).length>0));
			break;
		  case "#ut_password":
			return ($(what).val() == $('#ut_password').val());
			break;
		  default: 	
			return ($(what).val().length>0);
		}
		
	}
	
	catch (e){
		alert(e);
	}
}
var validate = new ws_validate;

function get_form_validation(frm_id){
	var oval,valid,validation_string;
	oval=$(frm_id)[0]._validation;
	for (nc in oval){
		if( validate.field("#"+nc,oval[nc])==false ){
			$("#"+nc).parent().addClass("bg_error");
			valid=false;
		}else{
			$("#"+nc).parent().removeClass("bg_error");
		}
	}
	$(".bg_error input, .bg_error select, .bg_error textarea").eq(0).focus();
	$(frm_id)[0].valid = valid;
	return valid;
}

function ws_user_form_validation(frm_id){
	// Convalida delle form di tipo USER FORM create dal BOM
	var ret;
	ret = true;
	$(frm_id).find('div.bg_error').removeClass('bg_error');
	$(frm_id).find('div.required').each(function(){
			var r = false;
			var in_rc;
			in_rc = $(this).find('input:radio,input:checkbox');
			if($(in_rc).size()>0){
				if ($(in_rc).filter('input:checked').size()>0){
					r=true;
				}
			}else{
				if($.trim($(this).find('input,select,textarea').val())!==''){
					r=true;
				}
			}
			if (r==false){$(this).addClass('bg_error');}
		});
	if ($(frm_id).find('.bg_error').size()>0){
		ret = false;
		$(frm_id).find('.bg_error:eq(0)').find('input, select, textarea').eq(0).focus();
	}
	return ret; 
}
	
function PulisciInput(arr_input) {
	$(arr_input).each(function(){
			if($(this).length){
				$(this)[0].tmp_input_val=$(this).val();
			}
			$(this).focus( function () {
					if (this.value==this.tmp_input_val) {
						this.value='';
					}
				}						  
			  );
			$(this).blur( function () {
					if (this.value=='') {
						this.value=this.tmp_input_val;
					}
				}
			  );
							   
		});
}

function nlt_togglePrivatoAzienda(){
	nlt_togglePrivatoAzienda.toggle = function(){
			var val;
			val = parseInt(this.value, 10);
			switch (val){
				case 7:
					$('.privato').show();
					$('.privato').find('input').removeAttr('disabled');
					$('.professionista').hide();
					$('.professionista').find('input').attr('disabled','disabled');
				break;
				case 8:
					$('.professionista').show();
					$('.professionista').find('input').removeAttr('disabled');
					$('.privato').hide();
					$('.privato').find('input').attr('disabled','disabled');
				break;
				default:
				break;
			}
		}
	$('#nlt_tipologia').change(nlt_togglePrivatoAzienda.toggle);
	nlt_togglePrivatoAzienda.toggle.apply($('#nlt_tipologia')[0]);
}

function togglePrivatoAzienda(){
	togglePrivatoAzienda.setPrivato = function(){
		$('#ut_azienda,#ut_partita_iva').attr('disabled','disabled').parent().addClass('hidden');
		$('#ut_nome,#ut_cognome,#ut_codice_fiscale').removeAttr('disabled','disabled').parent().removeClass('hidden');
	}
	togglePrivatoAzienda.setAzienda = function(){
		$('#ut_nome,#ut_cognome,#ut_codice_fiscale').attr('disabled','disabled').parent().addClass('hidden');
		$('#ut_azienda,#ut_partita_iva').removeAttr('disabled','disabled').parent().removeClass('hidden');
	}
	if($('.ws_register_user #togglePrivato:checked').size()>0){
		togglePrivatoAzienda.setPrivato();
	}else if($('.ws_register_user #toggleAzienda:checked').size()>0){
		togglePrivatoAzienda.setAzienda();
	}
	$('#togglePrivato').click(
			function(){
				if(this.checked){
					togglePrivatoAzienda.setPrivato();
				}else{
					togglePrivatoAzienda.setAzienda();
				}
			}
		);
	$('#toggleAzienda').click(
			function(){
				if(this.checked){
					togglePrivatoAzienda.setAzienda();
				}else{
					togglePrivatoAzienda.setPrivato();
				}
			}
		);
}

function doLoginAfterSubscribe(){
//	if($('#ws_register_user').size()>0){

		$('#ut_email').change(function(){
					$('#user_hidden').val($(this).val());
				});
		$('#ut_password, #ripeti_password').change(function(){
					$('#password_hidden').val( $(this).val() );
				});
	//}
}

function tabs_hp () {
	var arr = [];
	$("#tabs_hp").css({"overflow":"hidden"});
	//$("#tabs_hp").wrapInner('<div class="slider clearfix" style="width:2400px;"></div>');
	$("#tabs_hp div[id^='tab']").each(function(){
		$(this).addClass("clearfix").css({"float":"left", "width":"720px", "height":$(this).height() + "px"});
		arr.push($(this).height());
	});
	$("#tabs_hp .slider").css({"width":"2400px", "position":"relative", "overflow":"hidden", "height":$("#tabs_hp div[id^='tab']:eq(0)").height + "px"});
	$("#navigazione_contenuti ul li a").not(".archivio a").click(function(){
		$("#navigazione_contenuti ul li a").removeClass("on");
		$(this).addClass("on");
		//var tab = $("#navigazione_contenuti ul li a").index($(this));
		var tab = $("#tabs_hp .slider").children("div").index($(String(this.href.match(/#\w+/))));
		$("#tabs_hp .slider").animate({"left":"-" + tab * 720 + "px", "height":arr[tab] + "px"},800);
		return false;
	});
	//$("#tabs_hp .slider").css({"left":"-" + 2 * 720 + "px", "height":arr[2] + "px"});
}

// GOOGLE MAPS
/*
function show_google_maps2(){
		$('input.google_maps_data').each(function(){
			var llz = String($(this).val()).split('|');
			if( llz.length > 2){
				if (GBrowserIsCompatible()) {
					var d = $(this).parent(".google_maps");
					var map = new GMap2(d[0]);
					map.checkResize();
					map.setCenter(new GLatLng(parseFloat(llz[0]), parseFloat(llz[1])), parseInt(llz[2]));
					$(d).data('gmap', map);
					
					map.openInfoWindowHtml(map.getCenter(),document.createTextNode(llz[3])); 
					var latlng = new GLatLng(parseFloat(llz[0]), parseFloat(llz[1]));
					map.addOverlay(new GMarker(latlng));
					var mapTypeControl = new GMapTypeControl();
					//var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));
					var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,10));
						//map.addControl(mapTypeControl, topRight);
						GEvent.addListener(map, "dblclick", function() {
							map.removeControl(mapTypeControl);
							map.addControl(new GMapTypeControl(), bottomRight);
						});
						map.addControl(new GSmallMapControl());			
					
				}
			}
		});
}
*/



function show_google_maps_7(){
		var p = {lat:null,lng:null,zoom:null,div:null,html:null}
		var m = $('#gmap_7');
		var i = $(m).find('input.google_maps_data');
		if(i.size()==0){
			m.slideToggle('fast');
		}else{
			var llz = String(i.val()).split('|');
			if( llz.length > 2){
				p.lat = parseFloat(llz[0]);
				p.lng = parseFloat(llz[1]);
				p.zoom = parseInt(llz[2]);
				p.html =  '<div>' + llz[3] + '</div>';// + ' ***'
				p.div = $(m).children(".google_maps")[0];
				
				m.slideToggle('fast',function(){create_gmap(p);});
			}
		}
		return false;
}


function show_google_maps(){
		var p = {lat:null,lng:null,zoom:null,div:null,html:null}
		var m = $($(this).attr('href'));
		var i = $(m).find('input.google_maps_data');
		if(i.size()==0){
			m.slideToggle('fast');
		}else{
			var llz = String(i.val()).split('|');
			if( llz.length > 2){
				p.lat = parseFloat(llz[0]);
				p.lng = parseFloat(llz[1]);
				p.zoom = parseInt(llz[2]);
				p.html =  '<div>' + llz[3] + '</div>';// + ' ***'
				p.div = $(m).children(".google_maps")[0];
				
				m.slideToggle('fast',function(){create_gmap(p);});
			}
		}
		return false;
}

function create_gmap(p){
	if (GBrowserIsCompatible()) {
		
		var map = new GMap2(p.div);
		
		map.checkResize();
		map.setCenter(new GLatLng(p.lat, p.lng), p.zoom);
		map.openInfoWindowHtml(map.getCenter(), (p.html));
		var latlng = new GLatLng(p.lat, p.lng);
		var marker = new  GMarker(latlng);
		var map_center = map.getCenter();
		GEvent.addListener(marker, "click", function() {
				map.openInfoWindowHtml(map_center, (p.html));
			});
		map.addOverlay(marker);
		var mapTypeControl = new GMapTypeControl();
		var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,10));
			GEvent.addListener(map, "dblclick", function() {
				map.removeControl(mapTypeControl);
				map.addControl(new GMapTypeControl(), bottomRight);
			});
			map.addControl(new GSmallMapControl());	
	}
}

function diba_reload_modelli(){
	var sel_marca, sel_modello;
	sel_marca = $('select#marca');
	sel_modello = $('select#modello');
	sel_marca.change(function(){
		$('select#marca, select#modello').css('cursor','wait');
		sel_modello.children('option:gt(0)').remove();
		$.post('/diba_ajax_service.asp',{op:'getOptionsModelsByBrand', Marca:sel_marca.val()}, 
			function(data,status){
				sel_modello.append(data);
				$('select#marca, select#modello').css('cursor','default');
			});
	},'html');
	if((sel_modello.val() == '') && (sel_marca.val() !== '')){
		sel_marca.trigger('change');
	}
	
	return true;	
}

function diba_ricerca_x_riferimento(){
	$('#codice_riferimento').keydown(function(e){
			var ret = false;
			if(console){
				console.log(e.charCode);
				console.log(e.keyCode);
				}
			switch ( e.keyCode ){
				case 8:
				case 13:
				case 16:
				case 17:
				case 35:
				case 36:
				case 37:
				case 39:
					ret = true;
				break;
				default:
					if(e.keyCode > 45 && e.keyCode < 58){
						ret = true;
					}
					if(e.keyCode > 95 && e.keyCode < 106){
						ret = true;
					}
				break;
			}
			return ret;
		});
	$('#frm_ricerca_usato').submit(function(){
			var cr = parseInt($('#codice_riferimento').val(),10);
			if ( cr > 0 ) {
				location.href = "/viewdoc.asp?rif=" + cr;
				return false;
			}
		});
}

function diba_reload_concessionarie(){
	var sel_marca, sel_concessionaria;
	sel_marca = $('select#ut_marchio');
	sel_concessionaria = $('select#ut_concessionaria');
	sel_marca.change(function(){
		if(sel_concessionaria.size()==0) return;
		$('select#ut_marchio, select#ut_concessionaria').css('cursor','wait');
		sel_concessionaria.children('option:gt(0)').remove();
		$.post('/diba_ajax_service.asp',{op:'getOptionsDealershipByBrand', ut_marchio:sel_marca.val()}, 
			function(data,status){
				sel_concessionaria.append(data);
				$('select#ut_marchio, select#ut_concessionaria').css('cursor','default');
			});
	},'html');
	return true;	
}

function diba_reload_officine_concessionarie(){
	var sel_marca, sel_offic_conces;
	sel_marca = $('select#ut_marchio');
	sel_offic_conces = $('select#ut_officina_concessionaria');
	sel_marca.change(function(){
		if(sel_offic_conces.size()==0) return;
		$('select#ut_marchio, select#ut_officina_concessionaria').css('cursor','wait');
		sel_offic_conces.children('option:gt(0)').remove();
		sel_offic_conces.children('optgroup').remove();
		
		$.post('/diba_ajax_service.asp',{op:'getOptionsDealershipWorkshopByBrand', ut_marchio:sel_marca.val()}, 
			function(data,status){
				sel_offic_conces.append(data);
				$('select#ut_marchio, select#ut_officina_concessionaria').css('cursor','default');
			});
	},'html');
	return true;	
}

/* JSON FORM */
var ws_json_form = {
		theForm: "" ,
		init: function(p){
			try{
			$("body").after("<iframe name=\"ws_ifr_upload_file\" id=\"ws_ifr_upload_file\" style=\"display:none\" rows=\"1\" cols=\"1\" src=\"\"></iframe>");
			$(p).each(function(){this.target="ws_ifr_upload_file";});
			$(p).submit(ws_json_form.ajax_submit);
			}
			catch(e){alert(e);}
		},
		ajax_submit: function(){
			var post_data,ifr_target;
			try{
				ws_json_form.the_form = this;
				if(ws_json_form.the_form.valid==false){return false;}
				if($(this).attr("enctype")=="multipart/form-data"){
				/* upload files BEGIN */
				ifr_target = $("#ws_ifr_upload_file");
				if ($(ifr_target).size()==0){
					$("body").after("<iframe name=\"ws_ifr_upload_file\" id=\"ws_ifr_upload_file\" src=\"\"></iframe>");
				}
				this.target="ws_ifr_upload_file";
				$("#ws_ifr_upload_file").load(function(){
					   var d,s;
					   s="success";
					   d=eval("(" + frames['ws_ifr_upload_file'].document.body.innerHTML +")" );
					   ws_json_form.callback_json(d,s);
					});
				return true;
				/* upload files END*/
				}else{
					post_data = $(this).serializeArray();
					$.post($(this).attr("action"), post_data, ws_json_form.callback_json, "json");
				}
			}
			catch(e){
				self.status = (e);
			}
			return false;
		},
		callback_json:	function(vdata, textStatus){
			var d;
			try{
				d = vdata;
				if ($(ws_json_form.the_form).children("div.response").size()==0 ){$(ws_json_form.the_form).prepend("<div class=\"response\"></div>")}

				if(d.status=="success"){
					$(ws_json_form.the_form).children("div.response").html(d.data);
				}else{
					$(ws_json_form.the_form).children("div.response").html(d.error);
				}
				if(parseInt($(ws_json_form.the_form).height())>parseInt($(ws_json_form.the_form).children("div.response:eq(0)").height())){
					$(ws_json_form.the_form).children("div.response").css({"height": $(ws_json_form.the_form).height()+"px"});
				}
				$(ws_json_form.the_form).children("fieldset").fadeOut("fast",function(){$(ws_json_form.the_form).children("div.response").fadeIn("fast");});
				$(ws_json_form.the_form).children("div.response").hide();
			}
			catch(e){
				self.status = (e);
				alert(e);
			}
		},
		back_and_complete: function (chi){
			$(chi).parent().fadeOut('slow',function(){
				$(chi).parent().parent().children('fieldset').fadeIn('slow');
				return false;
			});
		}
	}

