var path_assoluto, co_id=1, tmp;
function init(){
	// assegno alla variabile co_id il valore assegnato nella querysrting
	tmp = location.search.toLowerCase().match(/co_id=(\d+)\D*/);
	$('#lingue a[href*=' + location.host + ']').addClass('on');
	if (tmp && tmp.length>0){co_id=tmp[1]}
	//menu();	
	PulisciInput("form input:text, .raform2 input:text ");
	my_accordion();
	//active_gallery();
	$('form').append('<input type="hidden" name="can_submit" value="'+Math.random()+'" />');
	$("form").submit(function (){return get_form_validation(this);}); //"#"+$(this).attr("id")
	ws_json_form.init("form.post_ajax");
	if(typeof(swfobject)!=='undefined'){
		// sostituisco l'elemento con id="animazione_swf" con l'oggetto FLASH indicato nel primo parametro
		swfobject.embedSWF("/forum.swf?co_id="+co_id, "animazione_swf", "940", "420", "9.0.0", "/js/swfobject/expressInstall.swf", {}, {wmode:'transparent'});
	}
	$("a.fancyframe").fancybox({
		overlayOpacity:0.8,
		overlayColor:"#000",
		padding:20,
		type:'iframe',
		frameHeight: 600,
		frameWidth: 680
	});	
	
	$("a.bookus_link").fancybox({
		overlayOpacity:0.8,
		overlayColor:"#000",
		padding:20,
		type:'iframe',
		hideOnOverlayClick: false,
		frameHeight: 600,
		frameWidth: 680
	});	
//	replace_flash_objects();	
}

/* Funzione per Menù 
- - - - - - - - - - - - - - - - - - - - */
function menu(){
	$("#menu_vert_3lev a.active").parent().parent().addClass("on");
	$("#menu_vert_3lev ul li ul").not(".on").hide();
	$("#menu_vert_3lev 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();
	$("img[src='']").src='/img/trasp.gif';

	
}
function apriMenu(){
	$("#menu_vert_3lev 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 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 */
/* VIRTUAL EXPLORE 
	delay=9000;
	virtual_explore(delay);
-------------------------*/


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;
	}	
}

var ve_pages = new Array();
function virtual_explore(delay){
	if (window.location.href.indexOf("&ve=1")>0){
		document.body.innerHTML+="<a href='"+window.location.href.replace('&ve=1','&ve=0')+"' style='position:fixed;top:0px;left:404px;z-index:100;padding:12px;border:1px solid #ff7777;background-color:#770000;color:#fff;'>stop virtual explore</a>";
		
		$("#menu_vert_3lev a").each(
					function(){
						if(this.href !=="#" && this.href.indexOf("?")>1 && this.href.indexOf("http://")<1)ve_pages.push(this.href+"&ve=1");
					});
		
		var i=0;
		i=ve_pages.indexOf(window.location.href);
		setTimeout(function(delay){if (i+1<ve_pages.length){window.location.href=ve_pages[i+1];}else{window.location.href=ve_pages[0];}},delay);
	} else if (window.location.href.indexOf("&ve=0")>0){
		document.body.innerHTML+="<a href='"+window.location.href.replace('&ve=0','&ve=1')+"' style='position:fixed;top:0px;left:404px;z-index:100;padding:12px;border:1px solid #ff7777;background-color:#770000;color:#fff;'>start virtual explore</a>";
	}
}

/* GALLERY NOTHICK
-------------------------------------------*/
function gallery_nothick(){
	var tg, gscreen, current,top, playing;
	tg = $("a.nothickbox");
	top = $(tg).size()-1;
	current=0;
	playing=0;
	var partenza = false;
	gscreen = $("img.gallery_screen");
	$(tg).click(function(){
						 	$(gscreen).attr("src",this.href); 
							current=$(tg).index(this); 
							$(tg).removeClass("current_img");
							$(this).addClass("current_img");
							return false;
							});
	$("a.gprevious").click(function(){
				var i, ni;
				$(tg).removeClass("current_img");
				if (top<0 ){return false;}
				if(current>0){
					i=current-1;
				}else{
					i=top;
				}
				current = i;
				ni=$(tg).eq(i).attr("href");
				if(ni!=="undefined"){
					$(gscreen).attr("src",ni);
					$(tg).eq(i).addClass("current_img");
				}
				return false;
			});
	$("a.gnext").click(function(){
				var ni,i;
				$(tg).removeClass("current_img");
				if (top<0 ){return false;}
				if(current<top){
					i=current+1;
				}else{
					i=0;
				}
				current = i;
				ni=$(tg).eq(i).attr("href");
				if(ni!=="undefined"){
					$(gscreen).attr("src",ni);
					$(tg).eq(i).addClass("current_img");
				}
				return false;
			});
	$("body").append("<img src='" + $(tg).eq(0).attr("href") + "' alt='' class='hidden_loader' style='display:none' /> ");
//	$("body img.hidden_loader").eq(0).load(function(){$(gscreen).attr("src",$(this).attr("src")); playNext();});
	nothick_playNext = function(){
		if(playing==1){
			if (current<=top){
					//$(gscreen).attr("src",$(tg).eq(current));
					$(tg).removeClass("current_img");
					current++;
					if (current>top){current=0;}
					$("body img.hidden_loader").eq(0).attr("src",$(tg).eq(current).attr("href"));
					$(tg).eq(current).addClass("current_img");
			}

			partenza=window.setTimeout(nothick_playNext,3000);
		}else{
			partenza=false;
		}
	}
	nothick_play=function(){
			playing=1;
			$("body img.hidden_loader").eq(0).load(activePlay);
			$(".nothick_play").removeClass("on");
			$(".nothick_stop").addClass("on");
			nothick_playNext();
			return false;
		}
	nothick_stop=function(){
			playing = 0;
			partenza = false;
			$("body img.hidden_loader").eq(0).unbind("load");
			$(".nothick_play").addClass("on");
			$(".nothick_stop").removeClass("on");
			return false;		
		}
	activePlay = function(){
		var ni=$(this).attr("src");
		$(gscreen).fadeOut("fast",function(){$(gscreen).attr("src",ni)}).fadeIn("fast");

	}
	$(gscreen).click(function(){if (playing==0){nothick_play();}else{nothick_stop()}});
	$(".nothick_play").click(nothick_play);
	$(".nothick_stop").click(nothick_stop);
}


/* CONVALIDA FORM
-------------------------------------------*/
function ws_validate(){}
ws_validate.prototype.isEmail = function (what)
{
   var i=new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,4}|[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;}
		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 "isNotChecked":
		  	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).parents('li').not('ul.input_group li').addClass("bg_error");
			valid=false;
		}else{
			$("#"+nc).parents('li').not('ul.input_group li').removeClass("bg_error");
		}
	}
	$(".bg_error input, .bg_error select, .bg_error textarea").eq(0).focus();
	$(frm_id)[0].valid = valid;
	return valid;
}
/* REPLACE FLASH OBJECTS*/
function replace_flash_objects()
{
	$(".replace_flash_objects").each(function ()
		{
			var f, re,p;
			f = String($(this).children("noscript").html()).replace("&lt;","<").replace("&gt;",">");

			while(f.indexOf("&lt;")>=0){
				f = f.replace("&lt;","<");
			}
			while(f.indexOf("&gt;")>=0){
				f = f.replace("&gt;",">");
			}
/*
			p="<[^>]{0,1}object[^>]*>|<[^>]{0,1}param[^>]*>";
			re = new RegExp();
			re.pattern=p;
			f.replace(re,"");
			re.pattern="&lt;";
			f.replace(re,"<");
			re.pattern="&gt;";
			f.replace(re,">");
*/
			if(f.length<10){f = $(this).children(".embed").html()}
//			$(this).prepend(f);
			this.innerHTML=f;
		}
	 );
}

/* 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;
			});
		}
	}

/* LANCIA INIT */
if(typeof($)=="function"){
	path_assoluto = location.href;
	$(document).ready (init);

}

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 always_bottom(){
	// per fissare la posizione di un elemento sempre in fondo alla pagina
	var ab, extra_height;
	if($('.always_bottom').size()>0){
		extra_height = 20;
		if($.browser.msie){extra_height = 0;} 
		ab = { left:0, top: $(window).height() - $('.always_bottom').height() - extra_height};
		$('.always_bottom').css({'position':'absolute','top': ab.top + 'px', 'left': ab.left + 'px'});
		$(window).resize(always_bottom); // ridimensionando la pagina l'elemento rimane sempre ancorato in basso
	}
}

function galleria_scrollable(){
	// richiede jquery.tools.js
	var gl1;
	var img = new Image();
	if($('#galleria_img .bm_galleria_immagini ul li').size()>0){
		$('#galleria_img').append('<a class="prevPage">Indietro</a>');
		$('#galleria_img').append('<a class="nextPage">Avanti</a>');
	}
	gl1 = $('#galleria_img .bm_galleria_immagini').scrollable({size: 5, items: 'ul', item:'li'}).circular().autoscroll({autoplay:true, interval:4000}).mousewheel({api: true});
	if(gl1){
		gl1.getItems().each(function(){
						$(this).children('a').click(function(){
								var url = $(this).attr('href');
								var zoom = $('#foto_pag img.doc_img_1'); 
								img.onload=function(){
									zoom.fadeTo('fast',0, function(){zoom.attr('src',url).fadeTo('fast',1)});
								}
								img.src=url;
								gl1.getItems().find('img').removeClass('active');
								$(this).find('img').addClass('active');
								return false;
						});
					});
		gl1.onSeek(function(){gl1.getItems().eq(this.getIndex()).children('a').click();});
	}
}

