/*
*   +------------------------------------------------------------------------------+ 
*       FUNCIONES   - Javascript -                                              
*   +------------------------------------------------------------------------------+ 
*
*/



/* 
*   Función: esString(str , maxCaracteres)
*   +---------------------------------------------------------------------------------------------------------+
*    Propósito:          Comprobar si una le pasamos una cadena de longitud máxima maxCaracteres
*    Argumentos:         str , maxCaracteres
*    Devuelve:   		 true o false
*   +---------------------------------------------------------------------------------------------------------+
*/ 

function esString(str , maxCaracteres)
{
  var err = 0
  
  if (str.length >= maxCaracteres)
  {
  	return (false);
  }
  else
  {
  	return (true);
  }

}
  
  
/* 
*   Función: esEntero(str)
*   +---------------------------------------------------------------------------------------------------------+
*    Propósito:          comprueba si el valor que se le pasa como argumento es un entero
*    Argumentos:         str
*    Devuelve:   		 true o false
*   +---------------------------------------------------------------------------------------------------------+
*/ 
function esEntero(str)
  {
  var err = 0
  var valid = "0123456789"
  var ok = "yes";
  var temp;

  for (var i=0; i< str.length; i++)
    {
	temp = "" + str.substring(i, i+1);
	if (valid.indexOf(temp) == "-1") err = 1;
	}
  
  if (err==1){
	return (false);
  } else {
	return (true);
  }
}  
  
    
/* 
*   Función: esFloat(str , numEnteros , numDecimales)
*   +---------------------------------------------------------------------------------------------------------+
*    Propósito:          Comprueba si el valor que se le pasa como argumento es un float 
*						 con un máximo de numEnteros en la parte entera y un máximo de numDecimales en la parte decimal
*    Argumentos:         str , numEnteros , numDecimales
*    Devuelve:   		 0 ( si es un float , cumple todas las condiciones )
*						 -1  ( no es un float o ha incumplido alguna condición : hay algun carácter , tiene demasiados decimales....)
*   +---------------------------------------------------------------------------------------------------------+
*/
function esFloat(str , numEnteros , numDecimales)
{
  var err = 0
  var valid = "0123456789.,"
  var ok = "yes";
  var temp;

  var numcomas=0;
  var numpuntos=0;  

  if (str=="")
  {
		err=1;
   }
   else
   {
		for (var i=0; i< str.length; i++)
   		{
			temp = "" + str.substring(i, i+1);
			if (temp==",") numcomas++;
			if (temp==".") numpuntos++;

			if (valid.indexOf(temp) == "-1") err = 1;
		 }

		if ( (numcomas) > 1 )
		{
			err = 1;
		}
		else
		{
			if (numcomas > 0) 
			{
				indiceComa = str.indexOf(",");
				if ( indiceComa > 0 )
				{
					antesdecoma = str.substring(0, indiceComa);
					despuesdecoma = str.substring(indiceComa+1, str.length);

					if (( antesdecoma.length > numEnteros ) || ( despuesdecoma.length > numDecimales )) {
						err = 1;
					}
				}
			}

			if ((numcomas == 0) && (numpuntos == 0))
			{
				if (str.length > numEnteros) {
					err = 1;
				}
			}
		
		}
		
	}		

  if (err==1){
		return (false);
  } else {
		return (true);
   }

}

 
 /* 
*   Funciones: isInteger , stripCharsInBag , daysInFebruary , DaysArray , isDate
*   +---------------------------------------------------------------------------------------------------------+
*    Propósito:         Comprobar si una fecha es válida ( en el formato dd/mm/yyyy )
*    Argumentos:        fecha
*    Devuelve:   		 true ( es una fecha valida )  o false ( no es una fecha valida )
*   +---------------------------------------------------------------------------------------------------------+
*/     


var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s)
{
	var i;
    for (i = 0; i < s.length; i++)
	{   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag)
{
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year)
{
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) 
{
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr)
{
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1)
	{
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		return false
	}
return true
}




 
 /* 
*   Función: CompareDate
*   +---------------------------------------------------------------------------------------------------------+
*    Propósito:         Comprobar si una fecha es mayor que la otra ( en el formato dd/mm/yyyy )
*    Argumentos:        fecha1 , fecha 2
*    Devuelve:   		1 = la fecha 1 es mayor
*					   -1 = la fecha 2 es mayor   
*						0 = las 2 fechas son iguales
*   +---------------------------------------------------------------------------------------------------------+
*/     

function CompareDate(a, b) {
  
  strA = a.split("/");
  strB = b.split("/");


  date1 = strA[0];   
  month1 = strA[1]; 
  year1 = strA[2];

  date2 = strB[0];   
  month2 = strB[1]; 
  year2 = strB[2];
  
  if (year1 > year2) return 1;
   else if (year1 < year2) return -1;
   else if (month1 > month2) return 1;
   else if (month1 < month2) return -1;
   else if (date1 > date2) return 1;
   else if (date1 < date2) return -1;
   else return 0;

}



 
 
/* 
*   Función: ContieneSoloLetras( str )
*   +---------------------------------------------------------------------------------------------------------+
*    Propósito:          Comprueba si el valores una cadena con únicamente letras
*    Argumentos:         str 
*    Devuelve:   		 true ( sólo existen letras )  o false ( existe algun carácter que no es una letra )
*   +---------------------------------------------------------------------------------------------------------+
*/     
function ContieneSoloLetras( str )
{
	if (str+"" == "undefined" || str+"" == "null" || str+"" == "")
		return false;
	var isValid = true;
	str += "";	// convert to a string for performing string comparisons.
  	for (i = 0; i < str.length; i++) {
		// Alpha must be between "A"-"Z", or "a"-"z"
		if ( !( ((str.charAt(i) >= "a") && (str.charAt(i) <= "z")) ||
      			((str.charAt(i) >= "A") && (str.charAt(i) <= "Z")) ) ) {
         				isValid = false;
         				break;
      			}
   		}

	return isValid;
}

 
 

/* 
*   Función: comprueba_email (str)
*   +---------------------------------------------------------------------------------------------------------+
*    Propósito:          Comprueba si una cadena tiene formato de email correcto ( por ej: no hay 2 arrobas )
*    Argumentos:         str 
*    Devuelve:   		 true ( es una dirección de email valida )  o false ( no es una dirección de email valida )
*   +---------------------------------------------------------------------------------------------------------+
*/     

function comprueba_email (str) 
{
     var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
     var regex = new RegExp(emailReg);
     return regex.test(str);
}
  
  
  
  
  
  
  


function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

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.0
  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 && document.getElementById) x=document.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];}
}

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}

function browserdetect(){
//returns 1 for IE, 2 for N6,3 for N4 and others
if(navigator.appName=="Microsoft Internet Explorer"){return 1;}
else if(navigator.appName=="Netscape" && parseInt(navigator.appVersion)==5){return 2;}
else{return 3;}
}



function PopupPic(sPicURL) { 
	window.open(sPicURL, "", "resizable=1,HEIGHT=200,WIDTH=200");
}

//Gradual-Highlight image script- By Dynamic Drive
//For full source code and more DHTML scripts, visit http://www.dynamicdrive.com
//This credit MUST stay intact for use

function high(which2){
theobject=which2
highlighting=setInterval("highlightit(theobject)",50)
}
function low(which2){
clearInterval(highlighting)
if (which2.style.MozOpacity)
which2.style.MozOpacity=0.3
else if (which2.filters)
which2.filters.alpha.opacity=30
}

function highlightit(cur2){
if (cur2.style.MozOpacity<1)
cur2.style.MozOpacity=parseFloat(cur2.style.MozOpacity)+0.1
else if (cur2.filters&&cur2.filters.alpha.opacity<100)
cur2.filters.alpha.opacity+=10
else if (window.highlighting)
clearInterval(highlighting)
}






function validaRGB(entry) {

var validChar = '0123456789ABCDEF';

entry=entry.toUpperCase();
strlen=entry.length;
if (strlen != 7) 
{
//    alert("El valor RGB debe tener exactamente 7 carácteres (# + 6 carácteres).");
    return false;
}

// Check for legal characters in string
for (var i = 1; i < 7; i++ ) 
{
    if (validChar.indexOf(entry.charAt(i)) < 0) 
	{
//       alert("El carácter '"+ entry.charAt(i) +"' no es un carácter RGB válido.");
       return false;
    }
}

return true;
}




/* 
*   Función: obtener_extension_fichero(fichero)
*   +---------------------------------------------------------------------------------------------------------+
*    Propósito:          Obtener la extensión del fichero
*    Argumentos:         
*    Devuelve:   		 
*   +---------------------------------------------------------------------------------------------------------+
*/ 

function obtener_extension_fichero(fichero)
{
	var vector_sep_comas = fichero.split(".");
	var leng = vector_sep_comas.length;
	var extension = vector_sep_comas[leng-1];
	
	return extension;
}




 /* 
*   Funciones: ListFind , ListFindNoCase , ListLast
*   +---------------------------------------------------------------------------------------------------------+
*    Propósito:         Comprobar si el fichero a subir tiene una extensión valida
*    Argumentos:       
*    Devuelve:   		true ( es una fecha valida )  o false ( no es una fecha valida )
*   +---------------------------------------------------------------------------------------------------------+
*/  
function ListFind(list, value)
{
  var i = 0;
  var delimiter = ',';
  var returnValue = -1;
  var _tempArray = new Array();
  if(ListFind.arguments.length == 3)
    delimiter = ListFind.arguments[2];
  _tempArray = list.split(delimiter);
  for(i = 0; i < _tempArray.length; i++)
  {
    if(_tempArray[i] == value)
    {
      returnValue = i;
      break;
    }
  }
  return returnValue;
}

function ListFindNoCase(list, value)
{
  var i = 0;
  var delimiter = ',';
  var returnValue = -1;
  var _tempArray = new Array();
  if(ListFindNoCase.arguments.length == 3)
    delimiter = ListFindNoCase.arguments[2].toLowerCase();
  list = list.toLowerCase();
  value = value.toLowerCase();
  _tempArray = list.split(delimiter);
  for(i = 0; i < _tempArray.length; i++)
  {
    if(_tempArray[i] == value)
    {
      returnValue = i;
      break;
    }
  }
  return returnValue;
}


function ListLast(list)
{
  var delimiter = ',';
  var returnValue = '';
  var _tempArray = new Array();
  if(ListLast.arguments.length == 2) delimiter = ListLast.arguments[1].toLowerCase();
  _tempArray = list.split(delimiter);
  
  if(_tempArray.length)
    returnValue = _tempArray[_tempArray.length - 1];
  else
    returnValue = list;
	
  return returnValue;
}


 /* 
*   Funciones: openNewWindow
*   +---------------------------------------------------------------------------------------------------------+
*    Propósito:         Abrir un popup en el centro de la pantalla
*    Argumentos:       
*    Devuelve:   		
*   +---------------------------------------------------------------------------------------------------------+
*/  

function openNewWindow(URLtoOpen,windowName,height,width)
{
windowFeatures ="menubar=no,scrollbars=no,location=no,favorites=no,resizable=no,status=no,toolbar=no,directories=no";
var test = "'";
winLeft = (screen.width-width)/2;
winTop = (screen.height-(height+110))/2;
myWin= open(URLtoOpen,windowName,"width=" + width +",height=" + height + ",left=" + winLeft + ",top=" + winTop + test + windowFeatures + test);
myWin.document.open();
myWin.document.close();
}



 /* 
*   Funciones: zoom, zoomhelper, clearzoom
*   +---------------------------------------------------------------------------------------------------------+
*    Propósito:         Hacer zoom sobre una foto
*    Argumentos:       
*    Devuelve:   		
*   +---------------------------------------------------------------------------------------------------------+
*/  
//Image zoom in/out script- by javascriptkit.com
//Visit JavaScript Kit (http://www.javascriptkit.com) for script
//Credit must stay intact for use

var zoomfactor=0.05 //Enter factor (0.05=5%)

function zoomhelper(){
if (parseInt(whatcache.style.width)>10&&parseInt(whatcache.style.height)>10){
whatcache.style.width=parseInt(whatcache.style.width)+parseInt(whatcache.style.width)*zoomfactor*prefix
whatcache.style.height=parseInt(whatcache.style.height)+parseInt(whatcache.style.height)*zoomfactor*prefix
}
}

function zoom(originalW, originalH, what, state){
if (!document.all&&!document.getElementById)
return
whatcache=eval("document.images."+what)
prefix=(state=="in")? 1 : -1
if (whatcache.style.width==""||state=="restore"){
whatcache.style.width=originalW
whatcache.style.height=originalH
if (state=="restore")
return
}
else{
zoomhelper()
}
beginzoom=setInterval("zoomhelper()",100)
}

function clearzoom(){
if (window.beginzoom)
clearInterval(beginzoom)
}





 /* 
*   Funciones: getSelectedRadio, getSelectedRadioValue, getSelectedCheckboxValue
*   +---------------------------------------------------------------------------------------------------------+
*    Propósito:         Funciones varias para radio y check boxes
*    Argumentos:       
*    Ejemplo: 		var checkBoxArr = getSelectedCheckbox(document.forms[0].MyCheckBox);
*					if (checkBoxArr.length == 0) { alert("No check boxes selected"); }
*
*   +---------------------------------------------------------------------------------------------------------+
*/  
function getSelectedRadio(buttonGroup) {
   // returns the array number of the selected radio button or -1 if no button is selected
   if (buttonGroup[0]) { // if the button group is an array (one button is not an array)
      for (var i=0; i<buttonGroup.length; i++) {
         if (buttonGroup[i].checked) {
            return i
         }
      }
   } else {
      if (buttonGroup.checked) { return 0; } // if the one button is checked, return zero
   }
   // if we get to this point, no radio button is selected
   return -1;
} // Ends the "getSelectedRadio" function

function getSelectedRadioValue(buttonGroup) {
   // returns the value of the selected radio button or "" if no button is selected
   var i = getSelectedRadio(buttonGroup);
   if (i == -1) {
      return "";
   } else {
      if (buttonGroup[i]) { // Make sure the button group is an array (not just one button)
         return buttonGroup[i].value;
      } else { // The button group is just the one button, and it is checked
         return buttonGroup.value;
      }
   }
} // Ends the "getSelectedRadioValue" function

function getSelectedCheckbox(buttonGroup) {
   // Go through all the check boxes. return an array of all the ones
   // that are selected (their position numbers). if no boxes were checked,
   // returned array will be empty (length will be zero)
   var retArr = new Array();
   var lastElement = 0;
   if (buttonGroup[0]) { // if the button group is an array (one check box is not an array)
      for (var i=0; i<buttonGroup.length; i++) {
         if (buttonGroup[i].checked) {
            retArr.length = lastElement;
            retArr[lastElement] = i;
            lastElement++;
         }
      }
   } else { // There is only one check box (it's not an array)
      if (buttonGroup.checked) { // if the one check box is checked
         retArr.length = lastElement;
         retArr[lastElement] = 0; // return zero as the only array value
      }
   }
   return retArr;
} // Ends the "getSelectedCheckbox" function

function getSelectedCheckboxValue(buttonGroup) {
   // return an array of values selected in the check box group. if no boxes
   // were checked, returned array will be empty (length will be zero)
   var retArr = new Array(); // set up empty array for the return values
   var selectedItems = getSelectedCheckbox(buttonGroup);
   if (selectedItems.length != 0) { // if there was something selected
      retArr.length = selectedItems.length;
      for (var i=0; i<selectedItems.length; i++) {
         if (buttonGroup[selectedItems[i]]) { // Make sure it's an array
            retArr[i] = buttonGroup[selectedItems[i]].value;
         } else { // It's not an array (there's just one check box and it's selected)
            retArr[i] = buttonGroup.value;// return that value
         }
      }
   }
   return retArr;
} // Ends the "getSelectedCheckBoxValue" function





 /* 
*   Funciones: Panorámicas
*   +---------------------------------------------------------------------------------------------------------+
*/  
function DoAutorotationStart() {
        document.ptviewer.startAutoPan( 0.5, 0.0, 1.0 );
}
function DoAutorotationStop() {
        document.ptviewer.stopAutoPan();
}
function DoZoomIn() {
	document.ptviewer.startAutoPan( 0.0, 0.0, 1.0/1.03 );
}
function DoZoomOut() {
	document.ptviewer.startAutoPan( 0.0, 0.0, 1.03 );
}
function DoShowHideHotspots() {
	document.ptviewer.toggleHS();
}
function DoReset() {
	document.ptviewer.gotoView( -45, -60, 80 );
}
function DisplayPan() {
	status = document.ptviewer.pan().toString() ;
}
function DisplayTilt() {
	status = document.ptviewer.tilt().toString() ;
}
function DisplayFov() {
	status = document.ptviewer.fov().toString() ;
}

function mousehs(n) {
	if( n== -1 )
   			document.cn.hsnum.value = "---" ;
	else
   			document.cn.hsnum.value = n ;
}
function getview(p,t,f) {
   document.cn.pan.value = p ;
   document.cn.tilt.value = t ;
   document.cn.fov.value = f ;
}

function NewPano(  ) {
	document.ptviewer.newPanoFromList(0);
}




function randomString(num_chars) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = num_chars;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	
	return randomstring;
}