Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};

var datePicker =
	function() {
		$("input.fecha").datepicker({
			dateFormat: 'dd-mm-yy',
			showOn: 'button',
			buttonImage: 'aniki/imgs/calendar.png',
			changeMonth: true,
			changeYear: true
		});
		
		$.datepicker.regional['es'];
	};
	
$(document).ready(function() {
	menuCiudad();
	
	aviso();
	
	publicar();
	
	if ($("body").is(".home")) {
	} else if ($("body").is(".anuncios")) {
		anuncios();
	} else if ($("body").is(".anuncio")) {
		anuncio();
		visibilidad();
	} else if ($("body").is(".publicar-anuncio")) {
		publicarAnuncio();
	} else if ($("body").is(".editar-anuncio")) {
		publicarAnuncio();
		editarAnuncio();
	} else if ($("body").is(".doPublicarAnuncio")) {
		visibilidad();
	}
});

function menuCiudad() {
	$(".selector-ciudad > a")
	.click(function(event) {
		var context = $(this).parent();
		$(this).focus(); // chrome
		event.preventDefault();
		$(".menu-ciudad", context).toggle();
	})
	.blur(function() {
		var context = $(this).parent();
		setTimeout(function() { $(".menu-ciudad", context).hide() }, 300);
	});
}

function publicarAnuncio() {
	$.extend({extAllowed: new Array("jpg", "jpeg", "png")});
	
	$("#main .menu-ciudad a")
	.click(function(event) {
		event.preventDefault();
		$("span.ciudad").html($(this).html());
		$("#ciudadId").val($(this).attr("id").substr(1));
		/*
		$(".selector-ciudad")
		.attr("id", "cambio-ciudad")
		.children("a").html("Cambiar de ciudad");
		*/
	});
	
	$('textarea.rte').tinymce({
		// Location of TinyMCE script
		script_url : siteRoot + 'js/tiny_mce/tiny_mce.js',
		
		/*
		// General options
		theme : "advanced",
		plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
		 
		// Theme options
		theme_advanced_buttons1 : "bold,italic,underline,|,strikethrough,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,undo,redo,link,unlink,formatselect,fontselect,fontsizeselect,code",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",

		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_resizing : true
		*/
		theme : "advanced",
		theme_advanced_buttons1 : "bold, italic, undo, redo, link, unlink",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left"
	});
	
	$("#pa-telefono").keypress(function (e) {
	  //if the letter is not digit then display error and don't type anything
	  if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) {
	    return false;
	  }
	});
	
	$("#frm-pa").submit(function() {
		if ($("#ciudadId").val() == '') {
			alert("Ciudad es obligatorio");
			$("#selecciona-ciudad > a").focus();
			return false;
		}
		if ($("#pa-telefono").val().length != 0 && $("#pa-telefono").val().length != 9) {
			alert("El número de teléfono debe tener una longitud de 9 caracteres");
			$("#pa-telefono").focus();
			return false;
		}
		if (!$("#pa-titulo").mandatory("Título")) return false;
		if (!$("#pa-descripcion").mandatory("Descripción")) return false;
		if (!$("#pa-email").mandatory("Email")) return false;
		
		if (!$("#pa-email").validateEmail(false)) return false;
		
		return true;
	});
	
	$("input.file").change(function() {
		var ext = $(this).val().split('.').pop();
		
		if (!$.extAllowed.inArray(ext.toLowerCase())) {
			alert("Únicamente están permitidos las imágenes con extension jpeg, jpg, png");
			$(this).val("");
		}
	});
}

function anuncios() {
	/*
	$("ul.anuncios li").equalHeights();
	$("ul.anuncios li .fecha").css("line-height", $("ul.anuncios li .fecha").height()+"px");
	*/
	$("a.eliminar").click(function(event) {
		event.preventDefault();
		
		$.ajax({
			type: "POST",
			url: "ajax/"+$(this).attr("href"),
			success: function(msg) {
				var json = eval('(' + msg + ')');
				var result = json.result;
				
				if (result.estado == 1) {
					location.reload(true);
				} else {
					alert(result.mensaje);
				}
			}
		});
	});
}

function editarAnuncio() {
	$("a.eliminar").click(function(event) {
		event.preventDefault();
		
		// elimina
		$(this).parents(".foto").remove();
		// renombra
		$("input.file").each(function(i) {
			$(this).attr("name", "foto"+(i+1));
		});
		// añade uno al final
		$('input[name=foto5]').parent().after('<div class="row"><input class="file" type="file" name="foto6">');
	});
	
	$("a.modificar").click(function(event) {
		event.preventDefault();
		
		// esconder actions
		$(this).parent().hide();
		// mostrar row
		$(this).parents(".foto").children(".row").removeClass("hide").children("input").removeAttr("disabled");
	});
	
	$("a.cancelar").click(function(event) {
		event.preventDefault();
		
		// esconder row
		$(this).parents(".foto").children(".row").addClass("hide").children("input").attr("disabled", "disabled");
		// mostrar actions
		$(this).parents(".foto").children(".actions").show();
	});
}

function anuncio() {
	var contactoAnunciante = contact("Envía un email al anunciante", "enviar-formulario-contacto", $('p.contacta a'));
	contactoAnunciante.init();
	
	var contactoSpam = contact("Marcar como spam / prohibido", "enviar-formulario-spam", $('a.opcion-spam'));
	contactoSpam.init();
	
	var contactoFotos = contact("Fotos falsas", "enviar-formulario-fotos", $('a.opcion-fotos'));
	contactoFotos.init();

	var contactoTelefono = contact("Número de teléfono falso", "enviar-formulario-telefono", $('a.opcion-telefono'));
	contactoTelefono.init();
	
	datePicker();
}

function aviso() {
	if ($("#basic-modal-content").size()) {
		$('#basic-modal-content').modal({
			close: false,
			onShow: function(dialog) {
				$(dialog.container).css('height','auto');
				this.setPosition();
			}
		});
		
		$("button.aviso-continuar").click(function(e) {
			e.preventDefault();
	
			$.ajax({
				type: "POST",
				url: "ajax/aviso-continuar.html",
				success: function(msg) {
					$.modal.close();
				}
			});		
		});

		$("button.aviso-salir").click(function(e) {
			e.preventDefault();
			
			window.location = "http://www.google.com/";
		});
	}
}

function contact(titulo, url, $link) {
	var contact = {
		init: function () {
			$link.click(function (e) {
				e.preventDefault();

				// load the contact form using ajax
				$.get("ajax/formulario-contacto.html?anuncioId="+$("input[name=id]").val()+"&titulo="+titulo, function(data){
					// create a modal dialog with the data
					$(data).modal({
						closeHTML: "<a href='#' title='Cerrar' class='modal-close'>x</a>",
						position: ["15%",],
						overlayId: 'contact-overlay',
						containerId: 'contact-container',
						onOpen: contact.open,
						onShow: contact.show,
						onClose: contact.close
					});
				});
			});
		},
		open: function (dialog) {
			// add padding to the buttons in firefox/mozilla
			if ($.browser.mozilla) {
				$('#contact-container .contact-button').css({
					'padding-bottom': '2px'
				});
			}
			// input field font size
			if ($.browser.safari) {
				$('#contact-container .contact-input').css({
					'font-size': '.9em'
				});
			}

			// dynamically determine height
			var h = 245;
			if ($('#contact-subject').length) {
				h += 26;
			}
			if ($('#contact-cc').length) {
				h += 22;
			}

			var title = $('#contact-container .contact-title').html();
			$('#contact-container .contact-title').html('Cargando...');
			dialog.overlay.fadeIn(200, function () {
				dialog.container.fadeIn(200, function () {
					dialog.data.fadeIn(200, function () {
						$('#contact-container .contact-content').animate({
							height: h
						}, function () {
							$('#contact-container .contact-title').html(title);
							$('#contact-container form').fadeIn(200, function () {
								$('#contact-container #contact-name').focus();

								$('#contact-container .contact-cc').click(function () {
									var cc = $('#contact-container #contact-cc');
									cc.is(':checked') ? cc.attr('checked', '') : cc.attr('checked', 'checked');
								});

								// fix png's for IE 6
								if ($.browser.msie && $.browser.version < 7) {
									$('#contact-container .contact-button').each(function () {
										if ($(this).css('backgroundImage').match(/^url[("']+(.*\.png)[)"']+$/i)) {
											var src = RegExp.$1;
											$(this).css({
												backgroundImage: 'none',
												filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' +  src + '", sizingMethod="crop")'
											});
										}
									});
								}
							});
						});
					});
				});
			});
		},
		show: function (dialog) {
			$('#contact-container .contact-send').click(function (e) {
				e.preventDefault();
				// validate form
				if (contact.validate()) {
					$('#contact-container .contact-title').html('Enviando...');
					$('#contact-container form').fadeOut(200);
					$('#contact-container .contact-content').animate({
						height: '80px'
					}, function () {
						$('#contact-container .contact-loading').fadeIn(200, function () {
							$.ajax({
								url: 'ajax/'+url+'.html',
								data: $('#contact-container form').serialize(),
								type: 'post',
								cache: false,
								dataType: 'html',
								success: function (msg) {
									var json = eval('(' + msg + ')');
									var result = json.result;
									
									$('#contact-container .contact-loading').fadeOut(200, function () {
										$('#contact-container .contact-title').html(result.estado ? 'Se ha enviado el mail' : result.mensaje);
									});
								},
								error: contact.error
							});
						});
					});
				}
			});
		},
		close: function (dialog) {
			$.modal.close();
		},
		error: function (xhr) {
			alert(xhr.statusText);
		},
		validate: function () {
			if (!$('#contact-container #contact-name').val()) {
				alert("Nombre es obligatorio");
				$('#contact-container #contact-name').focus();
				return false;
			}
			
			if (!$('#contact-container #contact-email').val()) {
				alert("Email es obligatorio");
				$('#contact-container #contact-email').focus();
				return false;
			}
			
			if (!$('#contact-container #contact-email').validateEmail()) return false;

			if (!$('#contact-container #contact-message').val()) {
				alert("Mensaje es obligatorio");
				$('#contact-container #contact-message').focus();
				return false;
			}

			return true;
		}
	};
	
	return contact;
}

function visibilidad() {
	datePicker();
	
	$(".destaca form.tpv").submit(function() {
		var operacion = $("input[name=operacion]", $(this)).val();
		var anuncioId = $("input[name=anuncioId]", $(this)).val();
		var tipo = $("input[name=tipo]", $(this)).val();

		if ($("input[name=mode]").size() && $("input[name=mode]").val() == 'on') {
			if (operacion == 'P') { // paquete
				var arrFechas = new Array();
				if (tipo == 3) { // a medida
					var lis = $(".lista-medida ul li");
					if (!lis.size()) {
						alert("Debe añadir al menos 1 paquete");
						return false;
					} else {
						lis.each(function(i) {
							arrFechas[i] = $(this).children("input[name=fecha-medida]").val();
						});
					}
				} else {
					var detalles = $(this).parents(".detalles");
					var ahora = new Date();
					arrFechas[0] = ahora.getFullYear()+'-'+(ahora.getMonth() + 1)+'-'+ahora.getDate()+' '+detalles.find("input[name=hora]").val()+":"+detalles.find("input[name=minutos]").val()+":"+"00";
				}
			} else {
				// caso de top 7.15,30
				if (tipo == '') tipo = $("select[name=tipoTopAnuncioId]").val();
			}
			
			var data = "anuncioId="+anuncioId+"&operacion="+operacion+"&tipo="+tipo;
			
			if (arrFechas != undefined) {
				for (i=0;i<arrFechas.length;i++) {
					data+= "&fecha[]="+arrFechas[i];
				}
			}
			
			$.ajax({
				type: "POST",
				url: "ajax/tx.html",
				data: data,
				async: false,
				success: function(msg) {
					var json = eval('(' + msg + ')');
					var result = json.result;
					
					if (!result.estado) {
						alert(result.mensaje);
					}
				}
			});
			
			return false;
			
		} else {
			var concept = $("input[name=CONCEPT]", $(this)).val();
			var preproceso = $("input[name=preproceso]", $(this)).val();
			$this = $(this);
			if (preproceso == 1) {
				// se hace de manera diferente porque hay que generar la firma a partir de datos del formulario
				// top 7, 15, 30
				var data = "id="+$("select[name=tipoTopAnuncioId]").val();
				var res = true;
				
				$.ajax({
					type: "POST",
					url: "ajax/detalles-form-tpv-top.html",
					data: data,
					async: false,
					success: function(msg) {
						var json = eval('(' + msg + ')');
						var result = json.result;
						
						if (!result.estado) {
							res = false;
							alert(result.mensaje);
						} else {
							// actualizar datos formulario
							$("input[name=AMOUNT]", $this).val(result.amount);
							$("input[name=CONCEPT]", $this).val(result.concept);
							$("input[name=REFERENCE]", $this).val(result.reference);
							$("input[name=SIGNATURE]", $this).val(result.signature);
							$("input[name=tipo]", $this).val(result.tipo);
							tipo = result.tipo;
						}
					}
				});
				
				if (!res) return false;
				
			} else if (operacion == 'P') { // paquete
				var arrFechas = new Array();
				if (tipo == 3) { // a medida
					var lis = $(".lista-medida ul li");
					if (!lis.size()) {
						alert("Debe añadir al menos 1 paquete");
						return false;
					} else {
						lis.each(function(i) {
							arrFechas[i] = $(this).children("input[name=fecha-medida]").val();
						});
						
						var data = "items="+lis.size();
						var res = true;
						
						$.ajax({
							type: "POST",
							url: "ajax/detalles-form-tpv-a-medida.html",
							data: data,
							async: false,
							success: function(msg) {
								var json = eval('(' + msg + ')');
								var result = json.result;
								
								if (!result.estado) {
									res = false;
									alert(result.mensaje);
								} else {
									// actualizar datos formulario
									$("input[name=AMOUNT]", $this).val(result.amount);
									$("input[name=REFERENCE]", $this).val(result.reference);
									$("input[name=SIGNATURE]", $this).val(result.signature);
								}
							}
						});
	
						if (!res) return false;
						
					}
				} else {
					var detalles = $(this).parents(".detalles");
					var ahora = new Date();
					arrFechas[0] = ahora.getFullYear()+'-'+(ahora.getMonth() + 1)+'-'+ahora.getDate()+' '+detalles.find("input[name=hora]").val()+":"+detalles.find("input[name=minutos]").val()+":"+"00";
				}
			}
			var data = "anuncioId="+anuncioId+"&operacion="+operacion+"&tipo="+tipo+"&referencia="+$("input[name=REFERENCE]", $(this)).val()+"&signature="+$("input[name=SIGNATURE]", $(this)).val();
			if (arrFechas != undefined) {
				for (i=0;i<arrFechas.length;i++) {
					data+= "&fecha[]="+arrFechas[i];
				}
			}
			var res = true;
			
			$.ajax({
				type: "POST",
				url: "ajax/guardartx.html",
				data: data,
				async: false,
				success: function(msg) {
					var json = eval('(' + msg + ')');
					var result = json.result;
					
					if (!result.estado) {
						res = false;
						alert(result.mensaje);
					}
				}
			});
		}
		
		return res;
	});
	
	$(".destaca .mas").click(function(e) {
		e.preventDefault();
		
		var detalles = $(this).parent("li").children(".detalles");
		detalles.toggle();
		var paquetes = $(this).parents("div.paquetes").size();
		$(this).html(detalles.is(":visible") ?  (paquetes ? "Ocultar paquete" : "Ocultar opciones de pago") : (paquetes ? "Crear paquete" : "Ver opciones de pago"));
	});
	
	$("button.anadir-paquete").click(function() {
		if ($(".lista-medida li").size() >= 25) {
			alert("El número máximo subidas es de 25");
			
			return false;
		}
		
		if (!$(".lista-medida ul").size()) {
			// crear ul
			$(".lista-medida").append("<ul>");
		}
		var ul = $(".lista-medida ul");
		var context = $(this).parents("li");
		var fecha = $("input[name=fecha]", context).val();
		var hora = $("input[name=hora]", context).val();
		var minutos = $("input[name=minutos]", context).val();
		var html = "<li>";
		html+= fecha + " a las " + hora + ":" + minutos + '&nbsp;<button type="button" class="eliminar-paquete">Eliminar</button>';
		var arrFecha = fecha.split("-");
		var fechabd = arrFecha[2]+'-'+arrFecha[1]+'-'+arrFecha[0];
		html+= '<input type="hidden" name="fecha-medida" value="'+fechabd+' '+hora+':'+minutos+':00'+'" />'
		html+= "</li>";
		ul.append(html);
		
		updatePrecioAMedida();
	});
	
	$("button.eliminar-paquete").live("click", function() {
		$(this).parent("li").remove();
		
		updatePrecioAMedida();
	});
	
	$(".destaca form.sms-telefono").submit(function() {
		var data = $(this).serialize()+"&id="+$("input[name=id]").val();
		
		$.ajax({
			type: "POST",
			url: "ajax/check-codigo-sms-telefono.html",
			data: data,
			success: function(msg) {
				var json = eval('(' + msg + ')');
				var result = json.result;
				
				if (!result.estado) {
					alert(result.mensaje);
				} else {
					alert("La operación se ha realizado correctamente, ya puede visualizar su anuncio destacado. Le hemos enviado a su correo electrónico el comprobante de pago. Muchas gracias por utilizar este servicio.");
				}
			}
		});
		
		return false;
	});
}

function updatePrecioAMedida() {
	var ul = $(".lista-medida ul");

	var items = ul.children("li").size();

	var precio = 0;
	if (items == 1) {
		precio = 1.5;
	} else if (items < 5) {
		precio = items;
	} else if (items >= 5 & items < 10) {
		precio = items * (1 - 0.15);
	} else if (items >= 10 & items < 20) {
		precio = items * (1 - 0.3);
	} else if (items >= 20) {
		precio = items * (1 - 0.4);
	} 
	
	precio = precio.toFixed(2);
	
	$("span.precio").html(precio.toString().replace(".", ","));
}

function publicar() {
	$("a.publicar").click(function() {
		if ($("#basic-modal-content-no-permitir-publicar").size()) {
			$('#basic-modal-content-no-permitir-publicar').modal({
				close: false,
				onShow: function(dialog) {
					$(dialog.container).css('height','auto');
					this.setPosition();
				}
			});
			
			return false;
		} else {
			return true;
		}
	});
}
