	var alfabeto = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>A-Za-z)+]/;
	var car_no_per = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;		
	var alfabeto_y_punto = /[(\*\(\)\[\]\+\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>A-Za-z)+]/;
	var url_val = /[(\*\(\)\[\]\+\,\;\'\"\`\~\\#\$\%\^\<\>)+]/;
	var fecha_valida = /^((?:0?[1-9])|(?:[12]\d)|(?:3[01]))\/((?:0?[1-9])|(?:1[0-2]))\/((?:19|20)\d\d)$/;
	
	new function() {
    jQuery.fn.validate = {    		
        init: function(o) {
          if(o.name == 'nombre') { return this.nombre(o) };
          if(o.name == 'precio_clic') { return this.precio_clic(o) };
          if(o.name == 'precio_vista') { return this.precio_vista(o) };
          if(o.name == 'n_max_banners') { return this.n_max_banners(o) };
          if(o.name == 'vistas_dia') { return this.vistas_dia(o) };
          if(o.name == 'texto') { return this.texto(o); };
          if(o.name == 'url') { return this.url(o) };
          if(o.name == 'numero') { return this.numero(o) };
          if(o.name == 'porcentaje') { return this.porcentaje(o) };
          if(o.name == 'descuento') { return this.descuento(o) };
          if(o.name == 'inversion') { return this.inversion(o) };
          if(o.name == 'credito') { return this.credito(o) };
          if(o.name == 'rango_desde') { return this.rango(o) };
          if(o.name == 'rango_hasta') { return this.rango(o) };
          if(o.name == 'peso') { return this.peso(o) };
          if(o.name == 'alto') { return this.alto(o) };
          if(o.name == 'ancho') { return this.ancho(o) };
        },
        nombre: function(o) {
           	if (o.value.match(car_no_per)) {
             		return doError(o,'No se permiten caracteres especiales.');
            } else if (o.value.length == 0) {
            		return doError(o,'Este campo no puede estar vac&iacute;o.');
            } else {
            		return doSuccess(o);
            };
        }, precio_clic: function(o) {
           	if (o.value.match(alfabeto_y_punto)) {
             		return doError(o,'Este campo debe ser num&eacute;rico ( punto decimal -> . ).');
            } else if (o.value.length == 0) {
            		return doError(o,'Este campo no puede estar vac&iacute;o.');
            } else {
            		return doSuccess(o);             		
            };
      	}, precio_vista: function(o) {
           	if (o.value.match(alfabeto_y_punto)) {
             		return doError(o,'Este campo debe ser num&eacute;rico ( punto decimal -> . ).');
            } else if (o.value.length == 0) {
            		return doError(o,'Este campo no puede estar vac&iacute;o.');
            } else {
            		return doSuccess(o);
            };
      	}, n_max_banners: function(o) {
           	if (o.value.match(alfabeto)) {
             		return doError(o,'Este campo debe ser num&eacute;rico.');
            } else if (o.value.length == 0) {
            		return doError(o,'Este campo no puede estar vac&iacute;o.');
            } else {
            		return doSuccess(o); 		
            };
      	}, vistas_dia: function(o) {
           	if (o.value.match(alfabeto)) {
             		return doError(o,'Este campo debe ser num&eacute;rico.');
            } else if (o.value.length == 0) {
            		return doError(o,'Este campo no puede estar vac&iacute;o.');
            } else {
            		return doSuccess(o);
            };
      	}, texto: function(o) {
           	if (o.value.match(car_no_per)) {
             		return doError(o,'No se permiten caracteres especiales.');
            } else if (o.value.length == 0) {
            		return doError(o,'Este campo no puede estar vac&iacute;o.');
            } else {
            		return doSuccess(o);
            };
      	}, url: function(o) {
           	if (o.value.match(url_val)) {
             		return doError(o,'No se permiten caracteres especiales.');
            } else if (o.value.length == 0) {
            		return doError(o,'Este campo no puede estar vac&iacute;o.');
            } else {
            		return doSuccess(o);
            };
      	}, numero: function(o) {
           	if (o.value.match(alfabeto)) {
             		return doError(o,'Este campo debe ser num&eacute;rico.');
            } else if (o.value.length == 0) {
            		return doError(o,'Este campo no puede estar vac&iacute;o.');
            } else if (o.value == 0) {
            		return doError(o,'Este campo debe ser mayor que cero.');
            } else {
            		return doSuccess(o); 		
            };
      	}, porcentaje: function(o) {
						if (o.value == '') {
            		return doError(o,'Por favor, indique el porcentaje.');
            } else {
            		return doSuccess(o); 		
            };
        }, descuento: function(o) {
           	if (o.value.match(alfabeto)) {
             		return doError(o,'Este campo debe ser num&eacute;rico.');
            } else if (o.value.length == 0) {
            		return doError(o,'Este campo no puede estar vac&iacute;o.');
            } else {
            		return doSuccess(o);             		
            };
      	}, inversion: function(o) {
           	if (o.value.match(alfabeto_y_punto)) {
             		return doError(o,'Este campo debe ser num&eacute;rico.');
            } else if (o.value.length == 0) {
            		return doError(o,'Este campo no puede estar vac&iacute;o.');
            } else if (o.value == 0) {
            		return doError(o,'Este campo debe ser mayor que cero.');
            } else {
            		return doSuccess(o);             		
            };
      	}, credito: function(o) {
           	if (o.value.match(alfabeto)) {
             		return doError(o,'Este campo debe ser num&eacute;rico.');
            } else if (o.value.length == 0) {
            		return doError(o,'Este campo no puede estar vac&iacute;o.');
            } else {
            		return doSuccess(o);             		
            };
				}, rango: function(o) {
						if (o.value.length == 0) {
            		return doError(o,'Este campo no puede estar vac&iacute;o.');
            } else if (!fecha_valida.test(o.value)) {
            		return doError(o,'El formato de la fecha <strong>' + o.name.substring(6) + '</strong> no es correcto');
          	} else {
            		return doSuccess(o);             		
            };
      	}, peso: function(o) {
           	if (o.value.match(alfabeto)) {
             		return doError(o,'Este campo debe ser num&eacute;rico.');
            } else if (o.value.length == 0) {
            		return doError(o,'Este campo no puede estar vac&iacute;o.');
            } else {
            		return doSuccess(o);             		
            };
      	}, alto: function(o) {
           	if (o.value.match(alfabeto)) {
             		return doError(o,'Este campo debe ser num&eacute;rico.');
            } else if (o.value.length == 0) {
            		return doError(o,'Este campo no puede estar vac&iacute;o.');
            } else {
            		return doSuccess(o);
            };
        }, ancho: function(o) {
           	if (o.value.match(alfabeto)) {
             		return doError(o,'Este campo debe ser num&eacute;rico.');
            } else if (o.value.length == 0) {
            		return doError(o,'Este campo no puede estar vac&iacute;o.');
            } else {
            		return doSuccess(o);
            };
         }       
     };

     function doSuccess(o) {
              jQuery('#' + o.id + '_img').html('');
              jQuery('#' + o.id + '_msg').html('');
              return true;
     }

     function doError(o,m) {
              jQuery('#' + o.id + '_img').html('<img src="/wp-content/plugins/gestor-publicidad/img/exclamation.gif" border="0" style="float:left;" />');
              jQuery('#' + o.id + '_msg').html(m);
              return false;
     }

	};
	
	var error_ubicacion = 0;
	var error_banner = 0;
	var error_campagna = 0;

	jQuery(document).ready(function() {
      jQuery('select').each(function () {
      		if (this.name == 'ubicacion_id')
      			cambiarPorcentaje_mostrarCatPos(this.value, 'ubicaciones',0);
      		else if (this.name == 'usuario_id') {
      			if (jQuery('#cam_id_act') != null)
      				cambiarCredito(this.value, 0);
      			else
      				cambiarCredito(this.value, 1);
      		}
      });
      
      /*if (jQuery('#descuento').attr("disabled") == false) {
      	jQuery('#precio_final').html('<strong>0&euro;</strong>');
      } else {
      	if (jQuery('#descuento').val != '0')
      		jQuery('#descuento').val('0');
      }*/
	});
	
	function recorrerCamposUbicacion(frm) {
      	jQuery.each(frm, function() {
						if (this.type == 'text') {
							if(!jQuery(this).validate.init(this)) {
								error_ubicacion++;
							}
						}
						if (this.type == 'hidden') {
							if ((this.name == 'objetos_vacio') && (this.value == 1)) {
								error_ubicacion++;
							}
						}
				});
	}
	
	function recorrerCamposBanner(frm) {
				var error_imagen = '';
				
      	jQuery.each(frm, function() {
						if (((this.name == 'texto') && (jQuery('input[@name=tipo]:checked').val() == 2)) ||
								((this.name == 'numero') && (jQuery('#tipo_con_id').val() != 3)) ||
								((this.name == 'inversion') && (jQuery('#tipo_con_id').val() == 3)) ||
										(this.name == 'url') ||
										(this.name == 'porcentaje')) { 
								if(!jQuery(this).validate.init(this)) {
										error_banner++;
								}
						}
				});
				
				frm.action = 'admin.php?page=gestor-publicidad/php/controlador.php';
				frm.target = '_self';
	}

	function recorrerCamposEdicionBanner(frm) {
      	jQuery.each(frm, function() {
						if ((this.name == 'url') ||
								(this.name == 'texto')) {
									if(!jQuery(this).validate.init(this)) {
											error_banner++;
									}
								}
				});
				
				frm.action = 'admin.php?page=gestor-publicidad/php/controlador.php';
				frm.target = '_self';
	}

	function validarFormularioUbicacion(frm) {
				recorrerCamposUbicacion(frm);

				if (error_ubicacion == 0) {
					frm.submit();
				} else {
					error_ubicacion = 0;
				}
	}
	
	function comprobarSeleccionadaUbiEliminar(frm) {
				var seleccionada = false;
      	jQuery.each(frm, function() {						
						if (this.type == 'checkbox') {
							if (this.checked) {
								seleccionada = true;
							}
						}
				});

				if (seleccionada) {
					if (confirm('¿Desea realmente eliminar las ubicaciones seleccionadas?'))
						frm.submit();
				} else
					alert('Por favor, seleccione una ubicacion.');
	}

	function comprobarSeleccionadaCamEliminar(frm) {
				var seleccionada = false;
      	jQuery.each(frm, function() {						
						if (this.type == 'checkbox') {
							if (this.checked) {
								seleccionada = true;
							}
						}
				});

				if (seleccionada) {
					if (confirm('¿Desea realmente eliminar las campañas seleccionadas?'))
						frm.submit();
				} else
					alert('Por favor, seleccione una campaña.');
	}
	function validarFormularioCampagna(frm) {
			error_campagna = 0;
			jQuery.each(frm, function() {
				if(!jQuery(this).validate.init(this)) {
					if (this.name == 'nombre')
						error_campagna++;
				}
			});

			if (error_campagna == 0) {
				jQuery('#nombre_campagna_gu').val(jQuery('#nombre').val());
				if (jQuery('#activa').attr('checked') == true)
					jQuery('#campagna_activa_gu').val(1);
				else
					jQuery('#campagna_activa_gu').val(0);
				jQuery('#campagna_descuento_gu').val(jQuery('#descuento').val());
				frm.submit();
			} else
				error_campagna = 0;			
	}

	function validarFormularioBanner(frm) {
			error_banner = 0;

			if (jQuery('input[@name=tipo]:checked').val() == 1) {
					comprobarFormatoTamanoArchivo();
			}

			recorrerCamposBanner(frm);
			
			if (error_banner == 0) {					
					jQuery('#nombre_campagna').val(jQuery('#nombre').val());
					if (jQuery('#activa').attr('checked') == true)
						jQuery('#campagna_activa').val(1);
					else
						jQuery('#campagna_activa').val(0);
					jQuery('#campagna_descuento').val(jQuery('#descuento').val());
					jQuery('#campagna_usuario').val(jQuery('#usuario_id').val());
					
					frm.submit();
			} else {
					error_banner = 0;
			}
	}
	
	function validarFormularioEdicionBanner(frm) {
			error_banner = 0;

			var or = document.getElementsByName('galeria_radio');
			var elegida_galeria = false;
      for (var i = 0; i < or.length; i++) {
         if (or[i].checked)
         		elegida_galeria = true;
     	}

			if ((jQuery('#imagen').val() != '') || (elegida_galeria))
					comprobarFormatoTamanoArchivoEd();

			recorrerCamposEdicionBanner(frm);
			if (error_banner == 0) {
					frm.submit();						
			} else {
					error_banner = 0;
			}
	}
	
	function validarFormularioEdicionUsuario(frm) {
			var error_usuario = 0;
      jQuery.each(frm, function() {
					if (this.name == 'credito') {
							if(!jQuery(this).validate.init(this)) {
									error_usuario++;
							}
					}
			});
			
			if (error_usuario == 0) {
					frm.submit();						
			} else {
					error_banner = 0;
			}
	}
	
	function cambiarTipoBanner(tipo1, tipo2) {
		jQuery('#' + tipo1).css('display','');
		jQuery('#' + tipo2).css('display','none');
	}
	
	function cambiarTipoCon() {
		var tipo = document.forms[1].tipo_con_id.value;
		jQuery('#inversion').val('0');
		if ((tipo == 1) || (tipo == 2)) {
				jQuery('#numero').val('0');				
				jQuery('#tipo_con_num').css('display','');				
				jQuery('#rango_fechas').css('display','none');
		} else if (tipo == 3) {
				jQuery('#tipo_con_num').css('display','none');
				jQuery('#rango_fechas').css('display','');
				calculos(2);
		}
	}
	
	function cambiarPorcentaje_mostrarCatPos(ubi_id_par, procedencia, idioma) {
		var ubi_id = 0;
		if (ubi_id_par == 0)
			ubi_id = document.forms[1].ubicacion_id.value;
		else
			ubi_id = ubi_id_par;

		url_p = plugin_url + '?ubi_id=' + ubi_id + '&idioma=' + idioma;
		html = jQuery.ajax({
  			url: url_p,
  			async: false
 		}).responseText;
 		jQuery('#porcentaje_select').html(html);

		// Introducimos datos de la ubicación actual en sesión
		var url_datos_ubi_actual = plugin_url_datos_ubicacion_actual + '?ubicacion_id=' + jQuery('#ubicacion_id').val();
		var valor = jQuery.ajax({
	  			url: url_datos_ubi_actual,
	  			async: false
	 	}).responseText;
	 	
		cambiarTipoCon();
	}
	
	function calculos(tipo) {
		var url_calculos = plugin_url_calculos;
		var error = false;
		var frm = document.forms[1];
		
		if (tipo == 1) {
      jQuery.each(frm, function() {
					if (this.name == 'numero') {
							if(!jQuery(this).validate.init(this)) {
									error = true;
							}
					}
			});
			url_calculos += '?numero=' + jQuery('#numero').val() + '&tipo_con=' + jQuery('#tipo_con_id').val();
		} else if (tipo == 2) {
      jQuery.each(frm, function() {
					if (this.name == 'rango_desde') {
							if(!jQuery(this).validate.init(this)) {
									error = true;
							}
					}
					
					if (this.name == 'rango_hasta') {
							if(!jQuery(this).validate.init(this)) {
									error = true;
							}
					}

			});
			url_calculos += '?desde=' + jQuery('#rango_desde').val() + '&hasta=' + jQuery('#rango_hasta').val();
		} else if (tipo == 3) {
      jQuery.each(frm, function() {
					if (this.name == 'inversion') {
							if(!jQuery(this).validate.init(this)) {
									error = true;
							}
					}
			});

			url_calculos += '?inversion=' + jQuery('#inversion').val() + '&tipo_con=' + jQuery('#tipo_con_id').val();;
		}
		
		url_calculos += '&tipo=' + tipo;

		if (!error) {
			jQuery('#rango_desde_img').html('');
			jQuery('#rango_hasta_img').html('');
		  jQuery('#rango_desde_msg').html('');
		  jQuery('#rango_hasta_msg').html('');

			var valor = jQuery.ajax({
		  			url: url_calculos,
		  			async: false
		 	}).responseText;

			if ((tipo == 1) || (tipo == 2)) {
				if (valor == '') {
						jQuery('#rango_desde_img').html('<img src="/wp-content/plugins/gestor-publicidad/img/exclamation.gif" border="0" style="float:left;" />');
	          jQuery('#rango_desde_msg').html('La fecha <strong>hasta</strong> debe ser posterior a la fecha <strong>desde</strong>.');
	      }						
				jQuery('#inversion').val(valor);
				jQuery('#inversion_img').html('');
				jQuery('#inversion_msg').html('');
			} else if (tipo == 3) {
				if ((jQuery('#tipo_con_id').val() == 1) || (jQuery('#tipo_con_id').val() == 2)) {
					jQuery('#numero').val(valor);
					jQuery('#numero_img').html('');
					jQuery('#numero_msg').html('');
				} else
					jQuery('#rango_hasta').val(valor);
			}
		}
	}
	
	function cambiarCredito(usr_id_par, nuevo) {
		var usr_id = 0;
		var activa = '';
		if (usr_id_par == 0)
			usr_id = document.forms[0].usuario_id.value;
		else
			usr_id = usr_id_par;

		if (jQuery('#activa').attr('checked') == true)
			activa = '&activa=1';
		else
			activa = '&activa=0';
		var puc = plugin_url_credito + '?usr_id=' + usr_id + activa + '&nuevo=' + nuevo;

		// Limpiamos el espacio de mensajes
		jQuery('#div_activa').html('');
		var html = jQuery.ajax({
  			url: puc,
  			async: false
 		}).responseText;
 		jQuery('#credito').html(html);
 		
 		var pug = plugin_url_galeria + '?usr_id=' + usr_id;

		html = jQuery.ajax({
  			url: pug,
  			async: false
 		}).responseText;
 		jQuery('#galeria').html(html);
	}

	function comprobarFormatoTamanoArchivo() {
 		jQuery('#incluir_banner').ajaxSubmit({
 			url: plugin_url_archivo,
 			target: jQuery('#imagen_msg'),
 			success: procesoRespuestaCFT
 		}); 		
	}
	
	function comprobarFormatoTamanoArchivoEd() {
			// Se comprueban el tamaño y el formato del archivo
	 		jQuery('#editar_banner').ajaxSubmit({
	 			url: plugin_url_archivo,
 				target: jQuery('#imagen_msg'),
 				success: procesoRespuestaCFT
 			});
 	}

	
	function procesoRespuestaCFT(responseText, statusText) {		
			if (responseText != '')
				error_banner++;
	}

	function generarPrecioDescuento(precio) {
		var error_descuento = 0;
		var descuento = 0;
		var html = '';
		
		if ((jQuery('#descuento').val().match(alfabeto)) || (jQuery('#descuento').val().length == 0)) {
			html = '<strong>0&euro;</strong>';
		} else {
			descuento = jQuery('#descuento').val();
			html = '<strong>' + (precio - precio*(descuento/100))  + '&euro;</strong>';
		}
		
		jQuery('#precio_final').html(html);
	}
	
	function validarEliminacionBannerSesion(indice) {
		if (confirm('¿Desea realmente eliminar el banner de la campaña?')) {
			jQuery('#indice').val(indice);
			jQuery('#nombre_campagna_el').val(jQuery('#nombre').val());
			if (jQuery('#activa').attr('checked') == true)
				jQuery('#campagna_activa_el').val(1);
			else
				jQuery('#campagna_activa_el').val(0);
			jQuery('#campagna_descuento_el').val(jQuery('#descuento').val());
			jQuery('#campagna_usuario_el').val(jQuery('#usuario_id').val());
			document.forms[2].submit();
		}
	}
	
	function desactivarRadioButtonGaleria() {
			var or = document.getElementsByName('galeria_radio');
      for (var i = 0; i < or.length; i++) {
         or[i].checked = false;
     	}
	}

	function MM_openBrWindow(theURL,winName,features) { //v2.0
		foto1 = new Image();
		foto1.src = (theURL);
		Control(theURL, winName, features);
  	//window.open(theURL,winName,features);
	}
	
	function Control(img, winName, features){
       verFoto(img, winName, features);
	}

	function verFoto(img, winName, features){
		if ((foto1.width == 0) && (foto1.height == 0)) {
				ventana=window.open(img,winName,features);
		} else {
       ancho=foto1.width+20;       
       alto=foto1.height+20;      
       cadena="width=640,height=480";
       ventana=window.open(img,"gestor_popup",cadena);
    }
  }
  
  /*
  function generarEstadisticas(idcbu, idtipocontratacion, idcampagna, idbanner, idubicacion, idubicacionwp) {
  	var url = 'wp-admin/admin.php';
  	url  += '?page=gestor-publicidad/php/controlador.php&accion=generar_estadistica&idcbu=' + idcbu + '&idtipocontratacion=' + idtipocontratacion;
  	url += '&idcampagna=' + idcampagna;
 		url += '&idbanner=' + idbanner;
 		url += '&idubicacion=' + idubicacion;
 		url += '&idubicacionwp=' + idubicacionwp;

  	jQuery.post(url);
  }
  */
  function generarEstadisticas(idcbu, clic_vista, idtipocontratacion) {
	var url = 'wp-admin/admin.php';
	url  += '?page=gestor-publicidad/php/controlador.php&accion=generar_estadistica&idcbu=' + idcbu + '&clic_vista=' + clic_vista + '&idtipocontratacion=' + idtipocontratacion;
	
	jQuery.post(url);
  }
  
  
  function consultarObjetosWP() {
		var zona_id = document.forms[0].zona_id.value;

		var url = plugin_url_consulta_objetos + '?zona_id=' + zona_id;
		var html = jQuery.ajax({
		  			url: url,
		  			async: false
		 	}).responseText;
		jQuery('#objetos_wp_div').html(html);
	}