var historyStack = new Array();
var historyStackIndex = 0;
var maxRowId = 0;
var errors = new Array();

var IMG_SEL = 'Sel';
var IMG_NOR = 'Nor';

function selDiv(control, color)
{
	control.style.background = color;
}

function unSelDiv(control)
{
	control.style.background = '';
}

function enlargeImage(url)
{
	window.open(url, "Aquarium Buenos Aires", "scrollbars=no,toolbar=0,location=0,statusbar=0,menubar=0,resizable=0,width=300,height=240,screenX=100,screenY=100,status=1");
}

function executeCommand(command, parameters)
{
	
	if (command == undefined) {
		command = document.forms[0].id;
	}

	var action="include/commands/" + command + ".php";

	document.forms[0].action = action;
	document.forms[0].submit();

}

function executeAjaxCommand(command, parameters, okMsg, errMsg)
{
	
	displayLoading();
	
	if (parameters == undefined) parameters = "";
	
	if (command == undefined)
	{
		command = document.forms[0].id;
	}
	
	// Gets form parameters
	if (document.getElementById(command))
	{
		for(i=0; i < document.getElementById(command).elements.length; i++)
		{
			if ( parameters != "" ) parameters = parameters + "&";
			parameters = parameters + document.getElementById(command).elements[i].name + "=" + document.getElementById(command).elements[i].value;
		}		
	}
			
	var action="include/commands/" + command + ".php";

	// Set up the request
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open('POST', action, true);

	// The callback function
	xmlhttp.onreadystatechange = function() 
		{
			if (xmlhttp.readyState == 4) {
				if (xmlhttp.status == 200) {
					var res = xmlhttp.responseText;
					closeLoading();
					if (res == 1 && okMsg != undefined)
						alert(okMsg);
					if (res == 0 && errMsg != undefined)
						alert(errMsg);
				}
			}
		}

	// Send the POST request
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", parameters.length);

	xmlhttp.send(parameters);
}

function executeAjaxCommandCallback(command, callback, parameters)
{
	displayLoading();

	if (command == undefined) 
	{
		command = document.forms[0].id;
	}
			
	var action="include/commands/" + command + ".php";

	if (parameters == undefined) parameters = "";

	// Gets form parameters
	if (document.getElementById(command))
	{
		for(i=0; i < document.getElementById(command).elements.length; i++)
		{
			if ( parameters != "" ) parameters = parameters + "&";
			parameters = parameters + document.getElementById(command).elements[i].name + "=" + document.getElementById(command).elements[i].value;
		}		
	}
			
	// Set up the request
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open('POST', action, true);

	// The callback function
	xmlhttp.onreadystatechange = function() 
		{
			if (xmlhttp.readyState == 4) {
				if (xmlhttp.status == 200) {
					var res = xmlhttp.responseText;
					closeLoading();
					if (callback != undefined) 
					{
						callback(res);
					}
				}
			}
		}

	// Send the POST request
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", parameters.length);

	xmlhttp.send(parameters);

}		

function historySave(url)
{
	historyStackIndex++;
	historyStack[historyStackIndex] = url;
}

function historyBack()
{
	history.back();
}

function historyForward()
{
	history.forward();
}

function hoverImage(component, action)
{
	url = component.src;
	dot = url.lastIndexOf('.');
	url_first_part = url.substring(0, dot-3);
	url_extension = url.substring(dot);
	component.src = url_first_part + action + url_extension;
}

function hoverTDBack(component, action)
{
	component.style.backgroundImage ='url(images/' + action + '.png)';
}

function agregarEspecie()
{
	
	var misPecesRowIndex = 1;
	
	if (document.all.chkEspecie.length != undefined) 
	{
		misPecesRowIndex = document.all.chkEspecie.length;
		maxRowId = misPecesRowIndex;
	}
	
	var container = document.all.divMisPeces;
	var newChild = document.createElement('div');
	var newChildName = 'divMisPecesRow' + misPecesRowIndex;

	newChild.setAttribute('id', newChildName);
	newChild.innerHTML = document.all.divMisPecesRow.innerHTML;
	container.appendChild(newChild);

	document.all.chkEspecie[misPecesRowIndex].value = newChildName;
}

function eliminarEspecie()
{

	for (var i=0; i < document.all.chkEspecie.length; i++)
	{
		if (document.all.chkEspecie[i].checked)
		{
			var container = document.all.divMisPeces;
			container.removeChild(document.getElementById(document.all.chkEspecie[i].value));
		}
	}
	
	var row = 0;
	for (var i=0; i <= maxRowId; i++)
	{
		var element = document.getElementById('divMisPecesRow' + i);
	
		if (element != undefined)
		{
			row++;
			element.setAttribute('id', 'divMisPecesRow' + row);
			document.all.chkEspecie[row].value = 'divMisPecesRow' + row;
		}
	}
	
}

function showData()
{

	for (var i=1; i < document.all.chkEspecie.length; i++)
	{
		alert('Dato ' + i + ': ' + document.all.txtCantidad[i].value + ' - ' + document.all.txtEspecie[i].options[document.all.txtEspecie[i].selectedIndex].text);
	}

}

function existeUsuario()
{
	// TODO: Hacer verificacion de usuario existente
	return false;
}

function validarDatosPersonales()
{
	
	// datos obligatorios
	if (!validateBlank("txtUsuario", "Debes ingresar el usuario.")) return false;
	if (!validateBlank("txtClave", "Debes ingresar la clave.")) return false;
	if (!validateBlank("txtConfirmacionClave", "Debes ingresar la confirmacion de la clave.")) return false;
	if (!validateBlank("txtNombre", "Debes ingresar tu nombre.")) return false;
	if (!validateBlank("txtApellido", "Debes ingresar tu apellido.")) return false;
	if (!validateBlank("txtFechaNacimiento", "Debes ingresar tu fecha de nacimiento.")) return false;
	if (!validateBlank("txtPais", "Debes seleccionar tu pais.")) return false;
	if (!validateBlank("txtProvincia", "Debes seleccionar tu provincia.")) return false;
	if (!validateBlank("txtCiudad", "Debes seleccionar tu ciudad.")) return false;
	if (!validateBlank("txtEmail", "Debes ingresar tu email.")) return false;
	if (!validateBlank("txtConfirmacionEmail", "Debes ingresar la confirmacion de tu email.")) return false;
	
	// validacion usuario y contrasena
	if (!validateElement("txtUsuario", (getValue("txtUsuario").length < 8 && getValue("txtUsuario") != "Xtian"), "Tu usuario debe tener entre 8 y 15 letras y/o numeros.")) return false;
	if (!validateElement("txtUsuario", (existeUsuario(getValue("txtUsuario"))), "El usuario seleccionado ya existe")) return false;
	if (!validateElement("txtClave", (getValue("txtClave").length < 6), "La clave debe tener entre 6 y 12 letras y/o numeros.")) return false;
	if (!validateElement("txtClave", (getValue("txtClave") != getValue("txtConfirmacionClave")), "La confirmacion de la clave no coincide con la clave ingresada.")) return false;

	// validacion fecha de nacimiento
	if (!validateElement("txtFechaNacimiento", (isDate(getValue("txtFechaNacimiento"))!=""), isDate(getValue("txtFechaNacimiento")))) return false;
			
	// validacion de email
	if (!validateElement("txtEmail", (!emailCheck(getValue("txtEmail"))), "La direccion de mail ingresada es incorrecta.")) return false;
	if (!validateElement("txtEmail", (getValue("txtEmail") != getValue("txtConfirmacionEmail")), "La confirmacion de la direccion de email no coincide con la direccion de email ingresada.")) return false;

	return true;

}

function calcularVolumenAcuario()
{
	
	var largo = getValue("txtLargo");
	var altura = getValue("txtAltura");
	var profundidad = getValue("txtProfundidad");
	
	if ( isInteger(largo) && isInteger(altura) && isInteger(profundidad) )
	{
		var volumen = parseInt(largo) * parseInt(altura) * parseInt(profundidad) / 1000;
		document.getElementById("txtVolumen").value = volumen;
	}

}

function validarDatosAcuarios()
{
	txtLargo
	txtAltura
	txtProfundidad


	return true;
}

function executeCmdAcuarios()
{

	var especiesCount = 0;
	
	if (document.all.chkEspecie.length) especiesCount = document.all.chkEspecie.length;

	var parameters = "especiesCount=" + (especiesCount - 1);

	// arma los parametros para los arrays de controles
	for (var i=1; i < especiesCount; i++)
	{
			parameters = parameters + "&txtEspecie" + i + "=" + document.all.txtEspecie[i].options[document.all.txtEspecie[i].selectedIndex].value;
		parameters = parameters + "&txtCantidad" + i + "=" + document.all.txtCantidad[i].value;
		parameters = parameters + "&txtTamanoSexo" + i + "=" + document.all.txtTamanoSexo[i].value;
	}
	
	executeCommand("cmdRegistracionDatosAcuarios", parameters);

}

function fillAjaxCombo(combo, parameters, output, div)
{
	parameters = 'idCombo=' + combo + "&" + parameters;

	var action="include/commands/cmdGetCombos.php";

	// Set up the request
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open('POST', action, true);

	// The callback function
	xmlhttp.onreadystatechange = function() 
		{
			if (xmlhttp.readyState == 4) {
				if (xmlhttp.status == 200) {
					var res = xmlhttp.responseText;
					div.innerHTML = '<SELECT id=' + output.id  + ' name=' + output.name + ' class=' + output.className + '>' + res + '</SELECT>';
				}
			}
		}

	// Send the POST request
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", parameters.length);

	xmlhttp.send(parameters);

}		

function TabPageClick(oBtn)
{
	aNameParts = oBtn.id.split('_');
	iBtnClickedIndex = parseInt( aNameParts[2] );         // the index of the clicked button

	if ( oBtn.className == "navUnselected" )
	{
		return true; // already selected 
	}

	oBtn.className = "navUnselected";

	for (i=0;  i <= 3; i++ )
	{
		if ( i == iBtnClickedIndex )
		{
			document.getElementById("uiTabPageDiv_" + aNameParts[1] + "_" + iBtnClickedIndex).style.display = "block"; // show the clicked layer
			continue;
		}
	 
		oBtn = document.getElementById("uiTabControl_"+ aNameParts[1] + "_" + i);
		
		if(oBtn)
		{
			document.getElementById("uiTabPageDiv_" + aNameParts[1] + "_" + i).style.display = "none";
			oBtn.className = "navSelected";
		}
		else break;
	}
}

function setContent(elementID) {

	if (document.getElementById) {
		var windowHeight = getWindowHeight();
		var windowWidth = getWindowWidth();
		if (windowHeight > 0) {
			var contentElement = document.getElementById(elementID);
			var contentWidth = contentElement.offsetWidth;
			var contentHeight = contentElement.offsetHeight;
			if (windowHeight - contentHeight > 0) 
			{
				contentElement.style.position = 'absolute';
				contentElement.style.top = document.body.scrollTop + ((windowHeight - contentHeight) / 2) + 'px';
				contentElement.style.left = document.body.scrollLeft + ((windowWidth - contentWidth) / 2) + 'px';
			}
		}
	}
}

function getWindowHeight() {
	var windowHeight = 0;
	if (typeof(window.innerHeight) == 'number') {
		windowHeight = window.innerHeight;
	}
	else {
		if (document.documentElement && document.documentElement.clientHeight) {
			windowHeight = document.documentElement.clientHeight;
		}
		else {
			if (document.body && document.body.clientHeight) {
				windowHeight = document.body.clientHeight;
			}
		}
	}
	return windowHeight;
}

function getWindowWidth() {
	var windowWidth = 0;
	if (typeof(window.innerWidth) == 'number') {
		windowWidth = window.innerWidth;
	}
	else {
		if (document.documentElement && document.documentElement.clientWidth) {
			windowWidth = document.documentElement.clientWidth;
		}
		else {
			if (document.body && document.body.clientWidth) {
				windowWidth = document.body.clientWidth;
			}
		}
	}
	return windowWidth;
}
