function FitToContent(id, maxHeight)
{
   var text = id && id.style ? id : document.getElementById(id);
   if ( !text )
      return;

   var adjustedHeight = text.clientHeight;
   if ( !maxHeight || maxHeight > adjustedHeight )
   {
      adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
      if ( maxHeight )
         adjustedHeight = Math.min(maxHeight, adjustedHeight);
      if ( adjustedHeight > text.clientHeight )
         text.style.height = adjustedHeight + "px";
   }
}
$(function(){

	$.getJSON("/stats.json",function(data) {
		var sm = data.skaits;
		var cl = data.clicks;
		$("#stats").html("kopā: <b>"+sm+"</b> īssaites un <b>"+cl+"</b> klikšķi");
  	});
	$("#saite").blur(function() {
		if ($.trim(this.value) == ''){
			this.value = (this.defaultValue ? this.defaultValue : '');
		}
  	});
  	$("#alias").blur(function() {
		if ($.trim(this.value) == ''){
			this.value = (this.defaultValue ? this.defaultValue : '');
		}
  	});
	$("#saite").keyup(function(){
		FitToContent(this, document.documentElement.clientHeight)
	});
	$("#aiziet").click(function(){
		var longurl = $("#saite").val();
		var alias = $("#alias").val();
		longurl = longurl.replace(/(\n\r|\n|\r)/gm,"");
		var kluda = false;
		if (longurl == "") {
			kluda = true;
		} else { kluda = false; }
		if(alias != "") {
			$.getJSON("/?mode=check&smurl="+ alias + "&callback=?", function(checkdata) {
				if(checkdata.available == true) {
					kluda = false;
					$.get("/?mode=shorten&url="+encodeURIComponent(longurl)+"&alias="+alias, function(smurl) {
						$("#saite").val(smurl);
						$("#saite").css("height","18px");
						$("#aiziet").hide();
						$("#custom").hide();
						$("#atpakal").show();
					});
				} else {
					kluda = true;
					alert(checkdata.error);
				}
			});
		}
		if ((kluda == false)&&(alias == "")) {
			$.get("/?mode=shorten&url="+encodeURIComponent(longurl), function(smurl) {
				$("#saite").val(smurl);
				$("#saite").css("height","18px");
				$("#aiziet").hide();
				$("#custom").hide();
				$("#atpakal").show();
			});
		}
		return false;
  	});
	$("#atpakal").click(function(){
		$("#saite").val("");
		$("#alias").val("");
		$("#atpakal").hide();
		$("#custom").show();
		$("#aiziet").show();
	});
});
