/*
########################################################
# Codename: Kriminal                                   #
# Description: Personal Website                        #
# Copyright (c) 2007 Maximiliano Kraszewski            #
# Email: dev(at)minimalart.org                         #
# Release 6.0 [build 20080724]                         #
# ==================================================== #
# @file: main.js                                       #
# @desc: jquery controller                             #
# @version: 1.0                                        #
# @date: 24/07/2008                                    #
########################################################
*/

$(document).ready(function() {
	
	
	/******************************
	+ OPEN LINKS IN A NEW WINDOWS
	*******************************/
	$("a[@rel~='external']").click(function(){
		window.open($(this).attr("href"));
		return false;
	});	
	
	/**************************
	+ DRAW DINAMIC ELEMENTS
	**************************/
	
	//adds a separator before and after main div
	$('#main').before("<div class='break-up'></div>");
	$('#main').after("<div class='break-down'></div>");
	//add a separator before each h4 (but the first)
	$('div.column.right h4:not(:first)').before("<div class='subSeparator'></div>");
	//add controls to gallery
	$('div.gallery').append("<div class='photo'><img src='' height='267' width='411' alt='' /></div><span><a href='' class='galleryHide'></a></span>");	
	//add a sliding box to the inconbox
	$('#iconBox').append("<div id='textBox'><div class='content'></div><div class='info'></div></div>");
	//add modal
	$('#container').after("<div id='modal'><div class='content'></div><div class='close'><a href='#' class='modalClose'>[ cerrar ]</a></div></div><div id='modalOverlay'></div>");


	/**************************
	+ SHOW AND HIDE PARAGRAPHS
	**************************/

	$('a.more').click(function() {
		var thisParagraph = $(this).parent("p");
		//show next (p) element
		$(thisParagraph).next("p").show('slow');
		//hide cursor
		$(this).hide();
		return false;
	});

	$('a.less').click(function() {
		//set to parent element (p)
		var thisParagraph = $(this).parent("p");
		//hide current (p) element
		$(thisParagraph).hide('slow');
		//ser html to previous (a) element
		$(thisParagraph).prev("p").children(".more").show();
		return false;
	});


	/**************************
	+ SHOW AND HIDE GALLERY
	**************************/

	$('a.galleryShow').click(function() {
		var allLinks = $(this).parents("ul").children("li").children("a");
		var galSpan = $(this).parents("ul").next("div").next("span").children("a");
		var galDiv = $(this).parents("ul").next("div");
		var galImg = galDiv.children("img");
		$(allLinks).removeClass("selected");
		$(this).addClass("selected");
		$(galImg).hide();
		$(galDiv).show();
		$(galImg).attr({"src": $(this).attr("href")});
		$(galImg).fadeIn('slow');
		$(galSpan).html("[ cerrar ]");
		$(galSpan).fadeIn('slow');
		return false;
	});

	$('a.galleryHide').click(function() {
		$(this).html(" ");
		$(this).parent('span').prev('div').hide();
		$(this).parent('span').prev("div").prev("ul").children("li").children("a").removeClass("selected");;
		return false;
	});
	

	/**************************
	+ ICONBOX & TEXTBOX
	**************************/

	$('#agradecimientos').click(function() {
		($(this).children("a")).toggleActive();
		$('#textBox').slideDown(function(){
			$('#textBox div.content').load('data/html/agradecimientos.html');
			$('#textBox div.info').append("<div class='cerrar'><a href='#' class='tbcerrar'>[cerrar]</a></div>");
		});
		$('#textBox div.content').fadeIn('slow');
		$('#textBox div.info').fadeIn('slow');
		return false;
	});

	$('#comentarios').click(function() {
		($(this).children("a")).toggleActive();
		$('#textBox').slideDown(function(){
			$('#textBox div.content').append("<h6></h6>");
			$('#textBox div.content').append("<div class='text'><p></p></div>");
			$('#textBox div.info').append("<div class='count'></div>");
			$('#textBox div.info').append("<ul><li id='first'><a class='first' title='Primero'> </a></li><li id='prev'><a class='prev' title='Anterior'></a></li><li id='next'><a class='next' title='Siguiente'></a></li><li id='last'><a class='last' title='Ultimo'></a></li></ul>");				
			$.ajax({
				type: "GET",
				url: "data/xml/comentarios.xml",
				dataType: "xml",
				complete: function(data) {
					var json = $.xmlToJSON(data.responseXML);
					var cantidad = json.comentario.length;
					var i = 0;
					getComments();
					function getComments(){
						var c = i+1;
						var fecha = json.comentario[i].fecha;
						var persona = json.comentario[i].persona;
						var texto = json.comentario[i].Text;
						$('#textBox h6').html(fecha+" <span>"+persona+"</span>");
						$('#textBox div.text p').html(texto);
						$('#textBox div.count').html(c +" de "+cantidad);
						
						$('#textBox div.info a').removeClass('inactive');
						if (i==0){
							$('#textBox div.info a.first').addClass('inactive');
							$('#textBox div.info a.prev').addClass('inactive');
						}
						if (i==(cantidad-1)){
							$('#textBox div.info a.last').addClass('inactive');
							$('#textBox div.info a.next').addClass('inactive');
						}
						

					}
					$('#textBox div.info').click(function(e) {
						if($(e.target).hasClass('inactive')){
						} else {
							if($(e.target).is('a.first')){
								i=0;
								getComments();
							} 
							if($(e.target).is('a.prev')){
								i--;
								getComments();
							} 
							if($(e.target).is('a.next')){
								i++;
								getComments();
							} 
							if($(e.target).is('a.last')){
								i=(cantidad-1);
								getComments();
							} 
						}
						e.preventDefault();
					});
				}
			});
			$('#textBox div.info').append("<div class='cerrar'><a href='#' class='tbcerrar'>[cerrar]</a></div>");
		});
		$('#textBox div.content').fadeIn('slow');
		$('#textBox div.info').fadeIn('slow');
		return false;
	});

	$('#contacto').click(function() {
		($(this).children("a")).toggleActive();
		$('#textBox').slideDown(function(){
			var msgName = "Escribe tu nombre";
			var msgEmail = "Escribe tu email";
			var msgMensaje = "Escribe tu mensaje";

			$('#textBox div.content').append("<form id='fm' method='post' action='contact.php'><fieldset><label for='fmName'>Nombre</label><input type='text' name='fmName' id='fmName' value='"+msgName+"' /><label for='fmEmail'>Email</label><input type='text' name='fmEmail' id='fmEmail' value='"+msgEmail+"'/><label for='fmMensaje'>Mensaje</label><textarea name='fmMensaje' id='fmMensaje' cols='10' rows='20'>"+msgMensaje+"</textarea><button type='submit'>Enviar</button></fieldset></form><div id='fmNotes'><div id='sendMsg'></div><p>Por medio de este formulario puedes enviarme tu opini&oacute;n sobre el sitio. <br /> O si lo prefieres, puedes hacerlo por email a la siguiente direcci&oacute;n: <a href='mailto:me@kriminal.com.ar'>me@kriminal.com.ar</a></p></div>");
			$('#textBox div.info').append("<div class='cerrar'><a href='#' class='tbcerrar'>[cerrar]</a></div>");
			
			$('#fmName').focus(function() {$(this).setFocus(msgName);});
			$('#fmEmail').focus(function() {$(this).setFocus(msgEmail);});
			$('#fmMensaje').focus(function() {$(this).setFocus(msgMensaje);});
			$('#fmName').blur(function() {$(this).setBlur(msgName);});
			$('#fmEmail').blur(function() {$(this).setBlur(msgEmail);});
			$('#fmMensaje').blur(function() {$(this).setBlur(msgMensaje);});

		
			$('#fm button').hover(
				function(){$(this).addClass("focus");},
				function(){$(this).removeClass("focus");}
			);
			
			$('#fm').ajaxForm({ 
				dataType: 'json', 
				beforeSubmit: validateData,
				success: showResponseData,
				clearForm: true
			}); 
			
			jQuery.fn.setFocus = function(message){
				$(this).removeClass();
				$(this).addClass("focus");
				if ($.trim($(this).val())==message) $(this).val("");
				return false;
			};

			jQuery.fn.setBlur = function(message){
				$(this).removeClass("focus");
				if ($.trim($(this).val())=="") $(this).val(message);
				return false;
			};

			function validateData(formData, jqForm, options) { 
			
				var form = jqForm[0]; 
				var nameVal = $.trim(form.fmName.value);
				var emailVal = $.trim(form.fmEmail.value);
				var mensajeVal = $.trim(form.fmMensaje.value);
				var sendError = false;
				var sendErrorMsg = "Hay errores en el formulario";
				
				if (!nameVal || nameVal == '' || nameVal == msgName){
					sendError = true;
					//sendErrorMsg += "<br />&nbsp;&middot; Nombre";
					$('#fmName').addClass("error");
				} 

				if (!isValidEmail(emailVal)){
					sendError = true;
					//sendErrorMsg += "<br />&nbsp;&middot; Email v&aacute;lido";
					$('#fmEmail').addClass("error");
				} 

				if (!mensajeVal || mensajeVal == '' || mensajeVal == msgMensaje){
					sendError = true;
					//sendErrorMsg += "<br />&nbsp;&middot; Mensaje";
					$('#fmMensaje').addClass("error");
				} 
				
				if (sendError){
					$("#sendMsg").removeClass();
					$("#sendMsg").addClass("error");
					$("#sendMsg").text("ERROR: verifica que todos los campos estén completos con datos válidos.");
					$("#sendMsg").fadeIn("slow");
					return false;
					
				} else {
					$("#sendMsg").removeClass();
					$("#sendMsg").addClass("sending");
					$("#sendMsg").html("enviando datos...");
					//$("#fm").submit();
				}
			};

			function showResponseData(data){
				$("#sendMsg").removeClass();
				if (data.response == "ok") {
					$("#sendMsg").addClass("success");
					$("#sendMsg").text(data.nombre+", tu mensaje fue enviado. Muchas gracias y espera respuesta en breve.");
				} else {
					$("#sendMsg").addClass("error");
					$("#sendMsg").text("Hubo errores en el envio de los datos. Intenta de nuevo más tarde.");
				}
			}
			
			function isValidEmail(str) {
				var at="@"
				var dot="."
				var lat=str.indexOf(at)
				var lstr=str.length
				var ldot=str.indexOf(dot)
				if (str.indexOf(at)==-1) 
					return false
				if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)	
					return false
				if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
					return false
				if (str.indexOf(at,(lat+1))!=-1)
					return false
				if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
					return false
				if (str.indexOf(dot,(lat+2))==-1)
					return false
				if (str.indexOf(" ")!=-1)
					return false
				return true					
			}
			
			
			
			
			
		});
		
		$('#textBox div.content').fadeIn('slow');
		$('#textBox div.info').fadeIn('slow');
		return false;
	});

	$('#textBox div.info').click(function(e) {
		if($(e.target).is('a.tbcerrar')) 
			$('#textBox div.info div.cerrar').children('a').textboxClose();
		e.preventDefault();
	});

	
	jQuery.fn.toggleActive = function(){
		$('#iconBox ul.bar li').children("a").removeClass("active");
		$(this).addClass("active");
		$('#textBox div.content').fadeOut(function(){
			$('#textBox div.content').empty();
			$('#textBox div.info').empty();
		});
		$('#textBox').slideUp('');
 	};

	jQuery.fn.textboxClose = function(){
		$('#iconBox ul.bar li').children("a").removeClass("active");
		$('#textBox div.content').fadeOut(function(){
			$('#textBox div.content').empty();
			$('#textBox div.info').empty();
		});
		$('#textBox').slideUp('');
	};

	/******************
	+ MODAL BOXES
	*******************/
	$('a.modalOpen').click(function(){
		$("#modal div.content").load(this.href);
		$('#modalOverlay').fadeIn('slow', function(){
			$('#modal').show();
		});
		return false;
	});

	$('#modal a.modalClose').click(	function(){
		$('.content').html("");	
		$('#modal').hide();
		$('#modalOverlay').hide();
		return false;
	});

	$('#modalOverlay').click(function(){
		//le pongo un trigger para que haga lo mismo que el link cerrar
		$("#modal a.modalClose").trigger('click');
		return false;
	});
}); 

