// Crea un input (type,name,value)
function createInput(type,name,value)
{
	var i = document.createElement("input");
	i.name = name;
	i.type = type;
	i.value = value;
	i.id = name;
	return i;
}
//==========================================================
// Funcion de prueba.
// Reemplazarla por include en server de produccion
// Recibe datos de campaña desde flash campanas/campanas.swf
// posicion: define lugar dentro de la pantalla
// id: define nombre de la campaña o producto
// archivo: define el nombre del txt
// ruta: define la url a abrir
// doc: define si es archiv
//==========================================================
function open_win(posicion,id,archivo,ruta,doc,pos1,pos2,maxv){
	var wns = Array("_self","_blank");
	var str = "";
	for(var i=0;i<open_win.arguments.length;i++){
		if(open_win.arguments[i] == "")
			str+="vacio\n";
			else
		str += open_win.arguments[i] + "\n";
	}
	//alert(posicion +" * "+ id +" * "+archivo+" * "+doc);
	grabaLog(posicion,id,archivo,"false",pos1,pos2,maxv);//true es asincrónico
	// - - - - - - -  href - - - - - - - -
	if (doc == "windows"){
		$("#container").append("<form action='"+ruta+"' target='_blank' id='new_link' style='display:none;'>&nbsp;</form>");
		$("#new_link").submit();
		$("#new_link").remove();
	}
	// - - - - - - -  href - - - - - - - -
	if(doc == "document"){
		document.location.href=ruta;
	}	else if(doc == "popup"){
		window.open(ruta,id,pos1);
	}
	//return false;
}
// LOG
xmlhttp = null;
function grabaLog(posicion,id,archivo,modo,pos1,pos2,maxv)
{
	 if (xmlhttp != null && xmlhttp.readyState != 0 && xmlhttp.readyState != 4)
	 {
	   xmlhttp.abort();
	 }
	 
	var url = "/createlog/createlog.asp?posicion="+posicion+"&id="+id+"&archivo="+archivo+"&ran="+Math.random()*100+"&lugar="+pos1+"&total="+pos2+"&maxview="+maxv;
	// code for Mozilla, etc.

	if (window.XMLHttpRequest)
	{
		xmlhttp=new XMLHttpRequest();
		if(!xmlhttp)return false;
		//xmlhttp.onreadystatechange=state_Change;
		xmlhttp.open("GET",url,(modo=="true"));
		xmlhttp.send(null);
	}
	// code for IE
	else if (window.ActiveXObject)
	{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		if (xmlhttp)
		{
			//xmlhttp.onreadystatechange=state_Change;
			xmlhttp.open("GET",url,(modo=="true"));
			xmlhttp.send();
		}
	}
}
//==============================================
// Cierra UL's abiertos usando style.display
//==============================================
function closeUls(){
	var uls = document.getElementsByTagName("ul");
	var t = uls.length;
	if(t < 1)return false;
	for(i=0;i<t;i++){
		if(uls[i].style.display == "block")
			uls[i].style.display = "none";
	}
}
//==============================================
// Prende o apaga un elemento usando style.display 
// Argumentos: id de elemento
//==============================================
var lastOpened = "";
var lastBotSelected = "";
function showHide(id,botId){
	if(botId != undefined){
		var defClass = getElement(botId).className;
		if(lastBotSelected != "")
			getElement(lastBotSelected).className = "";
		getElement(botId).className = defClass+" selected";
		getElement(botId).blur();
		lastBotSelected = botId;
	}
	if(getElement(id).style.display == "none"){
		// Cierra los abiertos
		//closeUls();
		if(lastOpened != "")
			getElement(lastOpened).style.display = "none";
		getElement(id).style.display = "block";
		lastOpened = id;
	}
	else{
		getElement(id).style.display = "none";
		lastOpened = "";
	}
}



function showHideSimple(id){
	if(getElement(id).style.display == "none"){
		getElement(id).style.display = "block";
	}
	else 
		getElement(id).style.display = "none";
}
//==============================================
// Prende un elemento y apaga el otro usando style.display 
// Argumentos: id de elementos (2)
//==============================================
function switchDivs(id1,id2){
	if(document.getElementById(id1).style.display == "none"){
		document.getElementById(id1).style.display = "block";
		document.getElementById(id2).style.display = "none";
	}
	else {
		document.getElementById(id2).style.display = "block";
		document.getElementById(id1).style.display = "none";
	}
}
//==============================================
// para colorear en rollover los tr de tabla con clase "clase"
// se puede llamar en body.onLoad
//==============================================
function tableruler(clase)
{
 if (document.getElementById && 
  document.createTextNode)
  {
   var tables=document.getElementsByTagName('table');
   for (var i=0;i<tables.length;i++)
   {
    if(tables[i].className==clase)
    {
     var trs=tables[i].getElementsByTagName('tr');
     for(var j=0;j<trs.length;j++)
     {
      if(trs[j].parentNode.nodeName=='TBODY' && trs[j].parentNode.nodeName!='TFOOT')
       {
       trs[j].onmouseover=function(){this.className='colored';return false}
       trs[j].onmouseout=function(){this.className='';return false}
     }
    }
   }
  }
 }
}
//================================================
// Agrega clase addClass a tags strTags clase strClass
// Si linkTag existe, contiene url para aplicar onclick
//================================================
function elementRollOver(strTag,strClass,addClass,linkTag) {
	for (i=0;i<document.getElementsByTagName(strTag).length; i++) {
		if (document.getElementsByTagName(strTag).item(i).className == strClass) {
			var newClass = strClass+" "+addClass;
			document.getElementsByTagName(strTag).item(i).onmouseover=function(){this.className=newClass;this.style.cursor="default";return false}
       		document.getElementsByTagName(strTag).item(i).onmouseout=function(){this.className=strClass;return false}
			if(linkTag != undefined){
			document.getElementsByTagName(strTag).item(i).onclick = function(){
				var t = this.getElementsByTagName(linkTag)[0];
				var a = t.getElementsByTagName("a")[0];
				if(a){
					var href = a.getAttribute("href");
					//document.location.href = href;
				}
			}
			}
		}
	}
}
//======================================================
// Retorna array con elementos con class determinada
// Implementaci{on de getElementsByClassName
//======================================================
document.getElementsByClass = function (needle)
{
  var tag  = "div";
  if(document.getElementsByClass.arguments[1])
  	tag = document.getElementsByClass.arguments[1];
  var         my_array = this.getElementsByTagName(tag);
  var         retvalue = new Array();
  var        i;
  var        j;

  for (i = 0, j = 0; i < my_array.length; i++)
  {
    var c = " " + my_array[i].className + " ";
    if (c.indexOf(" " + needle + " ") != -1)
      retvalue[j++] = my_array[i];
  }
  return retvalue;
}
/*======================================================
Aplica clase colored a tr's por medio de tablas de documento
 (tablas deben tener tbody)
 =======================================================*/
function colorRows(){
	var tabs = false;
	if(W3CDOM)
		tabs = document.getElementsByTagName("table");
	else
		tabs = document.tables;
	if(!tabs)return;
	for(var i=0;i<tabs.length;i++){
		tab = tabs[i];
		tbodies = tab.getElementsByTagName("tbody");
		for(var t = 0;t<tbodies.length;t++){
				tbody = tbodies[t];
				trs = tbody.getElementsByTagName("tr");
				for(var u=0;u<trs.length;u++){
					if(u%2)trs[u].className = "colored";
				}
		}
	}
}

function agrandarLayer(){
	$('#layer_right').animate({width:'690px'},500);
	};

function achicarLayer(){
	$('#layer_right').animate({width:'110px'},500);
	};


//Envio de mail por AJAX para campaña credilinea
function enviar_correo(nombre,nombre_invitado,email_invitado,puntos){
	$.ajax({
  		type: "GET",
  		url: "/mail_credilinea/mail.asp",
  		dataType: "script",
		data: "nombre="+nombre+"&nombre_invitado="+nombre_invitado+"&email_invitado="+email_invitado+"&puntos="+puntos,
		success:function(msg){
			alert(msg);
		}
	});

}

function mostrar_nocliente(){
		$("#valor_credito").remove().appendTo("#caluga_creditoraspe");
					$("#raspe").css({
							'top':'0',
							'left':'0'
					});
					if($.browser.msie == false ){
						$("#raspe").css('top','0');
						$("#valor_credito").css({
								'position':'absolute',
								'top':'156px',
								'left':'0',
								'height':'200px'
						});
					}else{
						$("#valor_credito").css({
								'position':'absolute',
								'top':'156px',
								'left':'0',
								'height':'200px'
						});
						}
					
					$("#valor_credito p").css({'margin':'0','padding':'18px 0 0','top':'0'});
					$("#clienteono").css('top','220px');
	}
	
	function formatNumber(num,prefix){
		prefix = prefix || '';
		num += '';
		var splitStr = num.split('.');
		var splitLeft = splitStr[0];
		var splitRight = splitStr.length > 1 ? '.' + splitStr[1] : '';
		var regx = /(\d+)(\d{3})/;
		while (regx.test(splitLeft)) {
			splitLeft = splitLeft.replace(regx, '$1' + '.' + '$2');
		}
		return prefix + splitLeft + splitRight;
	}
/*
function monto_preaprobado(rut){
		$("#raspe img").remove();
		$("#valor_credito").remove().prependTo("#caluga_creditoraspe");
		$.ajax({
			   type:"POST",
			   url:"/serv_raspe.asp",
			   data:"d_rut="+rut,
			   success:function(msg){
				   if((msg.indexOf('No es Cliente') == -1)&&(msg.indexOf("Cliente Sin")==-1)){
					$("#valor_credito p").html("<label class='blink'>"+formatNumber(msg,'$ ')+"</label>");
					$("#clienteono").css("background","url(/estilos/2008_08/bitmaps2008/obtener_credito.gif) 0 0 no-repeat");
					$("#raspe").append("<img src='/estilos/2008_08/bitmaps2008/top_estrella.gif' alt='Felicidades tienes un cr&eacute;dito Preaprobado'/>");
					$("#raspe img").css({
												'position':'absolute',
												'top':'0px',
												'left':'0px'
												}).fadeIn(2000);
					}else{
							$("#clienteono").css("background","");
							$("#clienteono").empty();
							$("#valor_credito p").html("<a href='/simuladores/credito_consumo/simulador.asp' title='Simulador de Cr&eacute;dito' class='txt_simula'>Para obtenerlo simula tu Cr&eacute;dito <span>Aqu&iacute;</span>.</a>");
							$("#raspe").append("<img src='/estilos/2008_08/bitmaps2008/top_estrella_nocliente.gif' alt='Felicidades Tienes hasta un 10% de descuento en la tasa al solicitar tu cr&eacute;dito por Internet'/>");
							$("#raspe img").css({
												'position':'absolute',
												'top':'0px',
												'left':'0px'
												}).fadeIn(2000);
							setTimeout('mostrar_nocliente()',3000)						
						}
					setTimeout('$(".blink").fadeOut(300).fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(300).fadeIn(300)',3000)
				},
				error:function(msg){
					$("#clienteono").empty();
					$("#valor_credito p").html("<a href='/simuladores/credito_consumo/simulador.asp' title='Simulador de Cr&eacute;dito' class='txt_simula'>Simula <span>Aqu&iacute;</span> las Condiciones Especiales de tu Cr&eacute;dito</a>");
					setTimeout('mostrar_nocliente()',3000)
				}
		});
	};
*/	
function monto_preaprobado_new(rut){
		var rut = limpiarRutNew(rut);
		if (verificarRutPreapoNew(rut) == true)
			{
				$("#ingreso_rut").fadeOut();
				$.ajax({
					   type:"POST",
					   url:"/serv_raspe.asp",
					   data:"d_rut="+rut,
					   success:function(msg){
					   	var auxmsg= new String(msg);
						   if((msg.indexOf('No es Cliente') == -1)&&(msg.indexOf("Cliente Sin")==-1)&&(auxmsg.length!=0))
								{

									$("#f_rut").val(rut);
									$("#mensaje1").fadeIn();	
									$("#mensaje2").hide();
								}
							else
								{
									$("#mensaje1").hide();	
									$("#mensaje2").fadeIn();	
								}
						},
						error:function(msg){
							$("#mensaje1").hide();	
							$("#mensaje2").fadeIn();
						}
				});
			}
	}

function verificarRutPreapo(strRut)
{	
	if (strRut != "")  
	{

	   straux = strRut.substring(strRut.length-1,strRut.length);
	   if (straux == "k") 
		 digVerifIn = straux.toUpperCase()
	   else
		 digVerifIn = straux;
	   straux = strRut.substring(0,strRut.length-1);
	   if (soloNumeros(straux) == 0)
		 digVerif = "KX"
	   else
		 digVerif = digitoVerificador(straux);

	   if(digVerif == digVerifIn){
			accionInterna=1;
			return true;
			}
	   else 
	   {
		   alert("RUT incorrecto.");
		   submitcount=0;
		   document.autent.d_rut.value="";
		   document.autent.d_pin.value="";
//		   document.autent.d_rut.focus();
		   //document.autent.d_rut.select();
		   accionInterna=0;		   
		   return false;
		   
		}
	} 
	else
	{	
		//alert("verificarRut")
		alert("Debe ingresar el RUT.");
		submitcount=0;
		document.autent.d_rut.value="";
//		document.autent.d_rut.focus();
		//document.autent.d_rut.select();		
		return false;
	}
}

function verificarRutPreapoNew(strRut)
{	
	if (strRut != "")  
	{

	   straux = strRut.substring(strRut.length-1,strRut.length);
	   if (straux == "k") 
		 digVerifIn = straux.toUpperCase()
	   else
		 digVerifIn = straux;
	   straux = strRut.substring(0,strRut.length-1);
	   if (soloNumeros(straux) == 0)
		 digVerif = "KX"
	   else
		 digVerif = digitoVerificador(straux);

	   if(digVerif == digVerifIn){
			accionInterna=1;
			return true;
			}
	   else 
	   {
		   alert("RUT incorrecto.");
		   submitcount=0;
		   $("#rut_preapo").val("");
//		   document.autent.d_rut.focus();
		   //document.autent.d_rut.select();
		   accionInterna=0;		   
		   return false;
		   
		}
	} 
	else
	{	
		//alert("verificarRut")
		alert("Debe ingresar el RUT.");
		submitcount=0;
		$("#rut_preapo").val("");
//		document.autent.d_rut.focus();
		//document.autent.d_rut.select();		
		return false;
	}
}

function limpiarRutNew(strRut){
	//document.autent.rut.value = $("#rut_preapo").val();
	var digVerif ="";
	var digVerifIn ="";
	var straux ="";
	var rutsgnp = "";
	while((new Number(strRut.charAt(0))==0)&&(strRut!="")){
		strRut=strRut.substring(1,strRut.length);
	}
	for (i=0; i < strRut.length; i++)
	{
		if ((strRut.charAt(i) != ".") && (strRut.charAt(i) != "-") && (strRut.charAt(i)!=" "))
		rutsgnp= rutsgnp + strRut.charAt(i);
	}
	return rutsgnp;
} 
