//Function for Ajax
function NewAjax()
{
	var xmlhttp=false
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP")
	} catch (e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
		} catch (E) {
			xmlhttp = false
		}
	}
 
	if (!xmlhttp && typeof XMLHttpRequest!='undefined')
	{
		xmlhttp = new XMLHttpRequest()
	}
	return xmlhttp
}

function addToFavorites(r_url, name){
   if ((navigator.appName=="Microsoft Internet Explorer") && (parseInt(navigator.appVersion)>=4)) {
      window.external.AddFavorite(r_url,name);
   }
   else {
      if(navigator.appName == "Netscape")
        window.sidebar.addPanel(name,r_url,'');

   }
}

function ActiveUser() {  
		var ajax = NewAjax();
		//$('OnLine_Users').innerHTML = "";
		ajax.open("GET", "/ajax_files/active_users.php?type=load" , true);  
		ajax.onreadystatechange=function()
		{
			if (ajax.readyState==4)
			{
					// si la información es válida   
				if (ajax.responseText.indexOf('invalid') == -1)   
				{   
					// Buscamos la div con id online   
					$('OnLine_Users').innerHTML = ajax.responseText;  
				}  
				else {  
					// Por si hay algun error   
					$('OnLine_Users').innerHTML = "Error llamando";  
				} 
			}
		}
		ajax.send(null)
	}  

	function UnactiveUser() { 
		var ajax = NewAjax();
		ajax.open("GET", "/ajax_files/active_users.php?type=unload", true);  
		ajax.send(null)
	} 

function addEvent(obj, evType, fn)
{ 
	if (obj.addEventListener)
	{ 
		obj.addEventListener(evType, fn, false); 
		return true; 
	} else if (obj.attachEvent)
	{ 
		var r = obj.attachEvent("on"+evType, fn); 
		return r; 
	} else { 
		return false; 
	} 
}

function LogIn(r_url){
	
	var ajax = NewAjax();
	var username = '';
	var password = '';
	var show = '';
	if($('username'))
	username = $('username').value;
	if($('password'))
	password = $('password').value;
	if($('show'))
	show = $('show').value;
	
	ajax.open("POST",'/ajax_files/users_login.php?username='+username+'&password='+password+'&show='+show,true)
	ajax.onreadystatechange=function()
	{
		if (ajax.readyState==4)
		{
			var ok = ajax.responseText
			if (ok == 'Y')
			{
				$('invalid_login').style.display = '';
				$('invalid_login').innerHTML = "Los datos de accesso son invalidos.";
			}
			else
			{
				if (r_url != "")
					goToUrl(r_url);
				else
					goToUrl('/index.php');
			}
		}
		else
		{
			$('invalid_login').innerHTML = "<center><img src='/media/images/loader.gif'><br><font color='#666666'></center>";
		}
	}
	ajax.send(null)
	
}

function remindPassword(){
	
	var ajax = NewAjax();
	var username = '';
	var show = '';
	if($('username'))
	username = $('username').value;
	if($('show'))
	show = $('show').value;
	
	ajax.open("POST",'/ajax_files/users_login.php?username='+username+'&show='+show,true)
	ajax.onreadystatechange=function()
	{
		if (ajax.readyState==4)
		{
			var ok = ajax.responseText
			$('remind').innerHTML = ok
		}
		else
		{
			$('remind').innerHTML = "<center><img src='/media/images/loader.gif'><br><font color='#666666'></center>";
		}
	}
	ajax.send(null)
	
}


function data_verification(inForm)
{
	if(($('c_name').value == "") || ($('c_email').value == "") || ($('c_subject').value == "") || ($('c_message').value == ""))
	{
		$('c_data_verif').style.display = '';
	}
	else
	{
		$('action').value = 'send';
		$('c_data_verif').style.display = 'none';
		$(inForm).submit();
	}	
}

function openPage(targetURL){
		window.open(targetURL);

}

//Ir a una pagin especifica
function goToUrl(targetURL)
{
	window.location=targetURL
}

//mostrar o ocultar una etiqueta div
function show_div (div_name)
{
	if($(div_name).style.display == '') 
	{
		$(div_name).style.display = 'none';
	} 
	else 
	{
		$(div_name).style.display = '';
	}

}

function isEmail(email, warning) 
{
	$(email).value = $(email).value.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
	var result = false; 
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test($(email).value)) 
		result= true;
if (result == false)
$(email+'_verif').style.display = '';
else
$(email+'_verif').style.display = 'none';

}

//funcion para verificar los caracteres
function specialCharacters(the_event)
{
	/*var numbers = "0123456789";
	var characters = " abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ¡!¿?()";
	var numbers_characters = numbers + characters;*/

	// 8 = BackSpace, 46 = Supr, 37 = flecha izquierda, 39 = flecha derecha, 38= flecha arriba, 40= flecha abajo
	var special_keys = [8, 46, 37, 39, 38, 40];
	
	// Seleccionar los caracteres a partir del parámetro de la función
 /* switch(permited) {
    case 'num':
      permited = numbers;
      break;
    case 'char':
      permited = characters;
      break;
    case 'num_char':
      permited = numbers_characters;
      break;
  }*/

  
 // Obtener la tecla pulsada 
  var eve = the_event || window.event;
  var character_code = eve.charCode || eve.keyCode;
 // var character = String.fromCharCode(character_code);
 
  // Comprobar si la tecla pulsada es alguna de las teclas especiales
  // (teclas de borrado y flechas horizontales)
  var special_key = false;
  for(var i in special_keys) {
    if(character_code == special_keys[i]) {
      special_key = true;
      break;
    }
  }


/*if (permited.indexOf(character) != -1)
special_key = true*/

return special_key;

}
//funcion para eliminar el espacion doble
function removeDoubleSpace(text_id)
{
	var CharArray=$(text_id).value.split('');
	if ((CharArray[CharArray.length -1] == " ")&&(CharArray[CharArray.length -1] == CharArray[CharArray.length -2]))
		$(text_id).value = $(text_id).value.substring(0,$(text_id).value.length-1);
}
//funcion para quitar espacion en blanco en el inicio 
function removeIniSpace(text_id)
{
  $(text_id).value = $(text_id).value.replace(/^\s+/,'');
}
//remover todos los espacion
function removeSpaces(text_id)
{
	removeIniSpace(text_id);
 	removeDoubleSpace(text_id);
}
//funcion para limitar el tamaño de caracteres en campo de texto
function charactersLimit(text_id, limit_id, limit, the_event) 
{
  removeSpaces(text_id);  
  if (specialCharacters(the_event) == false)
  {
	if($(text_id).value.length >= limit ) {
			return false;
		}
		else {
			$(limit_id).innerHTML = (limit - $(text_id).value.length)+" caracteres restantes.";
			return true;
		}
	
  }
}

//funcion para limitar la cantidad de palabras en un campo de texto
function wordsLimit(text_id, limit_id, limit, the_event) 
{
 removeSpaces(text_id);
	var words = $(text_id).value.split(' ');

if (specialCharacters(the_event) == false)
  {
	  if(words.length > limit ) {
		return false;
	  }
	  else {
		   $(limit_id).innerHTML = (limit - words.length)+" palabras restantes.";
		return true;
	  }
  }
}

//grabar informacion en el panel de administracion
function save_admin_data (inForm)
{
	if($('action').value == 'show')
		$('action').value = 'edit';
	if($('action').value == '')
		$('action').value = 'new';
	
	$(inForm).submit();
}

function delete_admin_data (inForm)
{
	if($('action').value == 'show')
	{
		$('action').value = 'delete';
		$(inForm).submit();
	}
	else
		alert('Debe escoger una opcion si desea eliminar.');
}

function search_admin_data (inForm)
{
	if($('search_param').value == '')
		alert('Debe digitar el parametro a buscar.');
	else
	{
		$('action').value = 'search';
		$(inForm).submit();
	}
	
}

function showImage(url,name, imgwidth, imgheight )
{
	
	if (!url.startsWith('http://')) 
	{
		url = 'http://' + url;
	}
	
	var popIt = new PopIt(url, 
	{
		title: name,
		isUrl: true,
		width: (imgwidth+20),
		height: (imgheight+30),
		isModal: true,
		isDraggable: false,
		isResizable: false,
		className: 'bluePopIt'
	});
	popIt.updateStatusText(name);
}

function showList()
{
	
	list_tit = $('list_title').value;
	popIt = new PopIt($('list').innerHTML, 
	{
		title: list_tit,
		height: 400,
		width: 600, 
		isModal: true,
		isDraggable: false,
		isResizable: false,
		className: 'bluePopIt'
	});
	popIt.updateStatusText(list_tit);
}

function stars_sel(star_num)
{
	for(i=1;i<=star_num;i++)
	{
		$(i+'star').style.background =' url(/media/images/star.png) center';
		$(i+'star').style.width = '32px';
		$(i+'star').style.height= '32px';
	}
}
function stars_unsel(star_num)
{
	for(i=1;i<=star_num;i++)
	{
		$(i+'star').style.background =' url(/media/images/star2.png) center';
	}
}

function verifyValues(elements)
{	
	var sw = 0;
	
	element = elements.split(',');
	for(i=0;i< element.length ;i++)
	{
		element[i] = element[i].replace(" ","");
		if (($(element[i]).type == 'text') || ($(element[i]).type == 'textarea') || ($(element[i]).type == 'select-one'))
		{
			if ($(element[i]).value == "")
			{
				$(element[i]+"_warning").style.display = '';
				sw = 1;
			}
			else
			{
				$(element[i]+"_warning").style.display = 'none';
			}
		}
		if ($(element[i]).type == 'checkbox')
		{
			checks = $('admin_form').getInputs('checkbox', element[i]); 
			check_name = element[i];
			check_name = check_name.replace('[]','');
			checked = 0;
			x = 0;
			while((checked == 0) && (x<checks.length))
			{
			   if (checks[x].checked){
				  checked = 1;
			   }
			   x++;
			}
			if (checked == 0)
			{
				$(check_name+"_warning").style.display = '';
				sw =1;
			}
			else
			{
				$(check_name+"_warning").style.display = 'none';
			}	
			
		}
		
		if (($('action').value != 'show') && ($(element[i]).type == 'file'))
		{
			if ($(element[i]).value == "")
			{
				$(element[i]+"_warning").style.display = '';
				sw = 1;
			}
			else
			{
				$(element[i]+"_warning").style.display = 'none';
			}				
		}
	}
	if (sw == 0)
		save_admin_data('admin_form');
}

function verifyValuesSingle(elements, inForm)
{	
	var sw = 0;
	
	element = elements.split(',');
	for(i=0;i< element.length ;i++)
	{
		element[i] = element[i].replace(" ","");
		if (($(element[i]).type == 'text') || ($(element[i]).type == 'textarea') || ($(element[i]).type == 'select-one'))
		{
			if ($(element[i]).value == "")
			{
				$(element[i]+"_warning").style.display = '';
				sw = 1;
			}
			else
			{
				$(element[i]+"_warning").style.display = 'none';
			}
		}
		if ($(element[i]).type == 'checkbox')
		{
			checks = $('admin_form').getInputs('checkbox', element[i]); 
			check_name = element[i];
			check_name = check_name.replace('[]','');
			checked = 0;
			x = 0;
			while((checked == 0) && (x<checks.length))
			{
			   if (checks[x].checked){
				  checked = 1;
			   }
			   x++;
			}
			if (checked == 0)
			{
				$(check_name+"_warning").style.display = '';
				sw =1;
			}
			else
			{
				$(check_name+"_warning").style.display = 'none';
			}	
			
		}
		
		
	}
	if (sw == 0)
		$(inForm).submit();
}

function showCategoriesGroups(module_id)
{
	
	var checks = $('admin_form').getInputs('checkbox', 'category_id[]'); 
	var checked_list;
	for (var x=0;x<checks.length;x++){
	   if (checks[x].checked){
		  if (checked_list == null)
		  	checked_list = checks[x].value;
		  else
		  	checked_list = checked_list+','+checks[x].value;
	   }
	}
	
	if(checked_list == null)
		$('selected_categories').innerHTML = "Debe seleccionar una categoria.";
	else
	{
		var ajax = NewAjax();
		url = '../../ajax_files/show_categories_groups.php?module_id='+module_id+'&category_id='+checked_list;

		ajax.open("POST", url,true)
		ajax.onreadystatechange=function()
		{
	
			if (ajax.readyState==4)
			{
				var ok = ajax.responseText
				$('selected_categories').innerHTML = ok
			}
			else
			{
				$('selected_categories').innerHTML = "<center><img src='/media/images/loader.gif'><br><font color='#666666'></center>";
			}
		}
		ajax.send(null)
	}
}

function showUrl(url,name)
{
	if (!url.startsWith('http://')) 
	{
		url = 'http://' + url;
	}
	
	var popIt = new PopIt(url, 
	{
		title: name,
		isUrl: true,
		width: 400,
		height: 200,
		isDraggable: false,
		isResizable: true,
		isModal: true,
		className: 'bluePopIt'
	});
	popIt.updateStatusText(name);
}

function showUrl_size(url,name,width,height)
{
	if (!url.startsWith('http://')) 
	{
		url = 'http://' + url;
	}
	
	var popIt = new PopIt(url, 
	{
		title: name,
		isUrl: true,
		width: width,
		height: height,
		isDraggable: false,
		isResizable: true,
		isModal: true,
		className: 'bluePopIt'
	});
	popIt.updateStatusText(name);
}

function getKeyCode(e){
	e= (window.event)? event : e;
	intKey = (e.keyCode)? e.keyCode: e.charCode;
	return intKey;
}

function enterLogIn(e, r_url){
	if (getKeyCode(e) == 13) 
		LogIn(r_url);
}

function htmlentities (string, quote_style) {
    // Convert all applicable characters to HTML entities  
    // 
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/htmlentities    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: nobbler
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // -    depends on: get_html_translation_table
    // *     example 1: htmlentities('Kevin & van Zonneveld');    // *     returns 1: 'Kevin &amp; van Zonneveld'
    // *     example 2: htmlentities("foo'bar","ENT_QUOTES");
    // *     returns 2: 'foo&#039;bar'
    var hash_map = {},
        symbol = '',        tmp_str = '',
        entity = '';
    tmp_str = string.toString();
 
    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {        return false;
    }
    hash_map["'"] = '&#039;';
    for (symbol in hash_map) {
        entity = hash_map[symbol];        tmp_str = tmp_str.split(symbol).join(entity);
    }
 
    return tmp_str;
}

function get_html_translation_table (table, quote_style) {
    // Returns the internal translation table used by htmlspecialchars and htmlentities  
    // 
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/get_html_translation_table    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // +   bugfixed by: Alex
    // +   bugfixed by: Marco    // +   bugfixed by: madipta
    // +   improved by: KELAN
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Frank Forte    // +   bugfixed by: T.Wild
    // +      input by: Ratheous
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js, meaning the constants are not
    // %          note: real constants, but strings instead. Integers are also supported if someone    // %          note: chooses to create the constants themselves.
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    var entities = {},
        hash_map = {},        decimal = 0,
        symbol = '';
    var constMappingTable = {},
        constMappingQuoteStyle = {};
    var useTable = {},        useQuoteStyle = {};
 
    // Translate arguments
    constMappingTable[0] = 'HTML_SPECIALCHARS';
    constMappingTable[1] = 'HTML_ENTITIES';    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
 
    useTable = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';
 
    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: " + useTable + ' not supported');
        // return false;   
	}
 
    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {
        entities['160'] = '&nbsp;';        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';
        entities['165'] = '&yen;';        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';
        entities['170'] = '&ordf;';        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';
        entities['175'] = '&macr;';        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';
        entities['180'] = '&acute;';        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';
        entities['185'] = '&sup1;';        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';
        entities['190'] = '&frac34;';        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';
        entities['195'] = '&Atilde;';        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';
        entities['200'] = '&Egrave;';        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';
        entities['205'] = '&Iacute;';        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';
        entities['210'] = '&Ograve;';        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';
        entities['215'] = '&times;';        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';
        entities['220'] = '&Uuml;';        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';
        entities['225'] = '&aacute;';        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';
        entities['230'] = '&aelig;';        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';
        entities['235'] = '&euml;';        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';
        entities['240'] = '&eth;';        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';
        entities['245'] = '&otilde;';        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';
        entities['250'] = '&uacute;';        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';
        entities['255'] = '&yuml;';    }
 
    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;'; 
 
    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);        hash_map[symbol] = entities[decimal];
    }
 
    return hash_map;
}

