var $ = jQuery.noConflict();

$(function() {
	// Destacados
	$('#featuredcontent a')
		.mouseover(function() {
			$('#featuredcontent p').text($('img',this).attr('alt'));
		})
		.mouseout(function() {
			$('#featuredcontent p').empty();
		});
		
	// Ampliación de imagenes
	$('a[@rel*=lightbox]').lightBox({txtImage: 'Imagen', txtOf: 'de'});
	
	// Submit comentarios
	$('#commentform #submit').click(function() {
		if (!/[a-zA-Z]/.test($('#comment').val())) {
			alert('No has escrito ningún comentario');
			return false;
		} else if (!/[a-zA-Z]/.test($('#author').val())) {
			alert('No has indicado tu nombre / nombre de tu personaje');
			return false;
		} else if ($('#email').length > 0 && !/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test($('#email').val())) {
			alert('No has indicado tu e-mail');
			return false;
		}
		if ($('#wowrealm').val() == 0) {
			$('#commentform').submit();
			return false;
		} else if ($('#email').length == 0) {
			$('#commentform').submit();
			return false;
		} else {
			$('#commentform').slideUp('normal');
			$('#commentform').before('<p class="cargandoarmeria">Cargando datos de la Armería...<br /><img alt="Cargando..." src="/images/cargando1.gif" /></p>');
			function returnError(msg) {
				if (msg == '0') {
					alert('Error de la aplicación. Por favor, vuelve a intentar el envío del comentario');
					$('.cargandoarmeria').remove();
					$('#commentform').slideDown('normal');
				} else if (msg == '1') {
					$('.cargandoarmeria').remove();
					var c = '<div class="comment-error" style="display: none;">';
					c += '<p><em>El personaje que has indicado en el formulario ('+$('#author').val()+' de '+$('#wowrealm option:selected').text()+') parece no existir en la Armería.</em></p>';
					c += '<p style="padding-bottom: 0;">Las posibles causas de este problema son:</p>';
					c += '<p>&nbsp;&nbsp;&nbsp;- El personaje no existe.<br />';
					c += '&nbsp;&nbsp;&nbsp;- El nivel del personaje es inferior a 10.<br />';
					c += '&nbsp;&nbsp;&nbsp;- La Armería no está funcionando correctamente.</p>';
					c += '<p class="botones" style="width: 488px;">';
					c += '<a href="#" class="com-send" style="background-image: url(/images/btn_enviarcoment.gif);"></a>';
					c += '<a href="#" class="com-change" style="background-image: url(/images/btn_cambiarpj.gif);"></a>';
					c += '<a href="#" class="com-retry" style="background-image: url(/images/btn_reintentar.gif);"></a>';
					c += '</p></div>';
					$('#commentform').before(c);
					// Enviar comment despues de error
					$('a.com-send').click(function() {
						$('#commentform').submit();
						return false;
					});
					// Volver al formulario de comment despues de error
					$('a.com-change').click(function() {
						$('.comment-error').fadeOut('fast',function() {
							$(this).remove();
						});
						$('#commentform').slideDown();
						return false;
					});
					// Reintentar lectura armeria despues de error
					$('a.com-retry').click(function() {
						$('.comment-error').fadeOut('fast',function() {
							$(this).remove();
							$('#commentform').before('<p class="cargandoarmeria">Cargando datos de la Armería...<br /><img alt="Cargando..." src="/images/cargando1.gif" /></p>');
							readArmory();
						});
						return false;
					});
					$('.comment-error').slideDown('normal');
				} else if (msg == '2') {
					$('.cargandoarmeria').remove();
					var c = '<div class="comment-error" style="display: none;">';
					c += '<p><em>El personaje que has indicado en el formulario ('+$('#author').val()+' de '+$('#wowrealm option:selected').text()+') pertenece a un usuario registrado de DeathKnight.es</em><br />Si continuas el comentario se enviará únicamente con el nombre, sin utilizar los datos del personaje.</p>';
					c += '<p class="botones" style="width: 332px;">';
					c += '<a href="#" class="com-send" style="background-image: url(/images/btn_enviarcoment.gif);"></a>';
					c += '<a href="#" class="com-change" style="background-image: url(/images/btn_cambiarpj.gif);"></a>';
					c += '</p></div>';
					$('#commentform').before(c);
					// Enviar comment despues de error
					$('a.com-send').click(function() {
						$('#commentform').submit();
						return false;
					});
					// Volver al formulario de comment despues de error
					$('a.com-change').click(function() {
						$('.comment-error').fadeOut('fast',function() {
							$(this).remove();
						});
						$('#commentform').slideDown();
						return false;
					});
					$('.comment-error').slideDown('normal');
				} else {
					alert(msg);
					$('.cargandoarmeria').remove();
					$('#commentform').slideDown('normal');
				}
			}
			function readArmory() {
				$.ajax({
					url: '/getarmeria.php',
					dataType: 'xml',
					cache: false,
					data: 'char='+$('#author').val()+'&realm='+$('#wowrealm').val(),
					type: "POST",
					error: function() {
						returnError('Error');
					},
					success: function(xml) {
						var iserror = $('error',xml).text();
						if (iserror) {
							returnError(iserror);
						} else {
							var c = '<input type="hidden" name="guildname" id="guildname" value="'+$('personaje',xml).attr('guildname')+'" />';
							c+= '<input type="hidden" name="genderid" id="genderid" value="'+$('personaje',xml).attr('genderid')+'" />';
							c+= '<input type="hidden" name="raceid" id="raceid" value="'+$('personaje',xml).attr('raceid')+'" />';
							c+= '<input type="hidden" name="classid" id="classid" value="'+$('personaje',xml).attr('classid')+'" />';
							c+= '<input type="hidden" name="level" id="level" value="'+$('personaje',xml).attr('level')+'" />';
							$('#commentform').append(c);
							$('#commentform').submit();
						}
					}
				});
			}
			readArmory();
			return false;
		}
	});
	// Lista mis personajes
	$('#comment-mycharlist').each(function() {
		var p = $('a',this).length;
		if (p > 6) {
			p = 6;
		}
		$(this).css('height',p*20+'px');
		$(this).before('<div class="comment-mycharlist-bg" style="height: '+((p*20)+6)+'px;"></div><div class="comment-mycharlist-border" style="height: '+((p*20)+2)+'px;"></div>');
		$('.comment-mycharlist-bg').css('opacity',0.6);
	});
	// Abrir lista mis personajes
	$('#com-selectpj').click(function() {
		$('.comment-mycharlist-bg, .comment-mycharlist-border, #comment-mycharlist').toggle();
		return false;
	});
	// Seleccionar personaje de la lista
	$('#comment-mycharlist a').click(function() {
		$('#com-selectpj span').text($(this).text());
		var pid = $(this).attr('id').replace(/pj-/,'');
		$('#author').val(lista_pjs[pid][0]);
		$('#wowrealm').val(lista_pjs[pid][5]);
		var a, g, r, c;
		if (lista_pjs[pid][4] < 60) {
			a = 'avatars';
		} else if (lista_pjs[pid][4] >= 60 && lista_pjs[pid][4] < 70 ) {
			a = 'avatars-60';
		} else if (lista_pjs[pid][4] >= 70 && lista_pjs[pid][4] < 80 ) {
			a = 'avatars-70';
		} else if (lista_pjs[pid][4] >= 80) {
			a = 'avatars-80';
		}
		$('#charselect-preview img').attr('src','/images/'+a+'/'+lista_pjs[pid][1]+'-'+lista_pjs[pid][2]+'-'+lista_pjs[pid][3]+'.gif');
		$('.comment-mycharlist-bg, .comment-mycharlist-border, #comment-mycharlist').hide();
		return false;
	});
	// Abrir form anyadir personaje
	$('.com-anyadirpj').click(function() {
		if ($('#comment-newpj fieldset').css('display') == 'none') {
			return false;
		}
		$('#comment-newpj').slideToggle('normal');
		return false;
	});
	// Guardar nuevo personaje
	$('.com-guardar').click(function() {
		if (!/[a-zA-Z]/.test($('#newpj-name').val())) {
			alert('No has indicado el nombre de ningún personaje');
			return false;
		}
		$('#comment-newpj fieldset').fadeOut('fast');
		$('#comment-newpj').append('<p style="position: absolute; top: 15px; width: 565px;" class="cargandoarmeria">Cargando Armería & Guardando datos...<br /><img alt="Cargando..." src="/images/cargando1.gif" /></p>');
		function returnError(msg) {
			if (msg == '0') {
				alert('Error de la aplicación. Por favor, vuelve a intentarlo.');
				$('.cargandoarmeria').remove();
				$('#comment-newpj fieldset').slideDown('normal');
			} else if (msg == '1') {
				$('.cargandoarmeria').remove();
				$('#comment-newpj').hide();
				var c = '<div class="comment-error" style="display: none;">';
				c += '<p><em>El personaje que has indicado en el formulario ('+$('#newpj-name').val()+' de '+$('#newpj-realm option:selected').text()+') parece no existir en la Armería.</em></p>';
				c += '<p style="padding-bottom: 0;">Las posibles causas de este problema son:</p>';
				c += '<p>&nbsp;&nbsp;&nbsp;- El personaje no existe.<br />';
				c += '&nbsp;&nbsp;&nbsp;- El nivel del personaje es inferior a 10.<br />';
				c += '&nbsp;&nbsp;&nbsp;- La Armería no está funcionando correctamente.</p>';
				c += '<p class="botones" style="width: 332px;">';
				c += '<a href="#" class="com-change" style="background-image: url(/images/btn_cambiarpj.gif);"></a>';
				c += '<a href="#" class="com-retry" style="background-image: url(/images/btn_reintentar.gif);"></a>';
				c += '</p></div>';
				$('#comment-newpj').after(c);
				// Volver al formulario de crear pj despues de error
				$('a.com-change').click(function() {
					$('.comment-error').fadeOut('fast',function() {
						$(this).remove();
					});
					$('#comment-newpj fieldset').show();
					$('#comment-newpj').slideDown();
					return false;
				});
				// Reintentar lectura armeria despues de error
				$('a.com-retry').click(function() {
					$('.comment-error').fadeOut('fast',function() {
						$(this).remove();
						$('#comment-newpj').show().append('<p style="position: absolute; top: 15px; width: 565px;" class="cargandoarmeria">Cargando Armería & Guardando datos...<br /><img alt="Cargando..." src="/images/cargando1.gif" /></p>');
						addCharacter();
					});
					return false;
				});
				$('.comment-error').slideDown('normal');
			} else if (msg == '2') {
				$('.cargandoarmeria').remove();
				$('#comment-newpj').hide();
				var c = '<div class="comment-error" style="display: none;">';
				c += '<p><em>El personaje que has indicado en el formulario ('+$('#newpj-name').val()+' de '+$('#newpj-realm option:selected').text()+') pertenece a un usuario registrado de DeathKnight.es</em></p>';
				c += '<p class="botones" style="width: 156px;">';
				c += '<a href="#" class="com-aceptar" style="background-image: url(/images/btn_aceptar.gif);"></a>';
				c += '</p></div>';
				$('#comment-newpj').after(c);
				// Volver al formulario de crear pj despues de error
				$('a.com-aceptar').click(function() {
					$('.comment-error').fadeOut('fast',function() {
						$(this).remove();
					});
					$('#comment-newpj fieldset').show();
					$('#comment-newpj').slideDown();
					return false;
				});
				$('.comment-error').slideDown('normal');
			} else if (msg == '3') {
				$('.cargandoarmeria').remove();
				$('#comment-newpj').hide();
				var c = '<div class="comment-error" style="display: none;">';
				c += '<p><em>El personaje que has indicado ya está en tu lista de personajes.</em></p>';
				c += '<p class="botones" style="width: 156px;">';
				c += '<a href="#" class="com-aceptar" style="background-image: url(/images/btn_aceptar.gif);"></a>';
				c += '</p></div>';
				$('#comment-newpj').after(c);
				// Volver al formulario de crear pj despues de error
				$('a.com-aceptar').click(function() {
					$('.comment-error').slideUp('fast',function() {
						$(this).remove();
					});
					$('#comment-newpj fieldset').show();
					return false;
				});
				$('.comment-error').slideDown('normal');
			} else {
				alert(msg);
				$('.cargandoarmeria').remove();
				$('#comment-newpj fieldset').slideDown('normal');
			}
		}
		function addCharacter() {
			$.ajax({
				url: '/getarmeria.php',
				dataType: 'xml',
				cache: false,
				data: 'char='+$('#newpj-name').val()+'&realm='+$('#newpj-realm').val(),
				type: "POST",
				error: function() {
					returnError('Error');
				},
				success: function(xml) {
					var iserror = $('error',xml).text();
					if (iserror) {
						returnError(iserror);
					} else {
						lista_pjs[$('personaje',xml).attr('id')] = new Array(
							$('#newpj-name').val(),
							$('personaje',xml).attr('genderid'),
							$('personaje',xml).attr('raceid'),
							$('personaje',xml).attr('classid'),
							$('personaje',xml).attr('level'),
							$('#newpj-realm option:selected').val()
						);
						$('#comment-mycharlist a:last').before('<a id="pj-'+$('personaje',xml).attr('id')+'" href="#" style="cursor: pointer;">'+$('#newpj-name').val()+' de '+$('#newpj-realm option:selected').text()+'</a>');
						$('#pj-'+$('personaje',xml).attr('id')).click(function() {
							$('#com-selectpj span').text($(this).text());
							var pid = $(this).attr('id').replace(/pj-/,'');
							$('#author').val(lista_pjs[pid][0]);
							$('#wowrealm').val(lista_pjs[pid][5]);
							var a, g, r, c;
							if (lista_pjs[pid][4] < 60) {
								a = 'avatars';
							} else if (lista_pjs[pid][4] >= 60 && lista_pjs[pid][4] < 70 ) {
								a = 'avatars-60';
							} else if (lista_pjs[pid][4] >= 70 && lista_pjs[pid][4] < 80 ) {
								a = 'avatars-70';
							} else if (lista_pjs[pid][4] >= 80) {
								a = 'avatars-80';
							}
							$('#charselect-preview img').attr('src','/images/'+a+'/'+lista_pjs[pid][1]+'-'+lista_pjs[pid][2]+'-'+lista_pjs[pid][3]+'.gif');
							$('.comment-mycharlist-bg, .comment-mycharlist-border, #comment-mycharlist').hide();
							return false;
						}).trigger('click');
						// recalcula altura select
						var p = $('#comment-mycharlist a').length;
						if (p > 6) {
							p = 6;
						}
						$('#comment-mycharlist').css('height',(p*20)+'px');
						$('.comment-mycharlist-bg').css('height',((p*20)+6)+'px');
						$('.comment-mycharlist-border').css('height',((p*20)+2)+'px');
						
						$('#comment-newpj').slideUp(function() {
							$('.cargandoarmeria').remove();
							$('#comment-newpj fieldset').show();
						});
						$('#newpj-name').val('');
					}
				}
			});
		}
		addCharacter();
		return false;
	});
});