/*

Librería javascript unificada TN

*/

// --- Variables de la librería -------------------------------------------------------------------

var _jstn_version = '0.38';
var _jstn_master_domain = 'tarsis.net';
var _jstn_this_domain;
var _jstn_allowed_domains = ['tarsis.net', 'tarsis.eu', 'esferahosting.com', 'barrasybarras.com', 'minostn.com', 'faunaiberica.org', 'horizonteflamenco.com', 'trendnova.com', 'motorola-emea.com', 'motorola-emb.com', 'motorola-ems.com'];

var _jstn_screen_width;
var _jstn_screen_height;
var _jstn_window_width;
var _jstn_window_height;
var _jstn_color_depth;
var _jstn_browser_name;
var _jstn_browser_version;
var _jstn_browser_language;
var _jstn_ajax_capable = false;
var _jstn_device_mobile = false;

var _jstn_ajax_server = './jstn/jstn_as/index.php';
var _jstn_ajax_url;
var _jstn_ajax_wait_message = '<span style="font-weight: bold; font-size: 12px; color: #999999; ">Actualizando...</span>'; // --- Puede ser HTML
var _jstn_ajax_dinamic_div;



// --- Funciones autoejecutadas ---------------------------------------------------------------------

function jstn_detect_current_domain() {
	url = document.location.href;
	tmp = url.toLowerCase();
	tmp = tmp.replace(/http\:\/\//g, '');
	tmp = tmp.replace(/https\:\/\//g, '');
	elements = tmp.split('\/');
	tmp = elements[0];
	tmp = tmp.replace(/www\./g, '');
	_jstn_this_domain = tmp;
	return;
}
jstn_detect_current_domain();


function jstn_block_other_domains() {
	is_allowed = false;
	tmp = _jstn_allowed_domains.length;
	for( i=0; i<tmp; i++ ) {
		if ( _jstn_this_domain == _jstn_allowed_domains[i] ) {
			is_allowed = true;
			break;
		}
	}
	if ( is_allowed == false ) {
		location.href = 'http://www.tarsis.net/';
	}
	return;
}
jstn_block_other_domains();


function jstn_detect_browser() {
	b_string = navigator.userAgent;
	if ( b_string.indexOf('MSIE') != -1 ) { _jstn_browser_name = 'Explorer'; }
	if ( b_string.indexOf('IEMobile') != -1 ) { _jstn_browser_name = 'Explorer Mobile'; _jstn_device_mobile = true; }
	if ( b_string.indexOf('Firefox') != -1 ) { _jstn_browser_name = 'Firefox'; }
	if ( b_string.indexOf('Safari') != -1 ) { _jstn_browser_name = 'Safari'; }
	// --- Safari debe estar antes que Chrome, que es un derivado
	if ( b_string.indexOf('Chrome') != -1 ) { _jstn_browser_name = 'Chrome'; }
	if ( b_string.indexOf('Opera') != -1 ) { _jstn_browser_name = 'Opera'; }
	if ( b_string.indexOf('Konqueror') != -1 ) { _jstn_browser_name = 'Konqueror'; }

	// --- Detección de dispositivos móviles
	if ( b_string.indexOf('iPhone') != -1 ) { _jstn_device_mobile = true; }
	if ( b_string.indexOf('iPod') != -1 ) { _jstn_device_mobile = true; }
	if ( b_string.indexOf('HTC') != -1 ) { _jstn_device_mobile = true; }
	if ( b_string.indexOf('Blackberry') != -1 ) { _jstn_device_mobile = true; }
	if ( b_string.indexOf('LG-') != -1 ) { _jstn_device_mobile = true; }
	if ( b_string.indexOf('LG/') != -1 ) { _jstn_device_mobile = true; }
	if ( b_string.indexOf('LGE-') != -1 ) { _jstn_device_mobile = true; }
	if ( b_string.indexOf('MOT-') != -1 ) { _jstn_device_mobile = true; }
	if ( b_string.indexOf('Nokia') != -1 ) { _jstn_device_mobile = true; }
	if ( b_string.indexOf('Samsung') != -1 ) { _jstn_device_mobile = true; }
	if ( b_string.indexOf('SonyEricsson') != -1 ) { _jstn_device_mobile = true; }
	if ( b_string.indexOf('iPAQ') != -1 ) { _jstn_device_mobile = true; }

	if ( b_string.indexOf('mobile') != -1 ) { _jstn_device_mobile = true; }
	if ( b_string.indexOf('midp') != -1 ) { _jstn_device_mobile = true; }
	if ( b_string.indexOf('mmp') != -1 ) { _jstn_device_mobile = true; }
	if ( b_string.indexOf('Symbian') != -1 ) { _jstn_device_mobile = true; }
	if ( b_string.indexOf('Android') != -1 ) { _jstn_device_mobile = true; }

	if ( _jstn_browser_name == '' ) {
		_jstn_browser_name = navigator.appName;
	}
	_jstn_browser_version = navigator.appVersion;
	// _jstn_browser_version = parseFloat(_jstn_browser_version);
	return;
}
jstn_detect_browser();


function jstn_detect_screen_dimensions() {
	_jstn_screen_width = screen.width;
	_jstn_screen_height = screen.height;
	if ( document.documentElement ) { // IE
		_jstn_window_width = document.documentElement.clientWidth;
		_jstn_window_height = document.documentElement.clientHeight;
	} else {
		_jstn_window_width = window.innerWidth;
		_jstn_window_height = window.innerHeight;
	}
	_jstn_color_depth = screen.colorDepth;
	return;
}
jstn_detect_screen_dimensions();


function jstn_parse_url_variables(url) {
	tmp = url;
	if ( tmp != "" ) {
		tmp = tmp + '";';
		tmp = tmp.replace(/\?/g, '');
		tmp = tmp.replace(/\&/g, '";');
		tmp = tmp.replace(/=/g, '="');
		tmp = unescape(tmp);
		eval(tmp);
	}
	return;
}
jstn_parse_url_variables(document.location.search);


function jstn_ajax_capable() {
	if ( window.XMLHttpRequest || window.ActiveXObject ) {
		_jstn_ajax_capable = true;
	}
	return;
}
jstn_ajax_capable();


// --- Funciones generales ---------------------------------------------------------------------------


function jstn_check_email(email) {
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	if ( filter.test(email) ) {
		testresults = true;
	} else {
		testresults = false;
	}
	return (testresults);
}


function jstn_check_phone_number(number) {
	is_valid = true;
	if ( isNaN(number) ) {
		return false
	}
	number = number.replace(/ /g, '');
	number = number.replace(/\./g, '');
	number = number.replace(/-/g, '');
	number = number.replace(/\+/g, '');
	number = parseInt(number);
	if ( number < 100000000 || number > 999999999999 ) {
		is_valid = false;
	}
	return is_valid;
}


function jstn_select_right_option(eid, okvalue) {
	objeto = document.getElementById(eid);
	options_length = objeto.options.length;
	for (var idx = 0; idx < options_length; idx++) {
		if ( objeto.options[idx].value == okvalue ) {
			objeto.selectedIndex = idx;
			break;
		}
	}
	return;
}


function jstn_create_ticket(letras, numeros) {
	ticket = "";

	chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	for(x=0; x<letras; x++) {
		l = chars.length;
		i = Math.floor(Math.random() * l);
		ticket += chars.charAt(i);
	}

	chars = "1234567890";
	for(x=0; x<numeros; x++) {
		l = chars.length;
		i = Math.floor(Math.random() * l);
		ticket += chars.charAt(i);
	}

	return ticket;
}


// --- Efectos DHTML -----------------------------------------------------------------------------


/* Modifica  contenido de un div*/
function jstn_change_content(eid, content) {
	div_cambiante = document.getElementById(eid);
	div_cambiante.innerHTML = content;
	return;
}


/* Conmuta la visibilidad de un id */
function jstn_switch(eid) {
	var element = document.getElementById(eid);

	if ( element.style.visibility == 'hidden' ) {
		jstn_switch_on(eid);
	} else {
		jstn_switch_off(eid);
	}

	return;
}


/* Hace desaparecer un id */
function jstn_switch_off(eid) {
	element = document.getElementById(eid);
	element.style.display = 'none';
	element.style.visibility = 'hidden';
	return;
}


/* Hace aparecer un id */
function jstn_switch_on(eid) {
	element = document.getElementById(eid);
	element.style.display = 'block';
	element.style.visibility = 'visible';
	return;
}


/* Centra un div de forma absoluta, independientemente de su tamaño y el ancho de pantalla */
function jstn_center_div(eid) {
	elemento = document.getElementById(eid);

	var ancho_pantalla = _jstn_window_width;
	var ancho_div = elemento.offsetWidth;

	valor_left = (ancho_pantalla - ancho_div) / 2;
	valor_left = Math.round(valor_left);
	valor_left = valor_left + 'px';

	elemento.style.position = 'absolute';
	elemento.style.left = valor_left;

	return;
}


function jstn_modify_width(eid, final) {
	objeto = document.getElementById(eid);
	ancho = objeto.clientWidth;
	ancho = parseInt(ancho);
	final = parseInt(final);
	if ( ancho < 0 ) {
		ancho = 0;
	}
	objeto.style.width = final + 'px';
	return;
}


function jstn_modify_height(eid, final) {
	objeto = document.getElementById(eid);
	alto = objeto.clientHeight;
	alto = parseInt(alto);
	final = parseInt(final);
	if ( alto < 0 ) {
		alto = 0;
	}
	objeto.style.height = final + 'px';
	return;
}


function jstn_modify_text_size(eid, direction) {
	objeto = document.getElementById(eid);
	var fontsize = objeto.style.fontSize;
	if ( fontsize == '' || fontsize == 'undefined' || !fontsize ) {
		fontsize = '100%';
	}
	fontsize = parseInt( fontsize.replace(/%/g, '') );
	if ( direction == '+' ) {
		fontsize = fontsize + 20;
	} else {
		fontsize = fontsize - 20;
	}
	fontsize = fontsize + '%';
	objeto.style.fontSize = fontsize;
	return;
}


function jstn_grayout(vis, options) {
	// Pass true to gray out screen, false to ungray
	// options are optional.  This is a JSON object with the following (optional) properties
	// opacity:0-100         // Lower number = less grayout higher = more of a blackout
	// zindex: #             // HTML elements with a higher zindex appear on top of the gray out
	// bgcolor: (#xxxxxx)    // Standard RGB Hex color code
	// grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
	// Because options is JSON opacity/zindex/bgcolor are all optional and can appear
	// in any order.  Pass only the properties you need to set.
	var options = options || {};
	var zindex = options.zindex || 10;
	var opacity = options.opacity || 30;
	var opaque = (opacity / 100);
	var bgcolor = options.bgcolor || '#000000';
	var dark=document.getElementById('darkenScreenObject');
	if (!dark) {
		// The dark layer doesn't exist, it's never been created.  So we'll
		// create it here and apply some basic styles.
		// If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
		var tbody = document.getElementsByTagName("body")[0];
		var tnode = document.createElement('div');           // Create the layer.
		tnode.style.position='absolute';                 // Position absolutely
		tnode.style.top='0px';                           // In the top
		tnode.style.left='0px';                          // Left corner of the page
		tnode.style.overflow='hidden';                   // Try to avoid making scroll bars
		tnode.style.display='none';                      // Start out Hidden
		tnode.id='darkenScreenObject';                   // Name it so we can find it later
		tbody.appendChild(tnode);                            // Add it to the web page
		dark=document.getElementById('darkenScreenObject');  // Get the object.
	}
	if (vis) {
		// Calculate the page width and height
		var pageWidth = _jstn_window_width+'px';
		var pageHeight = _jstn_window_height+'px';

		//set the shader to cover the entire page and make it visible.
		dark.style.opacity=opaque;
		dark.style.MozOpacity=opaque;
		dark.style.filter='alpha(opacity='+opacity+')';
		dark.style.zIndex=zindex;
		dark.style.backgroundColor=bgcolor;
		dark.style.width= pageWidth;
		dark.style.height= pageHeight;
		dark.style.display='block';
	} else {
		dark.style.display='none';
	}

}



var TimeToFade = 2000.0;
/*
Para que inicialmente no aparezca y haga un fade-in hay que establecer el valor de .FadeState a -2:
document.getElementById(eid).FadeState = -2;

La variable TimeToFade establece el número de milisegundos que tardará en producirse el efecto.

FadeState is one of 4 numbers: 2 means that the element is fully opaque, 1 means that the element is currently fading from transparent to opaque, -1 means that the element is currently fading from opaque to transparent, and -2 means that the element is fully transparent. If the FadeState property doesn't exist, we try and determine it from the state of the opacity css element.

If the FadeState is 1 or -1, it means that an animation is currently in progress.
*/

function jstn_fade(eid) {

	var element = document.getElementById(eid);

	if( element == null ) {
		return;
	}

	if( element.FadeState == null ) {
		if( element.style.opacity == null || element.style.opacity == '' || element.style.opacity == '1' ) {
			element.FadeState = 2;
		} else {
			element.FadeState = -2;
		}
	}

	if( element.FadeState == 1 || element.FadeState == -1 ) {
		element.FadeState = element.FadeState == 1 ? -1 : 1;
		element.FadeTimeLeft = TimeToFade - element.FadeTimeLeft;
	} else {
		element.FadeState = element.FadeState == 2 ? -1 : 1;
		element.FadeTimeLeft = TimeToFade;
		setTimeout("jstn_animateFade(" + new Date().getTime() + ",'" + eid + "')", 33);
	}

	return;

}


function jstn_animateFade(lastTick, eid) {

	var curTick = new Date().getTime();
	var elapsedTicks = curTick - lastTick;

	var element = document.getElementById(eid);

	if( element.FadeTimeLeft <= elapsedTicks ) {
		element.style.opacity = element.FadeState == 1 ? '1' : '0';
		element.style.filter = 'alpha(opacity = ' + (element.FadeState == 1 ? '100' : '0') + ')';
		element.FadeState = element.FadeState == 1 ? 2 : -2;
		return;
	}

	element.FadeTimeLeft -= elapsedTicks;
	var newOpVal = element.FadeTimeLeft/TimeToFade;
	if( element.FadeState == 1 ) {
		newOpVal = 1 - newOpVal;
	}

	element.style.opacity = newOpVal;
	element.style.filter = 'alpha(opacity = ' + (newOpVal*100) + ')';

	// ---
	if ( newOpVal < 0.15 ) {
		element.style.display = 'none';
		element.FadeState == -2;
	}

	setTimeout("jstn_animateFade(" + curTick + ",'" + eid + "')", 33);

}


function jstn_show_status(eid, timer, content) {
	if ( timer == '' ) {
		timer = 10;
	}
	TimeToFade = timer * 1000;
	obj = document.getElementById(eid);
	obj.style.display = 'block';
	obj.style.visibility = 'visible';
	obj.style.filter = 'alpha(opacity = 100)'; // IE
	obj.style.opacity = 1.0; // FF
	obj.FadeState = 2;
	obj.innerHTML = "<div title='Cerrar' style=\"float: right; cursor: pointer; font-weight: bold; color: #4444dd; \" onclick=\"jstn_fade('" + eid +"', " + TimeToFade + ")\">X</div>" + content;
	setTimeout("jstn_fade('" + eid + "')", TimeToFade);
	return;
}


function jstn_mostrar_tr(id) {
	if ( _jstn_browser_name == 'Explorer') {
		f_mostrar(id);
	} else {
		seccion = document.getElementById(id);
		seccion.style.visibility='visible';
		seccion.style.display='table-row';
	}
	return;
}


/*
<div id="st" onclick="jstn_switch('st');" style="position: absolute; top: 0px; left: 500px; background-color: #aaaaff; padding: 8px; width: 200px; visibility: hidden; display: none; cursor: pointer; "></div>
jstn_status_message('st', 'Documento guardado', 5);
*/

function jstn_status_message(eid, message, ttime) {
	ttime = ttime * 1000;
	document.getElementById(eid).innerHTML = message;
	jstn_switch(eid);
	if ( ttime > 0 ) {
		jstn_status_message_timer(eid, ttime);
	}
	return;
}


function jstn_status_message_timer(eid, ttime) {
	setTimeout("jstn_switch_off('"+ eid + "')", ttime);
	return;
}


/*
var _jstn_r_message = new Array();
_jstn_r_message[0] = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.";
_jstn_r_message[1] = "Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.";
var _jstn_now_showing = 0;
var _jstn_rotation_time = 5000;
*/

function jstn_content_rotation(eid, message_array, array_name) {
	if ( _jstn_rotation_time == 0 ) {
		_jstn_rotation_time = 10000;
	}
	num_r_messages = message_array.length;
	// nma = message_array.toSource(); // --- Crea nuevo array para poder pasar el parámetro en setTimeout
	_jstn_now_showing++;
	if ( _jstn_now_showing >= num_r_messages ) {
		_jstn_now_showing = 0;
	}
	// alert(_jstn_now_showing + ' : ' + message_array[_jstn_now_showing]);
	document.getElementById(eid).innerHTML = message_array[_jstn_now_showing];
	eval("com = \"jstn_content_rotation('"+ eid + "', " + array_name + ", '" + array_name + "')\"");
	// alert(com);
	setTimeout(com, _jstn_rotation_time);

	return;
}

// jstn_content_rotation('div_rotatorio', _jstn_r_message, '_jstn_r_message');


/*

.progress_container {
	width: 270px;
	height: 20px;
	border: 0px dotted red;
	margin-bottom: 0px;
	margin-top: 0px;
	z-index: 10;
}

.progress_border {
	float: left;
	background-color: #ffffff;
	border: 1px solid #555555;
	padding: 2px;
	width: 200px;
	height: 14px;
	text-align: left;
}

.progress_bar {
	float: left;
	height: 14px;
	background-color: #555555;
	text-align: left;
	width: 0px;
}

.progress_percentage {
	float: right;
	font-size: 1.1em;
	font-weight: bold;
	color: #555555;
}


<div class='progress_container'>
	<div class='progress_border'>
		<div id='pbar_1' class='progress_bar'>&nbsp;
		</div>
	</div>
	<div id='pper_1' class='progress_percentage'></div>
</div>

*/

function jstn_update_progress_bar(percentage, id_bar, id_percentage) {
	percentage_style = 2 * percentage; // --- Depends on the size of the bar. Here: 200px.
	percentage_style = percentage_style + 'px';
	html_percentage = percentage + "%";
	d_id_bar = document.getElementById(id_bar);
	d_id_bar.style.width = percentage_style;
	d_id_percentage = document.getElementById(id_percentage);
	d_id_percentage.innerHTML = html_percentage;
	return;
}


function jstn_check_box_checked(eid) {
	if ( document.getElementById(eid).checked == true ) {
		return true;
	} else {
		return false;
	}
	return false;
}



// --- AJAX ---------------------------------------------------------------------------------------------


function jstn_make_ajax_request(query, eid) {
	_jstn_ajax_dinamic_div = eid;
	_jstn_ajax_url = _jstn_ajax_server + '?' + query;
	jstn_update_dynamic_div(_jstn_ajax_wait_message);
	var httpRequest;

	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
		httpRequest = new XMLHttpRequest();
		if (httpRequest.overrideMimeType) {
			httpRequest.overrideMimeType('text/xml');
			// See note below about this line
		}
	} else if (window.ActiveXObject) { // IE
		try {
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!httpRequest) {
		alert('No se ha podido crear una instancia XMLHTTP');
		return false;
	}
	httpRequest.onreadystatechange = function() { jstn_alert_contents(httpRequest); };
	httpRequest.open('GET', _jstn_ajax_url, true);
	httpRequest.send(null);

}


function jstn_alert_contents(httpRequest) {

	if (httpRequest.readyState == 4) {
		if (httpRequest.status == 200) {
			// alert(httpRequest.responseText);
			jstn_update_dynamic_div(httpRequest.responseText);
		} else {
			alert('Ha habido un problema con la petición:\n' + _jstn_ajax_url + '\nEstatus respuesta: ' + httpRequest.status +'\nRespuesta: ' + httpRequest.responseText);
		}
	}

}


function jstn_update_dynamic_div(text) {
	// Firefox
	if ( document.getElementById ) {
		document.getElementById(_jstn_ajax_dinamic_div).innerHTML = text;
	// IE
	} else {
		document.all[_jstn_ajax_dinamic_div].innerHTML = text;
	}
	return;
}


var http_request = false;

function jstn_make_ajax_post_request(url, parameters, eid) {
	http_request = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			// set type accordingly to anticipated content type
			// http_request.overrideMimeType('text/xml');
			// http_request.overrideMimeType('text/html');
			// http_request.overrideMimeType('text/plain');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {}
			}
		}
		if (!http_request) {
		alert('No se ha podido crear una instancia XMLHTTP');
		return false;
	}

	// --- Escape de los parámetros para evitar error en Google Chrome
	/*
	parameters = encodeURI(parameters);
	parameters = escape(parameters);
	parameters=parameters.replace(/\+/g,"%2B");
	parameters=parameters.replace(/@/g,"%40");
	parameters=parameters.replace(/\./g,"%2E");
	parameters=parameters.replace(/-/g,"%2D");
	parameters=parameters.replace(/_/g,"%5F");
	parameters=parameters.replace(/ /g,"%20");
	parameters=parameters.replace(/\//g,"/");
	parameters = parameters.replace(/%26/g, "&");
	parameters = parameters.replace(/%3D/g, "=");
	parameters = parameters.replace(/&/g, "&amp;");
	alert(parameters);
	*/

	http_request.onreadystatechange = function() { jstn_devuelve_respuesta_post(eid) };
	http_request.open('POST', url, true);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.setRequestHeader("Content-length", parameters.length);
	// http_request.setRequestHeader("Connection", "close"); // --- El valor por defecto es Keep-alive y debe ser así.
	http_request.send(parameters);

	return;
}


function jstn_devuelve_respuesta_post(eid) {
	// resultado = 'debug = ' + http_request.readyState + ' / ' + http_request.status + ' / ' + http_request.responseText;
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			// alert(http_request.responseText);
			resultado = http_request.responseText;
			// document.getElementById(eid).innerHTML = resultado;
		} else {
			resultado = 'Ha habido un problema con la petición:\nEstatus respuesta:' + http_request.status + '\nRespuesta: ' + http_request.responseText;
		}
	}
	// alert('debug = ' + http_request.readyState + ' / ' + http_request.status + ' / ' + http_request.responseText);
	document.getElementById(eid).innerHTML = resultado;
	return;
}
