/**
* Administracion Maixon
*/
// ----------------- Varias funciones globales ------------------- 
// ..:: CARGA DE DATOS EN UN COMBO ::..

function cargar_select(control,miurl,valor) {
	 if (valor == undefined || valor =='') valor ='Ninguno';
	 j.ajax({
		url: 'admin/secciones/'+miurl,
		dataType: 'json',
		timeout: 70000,
		success: function (k) {
			var options = [], i = 0, n = 0;
			for (i = 0; i < k.length; i++) {
				if (typeof k[i] == 'object') {
					if (k[i] == valor) n = i;
						options.push('<option value="' + k[i][settings.key] + '">' + k[i][settings.value] + '</option>');
				} else if (typeof k[i] == 'string') {
					if (k[i] == valor) n = i;
						options.push('<option value="' + k[i] + '">' + k[i] + '</option>');
				}
			}
			j('#'+control).html(options.join(''));
			if (n) {
				j('#'+control)
					.find("option:eq("+n+")")
					.attr('selected', 'selected')
					.parent('select')
					.trigger('change');
			 } else {
				 j('#'+control)
					.find("option:eq(0)")
					.attr('selected', 'selected')
					.parent('select')
					.trigger('change');
			 }
		}/*,
		error: function(e,k){
			alert ("Por favor espere hasta que carge los datos de ubicacion...");
		}*/
		
	 });
	
}
//para buscador x mapa...
function cargar_select2(control,miurl,valor) {
	 if (valor == undefined || valor =='') valor ='Ninguno';
	 j.ajax({
		url: 'ubicaciones/'+miurl,
		dataType: 'json',
		timeout: 70000,
		success: function (k) {
			var options = [], i = 0, n = 0;
			for (i = 0; i < k.length; i++) {
				if (typeof k[i] == 'object') {
					if (k[i] == valor) n = i;
						options.push('<option value="' + k[i][settings.key] + '">' + k[i][settings.value] + '</option>');
				} else if (typeof k[i] == 'string') {
					if (k[i] == valor) n = i;
						options.push('<option value="' + k[i] + '">' + k[i] + '</option>');
				}
			}
			j('#'+control).html(options.join(''));
			if (n) {
				j('#'+control)
					.find("option:eq("+n+")")
					.attr('selected', 'selected')
					.parent('select')
					//.trigger('change');
			 } else {
				 j('#'+control)
					.find("option:eq(0)")
					.attr('selected', 'selected')
					.parent('select')
					//.trigger('change');
			 }
		}/*,
		error: function(e,k){
			alert ("Por favor espere hasta que carge los datos de ubicacion...");
		}*/
		
	 });
	
}
// ..:: VERIFICA SI ESTA CORRECTO EL EMAIL ::..
function isEmailAddress(theElement)
{
	var s = theElement.value;
	var filter=/^[A-Za-z][A-Za-z0-9_]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/;
	if (s.length == 0 ) return true;
	if (filter.test(s))
	return true;
	//else
	//alert("Ingrese una dirección de correo válida");
	theElement.focus();
	return false;
}
function isEmailAddress2(texto)
{
	var s = texto;
	var filter=/^[A-Za-z][A-Za-z0-9_]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/;
	if (s.length == 0 ) return true;
	if (filter.test(s))	return true;
	return false;
}
// ..:: CARGA RESULTADO DE PHP AL DIV ::..
function cargar_div(miurl, control, valor) {
	if (valor == undefined) valor = '';
	j.ajax({
		type: "GET",
		timeout: 7000,
		data: {inmob:valor},
		url: miurl,
		beforeSend: function () {
			j("#"+control).html('<center><img src="templates/images/loading.gif" /><br />Cargando...</center>');
		},
		success: function(result) {
			j("#"+control).fadeIn(500);
			j("#"+control).html(result);
		},
		error: function(e, result) { 
			j("#"+control).fadeIn(500);
			j("#"+control).html(result);
			//alert (e);
		}
	});
}
// ..:: CARGA DE BARRA DE CONTROLES ::..
function controles(n,id,midiv,miurl,opt) {
	j.ajax({
		type: "POST",
		url: miurl+".php",
		timeout: 7000,
		data: {accion:n, id:id, opt:opt},
		success: function(result) {
			if (result != "") {
				j("#"+midiv).html(result);
			}
		}
	});
}
// ..:: MUESTRA MENSAJE DE ERROR Y DESAPARECE UN TIEMPO ::..
function animar(control) {
	j("#"+control).fadeIn();
	j("#"+control).effect('shake', { distance: 4, times: 5, speed:50 })
	j("#"+control).animate({opacity: 1.0}, 1500).fadeOut('slow');
}
// ..:: OCULTA LA DIV DE MENSAJE DE ERROR ::..
function ocultar(midiv) {
	j("#"+midiv).hide();
}
// ..:: REVISA LAS MARCHAS (CHECKBOX) EN LA CONSULTA ::..
function revisar(control) {
var n = 1;
var sel = 0;
var id = '';
	for (i=0;i<control.length;i++) {
		if (control[i].checked) {
			if (n == 2) {
				sel=0;
				break;
			} else {
				id = control[i].value;
				sel=1;
			}
			n++;
		}
	}
	if (!sel) {
		alert ("Por favor seleccione una fila...");
		return undefined;
	} else {
		return id;
	}
}
function desactivar(control) {
	for (i=1;i<control.length;i++) {
		control[i].checked = 0;
	}
}
function saltar (control) {
	j('#'+control).focus();
}
function acentos (text) {
	 text = text.replace("Ä„", '&#260;'); //Ą
	 text = text.replace("Ä†", '&#262;'); //Ć
	 text = text.replace("Ä˜", '&#280;'); //Ę
	 text = text.replace("Å", '&#321;'); //Ł
	 text = text.replace("Åƒ", '&#323;'); //Ń
	 text = text.replace("Ã“", '&#211;'); //Ó
	 text = text.replace("Åš", '&#346;'); //Ś
	 text = text.replace("Å¹", '&#377;'); //Ź
	 text = text.replace("Å»", '&#379;'); //Ż
	 text = text.replace("Ä…", '&#261;'); //ą
	 text = text.replace("Ä‡", '&#263;'); //ć
	 text = text.replace("Ä™", '&#281;'); //ę
	 text = text.replace("Å‚", '&#322;'); //ł
	 text = text.replace("Å„", '&#324;'); //ń
	 text = text.replace("Ã³", '&#243;'); //ó
	 text = text.replace("Å›", '&#347;'); //ś
	 text = text.replace("Åº", '&#378;'); //ź
	 text = text.replace("Å¼", '&#380;'); //ż
	return text;
}

// ------ enter_tab ------
function enter_tab(control) {
	 j("#"+control+" :input[@type=text], #"+control+" select").keypress(function(e) {
		var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
		var nTabIndex=this.tabIndex+1;
		// get element type (text or select)
		var myNode=this.nodeName.toLowerCase();
		// allow enter/return key (only when in an input box or select)
		if((key == 13 || key == 9) && ((myNode == "input") || (myNode == "select")))
		{
			if (j("#"+control+" :select[@tabIndex='"+nTabIndex+"'],#"+control+" :input[@tabIndex='"+nTabIndex+"']").get(0)) {
				j("#"+control+" :select[@tabIndex='"+nTabIndex+"'],#"+control+" :input[@tabIndex='"+nTabIndex+"']").get(0).focus();
				return true;
			} else {
				return false;
			}
		}
	});
}
function enter_tab2(control) {
	j("#"+control+" :input[@type=text],#"+control+" :input[@type=password]").keyup(function(e) {
		if(e.keyCode == 13 || e.keycode== 9) {
			var nTabIndex=this.tabIndex+1;
			if (j("#"+control+" :input[@tabIndex='"+nTabIndex+"']").get(0)) {
				j("#"+control+" :input[@tabIndex='"+nTabIndex+"']").get(0).focus();
			} else {
				this.blur();
			}
		}
	});
}
// --- Solo numeros ---
function soloNumeros(evt) {
     evt = (evt) ? evt : event;
     var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
         ((evt.which) ? evt.which : 0));
     if (charCode < 48 || charCode > 57) {
         if (charCode != 8 && charCode != 9 && charCode != 45 && charCode != 46 && charCode != 116) {
            //alert(charCode);
            return false;
         }
     }
     return true;
}
/*
function createCookie(name,value,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+"="+value+expires+"; path=/";
}
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}
*/
function createPNG(src, width, height) {
    if (navigator.userAgent.indexOf("MSIE") != -1) {
        var element = document.createElement("span");
        element.style.filter = "progid:DXImageTransform.Microsoft." +
                               "AlphaImageLoader(src='" + src + "')";
    } else {
        var element = document.createElement("img");
        element.src = src;
    }
    element.style.width = width + "px";
    element.style.height = height + "px";
    return element;
}
function contar(control, minimoLetras) {
	total = parseInt(minimoLetras - control.value.length);
	if (total==0) 
		j('#nletras').html('0');	
	else
		j('#nletras').html(total);
}
function ismaxlength(obj){
var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
if (obj.getAttribute && obj.value.length>mlength)
obj.value=obj.value.substring(0,mlength)
else
contar(obj,mlength)
}
function createCookie(name,value,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+"="+value+expires+"; path=/";
}
function readCookie(c_name)
    {
        if (document.cookie.length>0)
        {
            c_start=document.cookie.indexOf(c_name + "=")
            if (c_start!=-1)
            {
                c_start=c_start + c_name.length+1
                c_end=document.cookie.indexOf(";",c_start)
                if (c_end==-1) c_end=document.cookie.length
                return unescape(document.cookie.substring(c_start,c_end))
            }
        }
        return ""
    }
function setCookie( name, value, expires, path, domain, secure ) 
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct 
expires time, the current script below will set 
it for x number of days, to make it for hours, 
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
( ( path ) ? ";path=" + path : "" ) + 
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}
function eraseCookie(name) {
    createCookie(name,"",-1);
}
// VALIDAR CUIT
function validarcuit() {
	var vec = new Array();
	var x=0;
	var cuit = document.getElementById("cuit").value;
	var digitoTmp;
	var n = cuit.lastIndexOf("-");
	var xyStr = cuit.substring(0, 2);
	var dniStr = cuit.substring(cuit.indexOf("-") + 1, n);
	var digitoStr = cuit.substring(n + 1, n + 2);
	xyStc = parseInt(xyStr);
	dniStc = parseInt(dniStr);
	digitoTmp = parseInt(digitoStr);
	if (xyStr.length != 2 || dniStr.length > 8 || digitoStr.length != 1) {
		return false;
	} else {	
		if (xyStc != 20 && xyStc != 23 && xyStc != 24 && xyStc != 27 && xyStc != 30 && xyStc != 33 && xyStc != 34) {
			return false;
		} else {
			ncuit = xyStr+dniStr;
			vec[0] = ncuit.charAt(0) * 5;
			vec[1] = ncuit.charAt(1) * 4;
			vec[2] = ncuit.charAt(2) * 3;
			vec[3] = ncuit.charAt(3) * 2;
			vec[4] = ncuit.charAt(4) * 7;
			vec[5] = ncuit.charAt(5) * 6;
			vec[6] = ncuit.charAt(6) * 5;
			vec[7] = ncuit.charAt(7) * 4;
			vec[8] = ncuit.charAt(8) * 3;
			vec[9] = ncuit.charAt(9) * 2;
			for(i=0;i<=9; i++) {
				x += vec[i];
			}
			dv = (11 - (x % 11)) % 11;
			if ( dv == digitoTmp )
				 return true;
			else {
				return false;
			} 
		}
	}
	alert (dv+" - "+digitoTmp);
}

// map google
var map;
var geocoder;
function initialize() {
  map = new GMap2(document.getElementById("map_canvas"));
  map.setCenter(new GLatLng(-34.6125277778, -58.3948305556), 16);
  //map.addControl(new GSmallMapControl());
  map.addControl(new GLargeMapControl);
  geocoder = new GClientGeocoder();
}

// addAddressToMap() is called when the geocoder returns an
// answer.  It adds a marker to the map with an open info window
// showing the nicely formatted version of the address and the country code.
function addAddressToMap(response) {
  map.clearOverlays();
  if (!response || response.Status.code != 200) {
	alert("Sorry, we were unable to geocode that address");
  } else {
	place = response.Placemark[0];
	point = new GLatLng(place.Point.coordinates[1],
						place.Point.coordinates[0]);
	marker = new GMarker(point);
	map.addOverlay(marker);
	marker.openInfoWindowHtml(place.address + '<br>' +
	  '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
  }
}

// showLocation() is called when you click on the Search button
// in the form.  It geocodes the address entered into the form
// and adds a marker to the map at that location.
function showLocation() {
  var address = document.form_busq.q.value;
  geocoder = new GClientGeocoder();
  geocoder.getLocations(address, addAddressToMap);
}

// findLocation() is used to enter the sample addresses into the form.
function findLocation(address) {
  document.form_busq.q.value = address;
  showLocation();
}
       