
// TODO: try to remove all those ugly eval() for a better compression.

/**
 * utility class with often used functions.
 * 
 * @author eesposito
 */

var VsUtil = {
	/**
	 * These functions simplify "dojo.connect" calls in our templates, for readability.
	 */
		
	popup: undefined,
	
	byId: function(domOrId){
		if (typeof domOrId == 'string'){
			return dojo.byId(domOrId);
		}
		return domOrId;
	},
	
	/**
	 * connectAndStop(domOrId:string, method: string, func: function)
	 * It takes just the id, method and function to call and automatically stops the event.
	 * 
	 * domOrId: 	id of, or element to connect on
	 * method: 		name of the method to which we are connecting
	 * func: 		function to be executed
	 */		
	connectAndStop: function(domOrId,method,func){
		
		var elem = this.byId(domOrId);
		
		if (!elem || !method || !func){
			console.warn(ekLang._("Waring, aborting connectAndStop() called with id="+domOrId+"; method="+method+"; func="+func));
			return;
		}
		if (typeof func != 'function'){
			console.warn(ekLang._("Waring, aborting connectAndStop() func parameter must be a function!!"));
			return;
		}
		dojo.connect(elem,method,function(e){
				dojo.stopEvent(e);
				return func(e);
			}
		);
	},
	
	/**
	 * onClick(domOrId:string,func:string,hover:boolean)
	 * 
	 * this function connects to the onClick method of "id" DOM element.
	 * hover: if true, sets a busy pointer when the mouse enters the element space.
	 */
	onClick: function(domOrId,func,hover){
		
		var elem = this.byId(domOrId);
		
		if (!elem || !func){
			console.warn(ekLang._("Waring, aborting onClick() called with id="+domOrId+"; func="+func));
			return;
		}
		
		if (hover){
			dojo.connect(elem,"onmouseover",function(e){
				elem.style.pointer="wait";
			});
			dojo.connect(elem,"onmouseout",function(e){
				elem.style.pointer="";
			});			
		}
		
		dojo.connect(elem,"onclick",function(e){
			dojo.stopEvent(e);
			eval(func);
		});
	},

	/**
	 * onClick(domOrId:string,startFunc:string,stopFunc:string,hover:boolean)
	 * 
	 * This function connects to the onMouseDown event (first mouse button)	
	 * of "id" DOM element and sets a "pointer" cursor when the elment is reached
	 * by the mouse (onMouseOver).
	 * 
	 * When onMouseDown is fired, a starFunc function is called.
	 * 
	 * The event is considered finished (and stopFunc called) when:
	 *   mouse exits from the element (onMouseOut)
	 *   mouse is released (onMouseUp, first mouse button)
	 */
	onMouseDown: function(domOrId,startFunc,stopFunc){
		
		var elem = this.byId(domOrId);
		if (!elem || !startFunc || !stopFunc){
			console.warn(ekLang._("Waring, aborting onMouseDown() called with id="+domOrId+"; startFunc="+startFunc+"; stopFunc="+stopFunc));
			return;
		}
				
		dojo.connect(elem,"onmousedown",function(e){
			if ( ( (!dojo.isIE || dojo.isIE>=9) && e.button == 0)
				|| (dojo.isIE && e.button&1) ){
				dojo.stopEvent(e);
				eval(startFunc);
			}
		});

		dojo.connect(elem,"onmouseup",function(e){
			if ( ( (!dojo.isIE || dojo.isIE>=9) && e.button == 0)
				|| (dojo.isIE && e.button&1) ){
				dojo.stopEvent(e);
				eval(stopFunc);
			}
		});	

		dojo.connect(elem,"onmouseover",function(e){
			dojo.stopEvent(e);
			elem.style.cursor='pointer';
			eval(stopFunc);
		});

		dojo.connect(elem,"onmouseout",function(e){
			dojo.stopEvent(e);
			elem.style.cursor='';
			eval(stopFunc);
		});
	},
	
	/**
	 * onOverButton(domOrId:string)
	 * 
	 * Animates an input button when clicked by scrolling its background.
	 */	
	onOverButton: function(domOrId){

		var elem = this.byId(domOrId);
		
		if (elem){			
			var y = elem.offsetHeight
			//TODO: use CSS with hover style.
			dojo.connect(elem,'onmouseover',function(){y = this.offsetHeight; this.style.cursor = 'pointer'; this.style.backgroundPosition = '0px '+(-y)+'px';});
			dojo.connect(elem,'onmouseout',function(){this.style.cursor = ''; this.style.backgroundPosition = '0px 0px';});
			dojo.connect(elem,'onmousedown',function(e){ if ((!dojo.isIE && e.button == 0) || (dojo.isIE && e.button&1) ){y = this.offsetHeight; this.style.backgroundPosition = '1px '+(1-y)+'px';this.blur();};});
			dojo.connect(elem,'onmouseup',function(e){if ((!dojo.isIE && e.button == 0) || (dojo.isIE && e.button&1) ){y = this.offsetHeight; this.style.backgroundPosition = '0px '+(-y)+'px';this.blur();};});
		}
	},
	
	/**
	 * showBusyPointer(elements:array)
	 * 
	 * sets a busy pointer for DOM elements in "elements" param.
	 */
	showBusyPointer: function (elements) {
		for (var i=0; i<elements.length; i++){
			if (elements[i]){
				elements[i].style.cursor = 'wait';
			}
		}
	},

	/**
	 * resetPointer(elements:array)
	 * 
	 * sets a click-pointer for DOM elements in "elements" param.
	 */
	resetPointer: function(elements){ 
		for (var i=0; i<elements.length; i++){
			if (elements[i]){
				elements[i].style.cursor = 'pointer';
			}
		}
	},
	
	/**
	 * Change text of input box when the user focus/blurs it.
	 * WARNING! This function connect to the onsubmit of the parent form
	 * to remove the onFocusTest, if the form is ajax, you should 
	 * care of remove the text by yourself.
	 */
	setInputTextDefaultMessage: function (fieldName,onFocusText, formJson){
	
		var input = dojo.byId(fieldName);
		
		var isPassword = input.getAttribute('type') == 'password';
		
		if (isPassword && dojo.isIE){
			return;
		}
		
		dojo.connect(input,'onfocus',function(){
			if(onFocusText == input.value){
				input.value = "";
				dojo.removeClass(input, 'widgetHelpMessage');
			}
			if (isPassword){
				input.setAttribute('type','password');
			}
		});
		dojo.connect(input,'onblur',function(){
			if(input.value == ''){
				if (isPassword){
					input.setAttribute('type','text');
				}
				input.value = onFocusText;		
				dojo.addClass(input, 'widgetHelpMessage');
			}
		});
		
		// Set starting value
		if (input.value == '' || input.value == onFocusText) {
			if (isPassword){
				input.setAttribute('type','text');
			}
			input.value = onFocusText;
			dojo.addClass(input, 'widgetHelpMessage');
		}
		
		if (formJson){
			dojo.connect(formJson, 'onPreValidate', function() {
				if(input.value == onFocusText) {
					input.value = '';
					dojo.removeClass(input, 'widgetHelpMessage');
				}
			});
			
			dojo.connect(formJson, 'onError', function() {
				if(input.value == ''){
					if (isPassword){
						input.setAttribute('type','text');
					}
					input.value = onFocusText;		
					dojo.addClass(input, 'widgetHelpMessage');
				}
			});
			
		}else{		
			//Instruct the form to clear the value if is the default text:
			dojo.connect(input.form, 'onsubmit', function() {
				if(input.value == onFocusText) {
					input.value = '';
					dojo.removeClass(input, 'widgetHelpMessage');
				}
			});
		}
	}
	
	,safeCall: function(f){
		if (typeof(f) == 'function')
			return f();
		return undefined;
	}
	
	/**
	 * JS link hiding functions.
	 */
	,reverseString: function(s) {
		return s.split("").reverse().join("");
	}
	
	,windowOpenReverse: function(reversedUrl) {
		window.open(VsUtil.reverseString(reversedUrl));
	}
	,windowLocationReverse: function(reversedUrl) {
		window.location = VsUtil.reverseString(reversedUrl);
	}

	,popupOpen: function(url,w,h,t,l){
		
		t = t? t: (screen.height - h) / 2; // Get rid of undefined.
		l = l? l: (screen.width - w) / 2;
		
		if (this.popup){
			this.popup.close();
		}
		
		return this.popup = window.open(url,null,'top='+t+',left='+l+',height='+h+',width='+w+',status=no, directories=no, toolbar=no, location=no, menubar=no,scrollbars=no, resizable=no');		
	}
	
	,popupOpenReverse: function(reversedUrl,w,h,t,l){
		
		t = t? t: (screen.height - h) / 2; // Get rid of undefined.
		l = l? l: (screen.width - w) / 2;
		
		if (this.popup){
			this.popup.close();
		}
		
		this.popup = window.open(VsUtil.reverseString(reversedUrl),null,'top='+t+',left='+l+',height='+h+',width='+w+',status=no, directories=no, toolbar=no, location=no, menubar=no,scrollbars=no, resizable=no');		
	},
	
	emailRegex : new RegExp(/^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/),
	telephoneRegex : new RegExp(/^\+?[\d ]+[/\-]?[\d ]+$/m),
		
	checkEmailForm : function (form) {
		try {
			var sError = "Attenzione\n";
			var oNome = form.nome;
			if (!oNome) {
				return false;
			}
	
			var oEmail = form.email;
			if (!oEmail) {
				return false;
			}
	
			var oTelefono = form.telefono;
			if (!oTelefono) {
				return false;
			}
	
			var oPrivacy = form.privacy;
			if (!oPrivacy) {
				return false;
			}
			
			if (oNome.value == "" || oNome.value == VsLang._("Nome")) {
				sError += "\n - Il campo NOME deve essere obbligatoriamente compilato\n";
			}
	
			if ( (oEmail.value == "" || oEmail.value == VsLang._("Email")) &&  (oTelefono.value == "" || oTelefono.value == VsLang._("Telefono"))) {
				sError += "\n - Almeno uno tra i campi email / telefono deve essere obbligatoriamente compilato\n";
			}
	
			if (oTelefono.value != "" && oTelefono.value != VsLang._("Telefono") && !this.telephoneRegex.test(oTelefono.value)) {
				sError += "\n - Inserire un telefono valido o lasciare il campo vuoto.\n";
			}
	
			if (oEmail.value != "" && oEmail.value != VsLang._("Email") && !this.emailRegex.test(oEmail.value)) {
				sError += "\n - Inserire un email in formato valido\n";
			}
	
			if (oPrivacy.checked != true) {
				sError += "\n - Deve essere acconsentito il trattamento dei dati personali\n";
			}
	
			if (sError != "Attenzione\n") {
				alert(sError);
				return false;
			}
			
			if(oEmail.value == VsLang._("Email")) {
				oEmail.value = "";
			}
			
			if(oTelefono.value == VsLang._("Telefono")) {
				oTelefono.value = "";
			}
	
			return true;
		} catch(e) {
			return false;
		}
	},

	checkErrorReportingForm : function(form) {
		try {
			var sError = "Attenzione\n";
			var oNome = form.nome;
			var oEmail = form.email;
			var oDescription = form.richieste;
			var oPrivacy = form.privacy;
		
			if (oEmail.value == "") {
				sError += "\n - Il campo EMAIL deve essere obbligatoriamente compilato\n";
			}
			if (oEmail.value != "" && !this.emailRegex.test(oEmail.value)) {
				sError += "\n - Inserire un email in formato valido\n";
			}
			if (oDescription.value == "") {
				sError += "\n - Il campo 'Descrivi l'errore' deve essere obbligatoriamente compilato\n";
			}
			if (oPrivacy.checked != true) {
				sError += "\n - Deve essere acconsentito il trattamento dei dati personali\n";
			}
			if (sError != "Attenzione\n") {
				alert(sError);
				return false;
			}
			return true;
		} catch(e) {
			return false;
		}
	},
	
	changeInputTextColor : function (oObj, sText, bOnFocus, sColor) {
	
		if (!oObj) {
			return(false);
		}

		if(oObj.value=='' || oObj.value==sText) {
			if (bOnFocus){
				oObj.value="";
			} else {	
				oObj.value=sText;
			}
		} else {
			sColor = oObj.style.color;
		}
		oObj.style.color=sColor;
		return (true);
	},
	
	showHide: function(domOrId,triggerer,showText,hideText,useInline){
		var node = this.byId(domOrId);
		
		if (!node){
			return console.log("VsUtil.showHide: element "+domOrId+ " not found!");
		}

		if (node.style.display == 'none'){
			if(useInline){
				node.style.display = 'inline';
			}else{
				node.style.display = 'block';
			}
			triggerer.innerHTML = hideText;
		}else{
			node.style.display = 'none'
			triggerer.innerHTML = showText;
		}
		return false;
	},
	
	showHideTypologyInline: function(domOrId,domOrId2){
		var node = this.byId(domOrId);
		var node2 = this.byId(domOrId2);

		if ((!node) && (!node2)){
			return console.log("VsUtil.showHide: element "+domOrId+ " not found!");
		}
		if (node.style.display == 'none'){
			node.style.display = 'inline';
			node2.style.display = 'none';
		}else{
			node.style.display = 'none';
			node2.style.display = 'inline';
		}
		return false;
	},
	
	getRadioValue: function(form,name){
		var radioObj = form[name];
		
		if(!radioObj)
			return "";

		var radioLength = radioObj.length;
		if(radioLength == undefined){
			if (radioObj.checked){
				return radioObj.value;			
			}else {
				return "";
			}
		}

		for(var i = 0; i < radioLength; i++) {
			if(radioObj[i].checked) {
				return radioObj[i].value;
			}
		}
		return "";
	},

	reloadCaptcha : function(captchaImgId) {
		if(dojo.byId(captchaImgId)) {
			dojo.byId(captchaImgId).src = '/vimages/default/captcha/'+parseInt(10000*Math.random())+ '.png';
		}
		if(dojo.byId('captcha')) {
			dojo.byId('captcha').value = '';
		}
	},
	
	uniqueId: 0,
	
	getUniqueId: function(){
		return this.uniqueId++;
	}
};
