/**
 * @author Askin Er
 */
$(document).ready(function(){
	
	
	var ERR_MSG = new Array();
	var default_TwitterMSG = "http://SeitLink.de twittert direkt";
	ERR_MSG["code"] ="Das eigene kürzel ist fehlerhaft";
	ERR_MSG["protocol"] ="Das Protokoll ist nicht definiert<brx/>Erlaubt sind: <b>http:, https: ,ftp:, mailto:, smb:, afp:</b>";

	$("#accordion").accordion({ header: "h3" });

	$("#ownButton").click(toggleOwn);

	$("#postIT").click(TwittIt);
	
	$("#long2short").click(long2short);
	
	$("#submit_badLink").click(function(){
		submit_Badlink(this);
	});
	$("#tellTwitter").click(function(){
		window.location.href = "http://twitter.com/home?status="+ $("#short").val();
	});
	
	$("#tellFacebook").click(function(){
		window.location.href = "http://www.facebook.com/share.php?u="+ $("#short").val();
	});
	
	var bookMark = document.location.search
	if (bookMark.length > 0)
	{
		var newUrl = bookMark.substring(5,bookMark.length);
		
		$("#long").val(decodeURIComponent(newUrl));
		long2short();		
	}
	
	$("#twitterMsg").attr("class","url ui-corner-all");
	$("#long").focus();
	function submit_Badlink(object)
	{
			$(object).unbind();
			$.ajax({
			   type: "GET",
			   url: "api.php",
			   data: "bad_url="+$("#bad_url").val(),
			   dataType: "text",
			   success: function(text){
					$(object).after('<div id="bad_msg">Nachricht versand</div>');
					$("#bad_msg").effect("bounce",500).animate({opacity: 0.0}, 3000,function(){
						$(this).remove();
							$("#submit_badLink").click(function(){
								submit_Badlink(this);
							});
					});
			  
			   },
			   error: function(){
			   		$(object).after('<div id="bad_msg">Nachricht versand</div>');
					$("#bad_msg").effect("bounce",500).animate({opacity: 0.0}, 3000,function(){
						$(this).remove();
							$("#submit_badLink").click(function(){
								submit_Badlink(this);
							});
					});
			   }
			 });

	}
	
	function long2short()
	{
		var url = 'longurl='+encodeURIComponent($("#long").val());
		if ($("#own").is(':visible')) {
			url +='&own='+$("#own").val();
		}

	
		if($("#long").val() != "")
		{ 
		
			$.ajax({
			   type: "GET",
			   url: "api.php",
			   data: url,
			   dataType: "text",
			   success: function(text){
			      var msg = text.split("ERR:");
			      if (msg.length == 1) 
				  {
						$("#short").val(text);
						showShortLink(text)
						resetOwn();
				  }
				  else 
				  {
				  		showErrTop(ERR_MSG[msg[1]]);
				  }	
			  
			   },
			   error: function(){
			   			showErrTop('Konnte URL nicht kürzen...');
			   }
			 });

		}
		else
		{
			showErrTop("Der zu kürzende Link fehlt");	
			
		}
		
	}
	
	function toggleOwn()
	{
		$("#own").slideToggle("slow",function(){
			if (!$("#own").is(':visible')) {
				$("#own").val("");
				bind_checkOwn();
			}
			else
			{
				unbind_checkOwn();
			}			
		});
	}
	
	function resetOwn()
	{
		if ($("#own").is(':visible')) {
				$("#own").slideToggle("slow").val("");
				unbind_checkOwn();
		}
		
	}
	
	function showErrTop(msg)
	{
		
		var html =	'<div class="grid_8" id="msg_box_long">'
					+'<span class="hint_bottom">'
					+'<span id="msg_long"></span>'
					+'<span class="hint-pointer_bottom">&nbsp;</span>'
					+ msg		
					+'</span>'
					+'</div>';
		$(html)
		.appendTo("#input_bg_long")
		.animate({opacity: 1.0}, 3000)
		.animate({opacity: 0.0}, 3000,function(){
			$(this).remove();
		});
		
	}
	
	function showShortLink(msg)
	{
		$("#buttonOptions").show();
		var html =	'<div class="grid_8" id="msg_box_long">'
					+'<span class="hint_bottom">'
					+'<span id="msg_long"></span>'
					+'<span class="hint-pointer_bottom">&nbsp;</span>'
					+ msg		
					+'</span>'
					+'</div>';
					
					
		ZeroClipboard.setMoviePath( 'http://seitlink.de/lib/jquery/ZeroClipboard.swf');
		var clip = new ZeroClipboard.Client();
		clip.setText(msg);
		clip.glue( 'd_clip_button', 'd_clip_container' );
		
		$(html)
		.appendTo("#input_bg_short")
		.animate({opacity: 1.0}, 3000)
		.animate({opacity: 0.0}, 3000,function(){
			$(this).remove();
		});

		
	}
	
	function unbind_checkOwn()
	{
	//	$("#own").unbind("keyup");
	}
	
	function bind_checkOwn()
	{
		return null;
	}	
		// Username validation logic
		var ownMSG = $("#lala");
		$("#own").keyup(function(){
            var t = this; 
			
            if (this.value!= this.lastValue && this.value.length > 3) 
			{
                                
				$.ajax({
                	url: 'api.php?check=&own=' + t.value,
                    dataType: 'text',
                    type: 'get',
                    success: function (text) {
                    	if(text == "true")
						{
							ownMSG.text("OK").css({color: 'green', "text-align": 'center'});
						}
						else
						{
							
							if(text == "ERR:free")
								return ownMSG.text("Schon vergeben").css({"color": 'red', "text-align": 'center'});;

							if(text == "ERR:long")
						 		ownMSG.text("Zu Kurz").css({"color": 'red', "text-align": 'center'});

						 	if(text == "ERR:code")
						 		ownMSG.text("Verbotene Zeichen").css({"color": 'red', "text-align": 'center'});
							
						}
                	}
                 });
             
                // copy the latest value to avoid sending requests when we don't need to
                this.lastValue = this.value;
            }
			else
				ownMSG.text("");
        });

		function shortUrlForTwitter(longUrl)
		{
			
			var result = longUrl;
			if(longUrl != "")
			{
				var url = 'api.php?longurl='+longUrl;
				$.ajax({
					type: "GET",
					url: url,
					dataType: "text",
					async:false,
					success: function(text){
				      	var msg = text.split("ERR:");
						if (msg.length == 1) 
						{
							result = text;
						}
						
					},
					error: function(){
						showErrTop('Konnte URL nicht kürzen...');
					}
				 });
			}
			
			return result;

		}
		
		function TwittIt()
		{
			
			var replaced = false;
			var words = $('#twitterMsg').val().split(" ");
			for(var i=0;i< words.length ; i++)
			{
				
				if (isUrl(words[i]))
				{
					var change =  shortUrlForTwitter(words[i]);
					var newVal = $('#twitterMsg').val().replace(words[i],change);
					$('#twitterMsg').val(newVal);
					replaced = true;
				}
			}	
			
			if(replaced)
				location.href="http://twitter.com/home/?status="+$('#twitterMsg').val();
		}

		function isUrl(s) {
			
			var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
			return regexp.test(s);
			
		}
		
		function emptyTwitterMSG()
		{
			if($('#twitterMsg').val() == default_TwitterMSG)
			{
				$('#twitterMsg').val("");
			}
		}

	
});

