// JavaScript Document

var win=null;
	
	
	
	function sendForm(array_fields,rta_field){
		if($('#'+rta_field).css("display")=='block')return;
		$('#'+rta_field).html("Sending message...");
		$('#'+rta_field).css("display","block");
		var ajax = new MyAjax();
		ajax.handleResp=function(resp){
			$('#'+rta_field).html(resp);	
			$('#'+rta_field).fadeOut(6000,function(){$('#'+rta_field).css("display","none");});
		}
		var vars='opc=sendForm';
		for(var i=0; i<array_fields.length;i++){
			vars+= "&"+array_fields[i]+"_desc="+$('#'+array_fields[i]).attr('title');
			vars+= "&"+array_fields[i]+"="+$('#'+array_fields[i]).val();
		}
		ajax.doSyncRequest("_ajax.php","GET","text",vars);
		
	}
	
	
	
	
	function checkAdminExists(){
		var ajax = new MyAjax();
		var returnValue = false;
		ajax.handleResp=function(resp){
				if(resp == 1){
					alert("El nombre de usuario ingresado ya existe");
					returnValue =  false;
				}
				else{
					returnValue =  true;
				}
		}
		ajax.doSyncRequest("_ajax_submit.php","GET","text","opc=checkAdminExists&username="+document.getElementById('text_username').value+"&id="+document.getElementById('id').value);
		return returnValue;
	}
	
	
	function upload(content,file,svar,id,multiple,win,opc){
		if(multiple=='no'){
			opener.document.getElementById(content).innerHTML='';
		}
		var ajax = new MyAjax();
		ajax.handleResp=function(resp){
			if(resp!=''){
				//alert("RESP: "+resp);
				/*
				var li = document.createElement("LI");
				li.style.float='left';
				li.innerHTML = resp;
				opener.document.getElementById(content).appendChild(li);
				*/
				
				opener.document.getElementById(content).innerHTML+=resp;
				var inputs;
				var lis = opener.document.getElementById(content).getElementsByTagName("li");
				var maxHeight=0;
				for( i=0;i<lis.length;i++){
					maxHeight=parseInt(lis[i].offsetHeight)>maxHeight?parseInt(lis[i].offsetHeight):maxHeight;
				}
				for( i=0;i<lis.length;i++){
					lis[i].style.height=maxHeight+"px";
				}
				for( i=0;i<lis.length;i++){
					inputs = lis[i].getElementsByTagName("input");
					for(var j=0;j<inputs.length;j++){
						
						
						if(inputs[j].name.indexOf(content+"Epigrafe")!=-1){
							//alert(inputs[j].id);
							opener.document.getElementById("temp_"+inputs[j].id).value=inputs[j].value;
						}
						else if(inputs[j].name.indexOf(content+"Link")!=-1){
							//alert(inputs[j].id);
							opener.document.getElementById("temp_"+inputs[j].id).value=inputs[j].value;
						}
						
					}
					
				}
				opener.ordenarElementos(content);
			}	
		}
		ajax.doSyncRequest("_ajax.php","GET","text","opc="+opc+"&content="+content+"&archivo="+file+"&svar="+svar+"&idRegistro="+id);
		window.close();
	}

	function removeImage(content,svar,file,id,lng){
		var ajax = new MyAjax();
		var element = document.getElementById(id);
		var msg;
		ajax.handleResp=function(resp){
			element.parentNode.removeChild(element);
			ordenarElementos(content);	  
		}
		if(lng=='en'){
			msg="Drop image?";
		}
		else if(lng=='es'){
			msg="Eliminar imagen?";
		}
		if(confirm(msg)){
			ajax.doAsyncRequest("_ajax.php","GET","text","opc=removeImage&content="+content+"&archivo="+file+"&svar="+svar+"&id="+id);
		}
	}
	
	function removeFile(content,svar,file,id,lng){
		var ajax = new MyAjax();
		var element = document.getElementById(id);
		ajax.handleResp=function(resp){
			element.parentNode.removeChild(element);
			ordenarElementos(content);	  
		}
		if(lng=='en'){
			msg="Drop image?";
		}
		else if(lng=='es'){
			msg="Eliminar imagen?";
		}
		if(confirm(msg)){
			ajax.doAsyncRequest("_ajax.php","GET","text","opc=removeFile&content="+content+"&archivo="+file+"&svar="+svar+"&id="+id);
		}	
	}

	function accessDenyMsg(idioma){
		if(idioma=='en'){
			alert('Sorry. You must be logged in to access this content');
		}
		if(idioma=='es'){
			alert('Debe estar registrado para acceder a este contenido.');
		}
	}



	function popImage(imageURL,imageTitle){
		//prompt("",imageURL);return;	
		PositionX = 100;
		PositionY = 100;
		defaultWidth = 500;
		defaultHeight = 500;
		var AutoClose = true;
		if (parseInt(navigator.appVersion.charAt(0))>=4){
		var isNN=(navigator.appName=="Netscape")?1:0;
		var isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;}
		var optNN='scrollbars=yes,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY;
		var optIE='scrollbars=yes,width=150,height=100,left='+PositionX+',top='+PositionY;
		if (isNN){imgWin=window.open('about:blank','',optNN);}
		if (isIE){imgWin=window.open('about:blank','',optIE);}
		with (imgWin.document){
		writeln('<html><head><title>Cargando ...</title><style>body{margin:0px;}</style>');writeln('<sc'+'ript>');
		writeln('var isNN,isIE;');writeln('if (parseInt(navigator.appVersion.charAt(0))>=4){');
		writeln('isNN=(navigator.appName=="Netscape")?1:0;');writeln('isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;}');
		writeln('function reSizeToImage(){');writeln('if (isIE){');writeln('window.resizeTo(100,100);');
		writeln('width=100-(document.body.clientWidth-document.images[0].width);');
		writeln('height=100-(document.body.clientHeight-document.images[0].height);');
		writeln('window.resizeTo(width,height);}');writeln('if (isNN){');
		writeln('window.innerWidth=document.images["imagenes"].width;');writeln('window.innerHeight=document.images["imagenes"].height;}}');
		writeln('function doTitle(){document.title="'+imageTitle+'";}');writeln('</sc'+'ript>');
		if (!AutoClose) writeln('</head><body bgcolor=000000 scroll="no" onload="reSizeToImage();doTitle();self.focus()">')
		else writeln('</head><body bgcolor=ffffff scroll="no" onload="reSizeToImage();doTitle();self.focus()" onblur="self.close()">');
		writeln('<img name="imagenes" src='+imageURL+' style="display:block"></body></html>');
		close();
		}
	}

/***********************************************************************/
	
	<!-- Begin
	function emailCheck (emailStr) {
	/* The following pattern is used to check if the entered e-mail address
	   fits the user@domain format.  It also is used to separate the username
	   from the domain. */
	var emailPat=/^(.+)@(.+)$/
	/* The following string represents the pattern for matching all special
	   characters.  We don't want to allow special characters in the address. 
	   These characters include ( ) < > @ , ; : \ " . [ ]    */
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	/* The following string represents the range of characters allowed in a 
	   username or domainname.  It really states which chars aren't allowed. */
	var validChars="\[^\\s" + specialChars + "\]"
	/* The following pattern applies if the "user" is a quoted string (in
	   which case, there are no rules about which characters are allowed
	   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	   is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")"
	/* The following pattern applies for domains that are IP addresses,
	   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	   e-mail address. NOTE: The square brackets are required. */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	/* The following string represents an atom (basically a series of
	   non-special characters.) */
	var atom=validChars + '+'
	/* The following string represents one word in the typical username.
	   For example, in john.doe@somewhere.com, john and doe are words.
	   Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")"
	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	/* The following pattern describes the structure of a normal symbolic
	   domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
	
	
	/* Finally, let's start trying to figure out if the supplied address is
	   valid. */
	
	/* Begin with the coarse pattern to simply break up user@domain into
	   different pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
	  /* Too many/few @'s or something; basically, this address doesn't
		 even fit the general mould of a valid e-mail address. */
		//alert("Email address seems incorrect (check @ and .'s)")
		return false
	}
	var user=matchArray[1]
	var domain=matchArray[2]
	
	// See if "user" is valid 
	if (user.match(userPat)==null) {
		// user is not valid
		//alert("The username doesn't seem to be valid.")
		return false
	}
	
	/* if the e-mail address is at an IP address (as opposed to a symbolic
	   host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
		// this is an IP address
		  for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				//alert("Destination IP address is invalid!")
			return false
			}
		}
		return true
	}
	
	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		//alert("The domain name doesn't seem to be valid.")
		return false
	}
	
	/* domain name seems valid, but now make sure that it ends in a
	   three-letter word (like com, edu, gov) or a two-letter word,
	   representing country (uk, nl), and that there's a hostname preceding 
	   the domain or country. */
	
	/* Now we need to break up the domain to get a count of how many atoms
	   it consists of. */
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 || 
		domArr[domArr.length-1].length>3) {
	   // the address must end in a two letter or three letter word.
	   //alert("The address must end in a three-letter domain, or two letter country.")
	   return false
	}
	
	// Make sure there's a host name preceding the domain.
	if (len<2) {
	   var errStr="This address is missing a hostname!"
	   //alert(errStr)
	   return false
	}
	
	// If we've gotten this far, everything's valid!
	return true;
	}
	//  End -->
	
	
	function toggleRadio(rObj) {
		if (!rObj) return false;
		rObj.__chk = rObj.__chk ? rObj.checked = !rObj.__chk : rObj.checked;
	}
	
		
	function updateLista(lista,tabla,position_field,id_field,inicio){
		
	
		//Para explorer poner id y name en los elementos, ya que el
		//getElementsByName funciona solo con algunos tags. Pero si no puede
		//encontrar por name encuentra por id!
		var filas,listInputs,listNumbers,listIds,ids;
		var ajax = new MyAjax();
		filas=document.getElementsByName("listFila");
		listNumbers=document.getElementsByName("listNumber");
		listIds=document.getElementsByName("listId");
		ids=new Array();
		for(i=0;i<filas.length;i++){
			listNumbers[i].innerHTML=(i+1)+'.-'+'&nbsp;&nbsp;';
			ids.push(listIds[i].value);
			if(i==0 || i%2==0){
				filas[i].className="row";
				filas[i].onmouseout=function(){this.className='row';};
			}
			else{
				filas[i].className="row2";
				filas[i].onmouseout=function(){this.className='row2';};
			}
		}
		ajax = new MyAjax();
		//alert(ids.join(','));
		ajax.handleResp=function(resp){
		}
		
		var ieVer=/*@cc_on function(){ switch(@_jscript_version){ case 1.0:return 3; case 3.0:return 4; case 5.0:return 5; case 5.1:return 5; case 5.5:return 5.5; case 5.6:return 6; case 5.7:return 7; }}()||@*/0;
		if(document.all && ieVer<=6){
			ajax.doSyncRequest("_ajax.php","GET","text","opc=orderList&ids="+ids.join(',')+"&table="+tabla+"&id_field="+id_field+"&position_field="+position_field+"&inicio="+inicio);	
		}
		else{
			ajax.doAsyncRequest("_ajax.php","GET","text","opc=orderList&ids="+ids.join(',')+"&table="+tabla+"&id_field="+id_field+"&position_field="+position_field+"&inicio="+inicio);
		}
						
	}
	
	function checkDate(y,m,d){
	   y=document.getElementById(y);
	   m=document.getElementById(m);
	   d=document.getElementById(d);
	   if(m.value==2){
			if(y.value % 4==0){
				if(d.value>29){
					d.value=29;
				}
			}
			else{
				if(d.value>28){
				d.value=28;
				}
			}
	   }
	   else{
			if(m.value==4||m.vlaue==6||m.value==9||m.value==11){
				if(d.value>30){
					d.value=30;
				}
			}
	   }	 
	}	
	
	function open_window( name, page, params ) {
		window.open( page, 'window_' + name, params );
	}
	
	function textCounter(field,maxlimit,evento) {
		if(in_array(evento.keyCode)){
			return;	
		}
		if (field.value.length > maxlimit){ // if too long...trim it!
				cancelEvent(evento);
				field.value = field.value.substring(0, maxlimit);
				ex=new Array('8','46','37','38','39','40');
		}
	}		
	
	function open_window( name, page, params ) {
		var winUpload = window.open( page, 'window' + name, params );
		winUpload.focus();
	}

	function uploadFile(tipo,svar,idRegistro) {
		open_window( 'image', 'upload_file.php?svar='+svar+'&tipo='+tipo+'&idRegistro='+idRegistro, 'top='+(((window.availHeight-120)/2))+',left='+(((window.availWidth-500)/2))+', width=500, height=120, resizable=yes, scrollbars=yes, status=no' );
	}
	
	function uploadGaleria(tipo,svar,idRegistro) {
		open_window( 'image', 'upload_image.php?svar='+svar+'&tipo='+tipo+'&idRegistro='+idRegistro, 'top='+(((window.availHeight-120)/2))+',left='+(((window.availWidth-500)/2))+', width=500, height=120, resizable=yes, scrollbars=yes, status=no' );
	}
	
	function editRecord( id ) {
		document.form.method			= 'POST';
		document.form.exec.value		= 'edit';
		document.form.id.value			= id;
		document.form.submit();
	}
	
	function newRecord( ) {
		editRecord( 0 );
	}

	function changeStatus( id,table ) {
		var ajax = new MyAjax();
		ajax.handleResp=function(resp){
			if(resp=="1"){
				document.getElementById('status'+id).src='../img/admin/icon_on.gif';
			}
			else{
				document.getElementById('status'+id).src='../img/admin/icon_off.gif';
			}
		}
		ajax.doAsyncRequest('_ajax.php','GET','text','opc=changeStatus&id='+id+'&table='+table);
	}

	function changeHistoryStatus( id,table ) {
		var ajax = new MyAjax();
		ajax.handleResp=function(resp){
			if(resp=="1"){
				document.getElementById('history'+id).src='../img/admin/icon_history_on.gif';
			}
			else{
				document.getElementById('history'+id).src='../img/admin/icon_history_off.gif';
			}
		}
		ajax.doAsyncRequest('_ajax.php','GET','text','opc=changeHistoryStatus&id='+id+'&table='+table);
	}

	function changeHighlight( id,table ) {
		var ajax = new MyAjax();
		ajax.handleResp=function(resp){
			if(resp=="1"){
				document.getElementById('highlight'+id).src='../img/admin/icon_highlighted_on.gif';
			}
			else{
				document.getElementById('highlight'+id).src='../img/admin/icon_highlighted_off.gif';
			}
		}
		ajax.doAsyncRequest('_ajax.php','GET','text','opc=highlightItem&id='+id+'&table='+table);
	}
	
	function changeHighlightRed( id,table ) {
		var ajax = new MyAjax();
		ajax.handleResp=function(resp){
			if(resp=="1"){
				document.getElementById('highlightRed'+id).src='../img/admin/icon_highlighted_red_on.gif';
			}
			else{
				document.getElementById('highlightRed'+id).src='../img/admin/icon_highlighted_off.gif';
			}
		}
		ajax.doAsyncRequest('_ajax.php','GET','text','opc=highlightRed&id='+id+'&table='+table);
	}
	
	function setHome( id,table ) {
		var ajax = new MyAjax();
		ajax.handleResp=function(resp){
			if(resp=="off"){
				document.getElementById('home'+id).src='../img/admin/icon_highlighted_off.gif';
			}
			else{
				if(resp!=''){
					document.getElementById('home'+resp).src='../img/admin/icon_highlighted_off.gif';
				}
			}
		}
		if(document.getElementById('home'+id).src.indexOf('icon_highlighted_on.gif')!=-1){
			document.getElementById('home'+id).src='../img/admin/icon_highlighted_off.gif';
		}
		else{	
			document.getElementById('home'+id).src='../img/admin/icon_highlighted_on.gif';
		}
		ajax.doAsyncRequest('_ajax.php','GET','text','opc=setHome&id='+id+'&table='+table);				
	}
	
	function setPrincipal( id,table,filter_field,filter_value) {
		var ajax = new MyAjax();
		ajax.handleResp=function(resp){
			
			if(resp == "off"){
				document.getElementById('principal'+id).src='../img/admin/icon_highlighted_red_off.gif';
			}
			else{
				if(resp!=''){	
					document.getElementById('principal'+resp).src='../img/admin/icon_highlighted_red_off.gif';
				}
			}
		}
		if(document.getElementById('principal'+id).src.indexOf('icon_highlighted_red_on.gif')!=-1){
			document.getElementById('principal'+id).src='../img/admin/icon_highlighted_red_off.gif';
		}
		else{	
			document.getElementById('principal'+id).src='../img/admin/icon_highlighted_red_on.gif';
		}
		ajax.doSyncRequest('_ajax.php','GET','text','opc=setPrincipal&id='+id+'&table='+table+'&filter_field='+filter_field+'&filter_value='+filter_value);				
	}

	function confirmDrop( id, table, sortable,order_field, lng ) {
		var msg="";
		if(lng=="es"){
			msg = 'Est seguro que desea eliminar el contenido seleccionado?';	
		}
		else if(lng=='en'){
			msg = 'Do you really want to delete selected item?';	
		}
		if ( confirm( msg ) ) {
			var ajax = new MyAjax();
			ajax.handleResp=function(resp){
			}
			document.getElementById('lista').removeChild(document.getElementById('listFila'+id));
			ajax.doSyncRequest("_ajax.php","GET","text","opc=dropItem&table="+table+"&id="+id+"&sortable="+sortable+"&order_field="+order_field);				
			if(sortable){
				updateLista("lista",table,order_field,"id");
			}
		}
	}

	function acceptContent( ) {
		document.form.exec.value		= 'save';
		document.form.submit();
	}

	
	function cancelContent( ) {
		window.location=window.location;
	}

	function checkTextLength(l){
		aux=new String();
		aux=event.srcElement.value;
		if(aux.length>=l){
			event.returnValue=false;
		}
	}
	
	function checkForm(frm,arr){ //(formulario, array de excepciones)
		var aux="";
			for(var i=0;i<document.getElementById(frm).elements.length;i++){
       			if(document.getElementById(frm).elements[i].type == "password" || document.getElementById(frm).elements[i].type == "text" || document.getElementById(frm).elements[i].type == "select"  || document.getElementById(frm).elements[i].type == "textarea" || document.getElementById(frm).elements[i].type == "select-one" || document.getElementById(frm).elements[i].type == "select multiple"){
		       		if(!in_array(arr,document.getElementById(frm).elements[i].id)){ 
						//document.frmOp.elements[i].checked = true;
						if(document.getElementById(frm).elements[i].value==""){
							aux=aux+"\n"+document.getElementById(frm).elements[i].title;
						}
						else{
							if(document.getElementById(frm).elements[i].id.indexOf('email')!=-1){
								if(!emailCheck(document.getElementById(frm).elements[i].value)){
									aux=aux+"\n"+document.getElementById(frm).elements[i].title;
								}
							}	
						}
						
					}
				}	
		   }
		   if(aux!=""){
				aux="You must complete these fields:" + aux;
			   	alert(aux);
				return false;
		   }
		   else{
				return true;
		   }	
	}	
	
	function checkFormFields(frm,arr,idioma){ //(formulario, array de campos a validar)
			var aux="";
			for(var i=0;i<document.getElementById(frm).elements.length;i++){
       			if(document.getElementById(frm).elements[i].type == "hidden"  ||document.getElementById(frm).elements[i].type == "password" || document.getElementById(frm).elements[i].type == "text" || document.getElementById(frm).elements[i].type == "select"  || document.getElementById(frm).elements[i].type == "textarea" || document.getElementById(frm).elements[i].type == "select-one" || document.getElementById(frm).elements[i].type == "select multiple" || document.getElementById(frm).elements[i].type == "select-multiple"){
					if(in_array(arr,document.getElementById(frm).elements[i].id)){ 
						if(document.getElementById(frm).elements[i].value==""){
							aux=aux+"\n"+document.getElementById(frm).elements[i].title;
						}
						else{
							if(document.getElementById(frm).elements[i].id.toLowerCase().indexOf('email')!=-1){
								if(!emailCheck(document.getElementById(frm).elements[i].value)){
									aux=aux+"\n"+document.getElementById(frm).elements[i].title;
								}
							}	
						}
					}
					
				}	
		   }
		  
		   if(aux!=""){
				if(idioma=='es'){
					aux="Debe completar los siguientes campos:" + aux;
				}
				if(idioma=='en'){
					aux="You must complete these fields:" + aux;
				}
			   	alert(aux);
				return false;
		   }
		   else{
				return true;
		   }	
	}	

	function in_array(mat,field){
			var i;
			for(i=0;i<mat.length;i++){
				if(mat[i].toLowerCase()==field.toLowerCase()){
					return true;
				}	
			}
			return false;	
	}


	function eventTrigger (e) {
	    	if (! e) e = event;
		    return e.target || e.srcElement;
	}
		
	function cancelEvent(e){
			if(navigator.userAgent.indexOf("MSIE")!=-1){
				e.returnValue=0;	
			}
			if(navigator.userAgent.indexOf("Gecko")!=-1){
				e.preventDefault();	
			}
	}
	function validateExtensions(file,ext,evt){
		var auxext=new String(file);
		var extPosibles;
		for (var i=0;i<ext.length;i++){
			if(i==0){
				extPosibles=ext[i];
			}
			else{
				extPosibles += ","+ext[i];
			}
		}
		auxext=auxext.substring(auxext.lastIndexOf('.')+1);
		if(!in_array(ext,auxext)){
			alert ("Slo se admiten las siguientes extensiones: \n"+extPosibles);
			cancelEvent(evt);	
		}
		else{
			return true;	
		}
	
	}
	
	function getMicrotime(){
		var ajax = new MyAjax();
		var micro = "";
		ajax.handleResp=function(resp){
			micro = resp;
		}
		ajax.doSyncRequest("_ajax.php","GET","text",'opc=getMicrotime');
		return micro;
	}
	
	function addAjaxForm(table,content){
		var ajax = new MyAjax();
		ajax.handleResp=function(resp){
			
			var auxdiv = document.createElement("DIV");
			//auxdiv.id = getMicrotime();
			//auxdiv.style.border = "1px dashed #CCCCCC";
			auxdiv.style.cssFloat = "left";
			//auxdiv.style.width = "230px";
			//auxdiv.style.padding = "10px";
			auxdiv.innerHTML=resp;
			
			document.getElementById(content).appendChild(auxdiv);
			//document.getElementById('<? echo $content;?>').innerHTML+='<div id="<? echo $micro?>" style="border: 1px dashed #CCC; width:230px; float:left; padding:10px">'+'<? echo $contenido?>'+'</div>';
		}
		ajax.doSyncRequest("_ajax.php","GET","text",'opc=ajaxForm&table='+table+'&content='+content);	
	}
	
	function deleteAjaxForm(idAjax,idRegistro,tabla){
		var ajax = new MyAjax();
		document.getElementById(idAjax).parentNode.removeChild(document.getElementById(idAjax));
		ajax.handleResp=function(resp){
			//document.getElementById(layer).innerHTML=resp;
		}
		ajax.doAsyncRequest("_ajax.php","GET","text",'opc=deleteAjaxForm&idRegistro='+idRegistro+'&tabla='+tabla);	
	}
	
	function loadAjaxCombo(sourceCombo,targetCombo,table,idField,descField,orderField,value,target_selected_value) {
		var combo = document.getElementById(targetCombo);
		combo.length=0;
		combo.options[combo.length]=new Option("Loading...",""); // AGREGO AL COMBO UN NUEVO ITEM
		var resp;
		if(window.ActiveXObject){
			resp = new ActiveXObject("Microsoft.XMLDOM"); 
			resp.async = false; 
			resp.load("_ajax_on_change.php?opc=loadComboIds&table="+table+"&idField="+idField+"&descField="+descField+'&orderField='+orderField+'&sourceField='+sourceCombo+'&value='+value); 
		}
		else{
			var ajax = new MyAjax();
			ajax.handleResp=function(rta){
				resp = rta;
			}
			ajax.doSyncRequest("_ajax_on_change.php","GET","xml","opc=loadComboIds&table="+table+"&idField="+idField+"&descField="+descField+'&orderField='+orderField+'&sourceField='+sourceCombo+'&value='+value);
		}
		combo.length=0;
		if(targetCombo.indexOf('filtro_')!=-1){
				combo.options[combo.length]=new Option("-Sin especificar-",""); // AGREGO AL COMBO UN NUEVO ITEM
		}
		for (i = 0; i < resp.getElementsByTagName('item').length; i++){ //RECORRO LOS TAGS "item" DEL XML
			var elemento = resp.getElementsByTagName('item')[i]; //OBTENGO EL TAG "item" actual
			var texto = elemento.getElementsByTagName('text')[0].firstChild.data; //OBTENGO EL VALOR DEL TAG "text" DENTRO DEL TAG "item" ACTUAL
			var id = elemento.getElementsByTagName('id')[0].firstChild.data; //OBTENGO EL VALOR DEL TAG "id" DENTRO DEL TAG "item" ACTUAL
			combo.options[combo.length]=new Option(texto,id); // AGREGO AL COMBO UN NUEVO ITEM
			if(id == target_selected_value){
				combo.options[i].selected=true;	
			}
		}
		
	}	



//-------------------------GRILLA DE PROPIEDADES------------------------------------------------------
	function changeProperties(layer,table_properties,field_properties,id){
		var ajax = new MyAjax();
		ajax.handleResp=function(resp){
			document.getElementById(layer).innerHTML=resp;
		}
		ajax.doAsyncRequest("_ajax.php","GET","text",'opc=changeProperties&layer='+layer+'&table_properties='+table_properties+'&propertiesField='+field_properties+'&id='+id);	
	}
	
	function updatePropertyString(listID,chainID){
		var list = document.getElementById(listID);
		var chain= document.getElementById(chainID);
		var strValues='';
		for(var i=0; i<list.options.length; i++){
				strValues += (strValues == ''?'':',') + list.options[i].value;
		}
		chain.value=strValues;
	}
	
	
	function updateProperty(listID,editorID,chainID,table,lng,id){
		
		var list = document.getElementById(listID);
		var editor = document.getElementById(editorID);
		if(list.selectedIndex < 0)return;
		var originalValue = list.options[list.selectedIndex].value;
		var newValue = editor.value;
		var chain= document.getElementById(chainID);
		list.options[list.selectedIndex].value=newValue;
		list.options[list.selectedIndex].text=newValue;
		editor.value='';
		list.selectedIndex=-1;
		updatePropertyString(listID,chainID);
		var ajax = new MyAjax();
		ajax.handleResp=function(resp){
		}
		ajax.doAsyncRequest("_ajax.php","GET","text",'opc=updateProperty&table='+table+'&old='+originalValue+'&new='+newValue+'&lng='+lng);
		if(parseInt(id) >0 ){
			ajax.doAsyncRequest("_ajax.php","GET","text",'opc=updatePropertyString&table='+table+'&propertyString='+chain.value+'&id='+id);
		}
		
	}
	function deleteProperty(listID,editorID,chainID,table,lng,id){
		var list = document.getElementById(listID);
		var editor = document.getElementById(editorID);
		var chain = document.getElementById(chainID);
		var originalValue = list.options[list.selectedIndex].value;
		if(list.selectedIndex >= 0 ){
			var rta=confirm("Desea eliminar el elemento seleccionado?");
			if(rta){
				list.remove(list.selectedIndex);
				updatePropertyString(listID,chainID);
				if(parseInt(id) >0 ){
					var ajax = new MyAjax();
					ajax.handleResp=function(resp){
					}
					ajax.doSyncRequest("_ajax.php","GET","text",'opc=updatePropertyString&table='+table+'&propertyString='+chain.value+'&id='+id);
					ajax.doSyncRequest("_ajax.php","GET","text",'opc=deleteProperty&table='+table+'&propertyString='+chain.value+'&value='+originalValue+'&id='+id);
				}
				editor.value='';
			}
		}
	}
	
	function addProperty(listID,editorID,chainID,table,lng){
		var list = document.getElementById(listID);
		var editor = document.getElementById(editorID);
		if(editor.value=='' )return;
		var chain= document.getElementById(chainID);
		var newItem = editor.value;
		var exists=false
		for(var i=0; i<list.options.length; i++){
			if(list.options[i].value == newItem){
				exists=true;	
				break;
			}
		}
		if(!exists){
			var opt= new Option(newItem,newItem);
			var listLength = list.length;
			list.options[listLength] = opt;
			updatePropertyString(listID,chainID);
		}
	}
	function upProperty(listID,chainID){
		var list = document.getElementById(listID);
		var chain = document.getElementById(chainID);
		var auxValue;
		if(list.selectedIndex > 0 ){
			auxValue=list.options[list.selectedIndex - 1].value;
			list.options[list.selectedIndex - 1].value = list.options[list.selectedIndex].value;
			list.options[list.selectedIndex - 1].text  = list.options[list.selectedIndex].text;
			list.options[list.selectedIndex].value = auxValue;
			list.options[list.selectedIndex].text = auxValue;
			list.selectedIndex=list.selectedIndex-1;
		}
		updatePropertyString(listID,chainID);
	}
	function downProperty(listID,chainID){
		var list = document.getElementById(listID);
		var chain = document.getElementById(chainID);
		var auxValue;
		if(list.selectedIndex < (list.options.length -1) ){
			auxValue=list.options[list.selectedIndex + 1].value;
			list.options[list.selectedIndex + 1].value = list.options[list.selectedIndex].value;
			list.options[list.selectedIndex + 1].text  = list.options[list.selectedIndex].text;
			list.options[list.selectedIndex].value = auxValue;
			list.options[list.selectedIndex].text = auxValue;
			list.selectedIndex=list.selectedIndex + 1;
		}
		updatePropertyString(listID,chainID);
	}
//--------------------------*******************-------------------------------------------------------
//------------------------ORDENAMIENTO DE IMAGENES Y ARCHIVOS-------------------------------------------
	function ordenarElementos(lista,elemento,dir){
		
		lista=document.getElementById(lista);
		var elements = lista.getElementsByTagName('li');
		var pos=0;
		if(elemento!='' && elemento!=null){
			elemento=document.getElementById(elemento);
			for(var i=0;i<elements.length;i++){
				if(elements[i].id==elemento.id){
					pos=i;
					break;
				}
			}
			if(dir=='last'){
				lista.removeChild(elemento);
				//lista.appendChild(elemento);
				lista.insertBefore(elemento, null);
			}
			if(dir=='first'){
				if(elements.length>0){
					if(pos>0){
						lista.removeChild(elemento);
						lista.insertBefore(elemento, elements[0]);
					}
				}
			}
			if(dir=='up'){
				if(elements.length>0){
					var anterior;
					if(pos>0){
						for(var i=0;i<elements.length;i++){
							if(i==pos-1){
								anterior=elements[i];
								break;
							}	
						}
						lista.removeChild(elemento);
						lista.insertBefore(elemento,anterior);
					}
				}
			}	
			if(dir=='down'){
				if(elements.length>0){
					var siguiente;
					
					if(pos<elements.length-1){
						for(var i=0;i<elements.length;i++){
							if(i==pos+1){
								siguiente=elements[i];
								break;
							}
						}
						lista.removeChild(elemento);
						lista.insertBefore(elemento,siguiente.nextSibling);
					}
				}
			}
		}
		elements = lista.getElementsByTagName('li');
		
		for(var i=0;i<elements.length;i++){
			if(i==0){
				var botonera=document.getElementById('botonera_'+elements[i].id);
				botones=botonera.getElementsByTagName("img");
				botones[0].style.visibility='hidden';
				botones[1].style.visibility='hidden';
				botones[3].style.visibility='visible';
				botones[4].style.visibility='visible';
			}
			else if(i==elements.length-1){
				
				var botonera=document.getElementById('botonera_'+elements[i].id);
				botones=botonera.getElementsByTagName("img");
				botones[0].style.visibility='visible';
				botones[1].style.visibility='visible';
				botones[3].style.visibility='hidden';
				botones[4].style.visibility='hidden';
			}
			else{
				var botonera=document.getElementById('botonera_'+elements[i].id);
				botones=botonera.getElementsByTagName("img");
				botones[0].style.visibility='visible';
				botones[1].style.visibility='visible';
				botones[3].style.visibility='visible';
				botones[4].style.visibility='visible';
			}
		}	
		if( elements.length==1){
			var botonera=document.getElementById('botonera_'+elements[0].id);
			botones=botonera.getElementsByTagName("img");
			botones[0].style.visibility='hidden';
			botones[1].style.visibility='hidden';
			botones[3].style.visibility='hidden';
			botones[4].style.visibility='hidden';
		}
		
		var maxHeight=0;
		for(var i=0;i<elements.length;i++){
			maxHeight=parseInt(elements[i].offsetHeight)>maxHeight?parseInt(elements[i].offsetHeight):maxHeight;
		}
		for(var i=0;i<elements.length;i++){
			elements[i].style.height=maxHeight+"px";
		}
			
	}

	//SELECTS MULTIPLES
	function swapItems(idOrigen,idDestino,accion){
		var origen=document.getElementById(idOrigen);
		var destino=document.getElementById(idDestino);
		var selected=Array();
		var alreadySelectedValues=Array();

		for(var i=0;i<destino.options.length;i++){
			alreadySelectedValues.push(destino.options[i].value);	
		}
		
		while(origen.selectedIndex!=-1){
			if(!in_array(alreadySelectedValues,origen.options[origen.selectedIndex].value)){
				selected.push(origen.selectedIndex);
			}
			origen.options[origen.selectedIndex].selected=false;
		}

		for(var i=0;i<selected.length;i++){
		//while(origen.selectedIndex!=-1){
			var opt=document.createElement("OPTION");
			opt.text=trim(origen.options[selected[i]].text);
			opt.value=origen.options[selected[i]].value;
			if(opt.value=='')return;
			try {
				destino.add(opt, null); // standards compliant; doesn't work in IE	
			}
			catch(ex) {
				destino.add(opt); // IE only
			}
			origen.options[selected[i]].style.color='#CCC';
			//origen.remove(origen.selectedIndex);
		}
		if(accion == 'actualizar'){
			for(var i=0;i<origen.length;i++){
				var opt=document.createElement("OPTION");
				opt.text=trim(origen.options[i].text);
				opt.value=origen.options[i].value;
				if(in_array(alreadySelectedValues,opt.value)){
					origen.options[i].style.color='#CCC';
				}
			}
		}
	
		/*
		//Ordenar items
		for(var i=0;i<(destino.length-1);i++){
			for(var j=i+1;j<destino.length;j++){
				if(destino.options[i].text>destino.options[j].text){
					var texto=destino.options[i].text;
					var valor=destino.options[i].value;
					destino.options[i].text=trim(destino.options[j].text);
					destino.options[i].value=destino.options[j].value;
					destino.options[j].text=trim(texto);
					destino.options[j].value=valor;
				}
			}
		}
		*/
	}
	
	function restoreItems(idOrigen,idDestino){
		
		var origen=document.getElementById(idOrigen);
		var destino=document.getElementById(idDestino);
		
		if(origen.selectedIndex==-1)return;
		
		var selectedValues=Array();
		var unselectedValues=Array();
		var unselectedText=Array();

		
		for (var i=0 ; i < origen.options.length ; i++) {
			
			if (origen.options[i].selected==true) {
				selectedValues.push(origen.options[i].value);
			}
			else{
				unselectedValues.push(origen.options[i].value);
				unselectedText.push(origen.options[i].text);
			}
		}
		origen.length=0;
		for(var i =0; i< unselectedValues.length ; i++){
			addItem(unselectedText[i],idOrigen,unselectedValues[i]);
		}
		
		for(var i=0;i<destino.options.length;i++){
			if(in_array(selectedValues,destino.options[i].value)){
				destino.options[i].style.color='#000';
			}
		}
		for(var i=0;i<(origen.length-1);i++){
			for(var j=i+1;j<origen.length;j++){
				if(origen.options[i].text>origen.options[j].text){
					var texto=origen.options[i].text;
					var valor=origen.options[i].value;
					origen.options[i].text=origen.options[j].text;
					origen.options[i].value=origen.options[j].value;
					origen.options[j].text=texto;
					origen.options[j].value=valor;
				}
			}
		}
	}
	

	function addItem(text,lista,value){
		if(text!=''){	
			lista=document.getElementById(lista);
			for(var i=0;i<lista.length;i++){
				if(lista.options[i].text==text){
					return;
				}
			}
			var opt = document.createElement("OPTION");
			opt.text=text;
			opt.value=value;
			try {
					lista.add(opt, null); // standards compliant; doesn't work in IE	
				}
				catch(ex) {
					lista.add(opt); // IE only
			}
		}
	}
	
	function removeItem(lista){
		lista=document.getElementById(lista);
		while(lista.selectedIndex!=-1){
			lista.remove(lista.selectedIndex);
		}
	}
	
	function selectAllItems(combo){
		var lista=document.getElementById(combo);
		for(var i=0;i<lista.length;i++){
			var opt=lista.options[i];
			opt.selected=true;
		}
	}
	function trim(cadena){
		for(i=0; i<cadena.length; ){
			if(cadena.charAt(i)==" ")
				cadena=cadena.substring(i+1, cadena.length);
			else
				break;
		}
	
		for(i=cadena.length-1; i>=0; i=cadena.length-1){
			if(cadena.charAt(i)==" ")
				cadena=cadena.substring(0,i);
			else
				break;
		}
		
		return cadena;
	}
		



