/**
* Esegue il submit di una form
* -form: nome della form per cui si vuole eseguire il submit
* -action: url da invocare
*/
function doPost(form, action)
{
    if (action && action!='') {
      document.forms[form].action = action;
    }
    document.forms[form].submit();
}

/**
* [Da utilizzare con il Validator delle struts]
* Esegue il submit di una form, ma prima invoca la funzione di
* validazione delle struts
*/
function doCheckAndPost(form, action)
{
  var f = document.forms[form];
  validator = "validate"+capitalizeCharAt(form,0)+"("+form+")";
  if (eval(validator))
    doPost(form,action);
}

/**
* Esegue un UPPER CASE del carattere in posizione 'pos' all'interno
* della stringa str
* - la stringa da modificare
* - la posizione del carattere da trasformare in maiuscolo
* ritorna la stringa modificata
*/
function capitalizeCharAt(str,pos) {
    if (pos>str.length) {
        return str;
    }
    var firstStr = str.substring(0,pos);
    var c = str.substring(pos,1);
    var secondStr = str.substring(pos+1,str.length-pos+1);
    return firstStr+c.toUpperCase()+secondStr;
}

/**
* Apre una finestra "confirm".
* - msg: il messaggio da visualizzare
* - action: l'url da invocare
* - params: eventuali parametri da passare nella richiesta
* //TODO: verificare l'url-encoding
*/
function confermaOperazione(msg, action, params) {
  if (confirm(msg)) {
    url = action+"?"+params;
    location.href = url;
    return true;
  }
  return false;
}


var popUpWin=0;
function openPopUp(URLStr, left, top, width, height)
{
  if(popUpWin)
  {
    if(!popUpWin.closed) popUpWin.close();
  }
  popUpWin = open(URLStr, 'popUpWin', 'toolbar=no,location=no,scrollbars=yes,directories=no,status=no,menubar=no,resizable=yes,copyhistory=yes,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
} 

// Assegna il fuoco alla finestra pop-up.
function popUpFocus(){
	setTimeout("popFocus()",150);
}

function popFocus() {
if (popUpWin!=null && !popUpWin.closed) 
	popUpWin.focus();
}



//---------------------------------------------------------------------
// Crea un riferimento all'oggetto con ID=elemID.
// Tale oggetto ha due proprietà: obj e style.
// Solo queste due proprietà possono essere utilizzate.
// Esempio: 
// var x= new makeObj("bloccoDati");
// alert(x.obj.id)
// - elemID: l'ID dell'oggetto che si vuole creare
//---------------------------------------------------------------------
function makeObj(elemID)
{
  if (document.getElementById)
  {
  	this.obj = document.getElementById(elemID);
	this.style = document.getElementById(elemID).style;
  }
  else if (document.all)
  {
	this.obj = document.all[elemID];
	this.style = document.all[elemID].style;
  }
  else if (document.layers)
  {
  	this.obj = getObjNN4(document,name);
   	//this.obj = document.layers[elemID];
   	this.style = document.layers[elemID];
  }
}

function getObjNN4(obj,name)
{
	var x = obj.layers;
	var foundLayer;
	for (var i=0;i<x.length;i++)
	{
		if (x[i].id == name)
		 	foundLayer = x[i];
		else if (x[i].layers.length)
			var tmp = getObjNN4(x[i],name);
		if (tmp) foundLayer = tmp;
	}
	return foundLayer;
}

//-------------------------------------------------------
// verifica se un elemento è visibile. Se lo è, torna true
// - elemID: l'ID dell'elemento
//-------------------------------------------------------
function isElementVisible(elemID) {
	var x= new makeObj(elemID);
	return (x.style.display != 'none');
}

//----------------------------------------------------------
// Cambia la visibilità di un elemento: se era nascosto lo 
// visualizza e viceversa
// - elemID: l'ID dell'elemento 
//----------------------------------------------------------
function changeElementVisibility(elemID)
{
	var x= new makeObj(elemID);
	x.style.display = (x.style.display == 'none') ? 'block' : 'none';
}


//----------------------------------------------------------
// Cambia la visibilità di un elemento: se era nascosto lo 
// visualizza e viceversa
// - elemID: l'ID dell'elemento 
//----------------------------------------------------------
function setElementVisibility(elemID, boolValue)
{
	var x= new makeObj(elemID);
	if (boolValue) {
		x.style.display = 'block';
	} else {
		x.style.display = 'none';		
	}
}

function changeStyle(el, styleName) {
	el.className=styleName;
}

function writit(text,id)
{
	if (document.getElementById)
	{
		x = document.getElementById(id);
		x.innerHTML = '';
		x.innerHTML = text;
	}
	else if (document.all)
	{
		x = document.all[id];
		x.innerHTML = text;
	}
	else if (document.layers)
	{
		x = document.layers[id];
		text2 = '<P CLASS="testclass">' + text + '</P>';
		x.document.open();
		x.document.write(text2);
		x.document.close();
	}
}



function TabBar (tabPrefix, numTab, notSelectedClass, selectedClass) {
	this.name=tabPrefix;
	this.numTab=numTab;
	this.notSelected=notSelectedClass
	this.selected=selectedClass;
}


function switchTab(tabBar, tabSel) {
	for ( var i=0; i<tabBar.numTab; i++) {
		var tabLabel = new makeObj(tabBar.name+i);
      if (i==tabSel) {
        //tab.style.backgroundColor=tabBar.selectColor;
		tabLabel.obj.className=tabBar.selected;
		setElementVisibility(tabBar.name+'Content'+i,true);
		
	  } else {
		//tab.style.backgroundColor=tabBar.color;
		tabLabel.obj.className=tabBar.notSelected;
		setElementVisibility(tabBar.name+'Content'+i,false);
	  }
	}
}









function changeCSS(nr)
{
	if (document.getElementsByTagName)
		x = document.getElementsByTagName('link');
	else if (document.all)
		x = document.all.tags('link');
	else
	{
		alert('This script does not work in your browser');
		return;
	}
	//nr--;
	for (var i=0;i<x.length;i++)
	{
		dis = !(i == nr);
		x[i].disabled = dis;
//alert(x[i].attributes['href'].value+"="+x[i].disabled);
	}
}












// -------------------------------------------------- Funzioni predefinite
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

//-----------------------------------------------

var CarrContact = {	
	options:{
		title:'Carrozzerie Fiduciarie'
	},
	registry:{},
	clear: function(){
		CarrContact.registry={};
	},
	digester: function(id){		
		var obj = CarrContact.registry[id];
		if(obj=='undefined' || obj==null){
			obj=$(id);	
			obj._CarrContactCloseTime=false;
			CarrContact.registry[id]=obj;			
		}
		return obj;			
	},
	hide: function(id){
		var box= CarrContact.digester(id);	
		box.hide();
		box._CarrContactCloseTime=new Date().getTime();
	},
	show: function(id){
		var box= CarrContact.digester(id);	
		var time = new Date().getTime();
		var ctime = time - (box._CarrContactCloseTime || time);			
		for(var key in CarrContact.registry){
			try{
				CarrContact.registry[key].hide();
			}catch(ex){
				alert(key);
			}
		}	
		if(ctime ==0 || ctime > 1000 /*ms*/){				
			box.show();		
		}		
	},
	send: function(id, chanel){
		if(chanel == 'email'){
			var dialog = new w3gDialogs.input({
				title:CarrContact.options.title,
				message:'inserisci l\'indirizzo e-mail',
				onAction:function(ret){CarrContact.sendByMail(ret,id)},
				cancel:true,
				/*focus:false,*/
				closable:true});		
		}else if(chanel == 'sms'){
			var dialog = new w3gDialogs.input({
				title:CarrContact.options.title,
				message:'inserisci il numero di cellulare',
				onAction:function(ret){CarrContact.sendBySMS(ret,id)},
				cancel:true,
				/*focus:false,*/
				closable:true});	
		}
	},
	sendByMail: function(ret,id){
		if(ret.button==w3gDialogs.OK){
			if(ret.input.match(/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/)){
				var wait = w3gWait('Invio in corso...',false,CarrContact.options.title);
				new Ajax.Request('/' + window.w3gContex + '/carrGetContact.do',
					{
					 onComplete:function(transport){wait.close();CarrContact.sendReport(transport)},
					 parameters:{
						idCarrozzeria:id,
						ctype:'email',
						email:ret.input,
						nocache:new Date().getTime()},
					 method:'GET'});
			}else
				w3gAlertWarning('L\'email non è valida.',function(){CarrContact.send(id, 'email')},CarrContact.options.title);
		}
	},
	sendBySMS: function(ret,id){
		if(ret.button==w3gDialogs.OK){
			if(ret.input.match(/^((\+|00)39){0,1}\s{0,1}3[0-9]{2}\s{0,1}[0-9]{7}$/)){
				var wait = w3gWait('Invio in corso...',false,CarrContact.options.title);
				new Ajax.Request('/' + window.w3gContex + '/carrGetContact.do',
					{
					 onComplete:function(transport){wait.close();CarrContact.sendReport(transport)},
					 parameters:{
						idCarrozzeria:id,
						ctype:'sms',
						mobile:ret.input,
						nocache:new Date().getTime()},
					 method:'GET'});
			}else
				w3gAlertWarning('Il numero non è valido.',function(){CarrContact.send(id, 'sms')},CarrContact.options.title);
		}
	},
	sendReport: function(transport){
		if (200 == transport.status){
			if(transport.responseText == null || transport.responseText == ''){
				w3gAlert('Invio completato!',false,CarrContact.options.title);
			}else
				w3gAlert(transport.responseText,false,CarrContact.options.title);
		}if (500 == transport.status){
			w3gAlertError(transport.responseText,false,CarrContact.options.title);
		}
	}
}
