// JavaScript Document

var http_request = false;
function createRequest() {
	http_request = false;
	if (window.XMLHttpRequest) {
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) {
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {}
		}
	}
	return http_request;
}

function makeTransparent( obj, ndx ) { 
	if (obj.style) {		
		if (obj.style.filter !== undefined) 
			obj.style.filter = 'alpha(opacity=' + ndx + ');';
		else {	
			if (obj.style.MozOpacity !== undefined) {			
				obj.style.MozOpacity = '0.' + ndx;
			}
			else {	
				if (obj.style.opacity !== undefined)
					obj.style.opacity = '0.' + ndx;
			}
		}
	}
}

function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name)
{
	createCookie(name,"",-1);
}

// vaildation functions
function validEmail( email ) {
	mailReg = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/;
	if (email.match(mailReg) )
		return true;
	else
		return false;
}

function validNumber( input ) {
    if( isNaN(Number(input ))) {
        return false;
    }
    else
        return true;
}

function validAlpha( input, imin, imax ) {
    if (!imin)
		imin = 0;
	if (!imax)
		imax = 255;
		
	input = trim(input);	
	
    if( input=='' || input.length < imin || input.length > imax )
        return false;
		
    if( input.match(/^\w*$/ )) {
        return true;
    }
    else
        return false;
}

function trim(str) {
	return str.replace( /^\s*/, '' ).replace( /\s*$/, '' );
}

// Login module
var loginFormAction = false;

function checkLogin() {
	var myForm = document.forms.loginForm;
	
	if (!myForm.email.value || !myForm.pass.value)
		return false;
	else
		return true;
}

function login() {
	var myForm = document.forms.loginForm;
	
	http_request = createRequest();
	if (!http_request) {
		alert( 'Error: No se pudo crear objeto HttpXmlRequest.' )
		return;
	}
	
	document.getElementById('loginformbutton').setAttribute('disabled', 'disabled');
	document.getElementById('loginformbutton').setAttribute('value', 'Espere...');
	
	http_request.open( 'POST', 'xml/xml_login.php', true );
	http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	http_request.onreadystatechange = performLogin;	
	http_request.send( 'user=' + myForm.email.value + '&pass=' + myForm.pass.value);
		
}

function performLogin() {
	if (http_request.readyState == 4) {
		document.getElementById('loginformbutton').removeAttribute('disabled');
		document.getElementById('loginformbutton').setAttribute('value', 'Enviar');
		if (http_request.status == 200) {
			var root = http_request.responseXML.getElementsByTagName('root').item(0);			
			if (root.getAttribute('success') == '1') {
				createCookie( 'interColorSessionId', root.getAttribute('sessionid') );
				if (loginFormAction)
					window.location = loginFormAction;
				else
					window.location = 'userhome.php';
			}
			else {
				alert( 'Nombre de usuario o contraseña no válidos.' );
				document.forms.loginForm.pass.value = '';
			}		
		}
		else {
			alert( 'Se ha producido un error enviando la información.\nInténtelo más tarde (' + http_request.status + ')' );
		}
	}
}

function logoff() {
	http_request = createRequest();
	if (!http_request) {
		alert( 'Error: No se pudo crear objeto HttpXmlRequest.' )
		return;
	}
	
	http_request.open( 'POST', 'xml/xml_logoff.php', false );
	http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');	
	http_request.send( 'sessionId=' + readCookie('interColorSessionId') );
	
	if (http_request.status == 200) {
		eraseCookie('interColorSessionId');
		window.location = 'index.php';
	}
	else {
		alert( 'Se ha producido un error enviando la información.\nInténtelo más tarde (' + http_request.status + ')' );
	}
}

// Ajax related functions
var invDiv = false;
var waitDiv = false;
function invalidate() {
	if (!invDiv) {
		invDiv = document.createElement('div');
		invDiv.id = 'invalidatorPanel';
		invDiv.style.zIndex = '500';
		invDiv.style.backgroundColor = '#555555';
		makeTransparent(invDiv, 50);
		invDiv.style.position = 'absolute';
		invDiv.style.top = '0';
		invDiv.style.left = '0';
		if (navigator.userAgent.indexOf('MSIE') != -1) {
			invDiv.style.width = document.body.clientWidth + 'px';
			invDiv.style.height = document.body.clientHeight + 'px';
		}
		invDiv.style.bottom = '0';
		invDiv.style.right = '0';
	}
	
	document.body.appendChild( invDiv );
}

function revalidate() {
	if (document.getElementById('invalidatorPanel')) 
		document.body.removeChild( document.getElementById('invalidatorPanel') );
}

function setWait() {
	if (!waitDiv) {
		waitDiv = document.createElement('div');
		waitDiv.id = 'waitWindow';
		waitDiv.style.zIndex = '501';
		waitDiv.style.backgroundColor = '#F8F6BF';
		waitDiv.style.border = '5px solid #FFFFFF';
		makeTransparent(waitDiv, 90);
		waitDiv.style.position = 'absolute';
		waitDiv.style.height = '30px';
		waitDiv.style.width = '200px';
		waitDiv.style.left = ((document.body.clientWidth / 2) - 100) + 'px';
		waitDiv.style.top = ((document.body.clientHeight / 2) - 15) + 'px';
		
		var tempP = document.createElement('p');
		tempP.style.fontFamilty = 'Arial';
		tempP.style.fontSize = '12px';
		tempP.style.color = '#5D5D5D';
		tempP.style.margin = '7px';
		tempP.style.textAlign = 'center';
		
		tempP.appendChild( document.createTextNode( 'Espere por favor...' ));
		waitDiv.appendChild(tempP);
	}
	
	invalidate();
	document.body.appendChild( waitDiv );
}

function stopWait() {
	if (document.getElementById('waitWindow')) {		
		document.body.removeChild( document.getElementById('waitWindow') );
		revalidate();
	}
}

var browserWindowHeight = 0;
var browserWindowWidth = 0;
function _calculateBrowserSize() {
	if (navigator.userAgent.indexOf('MSIE') != -1) {
		if (document.documentElement.clientWidth == 0)
			browserWindowWidth = document.body.clientWidth;
		else	
			browserWindowWidth = document.documentElement.clientWidth;
			
		if (document.documentElement.clientHeight == 0)
  			browserWindowHeight = document.body.clientHeight;
		else
			browserWindowHeight = document.documentElement.clientHeight;
	}
	else {
		browserWindowWidth = window.innerWidth;
  		browserWindowHeight = window.innerHeight;
	}
}

function createWin(winId, w, h) {
	if (!browserWindowHeight)
		_calculateBrowserSize();
		
	winDiv = document.createElement('div');
	winDiv.id = winId;
	winDiv.style.zIndex = '501';
	winDiv.style.backgroundColor = '#F8F6BF';
	winDiv.style.border = '5px solid #FFFFFF';	
	winDiv.style.position = 'absolute';
	winDiv.style.height = h + 'px';
	winDiv.style.width = w + 'px';
	winDiv.style.left = ((browserWindowWidth / 2) - (w /2)) + 'px';
	winDiv.style.top = ((browserWindowHeight / 2) - (h /2)) + 'px';		
	
	return winDiv;
}

function encodeSpanishEntities(str) {
	str = str.replace(/\ñ/g, '&ntilde;');
	str = str.replace(/\Ñ/g, '&Ntilde;');
	str = str.replace(/\á/g, '&aacute;');
	str = str.replace(/\é/g, '&eacute;');	
	str = str.replace(/\í/g, '&iacute;');
	str = str.replace(/\ó/g, '&oacute;');
	str = str.replace(/\ú/g, '&uacute;');	
	
	return str;
}

function decodeSpanishEntities(str) {
	str = str.replace(/\&ntilde;/g, 'ñ');
	str = str.replace(/\&Ntilde;/g, 'Ñ');
	str = str.replace(/\&aacute;/g, 'á');
	str = str.replace(/\&eacute;/g, 'é');	
	str = str.replace(/\&iacute;/g, 'í');
	str = str.replace(/\&oacute;/g, 'ó');
	str = str.replace(/\&uacute;/g, 'ú');	
	
	return str;
}
