///////////Funcions varies de javascript/////////////////


//Obre popup hotel per veure la foto i la descripció

function showPop(message, titol){
            $("#dialog-message").html(message);
            $("#dialog-message").dialog({ buttons: {"Ok": function() { $(this).dialog("close"); } }, title: titol, modal: true});
            
        }
function abrePopup(Hotel,Tipused) {
	var width = '750';
	var height ='750';
	window.open("HotelInfo.csp?a="+Hotel+"&ta="+Tipused, "", "resizable=yes, toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, width="+width+", height="+height);
}


//Funció que retorna string sense espais per la dreta ni per la esquerra
function Trim(STRING){
	STRING = LTrim(STRING);
	return RTrim(STRING);
}


//Funció que retorna string sense espais per la dreta
function RTrim(STRING){
	while(STRING.charAt((STRING.length -1))==" "){
		STRING = STRING.substring(0,STRING.length-1);
	}
	return STRING;
}


//Funció que retorna string sense espais per la esquerra
function LTrim(STRING){
	while(STRING.charAt(0)==" "){
		STRING = STRING.replace(STRING.charAt(0),"");
	}
	return STRING;
}

//Funció que borra opcions d'un combo
function borrarOpcions(nomCtrl,nomform){
	document[nomform][nomCtrl].options.length=0;
}


//Funció que carrega opcions d'un combo
//lis -> ha de ser un string amb les opcions separades amb | 
//Exemple de lis: 0-Seleccioni opcio|1-Apartaments|2-Hotels
//Explicacio lis: <<codi>>-<<descripció>>
function addOpcions (lis,nomCtrl,nomform) { 
	var a
	var regArr=new Array();
	regArr = lis.split('|'); //Com $Piece pero ho deixa en index diferents d'un array
	if (regArr[0]=="") {regArr[0]=lis} //si lis només te un registre, la funció split no retorna res, per tant ho movem nosaltres a pinyó.
	for(a=0;a<regArr.length;a++){
		var arrVal=new Array();
		arrVal=regArr[a].split("-"); //Contindra el codi - Descripció
		var oOption = document.createElement("OPTION");
		oOption.text=Trim(arrVal[1]);     //Descripció
		oOption.value=Trim(arrVal[0]);    //Codi
		document.getElementById(nomCtrl).options.add(oOption);
		//document[nomform][nomCtrl].options.add(oOption)
	}
 } 		

function showBubble(obj){ 
   	document[obj].style.position = 'absolute';
   	document[obj].style.top = mouseY+15;
   	document[obj].style.left = mouseX-100;
    document[obj].style.visibility = 'visible';
}

function showTipMouse(obj,isIE){ 
   	document.getElementById(obj).style.position = 'absolute';
   	if(isIE==true){
	   	document.getElementById(obj).style.top = mouseY-200;
	   	document.getElementById(obj).style.left = mouseX-100;
   	} else {
	   	document.getElementById(obj).style.top = mouseY+15;
  	 	document.getElementById(obj).style.left = mouseX;
   	}
    document.getElementById(obj).style.display = 'block';
}

function showTip(obj){ 
   	document.getElementById(obj).style.display = 'block';
}

function showTipPos(obj,pleft){ 
	document.getElementById(obj).style.left=pleft;
   	document.getElementById(obj).style.display = 'block';
}
 
function hideTip(obj){
	//document.getElementById(obj).style.visibility = 'hidden';
	document.getElementById(obj).style.display = 'none';
}


//funció que ens redirecciona a la pagina de desconnexió en cas de que salti el TimeOut
function desconnexio() {
	alert("Debido a un tiempo de inactividad prolongado ha sido desconectado de la sesión.");
	document.location = "desconnexio.csp";
}


function cridAjax(tipus,metode,classe,arguments,asyncron){
		var urlDesti=""
	  if (asyncron==null){asyncron=false}
	  if (tipus=="C"){var urlDesti="Controlador.Controlador.cls"}
	  if (tipus=="S"){var urlDesti="Sha1.Sha1.cls"}
	  return $.ajax({
   		type: "POST",
   		url: urlDesti,
   		data: "tipus="+tipus+"&metode="+metode+"&classe="+classe+"&"+arguments,
   		async: asyncron
   		//success: function(msg){
     		//alert( "Data Saved: " );
   		//}
 		}).responseText;	
}

function loadAjax(tipus,metode,classe,arguments,nomDiv,funcio){
	  $("#"+nomDiv).load("Controlador.Controlador.cls?tipus="+tipus+"&metode="+metode+"&classe="+classe+"&"+arguments,null,funcio);	
}

function tancarDIV(div){
	//oculta el popup i despres el reposiciona
	$("#"+div).jqmHide();
	//Activa possibles selects que hi hagin a la pantalla *** bug IE
	//hideSelects("inline");
	
}


function obrirDIV(div,argums,metode,classe,width,height, customfunction) {
	//Amaga possibles selects que hi hagin a la pantalla *** bug IE
	hideSelects("none");
	
	//mida del div
	var pWidth=width; pHeight=height;
	
	//mida de la pantalla
	var myWidth = 0, myTop = 0, top=0; left=0; 
	  if( typeof( window.innerWidth ) == 'number' ) {
	    //Non-IE
	    myWidth = window.innerWidth;
	    myTop = Math.round(window.innerHeight/2);
	  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	    //IE 6+ in 'standards compliant mode'
	    myWidth = document.documentElement.clientWidth;
	    myTop = Math.round(document.documentElement.clientHeight/2) //+ (document.documentElement.scrollTop || document.body.scrollTop);
	  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	    //IE 4 compatible
	    myWidth = document.body.clientWidth;
	    myTop = Math.round(document.body.clientHeight/2) + (document.documentElement.scrollTop || document.body.scrollTop);
	  }
	  
	  myWidth = $("body").width();
	  top=myTop - (pHeight / 2) - 23;
	  left=(myWidth - pWidth - 30) / 2; // EL 20 del padding....

	  
	//Inicialitza DIV 
	$('#'+div).css('top',top+'px');
	$('#'+div).css('left',left+'px');
	$('#'+div).css('width',pWidth+'px');
	$('#'+div).css('height',pHeight+'px');

 		
 	//contingut AJAX del div
 	var func=function() {$('#'+div).jqDrag('.jqDrag'); customfunction();}; //
	loadAjax("C",metode,classe,argums,div,func);
	
	
	if($('#'+div).css('display')!='none') {
		$('#'+div).css('display','none');
	}
	
	var that=this;
	this.pcallback = function () { };
		
	$('#'+div).jqm({
		trigger: false,
		modal: true, 
		onHide: function(h) { 
		  that.pcallback();
		  h.o.remove(); // remove overlay
		  h.w.fadeOut(300); // hide window
		},
		overlay: 60});
	$('#'+div).jqmShow();
}



function obrirDIV2(div,argums,metode,classe,width,height, customfunction) {
	//Amaga possibles selects que hi hagin a la pantalla *** bug IE
	hideSelects("none");
		
	//mida del div
	var pWidth=width; pHeight=height;
	
	//mida de la pantalla
	var myWidth = 0, myTop = 0, top=0; left=0; 
	//alert(window.innerWidth);
	  if( typeof( window.innerWidth ) == 'number' ) {
	    //Non-IE
	    myWidth = window.innerWidth;
	    myTop = Math.round(window.innerHeight/2);
	    //alert("myWidth:"+myWidth);
	   // alert("myTop:"+myTop);
	  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	    //IE 6+ in 'standards compliant mode'
	    myWidth = document.documentElement.clientWidth;
	    myTop = Math.round(document.documentElement.clientHeight/2) //+ (document.documentElement.scrollTop || document.body.scrollTop);
	    //alert("2");
	  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	    //IE 4 compatible
	    myWidth = document.body.clientWidth;
	    myTop = Math.round(document.body.clientHeight/2) + (document.documentElement.scrollTop || document.body.scrollTop);
	    //alert("3");
	  }
	  
	  myWidth = $("body").width();
	  top=myTop - (pHeight / 2) - 23;
	  left=(myWidth - pWidth - 30) / 2; // EL 20 del padding....
	  
	 // alert(top+"-"+left+"-"+pWidth+"-"+pHeight);

	  
	//Inicialitza DIV 
	$('#'+div).css('top',top+'px');
	$('#'+div).css('left',left+'px');
	$('#'+div).css('width',pWidth+'px');
	$('#'+div).css('height',pHeight+'px');

 		
 	//contingut AJAX del div
 	var func=function() {$('#'+div).jqDrag('.jqDrag'); customfunction();}; //
	loadAjax("C",metode,classe,argums,div,func);
	
	
	if($('#'+div).css('display')!='none') {
		$('#'+div).css('display','none');
	}
	
	var that=this;
	this.pcallback = function () { };
	
	$('#'+div).jqm({
		trigger: false,
		modal: true, 
		onHide: function(h) { 
		  that.pcallback();
		  h.o.remove(); // remove overlay
		  h.w.fadeOut(300); // hide window
		},
		overlay: 60});
	$('#'+div).jqmShow();
}


function hideSelects(val){
   if(!window.attachEvent) return false;
   var selects = document.getElementsByTagName("select");
   for( var i=0; i<selects .length; i++ ){
       selects[i].style.display = val;
   }
}


/****** funcions per validar dates *******/

/* valida si es numèric */
function esDigit(sChr){
	var sCod = sChr.charCodeAt(0);
	return ((sCod > 47) && (sCod < 58));
	}
	
/* valida separador d'un adata */
function valSep(oTxt){
	var bOk = false;
	bOk = bOk || ((oTxt.value.charAt(2) == "-") && (oTxt.value.charAt(5) == "-"));
	bOk = bOk || ((oTxt.value.charAt(2) == "/") && (oTxt.value.charAt(5) == "/"));
	return bOk;
}

/* numero de dies de cada mes*/
function finMes(oTxt){
	var nAny = oTxt.value.substr(6);
	var nMes = parseInt(oTxt.value.substr(3, 2), 10);
	var nRes = 0;
	switch (nMes){
		case 1: nRes = 31; break;
		case 2: nRes = 29; break;
		case 3: nRes = 31; break;
		case 4: nRes = 30; break;
		case 5: nRes = 31; break;
		case 6: nRes = 30; break;
		case 7: nRes = 31; break;
		case 8: nRes = 31; break;
		case 9: nRes = 30; break;
		case 10: nRes = 31; break;
		case 11: nRes = 30; break;
		case 12: nRes = 31; break;
	}
	if ((nMes==2) && (nAny%4==0)){nRes=28}
	return nRes;
}

/* valida el dia de la data */
function valDia(oTxt){
	var bOk = false;
	var nDia = parseInt(oTxt.value.substr(0, 2), 10);
	bOk = bOk || ((nDia >= 1) && (nDia <= finMes(oTxt)));
	return bOk;
}

/* valida el mes de la data */
function valMes(oTxt){
	var bOk = false;
	var nMes = parseInt(oTxt.value.substr(3, 2), 10);
	bOk = bOk || ((nMes >= 1) && (nMes <= 12));
	return bOk;
}


/* valida l'any de la data */
function valAny(oTxt){
	var bOk = true;
	var nAny = oTxt.value.substr(6);
	bOk = bOk && ((nAny.length == 2) || (nAny.length == 4));
	if (bOk){
		for (var i = 0; i < nAny.length; i++){
			bOk = bOk && esDigit(nAny.charAt(i));
		}
	}
	return bOk;
}


/* valida la data al complet */
function validarData(dat1,foc){
	if((foc="")||(foc==undefined)) foc=true;
	var bOk = true;
	if (dat1.value != ""){
		bOk = bOk && (valAny(dat1));
		bOk = bOk && (valMes(dat1));
		bOk = bOk && (valDia(dat1));
		bOk = bOk && (valSep(dat1));
		if (!bOk){if(foc==true) dat1.focus()}
	} else { bOk=0}
	return bOk;
}

//Carrega pàgina utilitzant ajax
function ajaxPage(div,urlDesti){
	$("#"+div).load(urlDesti);
}


function validarEmail(email){
	bOk=true;
	if(email==""){
		bOk=false;
	} else {
		var ArrEmail=email.split("@");
		if(Trim(ArrEmail[0])==""){
			bOk=false;
		}else{
			if((ArrEmail[1]==undefined)||(Trim(ArrEmail[1])=="")){
				bOk=false;
			} else {
				var domini=ArrEmail[1]
				var ArrDomini=domini.split(".")
				if((ArrDomini[1]==undefined)||(Trim(ArrDomini[1])=="")){
					bOk=false;
				}
			}	
		}
		//bOk=true;
	}
	return bOk;
}


function activarPuntRecollida(nh,os){
	var swc=false;
	for(i=1;i<=nh;i++){
		var arrOS=os.split("|");
		var np=arrOS[i-1]; //num persones
		for(z=1;z<=np;z++){
			if(document.getElementById("autobus"+i+z).checked==true){
				swc=true;
			}
		}
	}
	if(swc==true){
		document.getElementById("SpanPR1").style.display="block";
		document.getElementById("SpanPR2").style.display="block";
		document.getElementById("info").style.display="block";
		document.getElementById("info2").style.display="block";
	} else {
		document.getElementById("SpanPR1").style.display="none";
		document.getElementById("SpanPR2").style.display="none";		
		document.getElementById("info").style.display="none";
		document.getElementById("info2").style.display="none";
	}
}

function DiferenciaFechas (f1,f2) {

		   //Obtiene los datos del formulario
		   CadenaFecha1 = f1;
		   CadenaFecha2 = f2;
		   
		   //Obtiene dia, mes y año
		   var fecha1 = new fecha( CadenaFecha1 )   ;
		   var fecha2 = new fecha( CadenaFecha2 );
		   
		   //Obtiene objetos Date
		   var miFecha1 = new Date( fecha1.anio, fecha1.mes, fecha1.dia );
		   var miFecha2 = new Date( fecha2.anio, fecha2.mes, fecha2.dia );
		
		   //Resta fechas y redondea
		   var diferencia = miFecha1.getTime() - miFecha2.getTime();
		   var dias = Math.floor(diferencia / (1000 * 60 * 60 * 24));
		   return dias
		}
		
		function fecha( cadena ) {
		
		   //Separador para la introduccion de las fechas
		   var separador = "/";
		
		   //Separa por dia, mes y año
		   if ( cadena.indexOf( separador ) != -1 ) {
				var posi1 = 0;
				var posi2 = cadena.indexOf( separador, posi1 + 1 );
				var posi3 = cadena.indexOf( separador, posi2 + 1 );
				this.dia = cadena.substring( posi1, posi2 );
				this.mes = cadena.substring( posi2 + 1, posi3 );
				this.anio = cadena.substring( posi3 + 1, cadena.length );
		   } else {
				this.dia = 0;
				this.mes = 0;
				this.anio = 0 ;  
		   }
		}

		var materialFormatting = function(text){
			var newText = text;
			//array of find replaces
			var findreps = [
				{find:/^([^\-]+) \- /g, rep: '<span class="ui-selectmenu-item-header">$1</span>'},
				{find:/([^\|><]+) \| /g, rep: '<span class="ui-selectmenu-item-content">$1</span>'},
				{find:/([^\|><\(\)]+) (\()/g, rep: '<span class="ui-selectmenu-item-content">$1</span>$2'},
				{find:/([^\|><\(\)]+)$/g, rep: '<span class="ui-selectmenu-item-content">$1</span>'},
				{find:/(\([^\|><]+\))$/g, rep: '<span class="ui-selectmenu-item-footer">$1</span>'}
			];
			
			for(var i in findreps){
				newText = newText.replace(findreps[i].find, findreps[i].rep);
			}
			return newText;
		}

