/* INICIO *****************************/
//Funciones preparacion de lightbox y webpush
$(document).ready(function() {
	/**
	* Funciones webpush
	*/
	//TODO: Revisar donde afecta este cambio!!!!
	//$('input.inputBox').inputBox({'imgPath':'/PortalPersonas/framework/skins/personas_v21/img/i2bforms/'});

				$('.abrir_wp').click(function() {
					var wpPadre = $(this).parents('.bloque_info_contenido:first');
					var wp = wpPadre.find('.wp_bloque');
					if(!wp.is(':visible')) {
						wp.show();
						
					} else {
						wp.hide();
						wpPadre.find('.wp_alerta, .wp_exito').hide();
						wpPadre.find('input[type=text]').val('Nš EPCS');
					}
					return false;
				});
	
	/**
	* Acciones relacionados con tablas.
	*/
	$("table.tablaLiquida").each(function(){
		$(this).find("th:first").addClass("primera").css("text-align","left");
		$(this).find("th:last").addClass("ultima");
		
	});
	
	// Mueve todos los lightbox a la raiz del dom,
	// esto evita que tenga padrs con postion: relative
	// y al momento de aparecer quede centrado.
	$("div.vModal, div.lightbox").each(function() {
		var v = $(this);
		v.clone(true).appendTo('body:first');
		v.remove();
	});
	
	
	//Para levantar un lightbox con un #ancla
	$("a[href^='#'], a > img").click(function() {
		var $a = (this.tagName == 'A') ? $(this) : $(this).parent();
		var lbName = $a.get(0).href.match(/#([^#]+)/i);
		if (lbName == null) return;
		
		lbName = lbName[1];
		var $el = $('#vmodal-' + lbName);
		if ($el.size() == 0) return;
		
		$.vModal({id: "vmodal-" + lbName});
		return false;
	}); 
	
	
	/**
	* Funciones para login en lightbox
	*/
	
	//Ventana Modal de Login
	
	var pageLabelMiEPCS = "pageMIE_Home";
	
	var $aMiPCS = $("#cabecera_menu div.menu_principal_main a[href*='" + pageLabelMiEPCS + "'], #cabecera_menu div.menu_principal_main a:contains('Mi Entel'), a.miEntel");
	
	//$aMiPCS[0].href="/PortalPersonas/login/";
	var lbConf = getLoginConf();
	$aMiPCS.attr("href", lbConf.file);
	$aMiPCS.fancybox({
		'overlayOpacity'		:	0.5,
		'overlayColor'			:	'#000000',
		'hideOnContentClick'	: 	false,
		'hideOnOverlayClick' 	: 	false,
		'frameWidth' : lbConf.x,
		'frameHeight' : lbConf.y
	});

	//o por la Marca rel 
	var $aMiPCS = $("a[rel*='loginSimple']");
	
	$aMiPCS.fancybox({
		'overlayOpacity'		:	0.5,
		'overlayColor'			:	'#000000',
		'hideOnContentClick'	: 	false,
		'hideOnOverlayClick' 	: 	false,
		'frameWidth' : 225,
		'frameHeight' : 400
	});
	
	
	//o por la Marca rel 
	var $aMiPCS = $("a[rel*='loginDoble']");
	
	$aMiPCS.fancybox({
		'overlayOpacity'		:	0.5,
		'overlayColor'			:	'#000000',
		'hideOnContentClick'	: 	false,
		'hideOnOverlayClick' 	: 	false,
		'frameWidth' : 450,
		'frameHeight' : 400
	});

	var $aMiPCS = $("a[rel*='cambioEquipo']");
	
	$aMiPCS.fancybox({
		'overlayOpacity'		:	0.5,
		'overlayColor'			:	'#000000',
		'hideOnContentClick'	: 	false,
		'hideOnOverlayClick' 	: 	false,
		'frameWidth' : 600,
		'frameHeight' : 250
	});
	
});

function getLoginConf() {
	var conf = {x: 450, y: 380, file: appContext + "/login/"};
	if (appContext == "/PortalCorporaciones") {
		conf.x = 765;
		conf.y = 385;
	}
	if ($("#cabecera_menu li:contains('Call Center')").hasClass("seleccionado") && appContext == "/PortalEmpresas") {
		conf.x = 300;
		conf.y = 130;
		conf.file += "callCenter.jsp";
	}
	
	return conf;
}

function cargarContenido(el) {
	(function($) {
	//var opt = $(el).children('option:selected').val();
	
	if(opt != 0) {
		$.ajax({
			dataType: 'html',
			url: "equipos.html",	//"comunas.php?region="+opt
			cache: false,
			success: function(data) {
				$('#elegir_modelo').empty();
				var temp = $(data).find('div[id='+opt+']').find('div');
				//var opciones = '<a href="">Seleccione</a>'
				var opciones = '';
				temp.each(function(i) {//"javascript:seleccionar("'++'","selector_ano","ano_seleccionado");"
					opciones += '<a href="#" onclick="seleccionar(\''+$(temp[i]).attr('id')+'\',\'selector_modelo\',\'modelo_seleccionado\');return false;">'+$(temp[i]).html()+'</a>';
				});
				$('#elegir_modelo').html(opciones);
			}
		});
		
	} else {
		$('#elegir_modelo').empty();
	}
	
	/*$('#calles-select').hide();
	$('#calles-text').empty().show();*/
	})(jQuery);
}

function mostrar(div){  if(document.getElementById(div).style.display=='none')   document.getElementById(div).style.display='block';  else ocultar(div); } 
function ocultar(div){  divIdioma=div;  setTimeout(ocultarDelayed,100); } function ocultarDelayed(){  document.getElementById(divIdioma).style.display='none'; } 
function seleccionar(valor,origen,destino){  document.getElementById(origen).value=valor;  document.getElementById(destino).value=valor; } 




/* SELECTS *****************************/
//Funciones para manejo de la info de soporte Equipos
function Modelo(id,nombre,imagen){
	this.id=id;
	this.nombre=nombre;
	this.imagen=imagen;
}
function Marca(nombre) {
	this.modelos=new Array();
	this.nombre = nombre;
	this.addModelo = function(id,nombre,imagen) {
			this.modelos.push(new Modelo(id,nombre,imagen));
	}
}
function Equipo(){
	this.Equipos=new Array();
	this.addEquipo = function(marca,id,nombre,imagen) {
		var pos=this.indexOf(marca);
		if (pos==-1){
			pos=this.Equipos.push(new Marca(marca))-1;
		}
		this.Equipos[pos].addModelo(id,nombre,imagen);	
	}
	this.indexOf = function(s) {
		for (var x=0;x<this.Equipos.length;x++) if(this.Equipos[x].nombre == s) return x;
		return -1;
	}
	this.toJSON = function(){
		var json='{';
		
		for (var x=0;x<this.Equipos.length;x++){
			json+='"'+this.Equipos[x].nombre+'":{';					
			for (var y=0;y<this.Equipos[x].modelos.length;y++){						
				json+='"'+this.Equipos[x].modelos[y].nombre+'"';						
				json+=':{';
				json+='"id":"'+this.Equipos[x].modelos[y].id;
				json+='","nombre":"'+this.Equipos[x].modelos[y].nombre;
				json+='","imagen":"'+this.Equipos[x].modelos[y].imagen;
				json+='"}';
				if (y!=this.Equipos[x].modelos.length-1) 
					json+=',';
			}
			json+='}';	
			if (x!=this.Equipos.length-1) 
					json+=',';				
		}				
		
		return json+'}';
	}
}
//Fin funciones 
		
jQuery(document).ready(function ($) {
	
	if (!$("#selectormarca").get(0)) return;
	
	$("#customselector").customSelect();
	var select = $("#selectormarca").get(0);
	//if (typedef(select) != 'undefined')
	select.options.length = 0;
	var marca;
	for (marca in data) {
		//select.options[0] = new Option("-Seleccionar-", "");
		var op = new Option(marca, marca);
		op.title = "imagen";
		select.options[select.options.length] = op;
	}

	//if (typedef(select) != 'undefined')
		select.options[0].selected= true;
	
	$("#selectormarca").customSelect();
	
	$(".selectormarca_selectitems").click(function() {
		llenarSelectModelos(this.id);
		//console.log(this.id);
	});
	
	//selectormarca_selectoptions
	$(".selectormarca_selectoptions > div")
	.css({
		'height': '1.2em'
	}).find('img').empty();
	/**/
	$("#selectormarca_iconselect").val('- Seleccionar -');
	$("#customselector_iconselect").addClass('disabled');
	
 	if (typeof nodoActual == 'undefined') return;
 	
 	if (nodoActual && nodoActual != "") {
 		ID = nodoActual;
 		llenarSelectModelos(getMarcaFromModeloID(ID));
 		$('#customselector').val(ID);
 		$("#selectormarca_iconselect").val( getMarcaFromModeloID(ID) );
 		$("#customselector_iconselect").removeClass('disabled').val( getMarcaFromModeloID(ID, true) );
 		
		//El boton parte deshabilitado si no hay nada
		if (typeof nodoActual == 'undefined')
			disableSubmit();
		if (nodoActual == "")
			disableSubmit();
 		//if ($("#recordar").get(0))
			//$("#recordar").attr('disabled', false).get(0).checked = false;
 	}
	
	/**/
});

function llenarSelectModelos(marca) {
	(function($) {
		//console.log(marca);
		var modelo;
		var opciones='';
		for (modelo in data[marca]) {
			//console.log('Modelo: '+ modelo);
			var opcion = '<div class="customselector_selectitems" id="'+ data[marca][modelo].id +'">';
			opcion += '<img src="'+data[marca][modelo].imagen+'" />';
			opcion += '<span>'+data[marca][modelo].nombre+'</span>';
			opcion += '</div>';
			opciones += opcion;
		}
		
		//El boton parte deshabilitado si no hay nada
		if (typeof nodoActual == 'undefined')
			disableSubmit();
		if (nodoActual == "")
			disableSubmit();
		
		var alto=0;
		$("#customselector_iconselect").val("- Selecionar -").removeClass('disabled');
		$("#customselector_selectoptions").html(opciones);

		var ident = "customselector";
		
		// Cuando se hace click en un modelo, se activa el boton buscar
		// y el checkbox #recordar si es que existe.
		$("."+ident+"_selectitems").click(function(){
			$("."+ident+"_selectedclass").removeClass(""+ident+"_selectedclass");
			$(this).addClass(""+ident+"_selectedclass");
			var thisselection = $(this).find('span').text();
			$("."+ident+"_customselect").val(this.id);
			$("#recordar").val(this.id);
			//se carga la info al campo oculto
			$("#"+ident+"_iconselect").get(0).value = thisselection.replace(/<img[^>]*>/gi, "");
			$("#"+ident+"_iconselectholder").hide(100);
			enableSubmit();
		});

	})(jQuery);
}

// Obtiene nombre de marca segun id de telefono, si equipo es TRUE, devuelve el nombre del modelo.
function getMarcaFromModeloID(id, devuelveModelo) {
	if (id == "") return "----";
	var modelo;
	for (marca in data) {
		for (modelo in data[marca]) {
			//console.log(data[marca][modelo].id.match(/[0-9]+$/i) +' == ' + id.match(/[0-9]+$/i));
			if (data[marca][modelo].id == id)  {
				if (devuelveModelo)
					return modelo;
				else
					return marca;
			}
		}
	}
	return null;
}


function enableSubmit() {
	btnEnable();
	if ($("#recordar").attr('disabled', false).get(0))
		$("#recordar").attr('disabled', false).get(0).checked = false;
}
function disableSubmit() {
	btnDisable();
	//if ($("#recordar").get(0))
		$("#recordar").attr('disabled', true);//.get(0).checked = false;
}



$(document).ready(function(){

	btn_buscar = $('.btn_buscar')
	.bind('mouseover',function() {
		var imagen = $(this).find('img');
		if (!imagen.hasClass("disabled"))
			imagen.attr('src', imagen.attr('src').replace("_on", "_over"));
	})
	.bind('mouseout',function() {
		var imagen = $(this).find('img');
		if (!imagen.hasClass("disabled"))
			imagen.attr('src', imagen.attr('src').replace("_over", "_on"));
	})
	.bind('click',function(){
		var imagen = $(this).find('img');
		if (!imagen.hasClass("disabled"))
			$('#eleccion-modelo').submit();
		else
			return false;
	});
	
	if (typeof $("#q").get(0) != 'undefined') {
		if ($("#q").val() != "") {
			limpiarBusqueda($("#q")[0]);
		}
	}
	
	//El boton parte deshabilitado si no hay nada
	if (typeof nodoActual == 'undefined')
		btnDisable();
	else  {
		if (nodoActual == "")
			btnDisable();
	}
	
	//Busca el link de la ventana modal
	//$('a[href=#tutorialAnimado]').click( function() { $.vModal({id:'flashModal'}); return false; } );
});

function btnDisable() {
	var img = $('.btn_buscar img:first')
		.addClass('disabled')
		.parent()
			.css("cursor", "default")
		.end();
	if (img.attr('src')) {
		img.attr('src', $('.btn_buscar img:first').attr('src').replace("_on", "_off"));
	}
}


function btnEnable() {
	var img = $('.btn_buscar img:first')
		.removeClass('disabled')
		.parent()
			.css("cursor", "pointer")
		.end();
		
	if (img.attr('src')) {
		img.attr('src', $('.btn_buscar img:first').attr('src').replace("_off", "_on"));
	}
}

/*** CANAL INTERNACIONAL: Carga y despliega datos de tarifas. ***/
function sendDataTarifa() {
	$('#table-tarifa').hide();
	$('#table-title').hide();
	var param = document.forms[0].idTarifa.value;
	data = param.split('|');
	var idTarifa = data[0];
	var title = data[1];
	if(idTarifa != 0){
	
		parametros = "";
		parametros += "idTarifa="+ idTarifa;
		$("#ajax-mostrar-contenido").show();
		/* TODO: PortalCommon Ruta en Duro*/
		$.ajax({
				   type: "GET",
				   url: "/PortalPersonas/portlet/internacionalyroaming/obtenerTarifa.do",
				   data: parametros,
				   success: function(data){			   			
				   			$("#table-tarifa").fadeIn();			   			
				   			$("#table-tarifa").html(data).css("height","auto");	 
				   			$("#table-title").fadeIn();
				   			$("#table-title").html(title).css("height","auto");				   			 
				   			$("#ajax-mostrar-contenido").hide(); 	
				   			window.location.href="#ajax_tarifas_ldi";
				   }
			});
	}else{
		var data = "Debe seleccionar una opcion.";
		$("#table-tarifa").fadeIn();
		$("#table-tarifa").html(data).css("height","auto");	
	}	
	return false;
			   
}

/*** ENVIAR A UN AMIGO***/
function enviarAAmigo(){
	if(validarAAmigo()){     
		parametros = "";
		parametros += "url="+ encodeURIComponent(location.href);
		parametros += "&mail1="+ document.getElementById("actionForm_emailAmigo").value;
		parametros += "&name1="+ document.getElementById("actionForm_nombreAmigo").value;
		parametros += "&mail2="+ document.getElementById("actionForm_email").value;
		parametros += "&name2="+ document.getElementById("actionForm_nombre").value;
		parametros += "&skin="+ document.getElementById("actionForm_skin").value;
		$.ajax({
				type: "GET",
				url: "/PortalPersonas/portlet/common/enviaramigo/enviarAAmigo.do",
				data: parametros,
				success: function() {$.vModal();}				
			});
	}
}

function validarAAmigo(){
	if((document.getElementById("actionForm_emailAmigo").value == "")
	 ||(document.getElementById("actionForm_emailAmigo").value == null)){
		document.getElementById("msgEmailAmigo").innerHTML = "*requerido";
		return false;
	}else if((document.getElementById("actionForm_nombreAmigo").value == "")
		   ||(document.getElementById("actionForm_nombreAmigo").value == null)){
		document.getElementById("msgNombreAmigo").innerHTML = "*requerido";
		return false;
	}else if((document.getElementById("actionForm_email").value == "")
		   ||(document.getElementById("actionForm_email").value == null)){
		document.getElementById("msgEmail").innerHTML = "*requerido";
		return false;
	}else if((document.getElementById("actionForm_nombre").value == "")
		   ||(document.getElementById("actionForm_nombre").value == null)){
		document.getElementById("msgNombre").innerHTML = "*requerido";
		return false;
	}
	return true;		
}

function cleanAAmigo(param){
  document.getElementById(param).innerHTML = "";
}

/*** Caja de Busqueda ***/
function limpiarBusqueda(el) {
	$el = $(el).parent();
	var bg = $el.css("backgroundImage");
	$el.css("backgroundImage", bg.replace("_google",""));
}
function restaurarBusqueda(el) {
	if (el.value.length > 0) return;
	$el = $(el).parent();
	var bg = $el.css("backgroundImage");
	$el.css("backgroundImage", bg.replace("_770","_google_770"));
}


$(document).ready(function() {
	var $els = $('a.linkOneClick');
	
	/*
	var usingFancyBox = ($("a.btnVerdeGrande.link_contratar").length + $els.length > 0);
	if (usingFancyBox) {
		$.getScript(
			"/PortalPersonas/framework/skeletons/entel/js/jquery.fancybox-1.2.6.pack.js",
			function() {
				$('a.linkOneClick').oneClick({'centerOnScroll': false});
			}
		);
	}
	/*Fix Haack*/
	if ($els)
		$els.oneClick({'centerOnScroll': false});
	
	//Caja ganadores
	
	var numeroItems = 10;
	
	var $cajasGanadores = $("div.caja_lateral.ganadores ul");
	
	var liHeightCalc = $("div.caja_lateral.ganadores ul:first  li");
	var liHeight = liHeightCalc.height();
	liHeight += parseInt(liHeightCalc.css('padding-top'));
	liHeight += parseInt(liHeightCalc.css('padding-bottom'));
	
	if ($cajasGanadores.length > 0) {
		$.getScript(
			contextPath+"/framework/skeletons/entel/js/jScrollPane-1.2.3.min.js",
			function() {
				$cajasGanadores.each(function() {
						$ul =  $(this);
						if ($ul.find('li').length > numeroItems) {
							$ul.css({
								'overflow': 'auto',
								'height': liHeight*numeroItems
							}).jScrollPane({scrollbarWidth: 5});
						}
				});
			}
		);
	}
	
});


<!--
/**
 * Base para todas las secciones
 */
var tempTooltip;
$(document).ready(function(){
	eventualizaTooltips();
	eventualizaTextoTooltips();
	
});

function eventualizaTooltips() {
	/**
	 * Tooltips
	 */
	if($(".autoTooltip").length > 0) {
		
		var html = '<div id="tooltip1" class="tooltip1" style="top: 142px; left: 459px; display: none"><div class="flecha"><div class="texto">tooltip</div></div></div>';
		$('body').append(html);

		$(".autoTooltip").each(function() {
			var el = $(this);
			el.removeClass('activo');
			el.attr('tooltip', el.attr('title')).removeAttr('title');
		});
	 
		$(".autoTooltip").click(function(){
			
			var el = $(this);
			var tt = $('#tooltip1');
			var xy = el.offset();
			var text = el.attr('tooltip');
			
			var href = el.attr('href');
			//var activo = (tt.find('div').text() == text || (href == tempTooltip && href != 'javascript:;' && href != '#')) && tt.is(':visible'); //estoy haciendo click a un tooltip que esta activo ?
			var activo = (el.hasClass('activo')) && tt.is(':visible');
			
			if (activo) {
				
				var buttonBackg = el.css('backgroundImage').replace('tooltip/ico_x.gif', 'icons/ico_interrogacion.gif');
				el.css('backgroundImage', buttonBackg);
				
				var startTop = tt.offset().top;
				
				if($.browser.msie && $.browser.version <= 6.0) {
					tt.hide();
					
				} else {
					tt.animate({
						opacity: 0,
						top: startTop + 50 + 'px'
					}, 150);
				}			
				
				tt.queue(function() {
					$(this).css('display','none').dequeue();
				});
				
				$(".autoTooltip").removeClass('activo');
				tempTooltip = null;
			}
			else {
				
				if(el.hasClass("ext")) {
					tt.addClass("extendido");
				} else {
					tt.removeClass("extendido");
				}
				
				$('.autoTooltip').each(function() {
					var buttonBackg = $(this).css('backgroundImage').replace('tooltip/ico_x.gif', 'icons/ico_interrogacion.gif');
					$(this).css('backgroundImage', buttonBackg);
				});
				
				var buttonBackg = el.css('backgroundImage').replace('icons/ico_interrogacion.gif', 'tooltip/ico_x.gif');
				el.css('backgroundImage', buttonBackg);
				
				var idTooltip = el.attr('href');
				if(/^[#]{1,}(\s|[a-zA-Z])*/i.test(idTooltip)) {
					text = $(idTooltip).html();
				}
				
				
				
				$(".autoTooltip").removeClass('activo');
				el.addClass('activo');
				tempTooltip = idTooltip;
				
				tt.find('div.texto:first').html(text)
					.end().css({
						top: xy.top - tt.height(),
						left: xy.left - 112,
						display: 'block',
						zIndex: 149,
						opacity: 0
					});
					
				xy.top -= (parseInt(tt.height()) + 15);
				xy.left -= 112;
				
				if($.browser.msie && $.browser.version <= 6.0) {	
					tt.css('opacity',1).css({
						top: xy.top,
						left: xy.left
					});
					
				} else {
					tt.css({ top: xy.top-50 });
					tt.animate({
						top: xy.top, 
						opacity: 1
					}, 100);
				}
			}
			
			return false;
		});
	 }
	/*------------------ FIN TOOLTIP -----------------*/	
}
function eventualizaTextoTooltips() {
	/**
	 * Tooltips
	 */
	if($(".autoTextoTooltip").length > 0) {
		
		var html = '';
		html += '<div id="tooltip1" class="tooltip1" style="top: 142px; left: 459px; display: none">';
		html += '	<a href="#" class="tooltipCerrar" onclick="return cerrarTooltip()">cerrar</a>';
		html += '	<div class="flecha">';
		html += '		<div class="texto">tooltip</div>';
		html += '	</div>';
		html += '</div>';
		$('body').append(html);

		$(".autoTextoTooltip").each(function() {
			var el = $(this);
			el.removeClass('activo');
			//el.attr('tooltip', el.attr('title')).removeAttr('title');
		});
	 
		$(".autoTextoTooltip").click(function(){
			
			var el = $(this);
			var tt = $('#tooltip1');
			var xy = el.offset();
			//var text = el.attr('tooltip');
			
			var href = el.attr('href');
			var activo = (el.hasClass('activo')) && tt.is(':visible');
			
			if (activo) {				
				var startTop = tt.offset().top;
				
				if($.browser.msie && $.browser.version <= 6.0) {
					tt.hide();
					
				} else {
					tt.animate({
						opacity: 0,
						top: startTop + 50 + 'px'
					}, 150);
				}			
				
				tt.queue(function() {
					$(this).css('display','none').dequeue();
				});
				
				$(".autoTextoTooltip").removeClass('activo');
				tempTooltip = null;
			}
			else {
				
				if(el.hasClass("ext")) {
					tt.addClass("extendido");
				} else {
					tt.removeClass("extendido");
				}
				
				var idTooltip = el.attr('href');
				if(/^[#]{1,}(\s|[a-zA-Z])*/i.test(idTooltip)) {
					text = $(idTooltip).html();
				}
				
				$(".autoTextoTooltip").removeClass('activo');
				el.addClass('activo');
				tempTooltip = idTooltip;
				
				//alert((parseInt(xy.left) - parseInt(tt.width())/2 + parseInt(el.width()/2)));
				
				tt.find('div.texto:first').html(text)
					.end().css({
						top: xy.top - tt.height(),
						left: (parseInt(xy.left) - parseInt(tt.width())/2 + parseInt(el.width()/2))+'px',
						display: 'block',
						zIndex: 149,
						opacity: 0
					});
					
				xy.top -= (parseInt(tt.height()) + 15);
				//xy.left -= (parseInt(xy.left) - parseInt(tt.width())/2 + parseInt(el.width()/2));
				
				if($.browser.msie && $.browser.version <= 6.0) {	
					tt.css('opacity',1).css({
						top: xy.top,
						left: (parseInt(xy.left) - parseInt(tt.width())/2 + parseInt(el.width()/2))+'px'
					});
					
				} else {
					tt.css({ top: xy.top-50 });
					tt.animate({
						top: xy.top, 
						opacity: 1
					}, 100);
				}
			}
			
			return false;
		});
	 }
	/*------------------ FIN TOOLTIP -----------------*/	
}

function cerrarTooltip() {
	$('.tooltip1').hide();
	$(".autoTextoTooltip").removeClass('activo');
	return false;
}
