/**
 * This file contains the functionality for initializing all the scripts in the
 * site and also there are some main initial settings included here, such as
 * setting rounded corners automatically, setting the Twitter functionality,
 * etc.
 * 
 * @author Pexeto
 */

var tonicSite = {
	initSite : function() {
		// init the portfolio functionality


		// set the contact form functionality
		tonicContactForm.set();

		// set the news functionality


		// load the slider
		tonicSite.loadSlider();

		// sets the colorbox lightbox
		$("a[rel='lightbox']").colorbox();

		// load the scrolling functionality
		$('#menu ul li a').click(function(event) {
			event.preventDefault();
			var rel = $(this).attr('rel');
			if (rel && $('#' + rel)[0]) {
				$.scrollTo($('#' + rel), 700);
			}
		});

		// fix the IE6 position fixed issue
		if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
			$("#menu_container").css("position", "absolute");
			$(window).scroll(function() {
				$("#menu_container").css("top", $(window).scrollTop() + "px");
			});
		}

		// set the Cufon font replacement
		this.setCufon();

		// set rounded corners
		window.onload = this.setDefaultRoundedCorners;

	},

	/**
	 * Loads the Nivo image slider.
	 */
	loadSlider : function() {
		// load the Nivo slider
		$(window)
				.load(function() {
					$('#slider').nivoSlider( {
						effect : 'random', // Specify sets like:
						// 'fold,fade,sliceDown'
						slices : 20,
						animSpeed : 800,
						pauseTime : 5000,
						startSlide : 0, // Set starting Slide (0 index)
						directionNav : false, // Next & Prev
						directionNavHide : true, // Only show on hover
						controlNav : true, // 1,2,3...
						controlNavThumbs : false, // Use thumbnails for
						// Control
						// Nav
						controlNavThumbsFromRel : false, // Use image rel for
						// thumbs
						keyboardNav : true, // Use left & right arrows
						pauseOnHover : true, // Stop animation while hovering
						manualAdvance : false, // Force manual transitions
						captionOpacity : 0.8, // Universal caption opacity
						beforeChange : function() {
						},
						afterChange : function() {
						},
						slideshowEnd : function() {
						} // Triggers after all slides have been shown
					});

					// remove numbers from navigation
						$('.nivo-controlNav a').html('');

						// center the slider navigation
						var slideNumber = $('.nivo-controlNav a').length;
						var slideLeft = 960 / 2 - slideNumber * 21 / 2;
						$('.nivo-controlNav:first').css( {
							left : slideLeft
						});

						// set corners to the slider
						$('#slider_container')
								.append(
										'<div id="corner_left_top"></div><div id="corner_right_top"></div><div id="corner_left_bottom"></div><div id="corner_right_bottom"></div>');
					});
	},

	/**
	 * Displays the latest tweet- when the Twitter icon in the main menu is
	 * hovered, a tooltip with the tweet is shown.
	 * @param username the Twitter username
	 */
	showTwitterStatus : function(username) {

		$
				.ajax( {
					url : "http://twitter.com/statuses/user_timeline/"
							+ username + ".json?callback=?&count=2",
					dataType : "json",
					timeout : 15000,

					success : function(data) {
						var bubble = $('<div id="twitter_status" class="twt"><div id="twitter_status_top" class="twt"></div><p>' + data[0].text + '</p></div>');

						$("#menu").append(bubble);
						$('#twitter_status').css( {
							marginTop : -10
						}).hide();
						$("#menu_icon_right").hover(
								function() {
									$("#menu").find('#twitter_status').stop()
											.show().animate( {
												marginTop : 0
											});
								},
								function() {
									$("#menu").find('#twitter_status').stop()
											.animate( {
												marginTop : -10
											}).hide();
								});
					}
				});
	},

	/**
	 * Sets the Cufon font replacement.
	 */
	setCufon : function() {
		Cufon.replace('h1');
		Cufon.replace('h2');
		Cufon.replace('h3');
		Cufon.replace('h4');
		Cufon.replace('h5');
		Cufon.replace('h6');
	},

	/**
	 * Calls the function to set the rounded corners by default to all the
	 * elements from the "rounded_corner" class.
	 */
	setDefaultRoundedCorners : function() {
		tonicSite.setRoundedCorners($('img.rounded_corner'));
		$('.rounded_corner').not('img').corner();

	},

	/**
	 * Sets rounded corners to images.
	 * @param obj an image element
	 */
	setRoundedCorners : function(obj) {

		obj.each(function(i) {
			var width = $(this).width();
			var height = $(this).height();
			var src = $(this).attr('src');
			var divWrapper = $('<div></div>');

			var divClass = 'corner_wrapper';
			var classes = $(this).attr('class').split(' ');
			for ( var i = 0; i < classes.length; i++) {

				if (classes[i] !== 'rounded_corner') {
					divClass += ' ' + classes[i];
				}

			}

			$(this).addClass('hidden').wrap(divWrapper).hide();
			$(this).parent().css( {
				width : width,
				height : height,
				backgroundImage : 'url(' + src + ')'
			}).addClass(divClass).corner('7px');

		});

	}
};

/**
 * Contains the functionality of the send email form. Makes the validation and
 * sends the message.
 */
tonicContactForm = {
	emptyNameMessage : 'Por favor escriba su nombre',
	invalidEmailMessage : 'Escriba un email valido',
	emptyQuestionMessage : 'Escriba un mensaje',
	sentMessage : 'Mensaje enviado :)',
	set : function() {
		this.setSendButtonClickHandler();
		this.setInputClickHandler();
	},

	/**
	 * Sets the send button click event handler. Validates the inputs and if they are
	 * not valid, displays error messages. If they are valid- makes an AJAX request to the
	 * PHP script to send the message.
	 */
	setSendButtonClickHandler : function() {
		$("#send_button")
				.click(function(event) {

					event.preventDefault();
					valid = true;

						// remove previous validation error messages and warning styles
						$("#name_text_box").removeClass('invalid');
						$("#email_text_box").removeClass('invalid');
						$("#tlf_text_box").removeClass('invalid');						
						$("#question_text_area").removeClass('invalid');
						$('#invalid_input').hide();
						$('#sent_successful').hide();
						$('.question_icon').remove();
						$('.contact_message').remove();
						
						var rawtlf = $("#tlf_text_box");
						var tlf = rawtlf.val();

						// verify whether the name text box is empty
						var nameTextBox = $("#name_text_box");
						var name = nameTextBox.val();
						if (name == '' || name == null) {
							nameTextBox.addClass('invalid');
							valid = false;
							$(
									'<div class="question_icon"></div><div class="contact_message"><p>' + tonicContactForm.emptyNameMessage + '</p></div>')
									.insertAfter(nameTextBox);
						}

						// verify whether the inserted email address is valid
						var emailTextBox = $("#email_text_box");
						var email = emailTextBox.val();
						if (!tonicContactForm.isValidEmailAddress(email)) {
							emailTextBox.addClass('invalid');
							valid = false;
							$(
									'<div class="question_icon"></div><div class="contact_message"><p>' + tonicContactForm.invalidEmailMessage + '</p></div>')
									.insertAfter(emailTextBox);
						}

						// verify whether the question text area is empty
						var questionTextArea = $("#question_text_area");
						var question = questionTextArea.val();
						if (question == '' || question == null) {
							questionTextArea.addClass('invalid');
							valid = false;
							$(
									'<div class="question_icon"></div><div class="contact_message"><p>' + tonicContactForm.emptyQuestionMessage + '</p></div>')
									.insertAfter(questionTextArea);
						}

						if (!valid) {
							//the form inputs are not valid
							$('.contact_message').animate( {
								opacity : 0
							}, 0).hide();
							$('.question_icon').hover(
									function() {
										$(this).css( {
											cursor : 'pointer'
										});
										$(this).siblings('.contact_message')
												.stop().show().animate( {
													opacity : 1
												}, 200);
									},
									function() {
										$(this).siblings('.contact_message')
												.stop().animate( {
													opacity : 0
												}).hide();
									});

							$('#invalid_input').show();
						} else {
							//the form inputs are valid
							
							// show the loading icon
							$('#contact_status').html(
									'<div class="contact_loader"></div>');

							// the data is valid, sumbit the form
							urlToPhp = "send_email.php";

							var dataString = 'nombre=' + name + '&mensaje='
									+ question + '&email=' + email + '&tlf=' + tlf;

							$
									.ajax( {
										type : "POST",
										url : urlToPhp,
										data : dataString,
										success : function() {
											$("#submit_form").each(function() {
												this.reset();
											});
											$('#contact_status')
													.html(
															'<div class="check"></div><span>' + tonicContactForm.sentMessage + '</span>');
											setTimeout(function() {
												$('#contact_status').fadeOut(
														500,
														function() {
															$(this).html('')
																	.show();
														});
											}, 3000);
										}
									});
						}
					});
	},

	setInputClickHandler : function() {
		$('.form_input').click(function() {
			$(this).removeClass('invalid');
		});

		$('.form_input').live('keydown', function(e) {
			var keyCode = e.keyCode || e.which;

			if (keyCode == 9) {
				var index = $('.form_input').index($(this));
				$('.form_input').eq(index + 1).removeClass('invalid');
			}
		});
	},

	/**
	 * Checks if an email address is a valid one.
	 * 
	 * @param emailAddress
	 *            the email address to validate
	 * @return true if the address is a valid one
	 */
	isValidEmailAddress : function(emailAddress) {
		var pattern = new RegExp(
				/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
		return pattern.test(emailAddress);
	}
};

(function($) {
	$.fn.filterable = function(settings) {
		settings = $.extend({
			useHash: true,
			animationSpeed: 1000,
			show: { width: 'show', opacity: 'show' },
			hide: { width: 'hide', opacity: 'hide' },
			useTags: true,
			tagSelector: '#portfolio-filter a',
			selectedTagClass: 'current',
			allTag: 'categorias'
		}, settings);
		
		return $(this).each(function(){
		
			/* FILTER: select a tag and filter */
			$(this).bind("filter", function( e, tagToShow ){
				if(settings.useTags){
					$(settings.tagSelector).removeClass(settings.selectedTagClass);
					$(settings.tagSelector + '[href=' + tagToShow + ']').addClass(settings.selectedTagClass);
				}
				$(this).trigger("filterportfolio", [ tagToShow.substr(1) ]);
			});
		
			/* FILTERPORTFOLIO: pass in a class to show, all others will be hidden */
			$(this).bind("filterportfolio", function( e, classToShow ){
				if(classToShow == settings.allTag){
			/*		$(this).trigger("show"); tweek para limitar all*/
					$(this).trigger("show", [ '.' + classToShow ] );
					$(this).trigger("hide", [ ':not(.' + classToShow + ')' ] );			
				}else{
					$(this).trigger("show", [ '.' + classToShow ] );
					$(this).trigger("hide", [ ':not(.' + classToShow + ')' ] );
				}
				if(settings.useHash){
					location.hash = '#' + classToShow;
				}
			});
			
			/* SHOW: show a single class*/
			$(this).bind("show", function( e, selectorToShow ){
				$(this).children(selectorToShow).animate(settings.show, settings.animationSpeed);
			});
			
			/* SHOW: hide a single class*/
			$(this).bind("hide", function( e, selectorToHide ){
				$(this).children(selectorToHide).animate(settings.hide, settings.animationSpeed);	
			});
			
			/* ============ Check URL Hash ====================*/
			if(settings.useHash){
				if(location.hash != '')
					$(this).trigger("filter", [ location.hash ]);
				else
					$(this).trigger("filter", [ '#' + settings.allTag ]);
			}
			
			/* ============ Setup Tags ====================*/
			if(settings.useTags){
				$(settings.tagSelector).click(function(){
					$('#portfolio-list').trigger("filter", [ $(this).attr('href') ]);
					
					$(settings.tagSelector).removeClass('current');
					$(this).addClass('current');
				});
			}
		});
	}
})(jQuery);


$(document).ready(function(){
	
	$('#portfolio-list').filterable();

});

/*
 * 	Easy Slider 1.5 - jQuery plugin
 *	written by Alen Grakalic	
 *	http://cssglobe.com/post/4004/easy-slider-15-the-easiest-jquery-plugin-for-sliding
 *
 *	Copyright (c) 2009 Alen Grakalic (http://cssglobe.com)
 *	Dual licensed under the MIT (MIT-LICENSE.txt)
 *	and GPL (GPL-LICENSE.txt) licenses.
 *
 *	Built for jQuery library
 *	http://jquery.com
 *
 */
 
/*
 *	markup example for $("#slider").easySlider();
 *	
 * 	<div id="slider">
 *		<ul>
 *			<li><img src="images/01.jpg" alt="" /></li>
 *			<li><img src="images/02.jpg" alt="" /></li>
 *			<li><img src="images/03.jpg" alt="" /></li>
 *			<li><img src="images/04.jpg" alt="" /></li>
 *			<li><img src="images/05.jpg" alt="" /></li>
 *		</ul>
 *	</div>
 *
 */

(function($) {

	$.fn.easySlider = function(options){
	  
		// default configuration properties
		var defaults = {			
			prevId: 		'prevBtn',
			prevText: 		'',
			nextId: 		'nextBtn',	
			nextText: 		'',
			controlsShow:	true,
			controlsBefore:	'<div id="prev_post_nav">',
			controlsAfter:	'</div>',	
			controlsFade:	false,
			firstId: 		'firstBtn',
			firstText: 		'First',
			firstShow:		false,
			lastId: 		'lastBtn',	
			lastText: 		'Last',
			lastShow:		false,				
			vertical:		false,
			speed: 			800,
			auto:			false,
			pause:			2000,
			continuous:		false
		}; 
		
		var options = $.extend(defaults, options);  
				
		this.each(function() {  
			var obj = $(this); 				
			var s = $("li", obj).length;
			var w = $("li", obj).width(); 
			var h = $("li", obj).height(); 
			obj.width(w); 
			obj.height(h); 
			obj.css("overflow","hidden");
			var ts = s-1;
			var t = 0;
			$("ul", obj).css('width',s*w);			
			if(!options.vertical) $("li", obj).css('float','left');
			
			if(options.controlsShow){
				var html = options.controlsBefore;
				if(options.firstShow) html += '<div id="prev_post_nav"><span id="'+ options.firstId +'"><a id="prev_post_r" href=\"javascript:void(0);\">'+ options.firstText +'</a></span></div>';
				html += ' <span id="'+ options.prevId +'"><a id="prev_post_l" href=\"javascript:void(0);\">'+ options.prevText +'</a></span>';
				html += ' <span id="'+ options.nextId +'"><a id="prev_post_r" href=\"javascript:void(0);\">'+ options.nextText +'</a></span>';
				if(options.lastShow) html += ' <span id="'+ options.lastId +'"><a id="prev_post_l" href=\"javascript:void(0);\">'+ options.lastText +'</a></span>';
				html += options.controlsAfter;						
				$(obj).after(html);										
			};
	
			$("a","#"+options.nextId).click(function(){		
				animate("next",true);
			});
			$("a","#"+options.prevId).click(function(){		
				animate("prev",true);				
			});	
			$("a","#"+options.firstId).click(function(){		
				animate("first",true);
			});				
			$("a","#"+options.lastId).click(function(){		
				animate("last",true);				
			});		
			
			function animate(dir,clicked){
				var ot = t;				
				switch(dir){
					case "next":
						t = (ot>=ts) ? (options.continuous ? 0 : ts) : t+1;						
						break; 
					case "prev":
						t = (t<=0) ? (options.continuous ? ts : 0) : t-1;
						break; 
					case "first":
						t = 0;
						break; 
					case "last":
						t = ts;
						break; 
					default:
						break; 
				};	
				
				var diff = Math.abs(ot-t);
				var speed = diff*options.speed;						
				if(!options.vertical) {
					p = (t*w*-1);
					$("ul",obj).animate(
						{ marginLeft: p }, 
						speed
					);				
				} else {
					p = (t*h*-1);
					$("ul",obj).animate(
						{ marginTop: p }, 
						speed
					);					
				};
				
				if(!options.continuous && options.controlsFade){					
					if(t==ts){
						$("a","#"+options.nextId).hide();
						$("a","#"+options.lastId).hide();
					} else {
						$("a","#"+options.nextId).show();
						$("a","#"+options.lastId).show();					
					};
					if(t==0){
						$("a","#"+options.prevId).hide();
						$("a","#"+options.firstId).hide();
					} else {
						$("a","#"+options.prevId).show();
						$("a","#"+options.firstId).show();
					};					
				};				
				
				if(clicked) clearTimeout(timeout);
				if(options.auto && dir=="next" && !clicked){;
					timeout = setTimeout(function(){
						animate("next",false);
					},diff*options.speed+options.pause);
				};
				
			};
			// init
			var timeout;
			if(options.auto){;
				timeout = setTimeout(function(){
					animate("next",false);
				},options.pause);
			};		
		
			if(!options.continuous && options.controlsFade){					
				$("a","#"+options.prevId).hide();
				$("a","#"+options.firstId).hide();				
			};				
			
		});
	  
	};

})(jQuery);

$(document).ready(function() {  
 
    //select all the a tag with name equal to modal
    $('a[name=modal]').click(function(e) {
        //Cancel the link behavior
        e.preventDefault();
        //Get the A tag
        var id = $(this).attr('href');
     
        //Get the screen height and width
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();
     
        //Set height and width to mask to fill up the whole screen
        $('#mask').css({'width':maskWidth,'height':maskHeight});
         
        //transition effect     
        $('#mask').fadeIn(1000);    
        $('#mask').fadeTo("slow",0.8);  
     
        //Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();
               
        //Set the popup window to center
        $(id).css('top',  winH/2-$(id).height()/2);
        $(id).css('left', winW/2-$(id).width()/2);
     
        //transition effect
        $(id).fadeIn(2000); 
     
    });
     
    //if close button is clicked
    $('.window .close').click(function (e) {
        //Cancel the link behavior
        e.preventDefault();
        $('#mask, .window').hide();
    });     
     
    //if mask is clicked
    $('#mask').click(function () {
        $(this).hide();
        $('.window').hide();
    });         
     
});

function ahah(url, target) {
  document.getElementById(target).innerHTML = ' Fetching data...';
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (req != undefined) {
    req.onreadystatechange = function() {ahahDone(url, target);};
    req.open("GET", url, true);
    req.send("");
  }
}  

function ahahDone(url, target) {
  if (req.readyState == 4) { // only if req is "loaded"
    if (req.status == 200) { // only if "OK"
      document.getElementById(target).innerHTML = req.responseText;
    } else {
      document.getElementById(target).innerHTML=" AHAH Error:\n"+ req.status + "\n" +req.statusText;
    }
  }
}

function load(name, div) {
	ahah(name,div);
	return false;
}


