// JavaScript Document
$(document).ready(function(){
		
	
    $(".icoHelp").mouseover(function(event) {
	$("#capaPrincipal").slideDown();
        $("#capaHelp").slideDown();
    });
	
    $("#capaHelp, .icoHelp").click(function(event) {
		
        $("#capaHelp").slideUp();
        $("#capaPrincipal").slideUp();
        
    });
    
    $("#capaHelp").mouseout(function(event) {
        
        $("#capaHelp").slideUp();
	$("#capaPrincipal").slideUp();
        
    });
	
	
    $(".mostrar_logeo").click(function() {
       $(".form_logeo").toggle("fast", function(){
             $("#ml").removeClass();
             $("#ml").addClass("logeo_activo");
        });
    });
    
    $(".adds-ld").click(function(event) {
	
        $.get("http://www.limadelivery.info/operaciones.php",{idBanner: $('.adds-ld').attr("title")});
        
    });
        

	
	$("#frmregistro").validate({
			errorClass : 'error_validate',
			errorElement : 'span',
			submitHandler: function(form){ 
			    $("#registro").css("opacity","0.3");
			    $(".ajax-loading").css("display","block")
			    $.ajax({
                   url: "ajax.php?grabarCliente=si",
                   type: "POST",
                   data: $(form).serialize(),
                   success: function(response){
					   
					   var res = response.split('-')[0];
					   var id = response.split('-')[1];
					   if(res==1){
						   
					   $("#registro").animate({
					     right: parseInt($("#registro").css("right"))== 0 ?"-="+$("#registro").outerWidth() : 0
				            },1000, function(){ 
				           $("#registro").css("opacity","1");   
						   $("#registro").css("display","none");
						   $("#content_general_registro").load("ajax.php?viewRegistroPaso2=si&id="+id);
						   });
					   }else{
						   $("#registro").css("opacity","1");
						   $(".ajax-loading").css("display","none")   
					       $("span",$("#email").parent()).addClass("email_exist");
				           $("span",$("#email").parent()).html("El email ya existe!");
					   }
						  return false;
				  }
			   })
			}
	});
	

    $("#btn_continuar_registro2").live('click',function() {

		var rubros = document.frmregistro_parte2.elements['rubros[]'];
	    var v = false;
	    var numeroChekeados = 0;
	
	    for(i=0;i<rubros.length;i++){
		   if(rubros[i].checked==true){
			v = true;
			numeroChekeados++;
		   }	
	    }
	
	   if(v==false){
		   alert("Por favor seleccionar un rubro.");
		   return false;
	   }else if(numeroChekeados > 2){
		alert("Solo se permite seleccionar hasta 2 rubros.");
		return false;
	   }
		
		
		if($("#razon_social").val()==""){
		   $("span",$("#razon_social").parent()).addClass("error_validate2");
	       $("#razon_social").focus();
		   return false;
		}else{
		   $("span",$("#razon_social").parent()).removeClass();
		}
		
		if($("#descripcion").val()==""){
		   $("span",$("#descripcion").parent()).addClass("error_validate2");
	       $("#descripcion").focus();
		   return false;
		}else{
		   $("span",$("#descripcion").parent()).removeClass();
		}
		
		if($("#telefono_delivery").val()==""){
		   $("span",$("#telefono_delivery").parent()).addClass("error_validate2");
	       $("#telefono_delivery").focus();
		   return false;
		}else{
		   $("span",$("#telefono_delivery").parent()).removeClass();
		}
		
		if($("#email").val()==""){
		   $("span",$("#email").parent()).addClass("error_validate2");
	       $("#email").focus();
		   return false;
		}else{
		   $("span",$("#email").parent()).removeClass();
		}
		
		if($("#logo_r").val()==""){
		   $("span",$("#logo_r").parent()).addClass("error_validate2");
		   return false;
		}else{
		  var img = $("#logo_r").val().split('.')[1];
		
		  if(img!="jpg" && img!="JPG" && img!="gif" && img!="png" && img!="JPEG"){
		     alert('Formato no aceptado, solo se permiten (jpg, png, gif, JPG, JPEG)');
			 return false;
		  }
		}
		
		 $("#frmregistro_parte2").submit();
		 $("#registro2").css("opacity","0.3");    
		 $(".ajax-loading").show(); 
		 
	});
	
	
	$("#btn_finalizar_registro").live('click',function() {
		
		
	 var distritos = document.form_final.elements['distritos[]'];
		var c=false;
		for(i=0;i<distritos.length;i++){
		   if(distritos[i].checked==true){
			  c = true;
		   }	
	    }
	 
	 if(document.form_final.hora_inicio.value==""){
	     alert("ERROR: Seleccione la hora de Inicio de Lunes a Viernes");
		 return false;
	   }
	   
	   if(document.form_final.hora_fin.value==""){
	     alert("ERROR: Seleccione la hora Final de Lunes a Viernes");
		 return false;
	   }
	 
	 if($("#chkl-v").is(":checked")){
		 
	   if(document.form_final.hora_inicio.value==""){
	     alert("ERROR: Seleccione la hora de Inicio de Lunes a Viernes");
		 return false;
	   }
	   
	   if(document.form_final.hora_fin.value==""){
	     alert("ERROR: Seleccione la hora Final de Lunes a Viernes");
		 return false;
	   }
	   
	 }else{
	 
	     alert("ERROR: Seleccione uno de los dias");
		 return false;
	 
	 }
	 
	 if($("#chks").is(":checked")){
		 
	   if(document.form_final.hora_inicio_s.value==""){
	     alert("ERROR: Seleccione la hora de Inicio del Sabado");
		 return false;
	   }
	   
	   if(document.form_final.hora_fin_s.value==""){
	     alert("ERROR: Seleccione la hora Final del Sabado");
		 return false;
	   }
	   
	 }
	 
	 if($("#chkd").is(":checked")){
		 
	   if(document.form_final.hora_inicio_d.value==""){
	     alert("ERROR: Seleccione la hora de Inicio del Domingo");
		 return false;
	   }
	   
	   if(document.form_final.hora_fin_d.value==""){
	     alert("ERROR: Seleccione la hora Final del Domingo");
		 return false;
	   }
	   
	 }
	

		
	   if(c==false){
		alert("ERROR: Por favor seleccionar un distrito para su cobertura.");
		return false;
	   }
	
	    $.ajax({
                   url: "ajax.php?SaveRegistro3=si",
                   type: "POST",
                   data: $("#form_final").serialize(),
                   success: function(){
		
		            $("#registro3").css("opacity","0.3");    
		            $(".ajax-loading").show(); 
		            var id = encodeURIComponent($("#id_empresa").val());   
		            $("#registro3").animate({
					  right: parseInt($("#registro3").css("right"))== 0 ?"-="+$("#registro3").outerWidth() : 0
				     },1500, function(){ 
				           $("#registro3").css("opacity","1");   
						   $("#registro3").css("display","none");
						   $("#content_general_registro").load("ajax.php?viewEmpresaTemp=si&id="+id);
						  
					 });	  
				   
				   }
		});
		
	});
	
	
	$("#name").change(function() {
		if($(this).val()==""){
		   $("span",$(this).parent()).addClass("error_validate");
	       $("span",$(this).parent()).html("Ingrese un Nombre");
		   return false;
		}
	});
	
	$("#lastname").change(function() {
		if($(this).val()==""){
		   $("span",$(this).parent()).addClass("error_validate");
	       $("span",$(this).parent()).html("Ingrese sus Apellidos");
		   return false;
		}
	});
	
	$("#password").change(function() {
		if($(this).val()==""){
		   $("span",$(this).parent()).addClass("error_validate");
	       $("span",$(this).parent()).html("Ingrese una Contraseña");
		   return false;
		}
	});
	
	$("#email").change(function() {
		if($(this).val()==""){
		   $("span",$(this).parent()).addClass("error_validate");
	       $("span",$(this).parent()).html("Ingrese su Correo");
		   return false;
		}else{
		   $.post('ajax.php?ComprobarEmail=si',{email: $(this).val()}, function(data) {
			   if(data==1){
                  $("span",$("#email").parent()).addClass("email_exist");
				  $("span",$("#email").parent()).html("El email ya existe!");
			   }else{
				  $("span",$("#email").parent()).addClass("email_not_exist"); 
				  $("span",$("#email").parent()).html("El email esta disponible.");
			   }
           });
		}
	});
	
	$("#chkterminos").click(function() {
		if($("#chkterminos:checked").length ==0){
		   $("#span2",$(this).parent()).addClass("error_validate");
	       $("#span2",$(this).parent()).html("Acepte los terminos");
		   
		}else{  
		   $("#span2",$(this).parent()).removeClass();
		   $("#span2",$(this).parent()).html("");
		}
	});
	
	$('#busqueda').autocomplete({ 
		serviceUrl:'ajax.php',
		minChars:1, 
		delimiter: /(,|;)\s*/, // regex or character
		maxHeight:400,
		width:281,
		zIndex: 9999,
		deferRequestBy: 0, //miliseconds
		params: {filtroER:'Yes'}, //aditional parameters
		noCache: false, //default is false, set to true to disable caching
		onSelect: function(value, data){ 
		}
    });
	
	$('#distrito').autocomplete({ 
		serviceUrl:'ajax.php',
		minChars:1, 
		delimiter: /(,|;)\s*/, // regex or character
		maxHeight:400,
		width:281,
		zIndex: 9999,
		deferRequestBy: 0, //miliseconds
		params: {filtroD:'Yes'}, //aditional parameters
		noCache: false, //default is false, set to true to disable caching
		onSelect: function(value, data){ 
		}
    });

	$("#logo_r").filestyle({ 
          image: "aplication/webroot/imgs/choose-file.jpg",
          imageheight : 25,
          imagewidth : 105,
          width : 140
      });
	  

	$(".add").live("click", function(){
		
		$(".form_direcciones").append("<div class='content_direccion row'>"+' <div class="col1" > '+$("#lista_distritos").html()+"</div><div class='col2'> <input type='text' name='direccion[]'  size='30' class='txt_dir' /></div> <div class='col3'> <input type='text' name='telefono[]' size='26' class='txt_tel' /></div>"+'<a href="javascript:;" class="close"  onclick="deleteRow(this)"></a></div>');
		
	});
 	
	$("#all").live("click", function(){
		
		var chks=$("input:checkbox[name^='distritos']");
		chks.attr("checked",$(this).is(":checked"))
	})
	
	$("input[name^='distritos']").click(function(){
		var todos=$("input:checkbox[name^='distritos']")
		var activos=$("input:checked[name^='distritos']")
		$("#all").attr("checked",todos.length==activos.length)
		
	})


	$("#galery_images img").click(function(){	
		$("#big_image").hide();
		$("#big_image").attr("src",$(this).attr("title")).fadeIn("slow");
		$("#grande").attr("href",'aplication/webroot/imgs/catalogo/'+$(this).attr("alt")).fadeIn("slow");
		
	});
	
	$(function(){
		$('#menu li a').click(function(event){
			var elem = $(this).next();
			if(elem.is('ul')){
				event.preventDefault();
				$('#menu ul:visible').not(elem).slideUp();
				elem.slideToggle();
			}
		});
	});	
	
	$("#btn_buscar").click(function(){	
		var texto = $("#busqueda").val();
		//var distrito = $(".distrito :selected").text();	
		var distrito = $("#distrito").val();
		if(texto != "" ){
			texto = texto.replace(/(\s)/gi,"+");
                        distrito = distrito.replace(/(\s)/gi,"+");
			if( distrito != ""){texto = texto + '-en-' + distrito;} 
			//alert(texto);
                        busqueda("index.php",texto);
		}		
	});
		
	$("#btnv").click(function(){							
		$("#imagen_captcha").attr("src","captcha.php?ramd="+Math.random() * 9);						  
	});
	
	$("#btn_refresh").click(function(){							
		$("#imagen_captcha_registro").attr("src","captcha-registro.php?ramd="+Math.random() * 9);	
		$.get("operaciones.php",{option:'g-captcha'},function(data){
			$("#verifica_c").val(data);
		});					  
	});
	
		
	$.get("operaciones.php",{option:'g-captcha'},function(data){
		$("#verifica_c").val(data);
	});
	
	$("#send_comments").click(function(){
		$(this).preventDefault();
	});
	
	$('#form_comments').submit(function() {
		if(this.nombre.value == ''){
			alert("Ingrese su Nombre");
			this.nombre.focus();
			return false;
		}
		
		$.ajax({
			url: $(this).attr('action'),
			type:'POST',
			data:$(this).serialize(),
			success: function(data){
				if(data==0){
					
				}
			 }
		});
		return false;
	});
	
	
	
	$("a#login").fancybox();
	
	
	$('#j-joinSlideShare').live('click',function(e){
		e.preventDefault();
		if($('#modal_signup').is(":hidden")){
			$('#modal_signup').slideDown('slow');$('#fancy_outer').animate({height:'+=280'});
		}
		else{
			$('#modal_signup').slideUp('slow');
			$('#fancy_outer').animate({height:'-=280'});
		}
	});
	
	$('#j-signIn').live('click',function(e){
		e.preventDefault();
		if($('#modal_login').is(":hidden")){
			$('#modal_login').slideDown('slow');
			$('#fancy_outer').animate({height:'+=90'});
		}
		else{
			$('#modal_login').slideUp('slow');
			$('#fancy_outer').animate({height:'-=90'});
		}
	});
	
	$('#comentar').click(function(){
		if($("#comentario").val() == ''){
			alert("Ingrese su Comentario");
			$("#comentario").focus();
			return false;
		}
		$.ajax({
			url: 'ajax.php?saveComment=si',
			type:'POST',
			data:$("#form_comments").serialize(),
			success: function(data){
				$("#comentario").val("");
				alert("Su comentario esta siendo evaluado en estos momentos, Gracias.");
			}
		});
	});
	
	
});

function mostrar_registro3(ide){

    var id = encodeURIComponent(ide);
		 
		
        $("#registro2").animate({
					right: parseInt($("#registro2").css("right"))== 0 ?"-="+$("#registro2").outerWidth() : 0
				},2500, function(){ 
				           $("#registro2").css("opacity","1");   
						   $("#registro2").css("display","none");
						   $("#content_general_registro").load("ajax.php?viewRegistroPaso3=si&id="+id);
						   
						   });
						   
		
}

// pre-submit callback 
function showRequest(formData, jqForm, options) { 
    // formData is an array; here we use $.param to convert it to a string to display it 
    // but the form plugin does this for you automatically when it submits the data 
    var queryString = $.param(formData); 
 
    // jqForm is a jQuery object encapsulating the form element.  To access the 
    // DOM element for the form do this: 
    // var formElement = jqForm[0]; 
 
    alert('About to submit: \n\n' + queryString); 
 
    // here we could return false to prevent the form from being submitted; 
    // returning anything other than false will allow the form submit to continue 
    return true; 
} 
 
// post-submit callback 
function showResponse(responseText, statusText, xhr, $form)  { 
    // for normal html responses, the first argument to the success callback 
    // is the XMLHttpRequest object's responseText property 
 
    // if the ajaxForm method was passed an Options Object with the dataType 
    // property set to 'xml' then the first argument to the success callback 
    // is the XMLHttpRequest object's responseXML property 
 
    // if the ajaxForm method was passed an Options Object with the dataType 
    // property set to 'json' then the first argument to the success callback 
    // is the json data object returned by the server 
 
    alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + 
        '\n\nThe output div should have already been updated with the responseText.'); 
}


function GuardarRegistro(){
alert("GUARDAR");	
}

function checkCobertura(val){
	$(".item_distrito input[value='"+val+"']").attr("checked","checked");
	
}

function openWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}


function selectDistrito(obj){
	$(obj).parent().parent().parent().find("font").text($(obj).text());
	$(".idistrito").val($(obj).attr("rel"));
}
function deleteRow(obj){
	$(obj).parent().remove();
}

function busqueda(url,texto){
	
	document.fbuscar.action = url+'?q=' + texto;
	document.fbuscar.submit();
}

function checkTheKey(keyCode){
	if(event.keyCode==13){	
		valida();
		return true ;
	}
	return false ;
}

function validnum(e) { 
	tecla = (document.all) ? e.keyCode : e.which; 
	//alert(tecla)
    if (tecla==8 || tecla==46) return true; //Tecla de retroceso (para poder borrar) 
    // dejar la l�nea de patron que se necesite y borrar el resto 
    //patron =/[A-Za-z]/; // Solo acepta letras 
    patron = /\d/; // Solo acepta n�meros
    //patron = /\w/; // Acepta n�meros y letras 
    //patron = /\D/; // No acepta n�meros 
    // patron = /[\d.-]/; numeros el punto y el signo -
    te = String.fromCharCode(tecla); 
    return patron.test(te);  
	// uso  onKeyPress="return validnum(event)"
}



function validate(){
	
	if(document.f1.nombre.value==""){
		alert("ERROR: Por favor ingrese su Nombre");
		document.f1.nombre.focus();
		return false;
	}else if(document.f1.descripcion.value==""){
		alert("ERROR: Por favor describa lo que usted ofrece");
		document.f1.apellidos.focus();
		return false;
	}else if(document.f1.email.value==""){
		alert("ERROR: Por favor ingrese su Email");
		document.f1.email.focus();
		return false;
	}else if(document.f1.distrito.value==""){
		alert("ERROR: Por favor ingrese su distrito");
		document.f1.mensaje.focus();
		return false;
	}else if(document.f1.direccion.value==""){
		alert("ERROR: Por favor ingrese su direccion");
		document.f1.mensaje.focus();
		return false;
	}else if(document.f1.telefono.value==""){
		alert("ERROR: Por favor ingrese su Telefono");
		document.f1.telefono.focus();
		return false;
	}else{
		document.f1.action="registrar-delivery.php";
		document.f1.submit();
		
	}
	
}



function validate_registro(f1){
	var rubros = f1.elements['rubros[]'];
	var distritos = f1.elements['distritos[]'];
	var v = false;
	var c = false;
	var numeroChekeados = 0;
	
	for(i=0;i<rubros.length;i++){
		if(rubros[i].checked==true){
			v = true;
			numeroChekeados++;
		}	
	}
	for(i=0;i<distritos.length;i++){
		if(distritos[i].checked==true){
			c = true;
		}	
	}
	if(v==false){
		alert("Por favor seleccionar un rubro.");
		document.getElementById("list_rubros").style.border="1px solid #CC0000";
		window.scrollTo(0,0);
		return false;
	}
	else if(numeroChekeados > 2){
		alert("Solo se permite seleccionar hasta 2 rubros.");
		document.getElementById("rubros").focus();
		return false;
	}
	else if(f1.nombre.value==""){
		alert("Por favor ingrese Nombre o Razón Social");
		f1.nombre.focus();
		return false;
	}else if(f1.descripcion.value==""){
		alert("Por favor describa lo que usted ofrece");
		f1.descripcion.focus();
		return false;
	}else if(f1.telefono_delivery.value==""){
		alert("Por favor ingrese su Telefono");
		f1.telefono_delivery.focus();
		return false;
	}else if(f1.palabras_clave.value==""){
		alert("Por favor ingrese algunas palabras claves separado por (,).");
		f1.palabras_clave.focus();
		return false;
	}else if(c==false){
		alert("Por favor seleccionar un distrito para su cobertura.");
		return false;
	}else if($("#verifica_c").val() != f1.txtcaptcha.value){
		alert('Los caracteres ingresados son incorrectos');
		f1.txtcaptcha.focus();
		return false;	
	}
	f1.action="registrar-delivery.php";
}
