// CONTACTOS[0][0] NUMERO DE MOVIL
// CONTACTOS[1][0] ID DE CHECKBOX
var contactos=new Array('numero','idChk');
contactos[0]=new Array();
contactos[1]=new Array();
var reporte='';
var actual='';
var http_request = false;
var cambiando=false;
var eliminando=false;
var inSelAll=false;
var phpResult;
var choice=1;
var numeroExtra;
var contador;
var restantes=140;

// BOOLEANO DE TILDAR, si esta en false el checkbox se desactiva
// si esta en true, se activa, si esta en null, cambia el estado
var dialogOpen = false;
var timeleft=20,tout=0,tries=0;
function counter(idioma)
{
	try
	{
		timeleft = timeleft==0 ? 20 : --timeleft;
		if(timeleft==0) 
			tries++;
		if(timeleft==20) 
			$('#welcome1').find('.retry').show(); 
		$('#welcome1').find('.timeleft').text(timeleft);
		tout = setTimeout("counter('"+idioma+"')",1000);
		if(timeleft==1)
			$.post('/'+idioma+'/json/state','',function(r){
				if(r.exception){clearTimeout(tout);jsonException(r.exception);return;}
				if(r.estado){clearTimeout(tout);$('#popup').html(r.html);return;}
				if(tries==0){clearTimeout(tout);$('#popup').html(r.html);return;}				
		 },'json');
	}catch(e){alert(e.message)}
}
function retry(idioma,form)
{
	try
	{
		var str = 'pin='+form.pin.value;
				str+= '&tlf='+form.tlf.value;
		form.submit.disabled = true;
		$.post('/'+idioma+'/json/pin',str,function(r){
			if(r.exception){jsonException(r.exception);return;}
			if(r.redirect){alert(r.message);redirect(r.redirect);return;}
			if(r.message){jsonException(r.message);form.submit.disabled = false;}			
		},'json');
	}catch(e){alert(e.message);}
}
function hideError()
{
	try
	{
		document.getElementById('alert_error').style.display = 'none';
	}catch(e){}
}
function validate(idioma)
{
	try
	{
		if(!$('#mask').length) return;
		$('#mask').css('position','absolute');
		var maskHeight = $(document).height();
		var maskWidth  = $(document).width();
		$('#mask').css({'width':maskWidth,'height':maskHeight});
		$('#mask').css('z-index',1);
		$('#mask').css('left','0px');
		$('#mask').css('background-color','#333');
		$('#mask').css('filter','alpha(opacity=50)');
		$('#mask').css('-moz-opacity',.40);
		$('#mask').css('opacity',.40);
		$('#popup').css('display','block');
		$('#popup').css('z-index', 99);
		$('#popup').css('position','absolute');
		var contPos = $('#content').position();
		$('#popup').css('left',contPos.left+'px');
		$('#alert_error').css('z-index',9999);		
		counter(idioma);
		window.onresize = this.winresize; 
	}catch(e){}
}
function winresize()
{
	var maskHeight=$(document).height();
	var maskWidth=$(document).width();
	$('#mask').css({'width':maskWidth,'height':maskHeight});
	var contPos = $('#content').position();
	$('#popup').css('position','absolute');
	$('#popup').css('left',contPos.left+'px');
}
function redirect(url)
{
	if(!url) url = document.location;
	document.location.href = url;
}
function abrirAyuda(lang){
	try{
		var ui = $('.ui-dialog')
		if(ui.css('display')=='none')
		{
			ui.show();
			return;
		}		
		if(ui.css('display')=='block')	
			return;
		var obj = $('#help');	
				obj.css('display','block');	
				obj.dialog({draggable: true,height:350,width:500,resizable: false,show:'slide',hide:'slide'});	
		var o  = $('.ui-dialog-titlebar-close');o.css('margin-left','470px');
	}catch(e){
		var o  = $('.ui-dialog-titlebar-close');o.css('margin-left','470px');	
	}
}
function reloadCaptcha(lang,id)
{
	try
	{
		if(!id)	id = 'captcha';
		var obj = $('#'+id);
			obj.attr('src','/'+lang+'/captcha?r='+Math.random());
	}catch(e){alert(e.message);}
}
function addfriend(){
	try
	{
		
	}
	catch(e)
	{
		alert(e.message);
	}
}
function openConversacion(lang,element)
{
	try
	{
		var obj = $(element);
		var tlf = parseInt(obj.attr('id').split('tlf_')[1]);
		if(isNaN(tlf))
			return;
		str = 'tlf='+parseInt(tlf);
		$("#chat_contact").html('<div id="preloader" align="center" style="padding-top:20px;"><img src="'+basepath+'/img/loading.gif" /></div>');
		$.post('/'+lang+'/json/conversacion',str,function(response){
			if(response.exception)
			{
				$("#chat_contact").text('');
				jsonException(response.exception);
				return;
			}
			$('.user').find('img').attr('src',basepath+'/img/contactos_gris.png');
			obj.find('img').attr('src',basepath+'/img/contactos_verde.png');								
			$("#chat_contact").html(response.html);
			$("#chat_phone").text(' - '+parseInt(tlf));}
		,'json');
	}catch(e){}
}
function showpass(span){try{var el  = $(span);el.text(el.attr('code'));}catch(e){alert(e.message);}}
function hidepass(span){try{var el = $(span);el.text('**********');}catch(e){alert(e.message);}
}
function changePerfil(lang,form){
	form.perfilbtt.disabled = true;
	var str  = 'pass='+form.password.value;
			str += '&repeat='+form.repeat.value;
	$("#perfil").find('.topreloader').html('<div id="preloader"><img src="'+basepath+'/img/loading.gif" /></div>');
	$.post('/'+lang+'/json/perfil',str,function(response){
		if(response.exception){
			form.perfilbtt.disabled = false;
			$("#perfil").find('#preloader').remove();
			jsonException(response.exception);return;
		}		
		if(response.msg)
		{
			$('#txt_error_new').find('.error_2').html(response.msg);						
		}else
		{
			$('#txt_error_new').find('.error_2').html('');							
		}
		$('#txt_error_new').find('.oops').html(response.title);	
		$('#alert_error').css('display','block');
		$("#perfil").html(response.html);}
	,'json');
}
function jsonException(message)
{
	try
	{
		$('#txt_error_new').find('.oops').html(message);
		$('#alert_error').css('display','block');
		var wwidth = $(window).width();
		var	awidth = $('#alert_error').width();
		var left   = (wwidth	- awidth)/2;
		$('#alert_error').css('left',left+'px');
	}catch(e){}
}

function setmessage(id)
{
	try
	{
		var msg = $('#message_'+parseInt(id));
			msg = msg.length ? msg.attr('value') : '';
		var obj = $('#message');
			obj.val(msg);
	}
	catch(e)
	{
		//alert(e.message);
	}
}
function respuestaoptin(checkbox)
{
	try
	{
		var cbox = $(checkbox);
		var on   = cbox.attr('checked') ? 1 : 0;
		$.post('/json/respuestaoption','on='+on,function(r){
			if(r.exception){
				jsonException(r.message);
			}
			if(r.message){
				jsonException(r.message);
				$('.error_2').text('');
			}						
		},'json');
	}catch(e)
	{
		//alert(e.message);
	}
}
var emails = 0;
function addemail()
{
	try
	{
		if(emails==2) return;		
		emails++;		
		var o = $('#friendsemail');
		var html = o.html();
		while(html.indexOf('fnombre[0]')!=-1)
			html = html.replace('fnombre[0]','fnombre['+emails+']');
		while(html.indexOf('femail[0]')!=-1)
			html = html.replace('femail[0]','femail['+emails+']');
		while(html.indexOf('ftipo[0]')!=-1)
			html = html.replace('ftipo[0]','ftipo['+emails+']');			
		html = '<table id="friendsemail" class="fe_'+emails+'">'+html+'</table>';
		o.after(html);
		var el = $('.fe_'+emails);
			el.find('.last').after('<a href="javascript:delemail('+emails+')">Eliminar</a>');	
			el.find('.errors').remove();
		
	}
	catch(e)
	{
		alert(e.message);
	}
}
function delemail(i){try{emails--;var tb = $('.fe_'+i);tb.remove();}catch(e){/*alert(e.message);*/}}
function sendtofriend_front(form,idioma)
{
	try
	{
		var o = $('#sendto');
		var b = o.find('.submit_pin2');
			b.after('<img src="'+basepath+'/img/loading.gif" alt="Loading" id="preloader_friend" />');
			o.find('.errors').remove();
		var params = formToStr(form);
		$.post('/'+idioma+'/json/enviaramigo',params,function(r){
			$('#preloader_friend').remove();
			if(r.exception)
			{
				alert(r.exception);
				return;
			}
			if(r.errores)
			{
				for(var i = 0;i<r.errores.length;i++)
				{
					var el = o.find('#'+r.errores[i].id);
					/** patch **/
					if(!el.length)
					{
						el  = $(document.getElementById(r.errores[i].id));											
					}
					el.after('<p class="errors">'+r.errores[i].label+'</p>');					
				}
				return;
			}
			o.html(r.html);
		},'json');
	}
	catch(e)
	{
		alert(e.message);
	}
}
function sendtofriend(form,idioma)
{
	return;
}

function formToStr(form)
{
	try
	{
		var values = new Array();
		for(var i = 0;i<form.elements.length;i++)
		{
			var str = '';
			if(!form.elements[i].name) continue;
			if(form.elements[i].type=='submit')	continue;
			if(form.elements[i].type=='checkbox')
			{
				value = form.elements[i].checked ? 1 : 0;
			} 
			if(form.elements[i].type=='radio')
			{
				if(form.elements[i].checked)
				{
					value = form.elements[i].value;								
				}
				else
					continue;				
			}
			else
			{
				value = form.elements[i].value;				
			}
			str += form.elements[i].name;
			str += '=';
			str += value;		
			values.push(str);	
		}		
		return values.join('&');
	}
	catch(e)
	{
		return values.join('&');
	}	
}


var bTildar=null;
function cambiaVal(id,valor){
	document.getElementById(id).value=valor;	
}
function color(id){
	if(contador <= 3){
		contador++;
		document.getElementById(id).style.background="#EBA300";
		setTimeout("color('"+id+"')",500);
	} else {
		document.getElementById(id).style.background="#FFF";
	}
}
function marcar(id){
	document.getElementById(id).focus();
	contador=0;
	setTimeout("color('"+id+"')",1);
}
function agregar(numero){
	if(inArray(numero,contactos[0])===false){
		contactos[0].push(numero);
		contactos[1].push('');
	}
	verificarSeleccion();
}
function cambia(nombre,numero,idContacto){
	var cNombre=document.getElementById('nnombre');
	var cNumero=document.getElementById('nnumero');
	contacto=idContacto;
	cNombre.value=nombre;
	cNumero.value=numero;
}
function limitar(){
	var obj=document.getElementById('envio');
	if(obj.value.length > restantes){
		obj.value = obj.value.substring(0, restantes); 
	}
	setTimeout('limitar()',10);
}
function llenaSelect(){
	var select=document.getElementById("select");
	var combito = document.getElementById("select");
	combito.innerHTML='';
	for(var i=0;i<contactos[0].length;i++){
		combito.options[i] = null;
	}
	for(var i=0;i<contactos[0].length;i++){
		var opcion=document.createElement('option');;
		opcion.appendChild(document.createTextNode(contactos[0][i]));
		opcion.setAttribute("id","contacto_" + i);
		combito.appendChild( opcion );
	}
	if(combito.length==0){
		oculta('div_quitar');
	}	
}
function nExtra(){
	var numero=document.getElementById("inputNExtra").value;
	numeroExtra=numero;
	var poststr = "numero=" + numero +
			"&metodo=cnumero";
	choice=2;
	makePOSTRequest("/phpjs/funciones", poststr);
}

function mostrarMensaje(id){
	if(!document.getElementById('mensaje_' + id)) return false;
	document.getElementById('content_chat').style.display='block';
	document.getElementById('div_mensaje').innerHTML=document.getElementById('mensaje_' + id).value;
}

function modifica(){
	var poststr = "nombre=" + document.getElementById("nnombre").value +
		"&numero=" + document.getElementById("nnumero").value + 
		"&idContacto=" + contacto + "&enviaform=edcontacto";
	makePOSTRequest('/phpjs/contactos', poststr);
}
function olvido(){
  var poststr = "numero=" + document.getElementById('onumero').value +
		"&email=" + document.getElementById('oemail').value +
		"&enviaform=olvido";
	choice=3;
  makePOSTRequest("/phpjs/perfil", poststr);
}

function quitar(numero){
	pos=inArray(numero,contactos[0]);
	contactos[0].splice(pos,1);
	idChk=contactos[1][pos];
	contactos[1].splice(pos,1);
	if(idChk!=''){
		bTildar=false;
		tildar(idChk);
	}
	verificarSeleccion();
}
function sacar(){
	quitar(document.getElementById("select").value);
}
function tildar(idChk){
	var i;
	var para=document.getElementById('para');
	var chk=document.getElementById(idChk);
	if(chk){
		if(bTildar != null){
			chk.checked=bTildar;
		} else {
			chk.checked= !chk.checked;
		}
		bTildar=null;
	}
}
var marked_row = new Array;
//window.onload=seleccionaFilas;
function seleccionaFilas() {
    var rows = document.getElementsByTagName('tr');
    for ( var i = 0; i < rows.length; i++ ) {
        if (rows[i].className.indexOf('fila')==-1) {
            continue;
        }
        if ( navigator.appName == 'Microsoft Internet Explorer' ) {
            // but only for IE, other browsers are handled by :hover in css
            rows[i].onmouseover = function() {
                this.className += ' hover';
            }
            rows[i].onmouseout = function() {
                this.className = this.className.replace( ' hover', '' );
            }
        }
        rows[i].onmousedown = function() {
			if(eliminando){
				eliminando=false;
				return;
			}
			var unique_id;
            var checkbox;
            checkbox = this.getElementsByTagName( 'input' )[0];
            if ( checkbox && checkbox.type == 'checkbox' ) {
                unique_id = checkbox.name + checkbox.value;
            } else if ( this.id.length > 0 ) {
                unique_id = this.id;
            } else {
                return;
            }
            if ( typeof(marked_row[unique_id]) == 'undefined' || !marked_row[unique_id]) {
                marked_row[unique_id] = true;
            } else {
                marked_row[unique_id] = false;
            }
			if(marked_row[unique_id]){
				agregar(checkbox.value);
			}else {
				quitar(checkbox.value);
			}
            if ( marked_row[unique_id] ) {
				if(this.className.indexOf('marked')==-1){
					this.className += ' marked';
				}
            } else {
                this.className = this.className.replace(' marked', '');
            }
            if ( checkbox && checkbox.disabled == false ) {
                checkbox.checked = marked_row[unique_id];
            }
        }
        var checkbox = rows[i].getElementsByTagName('input')[0];
        if ( checkbox ) {
            checkbox.onclick = function() {
                this.checked = ! this.checked;
            }
        }
    }
	verificarSeleccion();
}
function seleccionarTodo(){
	var tab=document.getElementsByTagName('table');
	var valor=document.getElementById('selagenda').checked;
	inSelAll=true;
	for(var i=0;i<tab.length;i++){
		if(tab[i].id=='tabla_agenda'){
			inputs=tab[i].getElementsByTagName('input');
			for(var j=0;j<inputs.length;j++){
				if(inputs[j].type=="checkbox"){
					inputs[j].checked=valor;
					pos=inArray(inputs[j].value,contactos[0]);
					if(valor==true){
						if(pos===false){
							contactos[0].push(inputs[j].value);
							contactos[1].push('');
						}
					} else {
						contactos[0].splice(pos,1);
						contactos[1].splice(pos,1);
					}
				}
				bTildar=valor;
				tildar(inputs[j].id);
			}
		}
	}
	inSelAll=false;
	verificarSeleccion();
}
function verificarSeleccion(){
	var tab=document.getElementsByTagName('table');
	var selAgenda=document.getElementById('selagenda');
	if(!selAgenda){
		return;
	}
	var valor=true;
	var para=document.getElementById('para');
	var paso=false;
 	// RECORRE LA TABLA
	for(var i=0;i<tab.length;i++){
		// SI EL ID DE LA TABLA ES LA AGENDA
		if(tab[i].id=='tabla_agenda'){
			var rows = document.getElementsByTagName('tr');
			// RECORRE TODAS LAS FILAS
			for ( var j = 0; j < rows.length; j++ ) {
				// TOMA LOS INPUTS DE LA FILA
				inputs=rows[j].getElementsByTagName('input');
				// RECORRE TODOS LOS INPUTS
				for(var k=0;k<inputs.length;k++){
					pos=inArray(inputs[k].value,contactos[0]);
					if(inputs[k].type=="checkbox"){
						// SI ENCUENTRA EL VALOR EN ALGUNO DE LOS ARREGLOS
						// LO PONE EN CHECKED
						if(pos !== false){
							inputs[k].checked=true;
							contactos[1][pos]=inputs[k].id;
						}
						paso=true;
						if(inputs[k].checked==false){
							valor=false;
						}
						// SI LA CLASE DE LA FILA CONTIENE FILA
						if (!rows[j].className.indexOf('fila')) {
							// Y EL CHECKBOX NO ESTA EN FALSE
							if (inputs[k].checked===true) {
								// LES AGREGA A LA CLASE marked
								if(rows[j].className.indexOf('marked')==-1){
									rows[j].className += ' marked';
								}
							} else {
								rows[j].className = rows[j].className.replace(' marked', '');
							}
						}
					}
				}
			}
		}
	}
	if(paso){
		selAgenda.checked=valor;
	} else {
		selAgenda.checked=false;
	}
	para.value=contactos[0].join(";");
	llenaSelect();
	reporte="";
	for(i=0;i<contactos[0].length;i++){
		reporte+=contactos[0][i] + "	";
		reporte+=contactos[1][i] + "	";
		reporte+="\n";
	}
}
function intercambiar(){
	choice=4;
	makePOSTRequest("/phpjs/display","tpl=login");
}

/* FUNCIONES GLOBALES */
function alertContents() {
  if (http_request.readyState == 4) {
	 if (http_request.status == 200) {
		result = http_request.responseText;
		switch(choice){
			case 1:
				document.getElementById('agenda').innerHTML = result;
				seleccionaFilas();
				pn.init();
				break;
			case 2:
				if(result==1){
					document.getElementById('content_panel').innerHTML ='';
					agregar(numeroExtra);
				} else {
					document.getElementById('content_panel').innerHTML = '<div id="panel_error">' + result + '</div>';
				}
				numero='';
				break;
			case 3:
				document.getElementById('borde_ingreso').innerHTML = result;
				seleccionaFilas();
				break;
			case 4:
				document.getElementById('modulo_right').innerHTML = result;
				break;
			default:
				document.getElementById('panel_historial').innerHTML = result;
				show(1);
				seleccionaFilas();
				pn.init();
			break;
		}
		choice=1;
	 } else {
		alert('Ocurrio un problema con la peticion.');
	 }
  }
}

function contarPalabras(id,obj){
	try{
		limitar();
		texto = document.getElementById(id).value;
		numeroCaracteres = texto.length;
		primerBlanco = /^ /;
		ultimoBlanco = / $/;
		variosBlancos = /[ ]+/g;
		texto = texto.replace (primerBlanco,"");
		texto = texto.replace (ultimoBlanco,"");
		texto = texto.replace (variosBlancos," ");
		textoTroceado = texto.split (texto, " ");
		numeroPalabras = textoTroceado.length;
		document.getElementById(obj).innerHTML = '<strong>'+numeroCaracteres + " / " + restantes+'</strong>';
	}catch(e){ alert(e.message); }
}
function elimina(idContacto,nombre){
	if(confirm('�Esta seguro de eliminar al contacto "' + nombre +'"?')){
	  var poststr = "idContacto=" + idContacto +
					"&enviaform=econtacto";
		choice=1;
	  makePOSTRequest("/phpjs/contactos", poststr);
	}
}
function eliminaVacios(pajar){
	var i;
	var retorna='';
	for(i=0;i<pajar.length;i++){
		if(trim(pajar[i])!=''){
			if(retorna==''){
				retorna=pajar[i];
			} else {
				retorna=retorna + ";" + pajar[i];
			}
		}
	}
	return retorna.split(";");
}
function send(obj,formResponse) {
	var i,poststr='';
	for(i=0;i<obj.length;i++){
		if(obj[i].type.toLowerCase() == 'submit'){
			var formulario=obj[i].name;
			poststr+='&' + obj[i].id + "=" + obj[i].name;
		} else {
			poststr+='&' + obj[i].id + "=" + obj[i].value;
		}
	}
	switch(formulario){
		case 'ncontacto':
			break;
		case 'econtacto':
			choice=1;
			break;
		case 'olvido':
			choice=3;
			break;
	}
	makePOSTRequest(formResponse, poststr);
}

function inArray(aguja,pajar){
	var j;
	for(j=0;j<=pajar.length;j++)	{
		if(aguja==pajar[j] && aguja!=''){
			return j;
		}
	}
	return false;
}
function ltrim(s) {
   return s.replace(/^\s+/, "");
}
function makePOSTRequest(url, parameters) {
  http_request = false;
  if (window.XMLHttpRequest) { // Mozilla, Safari,...
	 http_request = new XMLHttpRequest();
	 if (http_request.overrideMimeType) {
		http_request.overrideMimeType('text/html');
	 }
  } 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('Cannot create XMLHTTP instance');
	 return false;
  }
  http_request.onreadystatechange = alertContents;
  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");
  http_request.send(parameters);
}
function muestra(id){
	document.getElementById(id).style.display = 'block';
}
function oculta(id){
	document.getElementById(id).style.display = 'none';
}
function rtrim(s) {
   return s.replace(/\s+$/, "");
}
function show(id){
	if(document.getElementById('link'+id).style.display != 'block' )
		document.getElementById('link'+id).style.display = 'block';
	else 
		document.getElementById('link'+id).style.display = 'none';
}
function trim(s) {
   return rtrim(ltrim(s));
}
