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 = $(frm).serialize();
		// ^^^ ho tolto l'accesso al name perche' potrebbero esserci in pagina + form con lo stesso nome
		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);
	}else if(frm)
		frm.submit();
	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;
}

var resultFadeOut = null;
var fadeOutTimer = 0;

function setRisultatiHide(){
	clearInterval(resultFadeOut);
	$("#ricercheRisultati").fadeOut("slow");
	resultFadeOut = null;
	fadeOutTimer = 0;
}
function setRisultatiShow(positionElement){
	window["positionElement"] = positionElement;
	if( !resultFadeOut ){
		$("#ricercheRisultati").fadeIn("slow")
							   .bind("mouseover", function(){fadeOutTimer=0;} )
							   .bind("mouseout", function(){fadeOutTimer=-1;} );
		
		// nascondo le select per via di IE
		var frm = positionElement.form;
		$(frm).children("fieldset").each( function(){$(this).hide();}) 
		resultFadeOut = setInterval( 'setRisultatiShow(window["positionElement"]);',1 );
	}
	else if(fadeOutTimer==-1 || fadeOutTimer>500){
		setRisultatiHide();
	}else{
		var obj = $(positionElement);
		var left = $(obj).offset( ).left + 2;
		var top = $(obj).offset( ).top + $(obj).outerHeight();
		$("#ricercheRisultati").css("top",top).css("left",left);
		fadeOutTimer++;
	}
}

function startQuickSearch(){
	if( this.value && this.value.length>2 ){
		// dati per la ricerca
		// viene fatta la chiamata e automaticamente viene sostituito il DIV coi risultati in pagina
		var frm = this.form;
		var qs = "?"+$(frm).serialize();
		sendGetData(qs,false);
		
		// inizia il posizionamento
		fadeOutTimer = 0;
		setRisultatiShow(this);
		
		// mantieni in posizionamento
		$(this).bind("mouseover", function(){fadeOutTimer=0;} )
	}else
		fadeOutTimer = -1;
}

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","");
	}
}

// on READY
 jQuery(document).ready(function() {
 	jQuery('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);
		}
	 })
	
	// 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]);
						}
					});
	}
}
