if(typeof MY_DOM_FILE == 'undefined'){
	alert('error de desarrollo. Esta libreria (my_utils) necesita my_dom.js');
}
if(! document.getElementsByClassName ){
	alert('err(7s2PCfsKs); Error de desarrollo. Esta libreria necesita prototype.js');
}
if(typeof MY_UTILS_FILE == 'undefined'){
	MY_UTILS_FILE = 1;
}else{
	alert('error de desarrollo. Se carga 2 veces el mismo archivo: MY_UTILS.js');
}

/*Globales miscelaneas ... */

var tableDnD = false;//automaton para ordenar tablas

var sort_message_is_active = false;

function fn_GetBrowser(){

	var strBrowser;

	if(navigator.appName.indexOf("Netscape") >= 0){
		if(navigator.appName.indexOf("Opera") >= 0 ){
			strBrowser = 'opera';
		}else{
			strBrowser = 'mozilla';
		}
	}else if(navigator.appName.indexOf("Opera") >= 0){
		strBrowser = 'opera';
	}else{
		if( navigator.appName.indexOf("Microsoft") >= 0 ){
			if( parseInt(navigator.appVersion) >= 4){
				strBrowser = 'iexporer';
			}else if( parseInt(navigator.appVersion) < 4){
				strBrowser = 'iexporer-old';
			}
		}else{
			strBrowser = 'unknow';
		}
	}
	return strBrowser;

} 

function checkThisOrNot(tagId, myBool){
    $(tagId).value = (myBool)? 1:0;

}


function setAllCheckBoxes(FormName, FieldName, CheckValue){
	if(!document.forms[FormName]){
                alert('err(4000623523');
		return;
        }
	var objCheckBoxes = document.forms[FormName].elements[FieldName];
	if(!objCheckBoxes){
                alert('err(o400w0623523');
		return;
        }
	var countCheckBoxes = objCheckBoxes.length;
	if(!countCheckBoxes){
		objCheckBoxes.checked = CheckValue;
	}else{
		// set the check value for all check boxes
		for(var i = 0; i < countCheckBoxes; i++){
			objCheckBoxes[i].checked = CheckValue;
                }
        }
}

function loadMyImage(image){
    if(!browser.isIE){
        return;
    }
    var img = document.createElement('IMG');

    img.src=image;

    var divy = document.createElement('DIV');

    divy.id = 'Uxd'+ Math.random();

    divy.appendChild(img);

    document.getElementsByTagName('BODY')[0].appendChild(divy)

    divy.style.display='none';

}



function markUnMarkCheckBoxs(formy_x, checkbox_name){

	var chck_box_boss = document[formy_x][checkbox_name + '_boss'];
	if(!chck_box_boss){
		alert('JS error: 4342434543543 '+"\n"+ 'cant find "_boss" element ');
		return
	}

	var cbGroup = document[formy_x][checkbox_name];
	if(!cbGroup){
		alert('JS error: 434243234143')
		return;
	}

	var checkbox_quantity = cbGroup.length;

// 	alert(checkbox_quantity);

	if(checkbox_quantity > 0)	{
		for (i = 0; i < checkbox_quantity; i++){
			cbGroup[i].checked = chck_box_boss.checked;
		}
	} else {
		cbGroup.checked = chck_box_boss.checked;
	}
}

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

function readCookie(name_of){
  var ca = document.cookie.split(';');
  var nameEQ = name_of + "=";
  for(var i=0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
    	if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
  return null;
}
// para identificar al browser
createCookie('browser_identifier', fn_GetBrowser());

//

function setChecked (formul,tag, is_true){
	if(is_true==0){
		tag.value=1;
	}else{
		tag.value=0;
	}
	tag.checked=true;
	document[formul].submit();
}

function add_session(formy){
	formy.session.value = session;
}
	






function addEvent(obj, evType, fn){
// funca asi: addEvent(objectToAddEvent, 'event sin el on', 'funcion'); o sea, en ejemplos: (window, 'load', code);

 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 parseArgs(args) {

  var AO = new Object();
  var AA = args.split("&");
  var TA = new Array();
  for (var i=0; i<AA.length; i++) {
    TA = AA[ i ].split("=");
    AO[ TA[0] ] = unescape( TA[1] );
  }
  return AO;
}

function convertHashToGet(argObj){
	var cnct = '';

	for(var key in argObj){
		cnct +='&amp;'+ key +'='+ escape(argObj[key]);
	}
	return cnct;
} 
	
function be_back_new_args (element_for_concate) {
		//alert('correcto: ' + window.location.protocol+window.location.hostname+window.location.pathname+'?'+element_for_concate );

		window.location = window.location.protocol+'//'+window.location.hostname+window.location.pathname+'?' + element_for_concate;
}

function goto_url (element_for_concate) {
	window.location = window.location.protocol+'//'+
		window.location.hostname +':'+ window.location.port+
		'/' + window.location.pathname.split('/')[1] +'\/'+
		window.location.pathname.split('/')[2] +'\/'+
		element_for_concate;
}
function goto_here_preserving_args (element_for_concate) {
		window.location =window.location.href +'&' + element_for_concate;
}
function reindex_selected (selObj, element_id){
	if (!selObj){
		alert('error err(U6234Jfs)   '+ element_id);
		return ;
	}
	if(!selObj.nodeName){
	   alert('error err(U7234Jfs)   ' + selObj +'   '+ element_id);
	   return ;
	}
	for(var ii = 0; ii < selObj.options.length; ii++){
		if(selObj.options[ii].value == element_id) {
			selObj.options[ii].selected= true;
// 			alert('si!');
		}
// 		alert(selObj.options[ii].value + ' ' + element_id);
	}
// 	alert(element_id + selObj.name);
}

function reindex_radio (selObj, element_id){
	if (!selObj){
		alert('error err(U62R44Jfs)   '+ element_id);
		return ;
	}

	for(var ii = 0; ii < selObj.length; ii++){
//         alert('aaaaaaaaa: ' + $selObj.value);
		if(selObj[ii].value == element_id) {
			selObj[ii].checked= true;
// 			alert('si!');
		}
// 		alert(selObj.options[ii].value + ' ' + element_id);
	}
// 	alert(element_id + selObj.name);
}

function convert_checkbox_bool_behavior (the_form ) {

		//alert (the_form.value + ' - ' + the_form.name + ' --> '+ the_form.length);
	for(var ia = 0; ia < the_form.length; ia++){
		if(the_form[ia].type == 'checkbox'){
		// alert('existe 1');
			if(the_form[ia].checked== false){
			//       alert('existe 2' );
				the_form[ia].checked= true;
				the_form[ia].value = the_form[ia].value + '_';
			}
		}
	}
}

function change_color_of (elem, color_entrada) {
    elem.style.backgroundColor=color_entrada;

}


var blinkPE = false;

var blinkNow = false;

var currentBlink = false;

var blinkCount = 0;

function blinkator (){
    if(!blinkNow){ return};
    var domObj = $(blinkNow);
    if(!domObj){
        alert('No hay un objeto para hacerle blinks. Decia que el id era: '+ tagId);
        if(blinkPE){
            clearInterval(blinkPE);
        }
        return;
    }
    if(blinkCount < 68){
        if ( ( blinkCount % 2 ) != 0){
            domObj.style.border='1px solid #cf1c1c';
        }else{
            domObj.style.border='1px solid #e35a07';
        }

    }else{
        clearInterval(blinkPE);
        var borderStyle = domObj.getAttribute('beforeBlink');
        if(borderStyle){
            domObj.style.border= borderStyle;
        }else{

            domObj.style.border='none';
        }

    }
    blinkCount++;
}

function blink_block (tagId){
    var domObj = $(tagId);
    if(!domObj){
        alert('No hay un objeto para hacerle blinks. Decia que el id era: '+ tagId);
        return;
    }
    if(blinkPE){
        clearInterval(blinkPE);
        var borderStyle = domObj.getAttribute('beforeBlink');
        if(borderStyle){
            domObj.style.border= borderStyle;
        }else{

            domObj.style.border='none';
        }
    }
    blinkNow = tagId;
    blinkCount = 0;

    var prev = domObj.style.border;
    if (prev){ domObj.setAttribute('beforeBlink', prev) };

    blinkPE = setInterval(blinkator, 10);

//     blinkMe.domObjs
}

function Popup(url,name,width,height,resize,scroll) {
var dialogWin = new Object();
dialogWin.width = width;
dialogWin.height = height;
now = new Date();
var millis=now.getTime();
var mstr=""+millis;
if (navigator.appName == "Netscape") {
dialogWin.left = window.screenX + ((window.outerWidth - dialogWin.width) / 2);
dialogWin.top = window.screenY + ((window.outerHeight - dialogWin.height) / 2);
var attr = 'screenX=' + dialogWin.left + ',screenY=' + dialogWin.top + ',resizable=' + resize + ',width=' + dialogWin.width + ',height=' + dialogWin.height + ',scrollbars=' + scroll + ',menubar=no,location=no,toolbar=no,status=no,directories=no';
} else if (document.all) {
dialogWin.left = (screen.width - dialogWin.width) / 2;
dialogWin.top = (screen.height - dialogWin.height) / 2;
var attr = 'left=' + dialogWin.left + ',top=' + dialogWin.top + ',resizable=' + resize + ',width=' + dialogWin.width + ',height=' + dialogWin.height + ',scrollbars=' + scroll + ',menubar=no,location=no,toolbar=no,status=no,directories=no';
}
var myWindow = window.open(url,name,attr);

myWindow.focus();
if (myWindow.opener == null) {myWindow.opener = self;}

	return myWindow;
}

var lockSendShit = false;


function sendThisShit (url, uri, tagId){

    if(lockSendShit){
        alert('wait');
        return;
    }

    lockSendShit = true;

    try {

        var newConnector = new SimpleAjax(XML_FILE);

        newConnector.connectingMessage();

        newConnector.addGetoSend(uri);

        newConnector.is_xml = true;

        //alert(domObj.id);

//         newConnector.preparareThisObject(thisObj);

        newConnector.display = new Display();

        newConnector.display.onResponseDo = function (){

            var command = searchOnDeepLevels(newConnector.display.xmlDoc,'command');

            if(command){

                var hashyGet =  newConnector.paramToSend.toQueryParams();

                //alert("\n ANDA ESTO, SE DETECTA COMMAND !!!!!! \n\n" + hashyGet['tmpl_id']+ "\n\n\n" );

                command = searchOnDeepLevels(command,'update');
                if(!command){
                        alert('no existe ese comando');
                }else if(  command.firstChild.nodeValue == 'yes') {

                        var myImg = $(tagId).getElementsByTagName('IMG')[0];
                        if(myImg){
//                             alert(myImg.src);
                            if(myImg.src.match(/deactive.gif$/)){
                                myImg.src ='/image/active.gif';
                            }else{
                                myImg.src ='/image/deactive.gif';
                            }
                        }else{
                            alert('ERROR');
                        }
                }else if(command.firstChild.nodeValue == 'no'){
                        alert('se intento update pero noi se pudo');
                }
            }else{
                alert("\nerror: NO SE DETECTA COMMAND !!!!!! \n\n"+command);
            }
            lockSendShit = false;

        }

        newConnector.display.onloadDocument('onResponseDo');

        newConnector.createConnection();

    }catch(e){
        alert(e.message);
    }

}

var enable_editors = false;

function displayEditors(){
    var editors = document.getElementsByClassName('my_editor_tool');
    for(var i=0; i < editors.length; i++){
        if(enable_editors){
            editors[i].style.display='none';

        }else{
            editors[i].style.display='block';

        }
    }
    enable_editors = (enable_editors)? false: true;
}

function toggleLayer(whichLayer){

	var hide_or_display = false;

	if(arguments && arguments.length > 1){
		hide_or_display = arguments[1];
// 		alert(hide_or_display);
		if(hide_or_display == 'hide'){
			hide_or_display = 'none';
		}else if(hide_or_display == 'display'){
			hide_or_display = 'block';
		}else{
			alert('error: es hide o display !!! error: 9845237457234579347');
			return;
		}
	}

    if (document.getElementById){
// this is the way the standards work

		var style2 = document.getElementById(whichLayer).style;
		if(hide_or_display){
			style2.display =hide_or_display;
		}else{
			style2.display = style2.display == 'none'? 'block':'none';
		}
		return style2.display;
	} else if (document.all){
// this is the way old msie versions work
        var style2 = document.all[whichLayer].style;
		if(hide_or_display){
                    style2.display = (hide_or_display == 'none' ?'':'block' ) ;
		}else{
                    style2.display = style2.display? "":"block";
		}
		return style2.display ? 'none': 'block';
    } else if (document.layers){
    // this is the way nn4 works
        var style2 = document.layers[whichLayer].style;
		if(hide_or_display){
                    style2.display = (hide_or_display == 'none' ?'':'block' ) ;
		}else{
                    style2.display = style2.display? "":"block";
		}
		return style2.display ? 'none': 'block';
    }
}

function isValidEmail (email){
    if(!email || email.length < 5){
        return false;
    }
    var splitted = email.match("^(.+)@(.+)$");
    if(splitted == null) return false;
    if(splitted[1] != null )
    {
      var regexp_user=/^\"?[\w-_\.]*\"?$/;
      if(splitted[1].match(regexp_user) == null) return false;
    }
    if(splitted[2] != null)
    {
      var regexp_domain=/^[\w-\.]*\.[A-Za-z]{2,4}$/;
      if(splitted[2].match(regexp_domain) == null) 
      {
	    var regexp_ip =/^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
	    if(splitted[2].match(regexp_ip) == null) return false;
      }// if
      return true;
    }
    return false;

}

function mouseOv (domObj,fontColOver, backColOver){

    var fontCol = '';

    if(domObj.style.color){
        fontCol = domObj.style.color;
    }

    var backCol = '';

    if(domObj.style.backgroundColor){
        backCol = domObj.style.backgroundColor;
    }

    domObj.setAttribute('backCol',backCol);
    domObj.setAttribute('fontCol',fontCol);
    domObj.setAttribute('backColOver',backColOver);
    domObj.setAttribute('fontColOver',fontColOver);

    domObj.style.backgroundColor = domObj.getAttribute('backColOver');
    domObj.style.color = domObj.getAttribute('fontColOver');

     domObj.onmouseover = function (){
         this.style.backgroundColor = this.getAttribute('backColOver');
         this.style.color = this.getAttribute('fontColOver');
//         alert(this.style.color);
     };
    domObj.onmouseout = function (){
        this.style.backgroundColor = this.getAttribute('backCol');
        this.style.color = this.getAttribute('fontCol');
    };
}

function firstUpperCase (stringy) {
            var first = stringy.substring(0,1);

            var allTheRest = stringy.substring(1);

            var upper = first.toUpperCase();

            // concatenate the uppercase with the rest
           return ( upper + allTheRest );
}

function cssInLineToDom(inLineCss){

	if(!inLineCss || inLineCss == ""){
		alert('error 9834592374571283787289475');
		//alert("ERROR \n \n cssInLineToDom() esta vacio");
		return "";
        }else if(browser.isNS){
            // no se hace nada de lo de abajo 
	}else if(inLineCss == 'vertical-align'){
		return 'VerticalAlign';
// 	}else if(inLineCss == 'color'){ parece que esto no era necesario
// 		return 'Color';
	}else if(inLineCss == 'border-color'){
		return 'borderColor';
        }else if(inLineCss == 'border-style'){
		return 'borderStyle';
        }

        if(inLineCss.match(/-/)){
		var elems = inLineCss.split(/-/);

		var tmpArray = elems[1].split("");
		var upp = tmpArray.shift();
		upp = upp.toUpperCase();
		upp += tmpArray.join("");
		//alert(elems[0]+upp);
		return elems[0]+upp;
	
	}else{

//  		alert('Pasa limpiiiiiiito: '+inLineCss);
	}
	return inLineCss;
}


function dom_check_advice(hashy){

	for (var i = 0; i < document.forms.length;i++){

		for (var aa in hashy){
			if(document.forms[i][aa]){
				document.forms[i][aa].style.borderColor = 'red';
			}
		}
	}
}

var NS4 = (navigator.appName == "Netscape" && parseInt(navigator.appVersion) < 5);

function addOption(theSel, theText, theValue){
  var newOpt = new Option(theText, theValue);
  var selLength = theSel.length;
  theSel.options[selLength] = newOpt;
}

function deleteOption(theSel, theIndex){ 
  var selLength = theSel.length;
  if(selLength>0)
  {
    theSel.options[theIndex] = null;
  }
}

function moveOptions(theSelFrom, theSelTo){
  
  var selLength = theSelFrom.length;
  var selectedText = new Array();
  var selectedValues = new Array();
  var selectedCount = 0;
  
  var i;
  
  // Find the selected Options in reverse order
  // and delete them from the 'from' Select.
  for(i=selLength-1; i>=0; i--){
    if(theSelFrom.options[i].selected){

      selectedText[selectedCount] = theSelFrom.options[i].text;
      selectedValues[selectedCount] = theSelFrom.options[i].value;
      deleteOption(theSelFrom, i);

      selectedCount++;
    }
  }

  // Add the selected text/values in reverse order.
  // This will add the Options to the 'to' Select
  // in the same order as they were in the 'from' Select.
  for(i=selectedCount-1; i>=0; i--){
    addOption(theSelTo, selectedText[i], selectedValues[i]);
  }

  if(NS4) history.go(0);
}


/*  y esto ??? esta en uso?, mejor usar addEvent() !!*/
var GLObjectOnLoad = new Object();
function execOnLoad (){
	for ( var i in GLObjectOnLoad){
		eval(GLObjectOnLoad[i]);
	}
}
/*##############*/


var bigcnct ='';
function recursiveGetTextFromHTML (myDom, tagName){
	var hermano =  myDom.firstChild;
	while(hermano){
// 		alert(hermano.nodeType);
		if(hermano.nodeType == 3){
			bigcnct += hermano.data.replace(/[\s+]/mgi, " ");
		}else if(hermano.nodeType == 1){
			if(hermano.href){
				bigcnct += '<a href="'+hermano.href+'">'+hermano.innerHTML+'</a>';
				//alert( bigcnct + ' ' + hermano.nextSibling);
				hermano = hermano.nextSibling;
				continue;
			}
		}

		if(hermano.firstChild && hermano.firstChild.nodeName){
			recursiveGetTextFromHTML(hermano, tagName);
		}

		hermano = hermano.nextSibling;
	}

}

function screenPosition(e){
/* Requeire que se le pase el parametro event
* detecta posicion del mouse en X e Y
* detecta resolucion del monitor
* checkea que un elemento con un ancho o largo establecido no se vaya afuera del screen:
	* Ejemplo:
		uso en html:
		<a href="#" onclick="funcion_que_muestra_un_widget(this, screenPosition(event));" >

		implementacion:

		LA FUNCION SE UTILIZA DENTRO DE OTRA, llamada desde dhtml para resolver el horrible problema de los eventos en js. Como resultado, la funcion "personalizada" recibe como parametro un objeto que contiene los siguientes ATRIBUTOS:

			xyobjeto.posx es la cantidad de pixels "de izq a derecha" en el que se ubica el lateral izquierdo del objeto clickeado
			
			xyobjeto.posy es la cantidad de pixels "de arriba a abajo" en el que se ubica el lateral superior del objeto clickeado

			xyobjeto.screen es un string con la resolucion de pantalla: ancho x alto

			xyobjeto.screenx es la cantidad de pixels de ancho qe tiene la pantalla

			xyobjeto.screeny es la cantidad de pixels de alto qe tiene la pantalla

		y las siguentes propiedades:

			xyobjeto.sGoingOutX(ancho_del_objeto_a_mover) suma el anchodel objeto que se va a mover con la cant de pixels de izq a derecha del elem clickeado y se fija si es mayor a la resolucion de pantalla

			xyobjeto.sGoingOutY(alto_del_objeto_a_mover) idem al anterior pero con la altura

*/
	var hashXY = new Object()
	hashXY['posx'] = 0;
	hashXY['posy'] = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY){
		hashXY['posx'] = e.pageX;
		hashXY['posy'] = e.pageY;
	}else if (e.clientX || e.clientY){
		hashXY['posx'] = e.clientX + document.body.scrollLeft;
		hashXY['posy'] = e.clientY + document.body.scrollTop;
	}

	if(screen.width){
		hashXY['screen'] = screen.width+'x'+screen.height;
		hashXY['screenx'] = screen.width;
		hashXY['screeny'] = screen.height;
	}else{
		hashXY['screen'] = false;
	}

        if(getcss('#main_admin_div','left') =='50%'){
            hashXY['posx'] -= 240;
        }

//         hashXY['screenx'] = parseInt(hashXY['screenx']) - 320;

//         alert(hashXY['screen']+ '  ' +hashXY['posx']+ '  ' + hashXY['posy'] );

	hashXY.isGoingOutX = function (elem_width){

		var matcher = elem_width.match(/^(\d+)px$/);

		if(!matcher){
			alert('corregir el formato en que se ingresa este dato, no es px??');
		}else if(matcher.length > 1){
			elem_width = parseInt(matcher[1]);
		}else{
			alert('corregir el formato en que se ingresa este dato, no es px??');
		}

		alert('Horizontal : '+ ( elem_width + hashXY['posx'] ) + ' screen: '+ hashXY['screenx']);
		if( ( elem_width + hashXY['posx'] ) > hashXY['screenx'] ){
			return true;
		}else if( elem_width < 0 ){
			return true;
		}
		return false;
	};

	hashXY.isGoingOutY = function (elem_height){
		var matcher = elem_height.match(/^(\d+)px$/);

		if(!matcher){
			alert('corregir el formato en que se ingresa este dato, no es px??');
		}else if(matcher.length > 1){
			elem_height = parseInt(matcher[1]);
		}else{
			alert('corregir el formato en que se ingresa este dato, no es px??');
		}

		alert('Vertical : '+ ( elem_height + hashXY['posy'] ) + ' screen: '+ hashXY['screeny']);

		if( ( elem_height + hashXY['posy'] ) > hashXY['screeny'] ){
			return true;
		}else if( elem_height < 0 ){
			return true;
		}
		return false;
	};

	return hashXY;

}

function moveWindowHere (domID, screenPositionObject ){ // mueve un div al lugar donde se hizo el click. Se llama:  moveWindowHere('myDivStyleBOX', screenPosition(event));
	if(!screenPositionObject || !screenPositionObject['screen']){
		alert('Es un objeto de screenPosition ??');
		return;
	}

	var domObj = document.getElementById(domID);

 	domObj.style.left = (screenPositionObject.posx) +'px';

 	domObj.style.top = (screenPositionObject.posy) +'px';

 	domObj.style.position= 'absolute';

// 	alert(screenPositionObject.screenx + ' '+screenPositionObject.screeny );
}

var idToEditWithStyleBox = false;

function closeStyleBox (event){
    var tagId = 'myDivStyleBOX';

    var startSearch =false;

    var isChildOf = false;

    if (browser.isIE){
        startSearch = window.event.srcElement;
// 	 alert(window.event.srcElement.tagName + '   '  + typeof startSearch.firstChild);
    }else if (browser.isNS){
        startSearch = event.target;
    }
//  	alert(startSearch.id);


    if(startSearch.id=='closeMePlease' ){
        isChildOf = false;
    }else if(startSearch && typeof startSearch == 'object'){
        while(startSearch){
            if(startSearch.id == tagId){
                isChildOf = true;
                break;
            }
            startSearch = startSearch.parentNode;
        }
    }

    if(!isChildOf){
        toggleLayer(tagId, 'hide');
        if (browser.isIE) {
            document.detachEvent("onclick", closeStyleBox);
        }
        if (browser.isNS) {
            document.removeEventListener("click", closeStyleBox,   true);
        }
    }
}



function showStyleBox(tagId , elemToFocusOn, mouseEvt){ //parametros: ( 'el tag del editor que aparece y desaparece', 'elemento que se esta editando', 'solo va "screenPosition(event)"')


    if (browser.isIE) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
            document.attachEvent("onclick", closeStyleBox);
    }
    if (browser.isNS) {
            document.addEventListener("click", closeStyleBox,  true);
    }

    moveWindowHere(tagId,mouseEvt);
    toggleLayer(tagId);
    idToEditWithStyleBox=elemToFocusOn;
    var inputObj = document.getElementById(idToEditWithStyleBox);

    if(!inputObj || typeof inputObj != 'object'){
            alert(' Falta el input sobre el que esamos editando ??? '+"\n"+'se llama: ' + idToEditWithStyleBox);
            return;
    }
    var myPreviewText = document.getElementById('edxx');

    myPreviewText.innerHTML=inputObj.value;

    var objete = document.getElementById(elemToFocusOn+'_css');


    if(objete && typeof objete == 'object'){
        var cssKeyValue = objete.value.split(/;/);
        if(!cssKeyValue ){
            alert(objete.value + ' No parece valido');
            return;
        }
        for(var i =0; i < cssKeyValue.length; i++){
            var keyAndValue = cssKeyValue[i].split(/:/);

            if(typeof keyAndValue == 'object' && keyAndValue.length == 2){
                var aSimpleSelect = document.cosete[keyAndValue[0]];
                for(var ii = 0; ii < aSimpleSelect.length; ii++){
                    if(aSimpleSelect[ii].value == keyAndValue[1]){
                        aSimpleSelect[ii].selected= true;
                    }
                }
                
                var inlineStyleToDomMethod = cssInLineToDom(keyAndValue[0]);
                if(inlineStyleToDomMethod ==''){
                    continue;
                }

                try {
                    myPreviewText.style[inlineStyleToDomMethod] = keyAndValue[1];

                    inputObj.style[inlineStyleToDomMethod] = keyAndValue[1];

                }catch(a){
                    alert(a.message + ' ' + inlineStyleToDomMethod);
                }
            }
        }
    }else{
        alert('Falta un hidden que se llame '+ tagId+'_css');
    }
}

function changeCssFromSelect(domObj,tagId){ /* algunos templates lo sobreescriben */

	domObj.style[cssInLineToDom(domObj.name)]= domObj.options[domObj.selectedIndex].value;
	document.getElementById('edxx').style[cssInLineToDom(domObj.name)] = domObj.options[domObj.selectedIndex].value;
	document.getElementById(tagId).style[cssInLineToDom(domObj.name)] = domObj.options[domObj.selectedIndex].value;

	var objete = document.getElementById(idToEditWithStyleBox+'_css');
	var cnctX = "";
	var formObj = document.cosete;
	for(var i = 0; i < formObj.length; i++){
		var formElem = formObj[i];

		if(formElem.type == "submit"){

		}else if(formElem.type == "select-one"){

			cnctX += formElem.name + ":" + formElem.options[formElem.selectedIndex].value+";";

		}else{
			alert(formElem.type + "  " + formElem.name );
		}
	}
	objete.value=cnctX;

	return false;
}


/* CSS funciones que transforman strings en hashes tipo Dom o hashes tipo Inline y al reves */



function cssTransformInlineStringToHash (stringy){ // o sea 'height:2px;font-weight:1;etc' a un hash 
    var pairs = stringy.match(/^\??(.*)$/)[1].split(';');

    return pairs.inject({}, function(params, pairString) {
      var pair  = pairString.split(':');
      var value = pair[1] ? pair[1] : 'undefined';
      params[pair[0]] = value;
      return params;
    });
}

function cssTransformInlineToDomHash(stringy){ // transforma un string en un hash tipo dom de css
    return cssTransformInlineHashToDomHash(cssTransformInlineToHash (stringy));
}

function cssTransformInlineHashToDomHash (inlineHashy){ // pasa de un hash inline (con keys como font-weight) a un hash que se puede usar en domObj.style[domKey] = 'etc';
    var toReturn = new Object();
    for(var akey in inlineHashy){
        toReturn[cssInLineToDom(akey)] = inlineHashy[akey];
    }
    return toReturn;
}

function cssTransformInlineHashToString (inlineHashy) { // pasa el hash de inline a string
    return $H(inlineHashy).map(function(pair) {
        return pair.join(':');
    }).join(';');
}

function cssTransformDomHashToString (domHashy) {// pasa un hash de css compatible con Dom  a string
    return $H(domHashy).map(function(pair) {
        var myKey = pair[0];
        var matches = myKey.match(/\s?(\w+)([A-Z]{1})(\w+)/);
        if(matches){
            var cnct_tmp = matches[1]+'-'+matches[2]+matches[3] +':'+ pair[1];
            return cnct_tmp.toLowerCase();
        }
        return pair.join(':').toLowerCase();
    }).join(';');
}

function getcss( selector, property ) {
    if ( !document.styleSheets ){ return null; }

    var sList = document.styleSheets;
    for (var ii = 0; ii < sList.length; ii++){
        var i, r, s= document.styleSheets[ii];
        if(s) {
            r = s.rules ? s.rules : s.cssRules;
            if(r) {
                i = r.length;
                while (i--) {
                    if(r[i].selectorText.toLowerCase() === selector.toLowerCase()) {
                        return ( r[i].style[property] );
                    }
                }
            }
        }
    }
    return null;
}
// fin css



// Cal

function mandarCoso(pars){

    var ajax = new Ajax.Request( XML_FILE, {
        parameters: pars,
        method:"post",
        onComplete: finalizar,
        onLoading: carganding
    });

}


function ajaxizar (){

    var parsingObj = $('to_delete_elem');

    if( ! parsingObj ){
//         alert('No hay un div id="to_delete_elem"');
        return;
    }


    var myLinks = parsingObj.getElementsByTagName('A');

    for (var ii = 0; ii < myLinks.length; ii++){

        var noajax = myLinks[ii].getAttribute('noajax');

        if(noajax){
            continue;
        }

        if(myLinks[ii].onclick){
            var myHr = myLinks[ii].getAttribute('myHref')
            if(myHr && myHr != ''){
//                 alert('no mfunciona como yo creia');
                myLinks[ii].href = '#';
            }
            continue;
        }


        var hRef = myLinks[ii].href;

        myLinks[ii].setAttribute('myHref', hRef);


        myLinks[ii].onclick = function (){

            var aa = this.getAttribute('myHref');
//             alert(aa);
            mandarCoso(aa);

        };

        myLinks[ii].href = '#';

    }

    if( $('auto_info') ){

        var autoInfo = $('auto_info');



        var myTypeIs = autoInfo.getAttribute('autoType');

        if(myTypeIs && ( myTypeIs == 'edit' ) ){ //||  isEditor == 'add' 

            var ajaxize = autoInfo.getAttribute('ajaxize');

            if(ajaxize && ajaxize != ''){

                var ww = $('button_back_to_list');

                if( ! ww ){
                    alert('err(917676762) mmmm, no hay back button ????');
                    return;
                }

                var whereToGo = ww.getAttribute('whereToGo');

                if(!whereToGo){
                    alert(' falta whereToGo en button_back_to_list ! ');
                }

                ww.onclick = function(){
                    var aa = this.getAttribute('whereToGo');
                    mandarCoso(aa);
                }

//                 alert(ww.id);

//                 var myFormName =  autoInfo.getAttribute('myFormName');

            }else{
//                  document.title = ' .....isEditor: ' + isEditor + '   ' + ajaxize;
            }
        }else if( myTypeIs && ( myTypeIs == 'list' ) ){

            var ajaxize = autoInfo.getAttribute('ajaxize');

            if(ajaxize && ajaxize != ''){

                var tochange_list = new Array();
    
                tochange_list.push('add_new_top_butt', 'add_new_middle_butt');
    
                for(var iia =0; iia < tochange_list.length; iia++){
        
                    var ww = $(tochange_list[iia]);
    
                    if( ! ww ){
                        continue;
                    }
        
                    var whereToGo = ww.getAttribute('whereToGo');
        
                    if(!whereToGo){
                        alert(' falta whereToGo en button_back_to_list ! ');
                    }
        
                    ww.onclick = function(){
                        var aa = this.getAttribute('whereToGo');
                        mandarCoso(aa);
                    }
    
                }
            }else{
                alert(" dice no ser ajax");
            }
//             document.title = ' .....isEditor: ' + isEditor + '   ';
        }

    }else{
//         document.title = ' .....dddddddddd: auto_info';
    }

}


addEvent(window,"load", ajaxizar);

function carganding(){

    if($('ZaG_xew_JA')) { $('ZaG_xew_JA').remove() }

    var div_msg = document.createElement('div');

    div_msg.style.zIndex = 2;

    div_msg.style.position = 'fixed';

    div_msg.style.right = '52px';

    div_msg.style.width = '33px';

    div_msg.style.top = '21px';

    var img = document.createElement('IMG');

    img.src='/image/spinner_red.gif';

    img.style.right = '112px';

    img.style.width = '26px';

    img.style.height = '26px';

    img.style.border = '0px';

    div_msg.appendChild(img);

    div_msg.style.border = '1px solid #d97272';

    div_msg.style.fontFamily = 'Arial, Helvetica, sans-serif';

    div_msg.style.fontWeight = 'normal';

    div_msg.style.color='#d97272';

    div_msg.style.fontSize ='8px';

    div_msg.id = 'ZaG_xew_JA';

    div_msg.appendChild(document.createTextNode('Loading . .. ....'));

    document.getElementById('datoslog').appendChild(div_msg);

}


function finalizar(resp){

    var e = resp.responseXML;//primer nodo XML de la respuesta


    var toInsert = searchOnDeepLevels(e, 'response');

    var err =  searchOnDeepLevels(e, 'error');

    try {

        if(0 && err && err.data && err.data != ''){
            if(err.data){
                alert(err.data);
            }else{
                alert(err.firstChild.data);
            }
            return;
       }
    }catch(e){
        alert('err(930183881) ' + e); // mal debugging
    }

    var to_replace_elem = $('to_replace_elem');

    if( to_replace_elem ){

        if( $('to_delete_elem') ){ // manera ideal: se supone que existen dos divs: "to_replace_elem" que es el contenedor, y "to_delete_elem" que es lo que se borra y se vuelve a crear para volver a borrar
            $('to_delete_elem').remove();

            var to_delete_elem = document.createElement("DIV");

            to_delete_elem.id= 'to_delete_elem' ;

            to_delete_elem.innerHTML = toInsert.firstChild.nodeValue;


            to_replace_elem.appendChild(to_delete_elem);

//             alert('polite');


        }else{ // manera chancha: existe un solo div y no esta definido que es lo que se va a borrar, entonces simplemente se borra todo lo que tiene adentro el contenedor y se empieza de cero para empezar a usar la otra manera
            to_replace_elem.innerHTML = '<div id="to_delete_elem">'+ toInsert.firstChild.nodeValue + '</div>';

//             alert('rude');
        }
    }else{
        if( $('to_delete_elem') ){
            var div_to_change = $('to_delete_elem');

            div_to_change.id = 'to_replace_elem';

            div_to_change.innerHTML = '<div id="to_delete_elem">'+ toInsert.firstChild.nodeValue + '</div>';
//             alert(' esto solo deberia pasar cada primera vez que se empieza el ajaxizado');

        }else{
            alert('Mal configurado: no tenes ni un to_replace_elem y ni siquiera un to_delete_elem !! miserable!' );

            return;
        }

    }

    try {

        var mycontent = $('to_delete_elem');

        var lista = mycontent.getElementsByTagName('script');

        eval (" function addEvent(baaa, beeee, funcione){  var funcionar = funcione; funcionar(); }"); //se sobreescribe la funcion addEvent(), ahora ejecuta todo inmediatamente despues de recibir la funcion

        for (var i=0; i < lista.length; i++){
            eval(lista[i].innerHTML); // recarga el javascript que estaba en los tags  <script>
        }
    }catch(e){
        alert('err(777591375) ' + e);
    }
    ajaxizar( 'to_delete_elem' );


    var execIncomingCmd = $('execIncomingCmd');

    if(execIncomingCmd){
        var msg = execIncomingCmd.getAttribute('command');
        if(msg){
            myWarnsMsgCommand(msg);
        }
        execIncomingCmd.remove();
    }


    try {
        window.location='#to_delete_elem';
        if($('ZaG_xew_JA')) { $('ZaG_xew_JA').remove() }
    }catch(e){
        alert('err(88932) '+ e);
    }
}




/*  automaton */

function makeMyNifty(){

    var divis = $('myWarnsAndMessages');

     $A(divis.getElementsByTagName('div')).each(function(elems){
         Nifty("div#"+elems.id ,"normal");
    });
    $A(divis.getElementsByTagName('div')).each(function(elems){
        $(elems.id).style.display='none';
    });
}

function mySortHasChange(cmd){
    if(sort_message_is_active){return};
    Nifty('div#change_sort' ,"normal");
    Effect.Appear('change_sort');
    sort_message_is_active = true;
}

function myWarnsMsgCommand(cmd){
    Nifty('div#'+cmd ,"normal");
    if(arguments.length > 1){
        if(arguments.length == 2){
            if(cmd == 'duplicated_element'){

                var dynTextin = $('duplicated_element_text');
                if(!dynTextin){ alert('Falta un elemento');return};
                dynTextin.appendChild( document.createTextNode(arguments[1]) );
            }else{
                alert('Se le paso mas de un parametro, dpero no parece estar implementado: ' + cmd);
                return;
            }

        }else{
            alert('Se le paso mas de un parametro, debe ser dinamico, implementar');
            return;
        }

    }

    var showThisCoso = $(cmd);
    if(!showThisCoso){
        alert('unknow command on template: '+ cmd +'. The command is not part of this template');
        return;
    }


    Effect.Appear(cmd);window.setTimeout('Effect.Fade('+cmd+')',3600); $(cmd).style.display='none';

}




// if(Element && typeof Element == 'object'){ /* este if es para que no de error cuando no se usa prototype*/

    /* Agregados que yo hago a prototype.js */
Element.addMethods({
	popme: function (thisDomObj) { // es un popup con los datos de cada atributo DOM en un nodo
	    var  cncty = '';
	    for(var aa in thisDomObj){
		    cncty +="\n"+ aa + ' = ' + thisDomObj[aa];
	    }
	    alert(cncty);
    },getInnerNodeByID : function  (thisDomObj, the_node_id){ /* devuelve el nodo que matchea con el id */
        return searchIdOnDeepLevels(thisDomObj, the_node_id);
    }, getInnerNodeByName : function  (thisDomObj, the_node_name){ /* devuelve el nodo que matchea con el id */

        return searchOnDeepLevels  (thisDomObj, the_node_name);
    },searchUpwardsById : function  (thisDomObj, the_node_id){ /* devuelve el nodo que matchea con el id buscando Hacia arriba */

        while (thisDomObj && thisDomObj.parentNode){
            if(thisDomObj.id == the_node_id){
                return thisDomObj;
            }
            thisDomObj = thisDomObj.parentNode;
        }
        return false;
    },searchInLevelById : function  (thisDomObj, the_node_id){ /* devuelve el nodo que matchea con el id buscando hacia abajo*/
	    if(!the_node_id){
		return false;
	    }
    
	    var my_brothers = thisDomObj.parentNode.firstChild;
    // 	alert(my_childrens.nodeName);
	    while(my_brothers){
		    if(my_brothers.id && my_brothers.id  == the_node_id){
			    return my_brothers;
		    }
		    my_brothers = my_brothers.nextSibling;
	    }
	    return false;
    }, searchInLevelByName : function  (thisDomObj, the_node_name ){ /* devuelve el nodo que matchea con el id */

	    if(!the_node_name || !thisDomObj){
		return false;
	    }
    
	    the_node_name = the_node_name.toUpperCase();
    
	    var my_brothers = thisDomObj.parentNode.firstChild;
    
    
	    while(my_brothers){
    
		    if(my_brothers.nodeName && my_brothers.nodeName  == the_node_name){
    // 		       	       alert('MATCHEA!!: - '+ my_brothers.nodeName + ' - '+ the_node_name );
			    return my_brothers;
		    }
		    my_brothers = my_brothers.nextSibling;
	    }
	    return false;
    },algunaCosa : function (){alert('sssssss')}

    });
    
    Object.extend(String.prototype, {
	extractIntegers: function () { // extrae el primer integer que encuentra en la cadena, si hay mas larga un throw , si hay menos devuelve undef
	    var coso = this.match(/(\d+)/gi);
    // 	alert(coso.length+ '   ' + coso);
    
	    if(coso.length > 1){

		    throw ' extractIntegers say: more than one group of numbers betwen chars: ' + this;
		    return parseInt(coso);
	    }else if(coso.length == 1){
		    return coso[0];
	    }else {
		    return false;
	    }
    }
});

Array.prototype.exists = function (x) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == x) return true;
    }
    return false;
}

/* fin agregados a prototype*/

 // fin
function menu_horizontal_index (){
    var ss = document.getElementsByClassName('menu_horiz');
    for(var i = 0; i < ss.length; i++){

        ss[i].style.zIndex = 505 - i;
        if(ss[i].firstChild){
            ss[i].firstChild.style.zIndex = 505 - i;
        }
//                 alert(ss[i].style.zIndex);
    }
}


Event.observe(window, 'load', menu_horizontal_index, false);


