var gallery;

$(document).ready(function(){
	
	//Show latest tweet
	jQuery("div.latest_tweet").tweet({
        avatar_size: 32,
        count: 1,
        username: "differentrecs",
        template: "{time}{join}{text}"
	});
    
	//Create a gallery
	gallery = new Gallery($("div.slides"));
	gallery.onSwap = updatePager;
	updatePager();
	gallery.startAutoplay();
	
	$("a.next, a.prev").click(function(){
		gallery.stopAutoplay();
		var me = $(this);
		if(me.hasClass("next")){
			gallery.next();
		}else {
			gallery.prev();
		}
		gallery.startAutoplay();
		return false;
	});
	
	//Remove default text on focus
	$("#email").focus(function(){
		if(this.value == 'Enter E-mail Address'){
			this.value = '';
		}
		$(this).removeClass("error");
	});
	
	//Add default text on blur
	$("#email").blur(function(){
		if(this.value == ''){
			this.value = 'Enter E-mail Address';
		}
	});

	//Validate and submit form
	$(".submit_d_button").click(function(){
		
		//Validate email
		var input = $("#email");
		var email = input.val();
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		if(!reg.test(email)){			
			input.addClass("error");
		}else {
			
			//Show preloader		
			$("#download_form").hide();
			
			//Reset info
			var info = $("#download_info");
			info.find("img").show();
			info.find("span").removeClass("error").html("");
			info.show("fast");
			
			//Send request to the server
			jQuery("#tmp_script").remove();
			jQuery("head").append("<script id='tmp_script' src='http://pias.us1.list-manage.com/subscribe/post-json?u=361e80debfd453d4a12f8d5d6&id=2311d74a99&c=send_link_callback&EMAIL="+encodeURIComponent(email)+"&subscribe=download&rand="+Math.random()+"'></script>");
		}
		return false;
	});
	
	//Share 
	$("a.share_icon").click(function(){
		window.open(this.href, '', "width=500,height=500");	
		return false;
	});
});

//Ajax send link callback
function send_link_callback(obj){
	
	var info = $("#download_info");
	info.find("img").hide();
	if(obj.result == "error"){		
		info.addClass("error").html(obj.msg);
		setTimeout(function(){
			$("#download_info").hide();
			$("#download_form").show("fast");
		}, 4000);
	}else {
		$("#download_info span").html("To complete the subscription process, please click the link in the email we just sent you.");
	}
}

//Update pager once slides has been changed
function updatePager(){
	var index = gallery.getIndex();
	var total = gallery.getTotalNum();
	var onpage = gallery.on_page;
	var from = Math.max(index * onpage + 1, 1);
	var to = Math.min(from + onpage - 1, total);
	
	$("#slider_pager").html(from + " - " + to + " of " + total + "&nbsp;&nbsp;&nbsp;");
}
