var $j = jQuery.noConflict();
$j(document).ready(function(){
    $j('.barra_idioma').show();
    $j(".btn_barra").click(function(){
       $j(".barra_idioma").slideToggle("normal");
       $j(this).toggleClass("metabtnactive");
   });

 }); 
$(function() {   
  $('tr.odd, tr.even').mouseover(function() {  
       $(this).addClass("overrow").show("slow");  
  } )  
  $('tr.odd, tr.even').mouseout(function() {  
      $(this).removeClass("overrow").show("slow");  
  } )   
})  

function doSubmit(id_form, action){
	$("#"+id_form).attr('action', action);
	$("#"+id_form).submit();
}

function doValid(id_form, action){
	
	if(initValidation(id_form)){
	
		$("#img_enviar").hide();
		doSubmit(id_form, action);		
	}
}

function load_ciudad(id_provincia) {
	html = $.ajax({
	type: "POST",
	url: "/mi_tree/registro/load_ciudad_co/"+id_provincia,
	async: false
	}).responseText;
	$('#localidad').html(html).hide().fadeIn("fast");
}



function contacto(){
	var form = document.contacto_form;
	var pre1 = false;

    with (form){
		for (var i = 0; i < motivo.length; i++) {
			if ( motivo[i].checked ) {pre1 = true;}
        }

		if (pre1 == false){
			alert("Debes seleccionar un motivo para tu consulta.");
            return;
        }else{
        	 if (/^([0-9a-zA-Z]([_.-w]*[0-9a-zA-Z])*@([0-9a-zA-Z]*[0-9a-zA-Z].)+([a-zA-Z]{2,9}.)+[a-zA-Z]{2,3})$/.test(email_.value)){
            doSubmit('contacto_form','contacto_action.php');
        	 }
        	 else{
        		 alert("La dirección de correo es incorrecta.\n");
                 return; 
        		 
        	 }
        }
	}
}

function validation_requests (id_form, url_action, num_preguntas){
	if(confirm("Estás seguro que desea enviar el informe? Comprueba los datos.")){
		var correcto = true;	
		// campos requeridos
		  $("#"+id_form).find(".required:visible").each(function(i) {
			id = $(this).attr("id");
		   valor=$(this).val();
			
		   if (valor=='' || valor=="0" || valor=="void"){
			   mark_field(id,'required');
			   correcto = false;		
		   }else 
				unmark_field(id,'required');
		 
		   });
		  
		  for(a=1; a<=num_preguntas; a++){
			  
			  // checkbox and radio ----------------------------------------------
			  var	k=0;	 
			  var	numero_total=false;
			  var checbox_validar = false;
				
			  $("#tr_pregunta_"+a).find(".required_check").each(function(i) {
				id = $(this).attr("id");
				
				// cogemos el id de cada uno y buscamos la longitud
				var checked = $("input[@id="+id+"]:checked").length; 
				if (checked == 0) { k++; } // sumamos uno al contador si encontramos vacío
				
				numero_total++;
				checbox_validar = true;
			
			  });
			  
			   if(true == checbox_validar && k==numero_total){ // comprobamos si hay como mínimo 1 seleccionado, de no ser así mostramos error
					correcto = false;
					 mark_field(id,'required');
					$(".tr_error_pregunta_"+a).show();				
			   }else{
				  $(".tr_error_pregunta_"+a).hide();
				}
				// FIN checkbox and radio----------------------------------------------		  
		  }
		  
		 if(correcto == true) doSubmit(id_form, url_action);
	}
}

function initValidation (id_form){

	var correcto = true;	
	// campos requeridos
	  $("#"+id_form).find(".required:visible").each(function(i) {
		   id = $(this).attr("id");
		   valor=$(this).val();
			disabled = $(this).attr("disabled");
			if(disabled != true){
			   if (valor=='' || valor=="0" || valor=="void"){
				   mark_field(id,'required');
				   correcto = false;		
			   }else 
					unmark_field(id,'required');
			}
	   });
	  
	  // campos radio requeridos
	  $("#"+id_form).find(".required_radio:visible").each(function(i) {
			id = $(this).attr("id");														   	
			name = $(this).attr("name");	   
		/*	alert($('input[name=check_tengo]:checked').val());
			if ($('input[name='+name+']:checked').val() !== null) {
			   unmark_field(id,'required');
				alert("1");	
		   }else{ 
		   		mark_field(id,'required');
			   correcto = false;	alert("0");					
		   }*/
	   });
	  
	  
	    
	   // checkbox ----------------------------------------------
	var	k=0;	 
	var	numero_total=false;
	var checbox_validar = false;
	
	// buscamos todos los checkbox que tengan la clase required_check
	   $("#"+id_form).find(".required_check:visible").each(function(i) {
		id = $(this).attr("id");
		 
	  	// cogemos el id de cada uno y buscamos la longitud
	    var checked = $("input[@id="+id+"]:checked").length; 
        if (checked == 0) { k++; } // sumamos uno al contador si encontramos vacío
		
		numero_total++;
		checbox_validar = true;

	   });

	
		
	   if(true == checbox_validar && k==numero_total){ // comprobamos si hay como mínimo 1 seleccionado, de no ser así mostramos error
		correcto = false;
		 mark_field(id,'required');
	 	$("#interested").show();
	   }else{

		   $("#interested").hide();
	   }
	   // FIN checkbox ----------------------------------------------
	  

     
	  
	// Aceptar condiciones	
	if($("#accept_cond:visible").attr("value") != undefined && $("#accept_cond:checked").val() == null){		
		mark_field('accept_cond','required');
		
	   correcto = false;
	}else{
		unmark_field('accept_cond','required');
	}
	  
	// campos password iguales	  
	pasw = $("#password").val();		
	repasw = $("#repassword").val();		
	if(pasw != undefined && pasw != ''){
		if (pasw == repasw){
   			unmark_field('password','match_password');  		
	   }else{ 
   		   mark_field('password','match_password');
		   correcto = false;
	   }  	
	}
	   
	  
	 
	// campos email
	$("#"+id_form).find(".valid_email:visible").each(function(i) {	
		id = $(this).attr("id");
	   valor=$(this).val();
	  
	   if (valor!='') {
	  if (!valor.match(/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i)){
	  	mark_field(id,'valid_email');
		correcto = false;
	  }else unmark_field(id,'valid_email');
	   }
	   });
	
	// campos numerico
	$("#"+id_form).find(".numeric:visible").each(function(i) {	
		id = $(this).attr("id");
	    valor=$(this).val();
	  
	   if (valor!='') {
	  if (!valor.match(/^\d+$/)){
	  	mark_field(id,'numeric');
		correcto = false;
	  }else unmark_field(id,'numeric');
	   }
	   });
	   
	 // min length
	 $("#"+id_form).find(".min_length:visible").each(function(i) {		
		id = $(this).attr("id");
	   valor=$(this).val();
	  if (valor!='') {
	  if (valor.length<6){
	  	mark_field(id,'min_length');
		correcto = false;
	  }
	   else unmark_field(id,'min_length');
	  }
	   });

	 $("#"+id_form).find(".minimum:visible").each(function(i) {			 
		id = $(this).attr("id");
	   valor=$(this).val();
	  if (valor!='') {
	  	id = $(this).attr("id");
	  	fieldcomp = id.substring(0, id.indexOf('_') );
	  	
	  	valor2=$("#"+fieldcomp).val();
	  
	  	if (parseInt(valor)>parseInt(valor2)){
	  	correcto = false;
	  	mark_field(id,'minimum');
		}
	   else unmark_field(id,'minimum');
	  }
	   }); 	  
	 
	 return correcto;
}

function mark_field (id, type)
{	
	$("#"+id).addClass("required_background");	
	//document.getElementById(id).style.backgroundColor="#ffffcc";
	//$("#"+id).addClass('fondo');

	$("#error_all_" + type).show();	
}

function unmark_field (id, type)
{	
	$("#"+id).removeClass("required_background");	
	$("#error_"+ id + "_" + type).hide();
	//$("../",id).remove("span");
}

function valid_panel(id_form, action){
	$("#alert_repeat_data").hide();
	if(validation_panel(id_form)){
		var tamano = $("#tamano").val();
		if($("#marca").attr('disabled')) html='ok'; 
		else{	html = $.ajax({
				type: "POST",		
				url: "/mi_tree/panel/comprobar_respuesta/"+tamano,
				async: false
				}).responseText;
		}
		
		//alert(html);
		if(html == 'respondido'){ 
			$("#alert_repeat_data").show();
			$("#tr_marca").addClass("tr_required_background");
			$("#tr_variedad").addClass("tr_required_background");
			$("#tr_tamano").addClass("tr_required_background");
			$("#alert_invalid_data").hide();
		}else{
			$("#alert_invalid_data").hide();
			$(".img_enviar").hide();
			doSubmit(id_form, action);		
		}
	}else $("#alert_invalid_data").show();
}

function validation_panel (id_form){

	var correcto = true;	
	// campos requeridos
	  $("#"+id_form).find(".required").each(function(i) {
			id = $(this).attr("id");
		   valor=$(this).val();
		   //alert(id);
			disabled = $(this).attr("disabled");
			if(disabled != true){
			   if (valor=='' || valor=="void"){
				   mark_tr(id,'tr_required_background');
				   unmark_tr(id, 'tr_not_answer');
				   correcto = false;		
			   }else 
					unmark_tr(id,'required');
				
			}
	   });
	  
	  // campos radio requeridos
	  $("#"+id_form).find(".required_radio:visible").each(function(i) {
			id = $(this).attr("id");														   	
			name = $(this).attr("name");	   
			disabled = $(this).attr("disabled");
			if(disabled != true){
				if ($('input[@name='+name+']:checked').val() !== null) {
				   unmark_tr(name,'required');
			   }else{ 
					mark_tr(name,'tr_required_background');
					unmark_tr(name, 'tr_not_answer');
				   correcto = false;
			   }
			}
	   });	   
	 // campos numerico
	$("#"+id_form).find(".numeric:visible").each(function(i) {	
			id = $(this).attr("id");
			valor=$(this).val();
		    disabled = $(this).attr("disabled");
			if(disabled != true){
			   if (valor!='') {
			  if (!valor.match(/^\d+$/)){
				mark_tr(id,'tr_required_background');
				unmark_tr(id, 'tr_not_answer');
				correcto = false;
			  }else unmark_tr(id,'numeric');
			   }
			}
	   });
	
	// campos numerico
	$("#"+id_form).find(".ean_code:visible").each(function(i) {	
			id = $(this).attr("id");
			
			valor=$(this).val();
		    disabled = $(this).attr("disabled");
			if(disabled != true){
			   if (valor!='') {
			  	 if (!checkEan(valor)){
					mark_tr(id,'tr_required_background');
					unmark_tr(id, 'tr_not_answer');
					alert("Revisa el código de barras. Debe ser sin espacios.");
					correcto = false;
			     }else{
					 unmark_tr(id,'numeric');					 
				 }
			   }
			}

	   });
	
	 return correcto;
}

function mark_tr (id, type)
{		
	$("#tr_"+id).addClass(type);			
}

function unmark_tr (id, type)
{	
	$("#tr_"+id).removeClass(type);		
}

function add_class(id, class2){

	$("#"+id).addClass(class2);

	
}

function remove_class(id, class2){

	$("#"+id).removeClass(class2);

	
}


function toggle_me(id){
	

		 $("#"+id).toggle();

}
						
function change_img(img, url){


document.getElementById(img).src=url;
	
}

function update_provincia(){
	cual = $('#provincia').attr("value");
    if(cual != '')
    {
        $('#show_loc').show('slow');
    }
	$("#registrate_p3").attr('action', 'registrate_p3.php');
	$("#registrate_p3").submit();
		
}


function show_whatever(id){

	$("#"+id).show();
	

}

function hide_whatever(id){

	//$("#"+id).hide();
	document.getElementById(id).style.visibility="hidden";


}






function change_sex_man(){

	document.getElementById('estado_civil').disabled="disabled";
	$("#estado_civil").hide();
	
	document.getElementById('estado_civil2').disabled="";
	$("#estado_civil2").show();
	
}

function change_sex_woman(){

	document.getElementById('estado_civil2').disabled="disabled";
	$("#estado_civil2").hide();
	
	document.getElementById('estado_civil').disabled="";
	$("#estado_civil").show();
	
}

// JavaScript Document

function onmouse_over(archivo, id, idioma){

eval("document."+id+".src='img/"+idioma+"/"+archivo+"'");
	
}

function onmouse_out(archivo, id, idioma){

eval("document."+id+".src='img/"+idioma+"/"+archivo+"'");
}
						
function borrar_opcion(text){
	if(confirm(text)){
		return true;
	}else return false;
}

function popup(page, title, width, height) {	
	window.open(page, title, "width=" + width + ",height="+height+",menubar=no,scrollbars=yes");
}

function cerrar(id){

	// Aparecían caracteres extraños así que he codificado el interrogante y la "a" con acento.
	if(confirm(String.fromCharCode(191)+'Estas seguro que quieres cerrar esta duda? Desaparecer\u00e1 de tu listado de respuestas.')){
		

	
		window.location = "/mi_tree/home/correocerrar/"+id;
	}

}

function doPost (uri, field_name, field_value)
{
	idForm=Math.round(Math.random()*10);
	
	htmlForm = "<form id='dyn_form' action='"+uri+"' method='POST'>";
	htmlForm+= "<input type='hidden' name='"+field_name+"' value='"+field_value+"' >";
	htmlForm+= "</form>";
	
	$("body").append(htmlForm);
	$("#dyn_form").submit();
}

function update_ciudades(server, name_field, ciudad_selected){
	var id_provincia = $("#"+name_field +"_provincia").attr("value");	
	if(ciudad_selected == '') $("#"+name_field +"_ciudad").attr("value");	

	var html = $.ajax({
		type: "POST",
  		url: server+"mi_tree/multi/update_ciudades/" + id_provincia + "/" + name_field + "/" + ciudad_selected,
  		async: false
	}).responseText;
	
	if(html != ''){
		var newOptions = unescape(html);
		newOptions = newOptions.replace(/\+/gi," ");
		
		$("#div_"+name_field+"_ciudades").html(newOptions);
		$("#tr_"+name_field+"_ciudades").show();		
	}else{
		$("#tr_"+name_field+"_ciudades").hide();
	}
}

/*
*Si el email es unico coloca una imagen de OK
*/

function email_unico(){
	var email = $("#email").val();
	var comprobar = false;
	if (email != '' && email.match(/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i)){
		
		var html = $.ajax({
			type: "POST",
			url: "/mi_tree/multi/is_email_unique/" + email,
			async: false
		}).responseText;
		//alert(html);
		if(html == 'yes'){
			$("#img_email_unique").html("<img src='/public/img/tick_green.png' alt='' />");
			$("#error_email_unique").hide();
			$("#email").css("background-color", "#FFF");
			comprobar = true;
		}else{
			$("#error_email_unique").show();
			$("#img_email_unique").html("&nbsp;&nbsp;");
			$("#email").css("background-color", "#FFE400");
		}
	}else $("#error_email_unique").hide();
	
	return comprobar;
}
/*
*Si el usuario es unico coloca una imagen de OK
*/
function usuario_unico(){
	var user = $("#user").val();
	var comprobar = false;
	if (user != ''){
		if( user.indexOf('@') != -1 ){
			
			$("#error_usuario_unique").show();
			$("#img_usuario_unique").html("<span class='verde_oscuro'>&nbsp;&nbsp; Caracter no permitido: @</span> &nbsp;");
			$("#user").css("background-color", "#FFE400");
			return comprobar;
		}
				
		var html = $.ajax({
			type: "POST",
			url: "/mi_tree/multi/is_user_unique/" + user,
			async: false
		}).responseText;
		//alert(html);
		if(html == 'yes'){
			$("#img_usuario_unique").html("<img src='/public/img/tick_green.png' alt='' />");
			$("#error_usuario_unique").hide();
			$("#user").css("background-color", "#FFF");
			comprobar = true;
		}else{
			$("#error_usuario_unique").show();
			$("#img_usuario_unique").html("&nbsp;&nbsp;");
			$("#user").css("background-color", "#FFE400");
		}
	}else $("#img_usuario_unique").hide();
	
	return comprobar;
}

/*
*Verifica que la referencia que nos brinda el usuario exista
*/
function amigo_existe(){
	var user = $("#codigo_amigo").val();
	var comprobar = false;
	if (user != ''){		
		var html = $.ajax({
			type: "POST",
			url: "/mi_tree/multi/amigo_existe/" + user,
			async: false
		}).responseText;
		//alert(html);
		if(html == 'yes'){
			$("#img_amigo_existe").html("<img src='/public/img/tick_green.png' alt='' />");
			$("#error_amigo_no_existe").hide();
			$("#codigo_amigo").css("background-color", "#FFF");
			comprobar = true;
		}else{
			$("#error_amigo_no_existe").show();
			$("#img_amigo_existe").html("&nbsp;&nbsp;");
			$("#codigo_amigo").css("background-color", "#FFE400");
		}
	}else $("#img_amigo_existe").hide();
	
	return comprobar;
}

/*
*esta seria la funcion a modificar para que el Barrio solo se vea en el caso de Argentina
*

$(document).ready(function(){
    $('#show_detalle').hide();
});
*/
function do_bar(){
	cual = $('#paises').attr("value");
	if(cual == 1)
    { 	
        $('#show_privado').show('slow');
        $('#show_prov').show('slow');
        
    }else{
        $('#show_privado').hide();
        $('#show_detalle').hide();
        $('#show_prov').show('slow');
    }
  }  
 /*
 function do_prov(){
	cual = $('#paises').attr("value");
	if(cual != ''){ 	
        $('#show_privado').show('slow');
    }else{
        $('#show_privado').hide();
        $('#show_detalle').hide();
        
    }
 }
 */
function do_detalle()
{
    enn = $('#barrio').attr('value');
    if(enn == 'si')
    {
        $('#show_detalle').show('normal');
       $('#show_detalle input').attr('disabled',false);
        
    }else
    {
        $('#show_detalle').show('normal');
        $('#show_detalle input').attr('disabled',true);
    }
}

/*
*Muestra un campo para comprobar que el usuario que rellena el formulario ya conoce a alguien dentro de la red
*de treemkt, si selecciona la opcion 2 (Como nos ha conocido = Por un amigo)
*
*/

function do_something(){							
	cual = $('#como_conocido').attr("value");

	if(cual == 2){ 	
		$('#codigo_amigo').show();
		$('#tr_codigo_amigo').show();
		$('#codigo_amigo_txt').show();
		$("#codigo_amigo").addClass("required").show("slow");
	}else{ $('#codigo_amigo').hide();  $('#codigo_amigo_txt').hide(); $('#tr_codigo_amigo').hide();}
}

function comprobar_registro(id_form, action){	
	if(initValidation(id_form) && email_unico() && usuario_unico()){
		$("#img_enviar").hide();
		doSubmit(id_form, action);
	}
}

function calcular_edad(dia_nacim,mes_nacim,anio_nacim)
{
    fecha_hoy = new Date();
    ahora_anio = fecha_hoy.getYear();
    ahora_mes = fecha_hoy.getMonth();
    ahora_dia = fecha_hoy.getDate();
    edad = (ahora_anio + 1900) - anio_nacim;
    if ( ahora_mes < (mes_nacim - 1))
    {
      edad--;
    }
    if (((mes_nacim - 1) == ahora_mes) && (ahora_dia < dia_nacim))
    { 
      edad--;
    }
    if (edad > 1900)
    {
    edad -= 1900;
    }
  return edad;
}

function mayor_de_14(){
	var dia = $("#dia").val();
	var mes = $("#mes").val();
	var ano = $("#ano").val();
	
	if(dia != 0 && mes != 0 && ano != 0){
		if(calcular_edad(dia, mes, ano) < 14){ $("#papa").show(); $("#papa2").show();  $(".mama").addClass("required").show("slow"); $("#accept_cond").show(); $("#error_mayor_14").show(); }
		else{ $("#papa").hide(); $("#papa2").hide();  $(".mama").removeClass("required").hide("slow"); $("#accept_cond").hide(); $("#error_mayor_14").hide(); }
	}else{
		$("#papa").hide(); $("#papa2").hide();  $(".mama").removeClass("required").hide("slow"); $("#accept_cond").hide();
	}
}

function ver_informe(id){
	var dominio = document.domain;
	document.write('<iframe src="http://www.treemkt.com/public/cuestionario_gogirls.php?dominio='+dominio+'&pagina=1" width="190" height="490" scrolling="no" frameborder="0" transparency><p>Texto alternativo para navegadores que no aceptan iframes.</p></iframe>');	
    document.write('<script type="text/javascript" src="http://w.sharethis.com/button/sharethis.js#publisher=847ede58-7d9b-432a-a338-99b68b2e4d01&amp;type=website&amp;post_services=email%2Cfacebook%2Ctwitter%2Cgbuzz%2Cmyspace%2Cdigg%2Csms%2Cwindows_live%2Cdelicious%2Cstumbleupon%2Creddit%2Cgoogle_bmarks%2Clinkedin%2Cbebo%2Cybuzz%2Cblogger%2Cyahoo_bmarks%2Cmixx%2Ctechnorati%2Cfriendfeed%2Cpropeller%2Cwordpress%2Cnewsvine"></script>');
}




function modificar_parte_arbol(nombre, url){
	var action = url.split("/");
	if (confirm("¿Estás seguro que quieres "+action[action.length-1]+" esta "+nombre+"?")){		
		
		var html = $.ajax({
			type: "POST",
			url: url,
			async: false
		}).responseText;
		
		var id_categoria = $("#categoria_id").val();
		var id_familia = $("#familia_id").val();
		var id_marca = $("#marca_id").val();
		var id_variedad = $("#variedad_id").val();		
		
		ver_categorias();
		
		if(id_categoria != '') ver_familias(id_categoria);
		if(id_familia != '') ver_marcas(id_familia);
		if(id_marca != '') ver_variedades(id_marca);
		if(id_variedad != '') ver_tamano(id_variedad);
	}
	else{
		return false;
	}	
}

function add_categoria(){
	
	var nombre = $('#nombre_categoria').val()
	var orden = $('#orden_categoria').val()
	
	if(nombre == '' || orden == ''){
		alert('Completa el Nombre y el Orden');
		return false;
	}
	
	$('#categoria_form').hide().fadeOut('slow');
	
	
	
	$('#nombre_categoria').attr('value', '');
	$('#orden_categoria').attr('value', '');
	
	var categoria_id = $("#form_categoria_id").val();
	
	if(categoria_id > 0){
		var html = $.ajax({
			type: "POST",
			data: "id_categoria="+categoria_id+"&nombre="+nombre+"&orden="+orden,
			url: "/admin/panel/edit_categoria/",
			async: false
		}).responseText;		
	}else{
		var html = $.ajax({
			type: "POST",
			data: "nombre="+nombre+"&orden="+orden,
			url: "/admin/panel/add_categoria/",
			async: false
		}).responseText;
	}
	
	$('#categoria').html(html).hide().fadeIn("fast");

	return false;
}


function add_familia(){
	
	var categoria = $('#categoria_id').val();
	
	if(categoria == null || categoria == "undefined"){
		
			alert('Antes de Crear, selecciona una Categoría');
	}else{
		
		
		var nombre = $('#nombre_familia').val()
		var orden = $('#orden_familia').val()
		
		if(nombre == '' || orden == ''){
			alert('Completa el Nombre y el Orden');
			return false;
		}
		
		$('#familia_form').hide().fadeOut('slow');		
		
		$('#nombre_familia').attr('value', '');
		$('#orden_familia').attr('value', '');
		
		var familia_id = $('#form_familia_id').val()
	
		if(familia_id > 0){
			var html = $.ajax({
				type: "POST",
				data: "familia_id="+familia_id+"&nombre="+nombre + "&orden="+orden,
				url: "/admin/panel/edit_familia/" + categoria,
				async: false
			}).responseText;
		}else{
			var html = $.ajax({
				type: "POST",
				data: "nombre="+nombre + "&orden="+orden,
				url: "/admin/panel/add_familia/" + categoria,
				async: false
			}).responseText;
		}
		$('#familia').html(html).hide().fadeIn("fast");
	
				
	}
	
	return false;
	
}


function add_marca(){
	
	var familia = $('#familia_id').val();
	
	if(familia == null || familia== "undefined"){
		
			alert('Antes de Crear, selecciona una Família');
	}else{
		
		
		var nombre = $('#nombre_marca').val()
		var orden = $('#orden_marca').val()
		
		if(nombre == '' || orden == ''){
			alert('Completa el Nombre y el Orden');
			return false;
		}
		
		$('#marca_form').hide().fadeOut('slow');		
		
		$('#nombre_marca').attr('value', '');
		$('#orden_marca').attr('value', '');
		
		var marca_id = $('#form_marca_id').val();
		if(marca_id > 0){
			var html = $.ajax({
				type: "POST",
				data: "marca_id="+marca_id+"&nombre="+nombre + "&orden="+orden,
				url: "/admin/panel/edit_marca/" + familia,
				async: false
			}).responseText;
		}else{
			var html = $.ajax({
				type: "POST",
				data: "nombre="+nombre + "&orden="+orden,
				url: "/admin/panel/add_marca/" + familia,
				async: false
			}).responseText;
		}
		$('#marca').html(html).hide().fadeIn("fast");
	
				
	}
	
	return false;
	
}

function add_variedad(){
	
	var marca = $('#marca_id').val();
	
	if(marca == null || marca== "undefined"){
		
			alert('Antes de Crear, selecciona una Marca');
	}else{
		
		
		var nombre = $('#nombre_variedad').val()
		var orden = $('#orden_variedad').val()
		
		if(nombre == '' || orden == ''){
			alert('Completa el Nombre y el Orden');
			return false;
		}
		
		$('#variedad_form').hide().fadeOut('slow');		
		
		$('#nombre_variedad').attr('value', '');
		$('#orden_variedad').attr('value', '');
		
		var variedad_id = $('#form_variedad_id').val();
		if(variedad_id > 0){
			var html = $.ajax({
				type: "POST",
				data: "variedad_id="+variedad_id+"&nombre="+nombre + "&orden="+orden,
				url: "/admin/panel/edit_variedad/" + marca,
				async: false
			}).responseText;
		}else{
			var html = $.ajax({
				type: "POST",
				data: "nombre="+nombre + "&orden="+orden,
				url: "/admin/panel/add_variedad/" + marca,
				async: false
			}).responseText;
		}
		$('#variedades').html(html).hide().fadeIn("fast");
	
				
	}
	
	return false;
	
}


function add_tamano(){
	
	var variedad = $('#variedad_id').val();
	
	if(variedad == null || variedad== "undefined"){
		
			alert('Antes de Crear, selecciona una Variedad');
	}else{
		
		
		var tamano = $('#tamano_tamano').val()
		var precio = $('#precio_tamano').val()
		var orden = $('#orden_tamano').val()
		
		if(tamano == ''){
			alert('Completa el Tamaño');
			return false;
		}
		
		if(precio == '') precio = 0;
		if(orden == '') orden = 1;
		
		$('#tamano_form').hide().fadeOut('slow');		
		
		$('#tamano_tamano').attr('value', '');
		$('#precio_tamano').attr('value', '');
		$('#orden_tamano').attr('value', '');
	
		var tamano_id = $('#form_tamano_id').val();
		if(tamano_id > 0){
			var html = $.ajax({
				type: "POST",
				data: "tamano_id="+tamano_id+"&tamano="+tamano + "&precio=" + precio + "&orden="+orden,
				url: "/admin/panel/edit_tamano/" + variedad,
				async: false
			}).responseText;
		}else{
			var html = $.ajax({
				type: "POST",
				data: "tamano="+tamano + "&precio=" + precio + "&orden="+orden,
				url: "/admin/panel/add_tamano/" + variedad,
				async: false
			}).responseText;
		}
		$('#tamano').html(html).hide().fadeIn("fast");
	
				
	}
	
	return false;
	
}


function show_secret_form(form, id){
	var html = $.ajax({
		type: "POST",		
		url: "/admin/panel/load_add_"+form+"/" + id,
		async: false
	}).responseText;
	
	$('#'+form).html(html).hide().fadeIn("slow");
	
	
}

function ver_categorias(){		
	var html = $.ajax({
		type: "POST",
  		url: "/admin/panel/ver_categorias/",
  		async: false
	}).responseText;
	
	$('#categoria').html(html).hide().fadeIn("fast");

	$('#familia').html('').hide().fadeIn("fast");
	$('#marca').html('').hide().fadeIn("fast");
	$('#variedades').html('').hide().fadeIn("fast");
	$('#tamano').html('').hide().fadeIn("fast");
}


function ver_familias(id_categoria){
	
		
	$('#categoria .item_arbol_selected').removeClass('item_arbol_selected');
	$('#categoria_'+id_categoria).addClass('item_arbol_selected');
	
	var html = $.ajax({
		type: "POST",
  		url: "/admin/panel/ver_familias/" + id_categoria,
  		async: false
	}).responseText;
	
	$('#familia').html(html).hide().fadeIn("fast");


	$('#marca').html('').hide().fadeIn("fast");
	$('#variedades').html('').hide().fadeIn("fast");
	$('#tamano').html('').hide().fadeIn("fast");
}


function ver_marcas(id_familia){
	
	$('#familia .item_arbol_selected').removeClass('item_arbol_selected');
	$('#familia_'+id_familia).addClass('item_arbol_selected');
	
	var html = $.ajax({
		type: "POST",
  		url: "/admin/panel/ver_marcas/" + id_familia,
  		async: false
	}).responseText;
	
	$('#marca').html(html).hide().fadeIn("fast");
	

	$('#variedades').html('').hide().fadeIn("fast");
	$('#tamano').html('').hide().fadeIn("fast")	
}

function ver_variedades(id_marca){
	
		
	$('#marca .item_arbol_selected').removeClass('item_arbol_selected');
	$('#marca_'+id_marca).addClass('item_arbol_selected');
	
	var html = $.ajax({
		type: "POST",
  		url: "/admin/panel/ver_variedades/" + id_marca,
  		async: false
	}).responseText;
	
	$('#variedades').html(html).hide().fadeIn("fast");
	
	$('#tamano').html('').hide().fadeIn("fast")	
}


function ver_tamano(id_variedad){	
	$('#variedades .item_arbol_selected').removeClass('item_arbol_selected');
	$('#variedad_'+id_variedad).addClass('item_arbol_selected');
	
	var html = $.ajax({
		type: "POST",
  		url: "/admin/panel/ver_tamanos/" + id_variedad,
  		async: false
	}).responseText;
	
	$('#tamano').html(html).hide().fadeIn("fast");		
}

function checkEan(eanCode) {
	// Check if only digits
	var ValidChars = "0123456789";
	for (i = 0; i < eanCode.length; i++) {
		digit = eanCode.charAt(i);
		if (ValidChars.indexOf(digit) == -1) {
			return false;
		}
	}

	// Add five 0 if the code has only 8 digits
	if (eanCode.length == 8 ) {
		eanCode = "00000" + eanCode;
	}
	// Check for 13 digits otherwise
	else if (eanCode.length != 13) {
		return false;
	}

	// Get the check number
	originalCheck = eanCode.substring(eanCode.length - 1);
	eanCode = eanCode.substring(0, eanCode.length - 1);

	// Add even numbers together
	even = Number(eanCode.charAt(1)) +
	       Number(eanCode.charAt(3)) +
	       Number(eanCode.charAt(5)) +
	       Number(eanCode.charAt(7)) +
	       Number(eanCode.charAt(9)) +
	       Number(eanCode.charAt(11));
	// Multiply this result by 3
	even *= 3;

	// Add odd numbers together
	odd = Number(eanCode.charAt(0)) +
	      Number(eanCode.charAt(2)) +
	      Number(eanCode.charAt(4)) +
	      Number(eanCode.charAt(6)) +
	      Number(eanCode.charAt(8)) +
	      Number(eanCode.charAt(10));

	// Add two totals together
	total = even + odd;

	// Calculate the checksum
    // Divide total by 10 and store the remainder
    checksum = total % 10;
    // If result is not 0 then take away 10
    if (checksum != 0) {
        checksum = 10 - checksum;
    }

	// Return the result
	if (checksum != originalCheck) {
		return false;
	}

    return true;
}
function LP_data(e){
key=(document.all) ? e.keyCode : e.which;
if ((key < 48 || key > 57) && (key !=8)){
alert("solo se pueden ingresar numeros");
return false;
}else{
return true;}
}

