$(document).ready(function() {     
     
    //Execute the slideShow, set 4 seconds for each images
    slideShow(5000);
    $("#lnkReview").button({ icons: {primary: 'ui-icon-mail-closed'}});
    $("#btnSubscribe").button({ icons: {primary: 'ui-icon-mail-closed'}});
    $("#btnTwitterPrev").button({ icons: {primary: 'ui-icon-circle-triangle-w'}, text: false});
    $("#btnTwitterNext").button({ icons: {primary: 'ui-icon-circle-triangle-e'}, text: false});
    $("#btnTwitterRefresh").button({ icons: {primary: 'ui-icon-refresh'}, text: false});
    $("#btnTwitterLatest").button({ icons: {primary: 'ui-icon-seek-first'}, text: false});	
		
	// wire button events.
	$("#btnTwitterPrev").click(function(event) { loadWall(page, -1)});
	$("#btnTwitterNext").click(function(event) { loadWall(page, 1)});
	$("#btnTwitterRefresh").click(function(event) { loadWall(page, 0)});
	$("#btnTwitterLatest").click(function(event) { loadWall(1, 0)});
			
	// disable HTML5 validation, implement jqtools validation and hotwire ajax submit.
	$("#frmSubscribe").attr('novalidate', 'novalidate').validator().submit(function(e) {
		// when data is valid 
		if (!e.isDefaultPrevented()) {
		  subscriptionSubmit();
		  
		  // prevent the form data being submitted to the server
		  e.preventDefault();
		}
		return false;
	});

	// present a nice notification with the first validation error.
	$("#frmSubscribe").bind("onFail", function(e, errors)  {
		// we are only doing stuff when the form is submitted
		if (e.originalEvent.type == 'submit') {
			var title = "No se puede proceder";
			var message = "Hay información que necesita ser completada:\n";
			message += "<strong>" + $("label[for='" + errors[0].input.attr("id") + "']").text() + "</strong>";
			uiNotify(title, message);
			errors[0].input.focus();
		}
	});
		
	// load twitter wall (ajax).
	loadWall(1, 0);
	
	$("a[rel^='prettyPhoto']").prettyPhoto({
		theme: 'dark_rounded'
		,default_width: 800
		,default_height: 600
	});
});
//-------------------------------------------------------------------------------------
// callable functions.
//-------------------------------------------------------------------------------------
function subscriptionSubmit()
{
	var options = {
		dataType: "json"
		,beforeSend: function(response) {
			$("#btnSubscribe").button({disabled: true});
		}
		,success: function(response) {
			var title = "Suscripción";
			var message = response.message;
			uiNotify(title, message);
		}
		,error: function() {
			var title = "Error";
			var message = "No se pudo establecer comunicación con el servidor.\n\nPor favor intenta de nuevo.";
			uiNotify(title, message);		
		}
		,complete: function(response) {
			$("#btnSubscribe").button({disabled: false});		
		}
	};
	
	$("#frmSubscribe").ajaxSubmit(options); 
}
//-------------------------------------------------------------------------------------
function loadWall(currentPage, direction) {
	// figure next page index.
	var nextPage = parseInt(currentPage) + parseInt(direction);
	
	// query the server for gallery information.
	$.getJSON("?mode=twitter&json=true&page=" + nextPage
		,function(data) {
			if (data)
			{
				var twittercontainer = $("#twittercontainer");
				twittercontainer.empty();
				
				if (data.list) {
					$.each(data.list, function(i) {
						var rowHTML = "<div id=\"twitter-" + this.wall_id + "\" class=\"twitter\" style=\"display: none\">";
						rowHTML += "<div class=\"colrow\">";
						rowHTML += "<div class=\"leftcol\">";
						rowHTML += "<a href=\"http://www.twitter.com/" + this.wall_name + "\" target=\"_blank\">";
						rowHTML += "<img src=\"" + this.wall_avatar_url + "\" border=\"0\" width=\"48\" height=\"48\"/>";
						rowHTML += "</a>";
						rowHTML += "</div>";
						rowHTML += "<div class=\"rightcol\">";												 
						rowHTML += "<p class=\"twitter_user\"><a href=\"http://www.twitter.com/" + this.wall_name + "\" target=\"_blank\">";
						rowHTML += "@" + this.wall_name;
						rowHTML += "</a></p>";
						rowHTML += "<p>" + this.wall_text + "</p>";
						rowHTML += "<p class=\"twitter_time\">" + this.wall_date + "</p>";
						rowHTML += "</div>";
						rowHTML += "</div>"; 						
						rowHTML += "<hr style=\"clear: both\"/>";
						rowHTML += "</div>";
						
						twittercontainer.append(rowHTML);
						
						// fade in thumbnail.
						$("#twitter-" + this.wall_id).fadeIn();					
					});
					
					// update counters.
					page = data.page;
					lastpage = data.lastpage;
					totalrows = data.totalrows;
					
					// enable/disable navigation buttons.
					$("#btnTwitterLatest").button({disabled: (totalrows == 0 || page == 1)});					
					$("#btnTwitterPrev").button({disabled: (totalrows == 0 || page == 1)});
					$("#btnTwitterNext").button({disabled: (totalrows == 0 || page == lastpage)});						
				} else {
					$("#btnTwitterLatest").button({disabled: true});
					$("#btnTwitterPrev").button({disabled: true});
					$("#btnTwitterNext").button({disabled: true});
				}
			} else {
				$("#btnTwitterLatest").button({disabled: true});				
				$("#btnTwitterPrev").button({disabled: true});
				$("#btnTwitterNext").button({disabled: true});				
			}
	});
} 
//------------------------------------------------------------------------------------- 
function slideShow(speed) {
    //append a LI item to the UL list for displaying caption
    $('ul.slideshow').append('<li id="slideshow-caption" class="caption"><div class="slideshow-caption-container"><h3></h3><p></p></div></li>');
 
    //Set the opacity of all images to 0
    $('ul.slideshow li').css({opacity: 0.0});
     
    //Get the first image and display it (set it to full opacity)
    $('ul.slideshow li:first').css({opacity: 1.0}).addClass('show');
     
    //Get the caption of the first image from REL attribute and display it
    $('#slideshow-caption h3').html($('ul.slideshow li.show').find('img').attr('title'));
    $('#slideshow-caption p').html($('ul.slideshow li.show').find('img').attr('alt'));
         
    //Display the caption
    $('#slideshow-caption').css({opacity: 0.7, bottom:0});
     
    //Call the gallery function to run the slideshow   
    var timer = setInterval('gallery()',speed);
     
    //pause the slideshow on mouse over
    $('ul.slideshow').hover(
        function () {
            clearInterval(timer);  
        }, 
        function () {
            timer = setInterval('gallery()',speed);        
        }
    );
	
	$(window).blur(function () {
	    clearInterval(timer);
	});    
}
//-------------------------------------------------------------------------------------
function gallery() {
    //if no IMGs have the show class, grab the first image
    var current = ($('ul.slideshow li.show')?  $('ul.slideshow li.show') : $('#ul.slideshow li:first'));
 
    //Get next image, if it reached the end of the slideshow, rotate it back to the first image
    var next = ((current.next().length) ? ((current.next().attr('id') == 'slideshow-caption')? $('ul.slideshow li:first') :current.next()) : $('ul.slideshow li:first'));
         
    //Get next image caption
    var title = next.find('img').attr('title');
    var desc = next.find('img').attr('alt');   
         
    //Set the fade in effect for the next image, show class has higher z-index
    next.css({opacity: 0.0}).addClass('show').animate({opacity: 1.0}, 1000);
     
    //Hide the caption first, and then set and display the caption
    $('#slideshow-caption').slideToggle(300, function () {
        $('#slideshow-caption h3').html(title);
        $('#slideshow-caption p').html(desc);
        $('#slideshow-caption').slideToggle(500);
    });
 
    //Hide the current image
    current.animate({opacity: 0.0}, 1000).removeClass('show');
}
