$(document).ready(function(){
	
	/*
	 * Validaciones para el formulario de promociones
	 */
	if ($('.formPromociones') != null) {
		
		generarFormPromocion($('.formPromociones'));
		
		// Controla los caracteres a ingresar en el input del rut
		$('#con_rut').keypress(function(evt){
			var key = evt.keyCode ? evt.keyCode : evt.which ;
			return (key <= 31 || (key >= 48 && key <= 57) || key == 75 || key == 107); 
		});
		
		$("#con_rut").blur(function(){
			formatearRut("con_rut");
		});
		
		$('.btnPromocion').click(function(){

			//Rescatando valores
			var nombre = $('#con_nombre').val();
			var rut = $('#con_rut').val();
			var email = $('#con_email').val();
			
			var alerta = 
				'<div id="alertaConcurso" class="alertaComentarios alertaNombre clearfix" style="display: none;">'+
					'<div class="contenidoAlerta">'+
						'<div class="flecha"></div>'+
						'<p style="margin:0;font-size:1.0em;"></p>'+
					'</div>'+
				'</div>';
			
			//validando
			if (nombre == "" || nombre == " " || nombre == "  ") {
				$('#con_nombre').parents('.formItem:first').after(alerta);
				$('#alertaConcurso').find('p:first').text('Debes ingresar tu nombre.');
				$('#alertaConcurso').fadeIn('slow');
			}
			else {
				if (rut == "" || rut == " " || rut == "  ") {
					$('#con_rut').parents('.formItem:first').after(alerta);
					$('#alertaConcurso').find('p:first').text('Debes ingresar tu rut.');
					$('#alertaConcurso').fadeIn('slow');
				}
				else {
					if (Rut(rut) == false) {
						$('#con_rut').parents('.formItem:first').after(alerta);
						$('#alertaConcurso').find('p:first').text('Debes ingresar un rut v\xE1lido.');
						$('#alertaConcurso').fadeIn('slow');
					}
					else {
						if (email == "" || email == " " || email == "  ") {
							$('#con_email').parents('.formItem:first').after(alerta);
							$('#alertaConcurso').find('p:first').text('Debes ingresar tu email.');
							$('#alertaConcurso').fadeIn('slow');
						}
						else {
							if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email) == false) {
								$('#con_email').parents('.formItem:first').after(alerta);
								$('#alertaConcurso').find('p:first').text('Debes ingresar un email v\xE1lido.');
								$('#alertaConcurso').fadeIn('slow');
							}
							else {
								//document.forms[2].submit();
								$.ajax({
									url: "http://www.sedal.cl/wp-content/themes/Sedal/cv_promocion/procesa_formulario.php",
									type: "POST",
									data: $("form#formPromocion").serialize(),
									success: function(data){
										abrirLB(data);
									}
								});
								return false;
							}
						}
					}
				}
			}
			return false;
		});
	}
	
	/*
	 * Ocular las validacioned del formularo de promociones
	 */
	if ($('.formPromociones') != null) {
		//oculta alerta nombre
		$('#con_nombre,#con_rut,#con_email').focus(function(){
			$('#alertaConcurso').fadeOut();
			$('#alertaConcurso').remove();
		});
	}
	/*
	$('.lightbox').fancybox({
		'padding'			: 1,
		'frameHeight'		: 550,
		'frameWidth'		: 750,
		'easingChange'		: true,
		//editando alto frames (arregla falla en ie7 y 8)
		//'callbackOnShow': altoIframe,
		'hideOnContentClick': false
	});*/
	
});

function abrirLB(data){
	var url = $('#bannerPost').find('img:first').attr('src').split('/img/')[0];
	$('a.btnNegro').attr('href',url+'/cv_promocion/lightbox.php?data='+data);
	$('a.btnNegro').addClass('lightbox iframe');
	$('.btnPromocion').fancybox({
		'padding'			: 1,
		'frameHeight'		: 580,
		'frameWidth'		: 595,
		'easingChange'		: true,
		//editando alto frames (arregla falla en ie7 y 8)
		'callbackOnShow': function(){
			$('#fancy_frame').css({'height':'635px'});
		},
		'hideOnContentClick': false
	});
	$('.btnPromocion').trigger('click');
	
}

function cerrarVentana(){
	$.fn.fancybox.close()
}

/*
 * Funcion para generar el formulario en el articulo.
 */
function generarFormPromocion(elemento){
	var form = 
		'<form id="formPromocion" name="concurso" method="post" action="" style="display:block;position:relative;">'+
			'<div class="formItem clearfix">'+
				'<input type="text" id="con_nombre" name="con_nombre" />'+
				'<label for="con_nombre">Nombre (Obligatorio)</label>'+
			'</div>'+
			'<div class="formItem clearfix">'+
				'<input type="text" id="con_rut" name="con_rut" />'+
				'<label for="con_rut">Rut (Obligatorio)</label>'+
			'</div>'+
			'<div class="formItem clearfix">'+
				'<input type="text" id="con_email" name="con_email" />'+
				'<label for="con_email">Mail (Obligatorio)</label>'+
			'</div>'+
			'<div class="clearfix" style="position:relative;">'+
				'<a href="#" class="btnNegro btnPromocion"><span class="fondoBoton"><span>Obt&eacute;n los cupones</span></span></a>'+
			'</div>'+
		'</form>';
	
	elemento.html(form);
	
	return false;	
}

/*
 * Funcion para formatear el rut
 */
function formatearRut(casilla){
	function formatearMillones(nNmb){
		var sRes = "";
		for (var j, i = nNmb.length - 1, j = 0; i >= 0; i--, j++)
		 sRes = nNmb.charAt(i) + ((j > 0) && (j % 3 == 0)? ".": "") + sRes;
		return sRes;
	}
	
	var casillaRut=document.getElementById(casilla);
	
	var rut=casillaRut.value;
	var ultimoDigito=rut.substr(rut.length-1,1);
	var terminaEnK = (ultimoDigito.toLowerCase()=="k");
	rutSinFormato=rut.replace(/\W/g,"");
	rut=rut.replace(/\D/g,"");
	var dv=rut.substr(rut.length-1,1);
	if(!terminaEnK){ rut=rut.substr(0,rut.length-1); }
	else{ dv="K"; }
	if(rut && dv) {
		casillaRut.value=formatearMillones(rut)+"-"+dv;
		//document.getElementById('buic_rutdv').value=rutSinFormato;
	}
}

/*
 * Funciones para validar el rut
 */
function revisarDigito( dvr ){	
	dv = dvr + ""	
	if ( dv != '0' && dv != '1' && dv != '2' && dv != '3' && dv != '4' && dv != '5' && dv != '6' && dv != '7' && dv != '8' && dv != '9' && dv != 'k'  && dv != 'K')	{		
		return false;	
	}	
	return true;
}

function revisarDigito2( crut ){
	largo = crut.length;	
	if ( largo < 2 ){		
		return false;	
	}	
	if ( largo > 2 )		
		rut = crut.substring(0, largo - 1);	
	else		
		rut = crut.charAt(0);	
	dv = crut.charAt(largo-1);	
	revisarDigito( dv );	

	if ( rut == null || dv == null )
		return 0	

	var dvr = '0'	
	suma = 0	
	mul  = 2	

	for (i= rut.length -1 ; i >= 0; i--){	
		suma = suma + rut.charAt(i) * mul		
		if (mul == 7)			
			mul = 2		
		else    			
			mul++	
	}	
	res = suma % 11	
	if (res==1)		
		dvr = 'k'	
	else if (res==0)		
		dvr = '0'	
	else{
		dvi = 11-res		
		dvr = dvi + ""	
	}
	if ( dvr != dv.toLowerCase() )	{
		return false	
	}

	return true
}

function Rut(texto){
	var tmpstr = "";	
	for (i = 0; i < texto.length; i++) {
		if (texto.charAt(i) != ' ' && texto.charAt(i) != '.' && texto.charAt(i) != '-') {
			tmpstr = tmpstr + texto.charAt(i);
		}
	}
	texto = tmpstr;
	largo = texto.length;

	if ( largo < 2 ){
		return false;
	}

	for (i=0; i < largo ; i++ ){
		if ( texto.charAt(i) !="0" && texto.charAt(i) != "1" && texto.charAt(i) !="2" && texto.charAt(i) != "3" && texto.charAt(i) != "4" && texto.charAt(i) !="5" && texto.charAt(i) != "6" && texto.charAt(i) != "7" && texto.charAt(i) !="8" && texto.charAt(i) != "9" && texto.charAt(i) !="k" && texto.charAt(i) != "K" ){
			return false;		
		}
	}

	var invertido = "";	
	for (i = (largo - 1), j = 0; i >= 0; i--, j++) {
		invertido = invertido + texto.charAt(i);
	}
	var dtexto = "";	
	dtexto = dtexto + invertido.charAt(0);	
	dtexto = dtexto + '-';	
	cnt = 0;	

	for ( i=1,j=2; i<largo; i++,j++ ){
		//alert("i=[" + i + "] j=[" + j +"]" );		
		if ( cnt == 3 ){
			dtexto = dtexto + '.';			
			j++;			
			dtexto = dtexto + invertido.charAt(i);			
			cnt = 1;		
		}		
		else{
			dtexto = dtexto + invertido.charAt(i);			
			cnt++;		
		}	
	}	

	invertido = "";	
	for (i = (dtexto.length - 1), j = 0; i >= 0; i--, j++) {
		invertido = invertido + dtexto.charAt(i);
	}
	if (revisarDigito2(texto)) {
		return true;
	}

	return false;
}
