var submitted_url = ""; //internal use
var tweetmax = 140; //maximum characters for tweet input
var urlbox_message = "Paste the long url here.."; //initial value for the original url box 
var number_of_cols = 4; //urltables col number
var currentRow = 0; //internal use
var scrollSpeed = 700; //speed for scrolling
var tabitems = 0; //internal use

//piwik initialization
var pkBaseURL = "http://twi.gy/pwk/";
piwik_action_name = '';
piwik_idsite = 1;
piwik_url = "http://twi.gy/pwk/piwik.php";
piwik_log(piwik_action_name, piwik_idsite, piwik_url);


$(document).ready(function(){
//------------------------------------------
//------------------------------------------
			
   $("#comment_count").text(tweetmax);
   $("#long_url").attr("value",urlbox_message);
   $("#underbar").hide();
   $("#tweetbar").hide();
   $("#register_pane").hide();
   $("#credentials").hide(); 
   var short_text = $("#comment").val(); //internal use
   charCalc();
   $("#and_tweet").hide();
   
   $('#home_header_container').show(); 
 
   //url table initialization
   tableInitialize();  
   //hiding the template row
   $("tr.urltab_row:has(.urltab_cell:contains('!###TEMPLATE###!'))").hide();
   tabitems = $("tr.urltab_row:visible:not(#buttons)").length;
   
    
    $('.emulate-hover').live("mouseover", function() {
        $(this).addClass("hovered");
    });
    
    $('.emulate-hover').live("mouseout", function() {
        $(this).removeClass("hovered");
    });
    
    
   //hiding url table if no previous url and if pagination exists if there is one page
   if (tabitems < 1 && (  $("#total").text() == 1 || !$("#total").text()   )) {
	   	$("#nolinks").show();
	   	$("#myurls_pane").hide();
   }
  
   //hiding things according to being logged on or not
   if (username.length==0){
	   //not logged in
	   $("#logon").hide();
   }else{
	   $("#nologon").hide();
	   $("#myurls_pane").show();
   }
	
    //UX ---------------------
	 //wraps the long url and puts the original
	 //version to the tooltip (for the url table)
   	function wrapURL(obj){ //obj->  $(".originalLink")
		 oldContent = $(obj).html();
		 $(obj).attr("title",oldContent);
		 if (oldContent.length > 50){
			 newContent = oldContent.substring(0,45)+"...";
		 }else{
			 newContent = oldContent;
		 }
		 $(obj).html(newContent); 
   	}
   
	 $(".originalLink").each(function (i){
		 wrapURL(this);	 
	 });  
   
   //binds everything in place even after 
   //the table content/rows etc changed dynamically	 
   function tableInitialize(){
   	//showing nolinks pane 
	tabitems = $("tr.urltab_row:visible:not(#buttons)").length;
	 if (tabitems < 1 && (  $("#total").text() == 1 || !$("#total").text()  )){
		 $("#nolinks").show();
	 }else{
		 $("#nolinks").hide();
	 }
	  
	//binds button functions 
		   $(".retweet").click(function(){
			   suffix = getCurrentSuffix(this);
			   twigyUrl = 'http://twi.gy/'+suffix;
			   short_text = twigyUrl;
			   $("#comment").val(twigyUrl);
			   charCalc();
			   //if andtweet pane is hidden, first show it
			   if ($("#and_tweet:visible").length == 0){
			   	$("#and_tweet").show();
			   }
			   $.scrollTo("#and_tweet", scrollSpeed );
			   return false;
		   });
		   
		   $(".stats").click(function(){
			   $.post(  "actions", 
					   	{act_type:"link_stats", suffix: getCurrentSuffix(this)},
					   	function(data){ statsDone(data); }
			   		  );
			   return false;
		   });
		      
		   $(".delete").click(function(){
		   	   buttonObject = this;
			   $.post(  "actions", 
					   	{act_type:"delete_link", suffix: getCurrentSuffix(this)},
					   	function(data){ deleteDone(data,buttonObject); }
			   		  );
			   return false;
		   });
   }//endof table initialize
  
   //table buttons callback functions
  	function deleteDone(data,obj){
		$(obj).parent().parent().fadeOut("fast", function(){tableInitialize();});
		//tableInitialize();
	}
	
	//TODO:
   function statsDone(data){
	   ;
   }
		   	   

	// commentbox
   function charCalc(){
	   var texts = $("#comment").val();
	   var len = texts.length;
	   $("#comment_count").text(tweetmax - len);
	   
	   if( (tweetmax - len) < 0){
		   $("#tweetit").attr("disabled","disabled");
	   }else{
		   $("#tweetit").removeAttr("disabled","disabled"); 
	   }
	   
   }
   
   $("#comment").keydown(function(event){
	   charCalc();
	  });
   
   $("#comment").keyup(function(event){
	   charCalc();
	  });
   
   $("#comment").mouseup(function(event){  
	   charCalc();
   	  });
   
   //submit button enabling XXX:not user friendly?
   function submitToggle(){
		 if ($.trim($("#long_url").val()) == submitted_url || $("#long_url").val()=="" )
		 {
			 $("#shortit").attr("disabled","disabled");
		 }else{
			 $("#shortit").removeAttr("disabled","disabled");
		 }
   }
   
   $("#long_url").keyup(function(event){
	   	submitToggle();
	    }
   );
   
   $("#long_url").mouseup(function(event){
	   	submitToggle();
	    }
  );
   
   $("#shortit").mousedown(function(event){
	   	submitToggle();
	    }
 );
   
   //urlbox
   $("#long_url").click(function(event){
	   if ( $("#long_url").val() == urlbox_message ) {
		   $("#long_url").val("");   
	   }   
	  }
     );
   
   //registration vs. login
   $("#register_button").click(function(){
	   if($("#register_pane").is(":hidden")){
		   $("#login_pane").slideUp("fast");
		   $("#register_pane").slideDown("fast");
		   $("#register_button a").text("Close")
	   }else{
            $("#login_pane").slideDown("fast");	   
		   $("#register_pane").slideUp("fast");
		   $("#register_button a").text("Register!")
	   }
	   return false;
   });
   
   $("#shortennow").click(function(){
	   $.scrollTo("#long_url_wrapper", scrollSpeed );
	   return false;
   });
   
   //FUNC  ---------------------
   
   //removes lines except for template line
   function clearTable(){
   		$("tr.urltab_row:visible:not(#buttons)").remove();
   }
   
   //adds a row to urltab using cloning
   function addRow(suffix, original_url, hits, creation_time){
		$("tr.urltab_row:first").clone().insertBefore("tr.urltab_row:first");
		var twigyURL = "twi.gy/" + suffix ;

		$(".urltab_row:first .twigyLink a").text(suffix);
		$(".urltab_row:first .twigyLink a").attr("href","http://"+twigyURL);
		$(".urltab_row:first .twigyLink a").attr("title",original_url);
		$(".urltab_row:first .originalLink").text(original_url);
		$(".urltab_row:first .hits").text(hits); //hits
		$(".urltab_row:first .timestamp").text(creation_time); //creation time
		
		//final remarks
		$("tr.urltab_row:first").show();
		tableInitialize();
		wrapURL($("tr.urltab_row:first .originalLink"));
   }
   
   
   //shortening ajax
   function shortDone(data){
	   if (!data.pass){
		   $("#underbar").text(data.message);
		   return;
	   }
	   
	   if (data.already_shortened){
	   		presenting = "Your already shortened url was ";
	   }else{
	   		presenting = "Your brand new shortened url is ";
	   }
	   data.message = $.trim(data.message);
	   $("#underbar").html(presenting + "<div class=\"newUrl\">"+data.message+"</div>");
	   submitted_url = $("#long_url").val();
	   $("#comment").val(data.message);
	   short_text = data.message;
	   $("#and_tweet").show();
	   $("#myurls_pane").show();
	   $.scrollTo("#underbar", scrollSpeed );
	   charCalc();
	   
	   if (data.already_shortened) {
	   		//TODO highlight or sth else
	   	}else{
	   		//add to table
			addRow(data.suffix, data.original_url, "0", data.time);
			$("#nolinks").hide();
		}	   
   }
   
   $("#shortit").click(function() {
   	   if (!urlValid()){
	   	 return false;
	   }
	   $("#underbar").show();
	   $("#shortit").attr("disabled","disabled");
	   $("#underbar").text("Shortening...");
	   
	   $.post(  "actions", 
			   	{act_type:"shorten", long_url: $.trim($("#long_url").val())},
			   	function(data){ shortDone(data); } , 
			   	"json"
	   		  );
	   return false;   
	   
	   } 	   
   );
   
   function urlValid(){
    candi = $.trim($("#long_url").val());
	
	if (candi.length == 0) {
		message = "You actually need to enter something";
		$("#underbar").text(message);
		$("#underbar").show();
		return false;
	}
	return true;
   }
   
   //login ajax
   function logDone(data){
	   if(data.pass){
		  $("#loginbar").text(data.message);
		  location.reload(true);
	   }else{
	   	   $("#logbut").removeAttr("disabled","disabled");	
		   $("#loginbar").text(data.message);
	   }	  
   }
   
   $("#login").submit(function() { 
       $("#logbut").attr("disabled","disabled");	
	   $.post(  "actions", 
			   	{act_type:"login", username: $("#username").val(), password: $("#password").val()},
			   	function(data){ logDone(data); },
			   	"json"
	   		  );
	   return false;
	   } 
   );
   
   //tweeting ajax
   function tweetDone(data){
	   $("#tweetit").removeAttr("disabled","disabled");
	   
	   if (data.pass){
	   		link = "<br /><a target='_blank' href='"+data.link+"' style='font-size: 80%'>View your tweet.</a>";
		   $("#tweetbar").html(data.message + link);
		   $.scrollTo("#myurls_pane", scrollSpeed );
	   }else{
	   	alert("false");
		   	$("#tweetbar").text(data.message);
	   }  
   }
     
   $("#tweetit").click(function() {
	   $("#tweetbar").show();
	   
	   //not logged in and credential form hidden?
	   if (username.length==0 && $("#credentials").is(":hidden")){
		   $("#credentials").slideDown();
		   return false;
	   }
	   
	   //not talking about the shortened url?
	   if ( $("#comment").val().indexOf(short_text) == -1 || short_text.length == 0){
		   return false;
	   }
	    
	   $("#tweetit").attr("disabled","disabled");
	   $("#tweetbar").text("Tweeting...");
	   
	   $.post(  "actions", 
			   	{act_type:"tweet", comment: $("#comment").val(),
			   		cusername: $("#cusername").val(),cpassword: $("#cpassword").val(),
			   		short_text : short_text },
			   	function(data){ tweetDone(data); } , "json"
	   		  );
	   return false;
	   } 
   );

   
   //registration
   function regDone(data){
	   if(data.pass){
		  $("#registerbar").text(data.message);
		  location.reload(true);
	   }else{
		   $("#registerbar").text(data.message);
	   }
   }
   
   //first level validation 
   function regCheck(){
	   
	   //empty data check
	   var fill = "";
	   
	   switch ("") {
	   	case $.trim($("#rusername").val()) :{
	   		fill = "username.";
	   		$("#registerbar").text("Please enter your "+fill);
	 	   return false;		
	   	}
	   	case $.trim($("#rpassword").val()) :{
	   		fill = "password.";
	   		$("#registerbar").text("Please enter your "+fill);
	 	   return false;		
	   	}
	   	case $.trim($("#remail").val()) :{
	   		fill = "email.";
	   		$("#registerbar").text("Please enter your "+fill);
	 	   return false;		
	   	}
	   }
	   
	   //email format check
	   var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	   if (!filter.test($.trim($("#remail").val()))) {
	   		$("#registerbar").text("Please enter a valid email.");
		 	   return false;	
	   }
	   return true;
   };
   
   $("#register").submit(function() {
	   if(regCheck()){
	   $.post(  "actions", 
			   	{act_type:"register", username: $("#rusername").val(), 
		   password: $("#rpassword").val(), email: $("#remail").val()},
			   	function(data){
					regDone(data);
				}, "json"
	   		  );}
	   return false;
	    
	   }
   );
   
   //signout
   function logoutDone(data){
   $("#loggedon_pane").text("Signing out...");
   location.reload(true);
   }
   
   $("#logout_button").click(function(){
	   $.post(  "actions", 
			   	{act_type:"logout"},
			   	function(data){ logoutDone(data); }
	   		  ); 
	   return false;
   });
   
   	//works for table buttons
   function getCurrentSuffix(obj){
	   var suffix = $(obj).parent().parent().children(".twigyLink").text();
	   return suffix;
   }
	
	//pagination
	function pagDone(data){
		if (data) {
			$("#numof").text(data.set);
			$("#total").text(data.total);
			clearTable();
			$.each(data.list, function(i , url){
				addRow(url.suffix, url.original_url, url.hits, url.creation_time);
			});
		}
	}
		
 	$(".pag").click(function(){
		id = $(this).attr("id");
		current = Number($("#numof").text());
		total = Number($("#total").text());
		switch (id){
			case "prev" :{
				setnum = current - 1;
				break;
			}
			case "next" :{
				setnum = current + 1;
				break; 
			}			
			case "last" :{
				setnum = total;	
				break;	
			}
			case "first" :{
				setnum = 1;	
				break;	
			}
		}

		if (setnum > 0 && setnum <= total && setnum != current  ) {
			$.post("actions", {
				act_type: "user_urls",
				set: setnum
			}, function(data){
				pagDone(data);
			}, "json");
		}
	   return false;	
		
	});

//-------------------------------------
});