function isDate(str){str = str||""; return str.search(/^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/)!=-1}
function showMessageInLightBox(text){
	// questa funzione serve per tutte le volte che voglio sovrascrivere la gif loading.. con un messaggio
	// dopo che ho finito l'operazione in corso
	var bLoading = $('#facebox .loading').length == 1;
	text = text||"";
	if(text.length){
		if( bLoading ){
			$.facebox.reveal(text);
		}else
			$.facebox(text);
	}else if(bLoading){
		$.facebox.close();
	}
	
}

// Response per chiamata xmlHTTP
function requestCallBack(sData,sStatus){
	var responseText; // vedere come gestire il messaggio di errore
	switch(sStatus){
		case "success":
			var oResponse = $( document.createElement("div") ).append(sData);
			oResponse.children().each( function(){
				if(this.id){
					var o = $("#"+this.id);
					if(o){
						o.empty();
						var sHtml = $(this).html();
						if(sHtml)
							o.html(sHtml);
					}
				}
			});
			var oResponseText = oResponse.children("#responseText")[0];
			if(oResponseText)
				responseText = oResponseText.innerHTML;
		break;
		case "error":
			responseText = "CLIENT ERROR: "+sData.responseText;
		break;
	}
	return responseText;
}

function ajaxCall(qs,data){	
	data = data||"";
	$.ajax({
		async: true,
		error: function(XMLHttpRequest, textStatus) {
					showMessageInLightBox( requestCallBack(XMLHttpRequest, textStatus) );
				},//func(XMLHttpRequest, textStatus);
		success: function(data, textStatus) {
					showMessageInLightBox( requestCallBack(data, textStatus) );
				},//func(data, textStatus),
		data: data,
		type: "POST",
		url: "ajaxRequests.asp"+qs,
		scriptCharset:"iso-8859-1"
	});
}

// Post di un form in Ajax
function sendData(frm,bLightBox){
	if( frm ){
		var data = [];
		for(var i=0,v,n;i<frm.elements.length;i++){
			if( !frm.elements[i].name ) continue;
			v = null;
			n = null;
			switch(frm.elements[i].type){
				case "select-one":
					n = frm.elements[i].name;
					v = frm.elements[i].options[frm.elements[i].selectedIndex].value;
				break;
				case "radio":
				case "checkbox":
					if(frm.elements[i].checked){
						n = frm.elements[i].name;
						v = frm.elements[i].value;
					}
				break;
				default:
					n = frm.elements[i].name;
					v = escape(frm.elements[i].value);
				break;
			}
			if(n){
				data.push(n + "=" + v );
			}
		}
		data = data.join("&");
		bLightBox = bLightBox==false?false:true;
		var qs = frm.action.split("?");
		if(qs.length>1) qs = "?"+qs[1];
		else qs = "";
		if(bLightBox)
			$.facebox(function(){ ajaxCall(qs,data); });
		else
			ajaxCall(qs,data);
	}
	return false;
}

function sendGetData(qs,bLightBox){
	qs = (qs||"").split("?");
	bLightBox = bLightBox==false?false:true;
	if(qs.length>1) qs = "?"+qs[1];
	else qs = "";
	if(qs){
		if(bLightBox)
			$.facebox(function(){ ajaxCall(qs); });
		else
			ajaxCall(qs);
	}
	return false;
}

function enableMainFormQuickResults(mainFormSearchFld){
	var resultsDiv = $('div#ricercheRisultati');
	mainFormSearchFld = $(mainFormSearchFld);
	mainFormSearchFld.keyup(function(e){
		e.preventDefault();
		if( mainFormSearchFld.val().length <3 ){
			resultsDiv.html("");
			return;
		}
		
		var frm = this.form;
		var qs = "?" + $(frm).serialize();
		sendGetData(qs,false);
		
		var left = mainFormSearchFld.offset( ).left;
		var top = mainFormSearchFld.offset( ).top + mainFormSearchFld.outerHeight();
		resultsDiv.css("top",top)
				  .css("left",left)
				  .fadeIn("slow")
				  .bind("mouseout", function(e){ hideResults(e); });
				  
	}).bind("mouseout", function(e){ hideResults(e); });
	
	function hideResults(e){
		var x1 = resultsDiv.offset( ).left;
		var x2 = x1 + resultsDiv.outerWidth();
		var y1 = resultsDiv.offset( ).top - mainFormSearchFld.outerHeight();
		var y2 = y1 + resultsDiv.outerHeight() + mainFormSearchFld.outerHeight();
		var mouseX = e.pageX;
		var mouseY = e.pageY;
		
		if( mouseX<x1 || mouseX>x2 || mouseY<y1 || mouseY>y2 )
			resultsDiv.fadeOut("slow");
		
	}
}


function switchTab(id,parentID){
	var o = document.getElementById(parentID);
	if(o){
		$(o).children().each( function(){
									if( id!=parentID )
										$(this).hide();
									else
										$(this).show("slow");
							})
		$("#"+id).show("slow");
	}
}

function setVoteValue(el){
	$(el).removeClass("starOFF").addClass("starON");
	$(el).prevAll().removeClass("starOFF").addClass("starON");
	$(el).nextAll().removeClass("starON").addClass("starOFF");
	el.form["value"].value = el.name;
	el.blur();
}


// YOUTUBE 
function showVideo(ID){
	$.facebox('<div id="readyYtApiPlayer">Loading...</div>');
	
	var params = { allowScriptAccess: "always" };
	var atts = { id: "readyYtPlayerEMB_"+ID };
	swfobject.embedSWF("http://www.youtube.com/v/"+ID+"&enablejsapi=1&playerapiid="+ID, 
						"readyYtApiPlayer", "480", "295", "8", null, null, params, atts);
	
	$(document).bind('close.facebox', function(){
		stopFlashVideo("readyYtPlayerEMB_"+ID);
	})
	
	return false;
}

function onYouTubePlayerReady(pID) { 
 	var player = document.getElementById("readyYtPlayerEMB_"+pID);
	if(player)
		player.playVideo();
}

function stopFlashVideo(name){
	var player = document.getElementById(name);
	if(player){
		//player.stopVideo(); funzione youtube
		//player.clearVideo(); funzione youtube
		player.StopPlay();
	}
}

function getFlashObj(movie){
	if(window.document[movie]){
		return window.document[movie];
	}
	if(navigator.appName.indexOf("Microsoft Internet")==-1){
		if (document.embeds && document.embeds[movie])
			return document.embeds[movie]; 
		else
			return document.getElementById(movie);
	}
}

function setFlashVideoSettings(_name) {
	var movieObj = getFlashObj(_name);
	if(movieObj){
		var width = movieObj.TGetProperty("/", 8);
		var height = movieObj.TGetProperty("/", 9);
		movieObj.setAttribute("width",width);
		movieObj.setAttribute("height",height);
	}
	$('#facebox').css('left', $(window).width() / 2 - ($('#facebox table').width() / 2));
	
	$(document).bind('close.facebox', function(){
		stopFlashVideo(_name);
	})
}
	
function setParentIFrameWidth(iframeName){
	var oWin = window.parent;
	if(oWin){
		var oFrame = oWin.document.getElementById("iframeName");
		oFrame.height = oWin.document.body.scrollHeight;
		oFrame.width = oWin.document.body.scrollWidth;
	}
}

function showOtherDestionationPopUp(){
	var sHTML = '<iframe src="otherDestination.asp" name="otherDestinationIframe" id="otherDestinationIframe" frameborder="0"></iframe>';
	showMessageInLightBox(sHTML);
}

function uploadifyOnAllComplete(event,data){
	$("#registrationMainForm").submit();
}
function uploadifyOnComplete(event,queueID,fileObj,response,data){
	var a = response.split("|");
	// 0 - responso (SUCCESS/ERROR)
	// 1 - Nome file inserito (PRENDO QUELLO DAL RESPONSO PERCHE' POTREBBE ESSER STATO RINOMINATO PER VIA DEI DUPLICATI)
	if(a[0]=="SUCCESS"){
		$("#registrationMainForm input[id='file_upload_value']").attr("value",a[1]);
	}
}
function uploadifyOnSelect(event,queueID,fileObj){
	// serve per precompilare il campo col valore per il check dei campi obbligatori
	if(fileObj && fileObj.name){
		$("#registrationMainForm input[id='file_upload_value']").attr("value",fileObj.name);
	}
}
function uploadifyOnCancel(event,queueID,fileObj,data){
	if(fileObj && fileObj.name){
		$("#registrationMainForm input[id='file_upload_value']").attr("value","");
	}
}
function addElementBlockHeight(){
	var h = $(this).height();
	var w = $(this).width();
	// per mantenere l'altezza dell'elemento nascosto
	var o = $('<div class="readyTemporayHiddenElementBlock">&nbsp;</div>');
		o.height(h);
		o.width(w);
	$(this).before(o);
	//$(this).hide();
	$(this).addClass("readyTemporayHiddenElement");
	
}
// on READY
 jQuery(document).ready(function() {
 	$('a[rel*=facebox]').facebox();
	
	// VIDEO TEMPORANEO ridimensiono il filmato flash aperto
	$(document).bind('reveal.facebox', function() {
		var myMovie = document.getElementById("myMovie");
		if(myMovie){
			setTimeout('setFlashVideoSettings("myMovie")',100);
		}
	 })
	
	// GESTIONE FILMATI FLASH CON LIGHTBOX APERTO/CHIUSO
	$(document).bind('close.facebox', function(){
		$(".readyTemporayHiddenElement").removeClass("readyTemporayHiddenElement")
								//.show()
								;
		$(".readyTemporayHiddenElementBlock").remove();
	})
	$(document).bind('loading.facebox', function(){
		$("object").each(addElementBlockHeight);
		$("iframe[id!='facebox_overlay_iframe']").each(addElementBlockHeight);
	})
	// ------------------------------------------------
	
	// UPLOAD FILE
	var file_upload = $('#file_upload');
	file_upload.uploadify({
						'uploader'  	: template_var_skinFolder+'browse_button.swf',
						'script'    	: 'uploadFiles.asp',
						'cancelImg' 	: template_var_skinFolder+'ico_ball_red2.gif',
						'multi'			: false,
						'auto'      	: false,
						'fileDesc'		: 'Only .gif;.jpg;.png;.rar;.zip;.txt;.pdf;.tif;.bmp',
						'fileExt'		: '*.gif;*.jpg;*.jpeg;*.png;*.rar;*.zip;*.txt;*.pdf;*.tif;*.bmp',
						'buttonText'	: chooseFileToUpload,
						onAllComplete	: uploadifyOnAllComplete,
						onComplete		: uploadifyOnComplete,
						onSelect		: uploadifyOnSelect,
						onCancel		: uploadifyOnCancel
						});
	
	$("#registrationMainFormSubmit").bind("click",function(){
		if( checkFRM($("#registrationMainForm")[0]) ){
			if( file_upload.length>0 && $(".uploadifyQueueItem").length>0 ){
				file_upload.uploadifyUpload();
				return false;
			}else{
				return true;
			}
		}else{
			return false;
		}
    });
 })

function setRegFormFieldsToUpperCase(){
	$("#registrationMainForm").find("input[type='text']").each(function(){
												var fldName = $(this).attr("name").replace(/__\*$/,"");
												fldName = decryptString(fldName);
												switch(fldName){
													case "mail": case "mail_2":
													case "userID":
													break;
													default:
														$(this).css("text-transform","uppercase");
														$(this).bind("keyup",function(){
															var upper = $(this).val().toUpperCase(); // in questo modo invia effettivamente i dati in uppercase
																									 // lascio anche lo stile cosi' non si vede la trasformazione durante la digitazione
															$(this).val(upper);
														});
													break;
												}
										  })
}

var arrTopLevelDomains = [];
function setGoogleAnalyticsClickEvents(){
	// http://www.google.com/support/analytics/bin/answer.py?hl=it_IT&answer=175538&utm_id=ad
	if( arrTopLevelDomains.length ){
		$("a").click(function(){
					var href = $(this).attr("href");
					var bOK = false;
					for(var i=0;i<arrTopLevelDomains.length;i++){
						if( href.indexOf(arrTopLevelDomains[i])!=-1 ){
							bOK = true;
							break;
						}
					}
					if( bOK ){
						_gaq.push(['_link', href]);
						return false;
					}
				});
		$("form").submit(function(){
						var href = $(this).attr("action");
						var bOK = false;
						for(var i=0;i<arrTopLevelDomains.length;i++){
							if( href.indexOf(arrTopLevelDomains[i])!=-1 ){
								bOK = true;
								break;
							}
						}
						if( bOK ){
							_gaq.push(['_linkByPost', this]);
						}
					});
	}
}

function initDisclaimer(mess){
	showMessageInLightBox(mess);
	$(document).unbind('close.facebox');
	$("#disclaimerKO").click(function(){
								window.location.href = "http://www.google.it";
							})
}

function resizeIframe(objID){
	var helpFrame = $("#" + objID);
	var innerDoc = (helpFrame.get(0).contentDocument) ? helpFrame.get(0).contentDocument : helpFrame.get(0).contentWindow.document;
	var height = innerDoc.body.scrollHeight + 35;
	helpFrame.height(height);
	return height;
}
