// JavaScript Document
function changePage(nextPage,params,url){
	//creo un formulario para mandar la info por post
	myform = document.createElement("form");
	myform.setAttribute("method","post");
	myform.setAttribute("action",url);
	myform.setAttribute("id","formPaging");
	myform.style.display = "none";
	
	//cargo el nextPage que seleccionaron para enviar por post
	input = document.createElement("input");
	input.setAttribute("name","nextPage");
	input.setAttribute("value",nextPage);	
	myform.appendChild(input);
	
	//cargo los parametros para enviar por post
	params = params.split("*");
	var data;
	for(var i = 0; i < params.length; i++){
		data = params[i].split("=");
		input = document.createElement("input");
		input.setAttribute("name",data[0]);
		input.setAttribute("value",data[1]);
		myform.appendChild(input);
	}

	document.body.appendChild(myform);
	myform.submit();
}

function showQuickSearch(){
	var quicksearch = document.getElementById("quicksearch");
	
	if(quicksearch.style.display == "none"){
		quicksearch.style.display = "";		
	}
	else{
		quicksearch.style.display = "none";
	}
}

//para encontrar la posicion de un objeto
function findPos(obj) {

	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
			//alert(obj.offsetTop);
		}
	}
	//return [curleft,curtop];
	return curtop;
}

//devuelve el alto en pixeles de la pagina
function alto_pagina()
{
	//funciona tanto en Netscape, Mozilla, Opera, Firefox como en Internet Explorer
	if( typeof( window.innerHeight ) == 'number' )
		h = window.innerHeight; //no es IE
	else
		if( document.body && document.body.clientHeight )
			h = document.body.clientHeight; //IE 4 o superior

	return h;
}

function validar_awb_number(campo)
{
	var pattern = /^([0-9]){3}(-([0-9]){4}-([0-9]){4}|([0-9]){8})$/;
	
	if(!pattern.test(campo.value))
	{ 
		alert("Invalid AWB Number. Valid Format: NNN-NNNN-NNNN or NNNNNNNNNNN");
		campo.value = '';
		campo.focus();
		return false;
	}
	return true;
}
/*
function validar_awb_number(field)
{
	var valid = "0123456789-";
	var ok = "yes";
	var temp ;
	for (var i=0; i<field.value.length; i++)
	{
		temp = "" + field.value.substring(i, i+1);
		if (valid.indexOf(temp) == "-1")
		{
			ok = "no";
			leyend = "One of the characters is not valid. The AWB Number number must fulfill the following format: NNN-NNNN-NNNN. The '-' character is optional."
		}
		else
		{
			if (field.value.indexOf("-")=="-1" || (field.value.indexOf("-")=="3" && field.value.lastIndexOf("-")=="8") )
			{
				ok= "yes";
				leyend="";
			}
			else
			{
				ok = "no";
				leyend = "The character '-' is out of place. The AWB number must fulfill the following format: NNN-NNNN-NNNN. The '-' character is optional.";
			}

		}
	}

	//alert(ok);
	largo=parseInt(field.value.length);
	//alert(field.value.length)
	//alert(field.value.lastIndexOf("-"));
	//alert(field.value.lastIndexOf("-"));

	if (largo < 11)
	{
		ok="no";
		leyend += " The AWB Number is too short.";
	}

	//hasta aca si esta todo bien es porque no tiene - y son todos numericos o porque tiene - y numeros pero todo ubicado correctamente
	//ahora falta validar que si no tiene - ,  los numeros del master no sean mas de 11
	if (field.value.indexOf("-")=="-1" && largo > 11)
	{
		ok="no";
		leyend += " The AWB Number is too big.";
	}

	//alert(leyend);

	if (ok == "no")
	{
		alert(leyend);
		field.value = "";
		field.focus();
		return false;
   }
   return true
}
*/
//calcular la suma de las columnas de los houses
function sumar_columna_house(col)
{
	var sum = 0;
	//los numeros de filas que hay
	var filas_houses = document.getElementById("filas_houses");
	//el td donde imprimo la suma
	var tdSuma = document.getElementById("sum_"+col);

	//la variable filas_houses contiene un string con el formato 0*1*2*5*9* (filas 0 1 2 5 y 9), las tengo que meter en un vector
	var vec_filas_houses = filas_houses.value.split("*");
	//uso filas_houses.length -1 xq el array tiene un * al final y eso me genera una entrada mas en el vector
	for(i=0; i < vec_filas_houses.length-1  ; i++)
	{
		//alert(vec_filas_houses[i]);
		sum = eval(document.getElementById(col+"_"+vec_filas_houses[i]).value+"+"+sum);		
	}
	//esto lo hago para que no me imprima mas de 2 decimales	
	sum = String(sum);	
	if(sum.indexOf(".") != -1)
		sum = sum.substring(0,sum.indexOf(".")+4)

	tdSuma.innerHTML = sum;

}

function suma_columna(col) {

	var filas_houses = document.getElementById("filas_houses");
	var vec_filas_houses = filas_houses.value.split("*");
	var sum=0;
	//	cuento solo las activadas
	for(i=0; i < vec_filas_houses.length-1  ; i++)
	{
		//alert(vec_filas_houses[i]);
		sum = eval(document.getElementById(col+"_"+vec_filas_houses[i]).value+"+"+sum);
	}
	return sum;

}



//funcion para validar el campo de un formulario enviandole los caracteres que son validos
function validate(field, valid)
{
	var ok = "yes";
	var temp;
	//si el campo es vacio
	if(field.value.length == 0)
		ok = "no";
	for (var i=0; i<field.value.length; i++)
	{
		temp = "" + field.value.substring(i, i+1);
		if (valid.indexOf(temp) == "-1") //si no encuentra el caracter temp entre los validos, devuelve -1
			ok = "no";
		else
			if (field.value.indexOf(".") != field.value.lastIndexOf(".")) //indexOf devuelve la poscision donde se encuentra el caracter
			{
				ok = "no";
			}
	}

	if (ok == "no")
	{
		field.select();
		return false;
   }
   else return true;
}

//valida una fecha con el formato MM/DD/YYYY
function validar_fecha(fecha)
{
	var arr_fecha = fecha.split("/");
	var month = parseInt(arr_fecha[0],10);
	var day = parseInt(arr_fecha[1],10);
	if(!isInt(arr_fecha[2]))
		return false;

	switch(month)
	{
		case 01:
		case 03:
		case 05:
		case 07:
		case 08:
		case 10:
		case 12:
				if(day > 31)
					return false;
				else
					return true;
			break;

		case 02:
				if(day > 29)
					return false;
				else
					return true;
			break;
		case 04:
		case 06:
		case 09:
		case 11:
			if(day > 30)
				return false;
			else
				return true;
		break;

		default: return false;

	};

}

function getValue(form, campo)
{
	return eval("document."+form+"."+campo+".value");

}

//verifica una fecha con el formato MM/DD/YYYY
function verificar_fecha(fecha)
{
	var texto;
	var arr_fecha = fecha.split("/");

	if (fecha=="MM/DD/YYYY" || !fecha)
		return texto;

	if(arr_fecha.length == 3)
	{
		if(!isInt(arr_fecha[0]) || arr_fecha[0] == 0 ||  arr_fecha[0] > 12)
			texto = "Wrong Date Format. The month should be a number between 01 and 12";
		else
			if(!isInt(arr_fecha[1]) || arr_fecha[1] == 0 ||  arr_fecha[1] > 31)
				texto = "Wrong Date Format. The day should be a number between 01 and 31";
			else
				if(!isInt(arr_fecha[2]) || arr_fecha[2].length != 4)
					texto = "Wrong Date Format. The Year should be of 4 digits";

	}
	else
		texto = "Wrong Date Format. Remember it should be MM/DD/YYYY";

	return texto;
}
function isInt(valor) {
	var pattern = /[0-9]/;
	return pattern.test(valor);
}

//valida con expresiones regulares que el formato sea el correcto XXXXXXXXXXX o XXX-XXXX-XXXX
function validar_formato_master(campo)
{

	var pattern = /^[0-9]{3}(\-[0-9]{4}\-|[0-9]{4})[0-9]{4}$/;
	//alert(pattern.test(campo.value));
	if(!pattern.test(campo.value) && campo.value)
	{
		alert("Wrong MasterAWB# format. Remember it should be XXXXXXXXXXX or XXX-XXXX-XXXX");
		campo.value = "";
		return false;
	}
	return true;
}
/**
 *
 * @access public
 * @return void
 **/
function checkMAWBsearch(){
	var mawb = document.form_awb_qj.master_qj;
	var customer = document.form_awb_qj.customer_qj;
	//alert(mawb.value);
	if(mawb.value)
	{
		return validar_formato_master(mawb);
	}
	else if(customer.value)
		return true;
	else
	{
		alert('Please fill utleast one search parameter');
		return false;
	}
}
function ActualizarCeldaAir (valor,nomTD,nomPag) {

	document.getElementById("ifr").src	=	nomPag + '?airline=' + valor + '&nomcelda=' + nomTD;
	//alert(document.getElementById("ifr").src);
}

function ActivarComandoTransferencia(show) {

	var celda	=	document.getElementById("tda");
	var elem	=	document.getElementById("air_input");
	var celda2	=	document.getElementById("tdt");
	var flight	=	document.getElementById("transfered_flight");

	if (show) {
		celda.style.visibility = 'visible';
		celda2.style.visibility = 'visible';
	}
	else {
		celda.style.visibility = 'hidden';
		elem.value='';
		celda2.style.visibility = 'hidden';
		flight.value = '';
	}

}

function ActivarComandoPod(show) {

	var pod1	=	document.getElementById("pod1");
	var pod2	=	document.getElementById("pod2");
	var pod3	=	document.getElementById("pod3");
	var pod4	=	document.getElementById("pod4");
	var pod5	=	document.getElementById("pod5");
	var pod6	=	document.getElementById("pod6");
	var receiver	=	document.getElementById("receiver");
	var receiver_company	=	document.getElementById("receiver_company");
	var pod_notes	=	document.getElementById("pod_notes");

	if (show) {
		texto = 'visible';
	}
	else {
		texto = 'hidden';
		receiver.value='';
		receiver_company.value='';
		pod_notes.value='';
	}

	pod1.style.visibility = texto;
	pod2.style.visibility = texto;
	pod3.style.visibility = texto;
	pod4.style.visibility = texto;
	pod5.style.visibility = texto;
	pod6.style.visibility = texto;

}

function ActivarComandoPPQ(show) {
	var td_fecha	=	document.getElementById("td_fecha");
	var td_fecha_1	=	document.getElementById("td_fecha_1");
	var td_time	=	document.getElementById("td_time");
	var td_time_1	=	document.getElementById("td_time_1");

	if (show)
		texto = 'visible';
	else
		texto = 'hidden';


	td_fecha.style.visibility = texto;
	td_fecha_1.style.visibility = texto;
	td_time.style.visibility = texto;
	td_time_1.style.visibility = texto;

}

function validate_numerico(campo)
{		
	var pattern = /^([0-9])+(\.([0-9])+)?$/;
	
	if(!pattern.test(campo.value))
	{ 
		alert("Invalid Number");
		campo.value = 0;
		campo.focus();
		campo.select();
		return false;
	}
	return true;
}

function verificar_destination(texto)
{
	//document.getElementById("text2").innerHTML = texto;
	iframe = document.getElementById("ifr");
	iframe.src = "warehouseXML.php?dest="+texto+"&cambio_dest=1";
}

//la uso para buscar en el select cuyo id me pasen por parametro el texto
function buscarEnSelectText(text,id_select)
{
	var sel = document.getElementById(id_select);
	var seguir = 1;
	var i = 0;
	pattern =  new RegExp( "^"+text, "gi");
	while(i < sel.length && seguir)
	{
		if(pattern.test(sel.options[i].innerHTML))
		{
			sel.selectedIndex = i;
			seguir = 0;
		}
		i++;
	}
}
function buscarEnSelectTextShipper(text,id_select)
{
	var sel = document.getElementById(id_select);
	var seguir = 1;
	var i = 0;
	if(text.length > 2)
	{
		iframe = document.getElementById("ifr");
		iframe.src = "masterXML.php?step=5&key="+text;
	}
	
	pattern =  new RegExp( "^"+text, "gi");
	while(i < sel.length && seguir )
	{
		if(pattern.test(sel.options[i].innerHTML))
		{
			sel.selectedIndex = i;
			seguir = 0;
		}
		i++;
	}
}
function buscarEnSelectTextConsignee(text,id_select)
{
	var sel = document.getElementById(id_select);
	var seguir = 1;
	var i = 0;
	if(text.length > 2)
	{
		iframe = document.getElementById("ifr");
		iframe.src = "masterXML.php?step=6&key="+text;
	}
	
	pattern =  new RegExp( "^"+text, "gi");
	while(i < sel.length && seguir )
	{
		if(pattern.test(sel.options[i].innerHTML))
		{
			sel.selectedIndex = i;
			seguir = 0;
		}
		i++;
	}
}
function buscarEnSelectText_bk(text,id_select)
{
	var sel = document.getElementById(id_select);
	var seguir = 1;
	var i = 0;
	//var long = text.length;
	//var op1 = text.toUpperCase();
	//var op2 = "";
	//var pattern = '/car+/gi';
	pattern =  new RegExp( "^"+text, "gi");
	//alert(pattern);
	//var pattern = text;

	while(i < sel.length && seguir)
	{
		//si encuentra el caracter ingresado lo selecciono	
		//if(sel.options[i].innerHTML.substring(0,long).toUpperCase() == text.toUpperCase())
		//op2 = sel.options[i].innerHTML;
		//op2 = op2.substr(0,long);
		//op2 = op2.toUpperCase();
		//if(op2  == op1 )
		if(pattern.test(sel.options[i].innerHTML))
		{
			sel.selectedIndex = i;
			seguir = 0;
		}
		i++;
	}
}

function verificar_destino(texto)
{
	//document.getElementById("text2").innerHTML = texto;
	iframe = document.getElementById("ifr");
	iframe.src = "masterXML.php?dest="+texto+"&cambio_dest=1";
}

function closePopUp(popUp,opener){
	var popUp = document.getElementById(popUp);	
	popUp.style.display = 'none';
	var doc = document.getElementById(opener);	
	doc.style.display = 'block';
}

function openPopUp(popUp,opener){
	var popUp = document.getElementById(popUp);	
	popUp.style.display = 'block';
	var doc = document.getElementById(opener);	
	doc.style.display = 'none';	
}
function toggle(menu)
{	
	objChange = document.getElementById(menu);
	if(objChange.style.display == 'none')
		objChange.style.display = '';	
	else
		objChange.style.display = 'none';
}


// BROWSER DETECTION
var BrowserDetect = {
		init: function () {
			this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
			this.version = this.searchVersion(navigator.userAgent)
				|| this.searchVersion(navigator.appVersion)
				|| "an unknown version";
			this.OS = this.searchString(this.dataOS) || "an unknown OS";
		},
		searchString: function (data) {
			for (var i=0;i<data.length;i++)	{
				var dataString = data[i].string;
				var dataProp = data[i].prop;
				this.versionSearchString = data[i].versionSearch || data[i].identity;
				if (dataString) {
					if (dataString.indexOf(data[i].subString) != -1)
						return data[i].identity;
				}
				else if (dataProp)
					return data[i].identity;
			}
		},
		searchVersion: function (dataString) {
			var index = dataString.indexOf(this.versionSearchString);
			if (index == -1) return;
			return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
		},
		dataBrowser: [
			{
				string: navigator.userAgent,
				subString: "Chrome",
				identity: "Chrome"
			},
			{ 	string: navigator.userAgent,
				subString: "OmniWeb",
				versionSearch: "OmniWeb/",
				identity: "OmniWeb"
			},
			{
				string: navigator.vendor,
				subString: "Apple",
				identity: "Safari",
				versionSearch: "Version"
			},
			{
				prop: window.opera,
				identity: "Opera"
			},
			{
				string: navigator.vendor,
				subString: "iCab",
				identity: "iCab"
			},
			{
				string: navigator.vendor,
				subString: "KDE",
				identity: "Konqueror"
			},
			{
				string: navigator.userAgent,
				subString: "Firefox",
				identity: "Firefox"
			},
			{
				string: navigator.vendor,
				subString: "Camino",
				identity: "Camino"
			},
			{		// for newer Netscapes (6+)
				string: navigator.userAgent,
				subString: "Netscape",
				identity: "Netscape"
			},
			{
				string: navigator.userAgent,
				subString: "MSIE",
				identity: "Explorer",
				versionSearch: "MSIE"
			},
			{
				string: navigator.userAgent,
				subString: "Gecko",
				identity: "Mozilla",
				versionSearch: "rv"
			},
			{ 		// for older Netscapes (4-)
				string: navigator.userAgent,
				subString: "Mozilla",
				identity: "Netscape",
				versionSearch: "Mozilla"
			}
		],
		dataOS : [
			{
				string: navigator.platform,
				subString: "Win",
				identity: "Windows"
			},
			{
				string: navigator.platform,
				subString: "Mac",
				identity: "Mac"
			},
			{
				   string: navigator.userAgent,
				   subString: "iPhone",
				   identity: "iPhone/iPod"
		    },
			{
				string: navigator.platform,
				subString: "Linux",
				identity: "Linux"
			}
		]

	};
	BrowserDetect.init();