var _delete=false;
var cale;
$(function() {
 jQuery.getScript("js/calendar/zapatec.js", function() {
  jQuery.getScript("js/calendar/calendar.js", function() {
   jQuery.getScript("js/calendar/calendar-no.js", function() {
		jsbitch.initcalendar(function(today) {
			jsbitch.init();
			jsbitch.bydate(today);
		});
   });
  });
 }); 
 $("#search").keyup(function (ev) {
 	if(ev.keyCode==13 || $(this).val().length == 0) {
 	 if($(this).val().length == 0) {
 		jsbitch.hideSearchPad();
 	 }
 	 $(this).focus();
 	}
 	else
 	if($(this).val().length > 3 && ev.keyCode!=9 && ev.keyCode!=16 && ev.keyCode!=17 && ev.keyCode!=18 && ev.keyCode!=19 && ev.keyCode!=20 && ev.keyCode!=27 && ev.keyCode!=33 && ev.keyCode!=34 && ev.keyCode!=35 && ev.keyCode!=36 && ev.keyCode!=37 && ev.keyCode!=38 && ev.keyCode!=39 && ev.keyCode!=40) {
 	 $("#rapidsearch").fadeIn("fast", function() {
 		$("#rapidsearch #result").html("<img src=\"gfx/loader.gif\" style=\"position:relative;left:130px;top:50px;\"/>");
 		jsbitch.search($("#search").val(), function(s) {
 		 jsbitch.resetpg();
 		 
 		 SEARCH_ENGINE_ROWS_FOUND = jsbitch.replaceAll(s.funnet,",","");
 		 SEARCH_ENGINE_ROWS = s.svar;
 		 
 		 $("#rapidsearch #resultheader").html("<div style=\"float:left;\"><em>"+s.beskjed.toLowerCase().substring(0,(s.beskjed.length<10 ? s.beskjed.length : 10)) + (s.beskjed.length==11 ? "." : "") + (s.beskjed.length==12 ? ".." : "") + (s.beskjed.length>12 ? "..." : "") + "</em>: <span id=\"searchidx\"></span> av " + s.funnet + "</div><div style=\"float:right;\"><input type=\"submit\" id=\"previous\" value=\"« Forrige\" \>&nbsp;<input type=\"submit\" id=\"next\" value=\"Neste »\" \>&nbsp;<a href=\"#\" id=\"close\">Lukk</a></div>");	
 		 
 		 $("#rapidsearch #result").empty().css("opacity","0.9");
 		 $("#previous").click(function() {
 		  jsbitch.previous();
 		 });
 		 $("#next").click(function() {
 		  jsbitch.next();
 		 });
 		 
 		 $("#close").click(function() {
 		  jsbitch.hideSearchPad();	
 		 });
 		 
 		 jsbitch.setpg(1);
 		 
 		 $("#rapidsearch #result").fadeIn("slow");	
 		 $("#search").focus();
 		});
 	 });
 	}
 });
 $("#txtSkjellsord").val("");
 $("#search").val("").focus();
 $("#cmdSend").attr("disabled","")
 .click(function() {
 	$(this).blur();
 	$("#txtSkjellsord").focus().val(jsbitch.trim($("#txtSkjellsord").val()));
 	$("#cmdSend").attr("disabled","true");
 	jsbitch.add($("#txtSkjellsord").val(), function(s) {
 	  
 	 switch(s.svar) {
 	 	case 100 : 
 	 	 $("#txtSkjellsord").val("");
 	 	 $("#count").html(s.antall);
 	 	 jsbitch.bydate(Dates.YMD);
 	 	 $("#err").html(s.beskjed)
 	 	  .css("color","green")
 	 	  .fadeIn("fast")
 	 	  .animate({opacity:1.0},3000)
 	 	  .fadeOut("fast", function() {
 	 	  	$("#cmdSend").attr("disabled","");
 	 	  	$("#txtSkjellsord").focus();
 	 	  });
 	 	break;
 	 	case 101 : 
 	 	 $("#err").html(s.beskjed)
 	 	  .css("color","red")
 	 	  .fadeIn("fast")
 	 	  .animate({opacity:1.0},3500)
 	 	  .fadeOut("fast", function() {
 	 	  	$("#cmdSend").attr("disabled","");
 	 	  	$("#txtSkjellsord").focus();
 	 	  });
 	 	break;
 	 	case 102 : 
 	   $("#err").html(s.beskjed)
 	 	  .css("color","red")
 	 	  .fadeIn("fast")
 	 	  .animate({opacity:1.0},4000)
 	 	  .fadeOut("fast", function() {
 	 	  	$("#cmdSend").attr("disabled","");
 	 	  	$("#txtSkjellsord").focus();
 	 	  });	
 	 	break;
 	 	case 103 : 
 	   $("#err").html(s.beskjed)
 	 	  .css("color","red")
 	 	  .fadeIn("fast")
 	 	  .animate({opacity:1.0},4000)
 	 	  .fadeOut("fast", function() {
 	 	  	$("#cmdSend").attr("disabled","");
 	 	  	$("#txtSkjellsord").focus();
 	 	  });	
 	 	break;
 	 }
 	});
 });
});
var SEARCH_ENGINE_ROWS_FOUND=0;
var SEARCH_ENGINE_ROWS;
var jsbitch = {
 MAX_ROWS_IN_RESULT : 7,
 MAX_ROWS_IN_LETTER_RESULT : 5,
 LETTER_COLUMS : 4,
 replaceAll : function(txt, from, to) {
 	 while(txt.indexOf(from)>=0) {
 	 	txt=txt.replace(from, to);
 	 }
 	 return txt;
 },
 hideSearchPad : function(){
 	$("#search").val("").focus();
 	$("#rapidsearch").fadeOut("fast", function() {
 		
 		$("#rapidsearch #resultheader").empty();	
 		$("#rapidsearch #result").empty();	
 	});
 },
 pagecb : function(previous, next, callback) {
 	 $(previous[0]).attr("disabled", previous[1]).blur().css("color",(previous[1] ? "#cccccc" : "#7fb521"));
 	 $(next[0]).attr("disabled", next[1]).blur().css("color",(next[1] ? "#cccccc" : "#7fb521"));
 	 if(callback) callback();
 },
 previous : function() {
 	this.setpg(-1);
 },
 next : function() {
 	this.setpg(+1);
 },
 setpg : function(pgno, callback) {
 	var v = parseInt($("#search_engine_pgno").val())+pgno;
 	if(v > 0)
 		$("#search_engine_pgno").val(v);
 		
 	var from = (parseInt($("#search_engine_pgno").val())*this.MAX_ROWS_IN_RESULT-this.MAX_ROWS_IN_RESULT+1);
 	var to = (parseInt($("#search_engine_pgno").val())*this.MAX_ROWS_IN_RESULT);
 	if(to > SEARCH_ENGINE_ROWS_FOUND) {
 	 to = SEARCH_ENGINE_ROWS_FOUND;
 	}
 	
 	if(to==0) {
 		from=0;
 	}
 	
 	$("#searchidx").html(from + "-" + to);
 	
 	 var r="";
 	 for(var i=from-1;i<to;i++) {
 	 	if(SEARCH_ENGINE_ROWS[i]) r+="<p class=\"" + SEARCH_ENGINE_ROWS[i][0] + "\">"+SEARCH_ENGINE_ROWS[i][0]+ (SEARCH_ENGINE_ROWS[i][1]=="1" ? jsbitch.DESCRIPTION_IMAGE : "") + "</p>";
	  if(i+1==this.MAX_ROWS_IN_RESULT) break;
	 }
	 $("#rapidsearch #result").html(r);
	 $.each($("#rapidsearch #result p"), function(i) {
	 	$(this).click(function() {
  		jsbitch.showInfoPad((SEARCH_ENGINE_ROWS[i+from-1][0]+""), function() {
  			
  		});
  	 }).css("cursor","pointer").css("cursor","hand");
  	});
	 $("#rapidsearch #result p").hover(function() {
  	$(this).css("background-color","#e5e5e5");
   }, function() {
  	$(this).css("background-color","transparent");
  });
	 this.pagecb(
	  ["#previous",$("#search_engine_pgno").val()=="1"], 
	  ["#next",to==SEARCH_ENGINE_ROWS_FOUND], function() {
	   $("#search").focus();	
	  });
 },
 resetpg : function() {
 	$("#search_engine_pgno").val(0);
 },
 init : function() {
  this.initletters();
    this.resetpg();
  /*this.ax("type=initial", function(s) {
  	$("#count").html(s.antall);
  });*/	
 },
 initletters : function() {
  
  $("#letterprevious").click(function() {
  	if(jsbitch.isLeftEdge()=="false") {
	  	$(this).attr("disabled", true);
	  	var p = parseInt($("#letter_pgno").val());
	  	$("#letter_pgno").val(p-1);
		  	jsbitch.getletters((p-1)*jsbitch.MAX_ROWS_IN_LETTER_RESULT*jsbitch.LETTER_COLUMS,$("#letter").val(), function(start, end, total) {
		  	 $("#letterprevious").attr("disabled", false);	
		  	});
	  }
  });
  $("#letternext").click(function() {
  	if(jsbitch.isRightEdge()=="false") {
	  	$(this).attr("disabled", true);
	  	var p = parseInt($("#letter_pgno").val());
	  	$("#letter_pgno").val(p+1);
	  	jsbitch.getletters((p+1)*jsbitch.MAX_ROWS_IN_LETTER_RESULT*jsbitch.LETTER_COLUMS,$("#letter").val(), function(start, end, total) {
	  	 $("#letternext").attr("disabled", false);	
	  	});
	  }
  });
  $(".letters").click(function() {
  	$("#letter_pgno").val(0);
	  $("#letter").val($(this).attr("id").replace("letter_",""));
	  $(".letters").css("color","#7FB521");
  	$(this).css("color","#c7c7c7");
  	jsbitch.getletters(0,$(this).attr("id").replace("letter_",""), function(start, end, total) {
  		$("#alphalist").fadeIn("fast",function() {
  			
  		});
  	});
  });
  $(".letters:first").click();
 },
 DESCRIPTION_IMAGE : " <img src=\"gfx/description.gif\" alt=\"Ordet har en beskrivelse\" title=\"Ordet har en beskrivelse\"/>",
 getletters : function(pos, letter, callback) {
 	jsbitch.ax("type=lettersearch&pos=" + pos + "&rows=" + jsbitch.MAX_ROWS_IN_LETTER_RESULT*jsbitch.LETTER_COLUMS + "&letter=" + encodeURIComponent(letter), function(s) {
 	 $("#lettercount").html("1-" + s.funnet + " av " + s.beskjed);
 	 var str="";
 	 $("#alphalist tr:first td").html("");
 	 var j=0;
 	 for(var i=0;i<s.svar.length;i++) {
 	 	if(i % jsbitch.MAX_ROWS_IN_LETTER_RESULT == 0 && i>0) j++;
 	 	$("#alphalist td").eq(j).append("<p class=\"" + s.svar[i][0] + "\">" + s.svar[i][0] + (s.svar[i][1]=="1" ? jsbitch.DESCRIPTION_IMAGE : "") + "</p>");
 	 }
 	 $.each($("#alphalist p"), function(i) {
 	 	 $(this).click(function() {
  		jsbitch.showInfoPad(s.svar[i][0], function() {
  			jsbitch.getletters(pos, letter);
  		});
  	 });
  	});
 	 for(var i=j;i<4;i++) { //push em to the left
 	 	$("#alphalist td").eq(j).css("width","120px");
 	 }
 	 
 	 var pg=parseInt($("#letter_pgno").val())+1;
 	 var s1=s.svar.length;
 	 var s2=parseInt(jsbitch.replaceAll(s.beskjed,",",""));
 	 
 	 var n1=((pg*((jsbitch.MAX_ROWS_IN_LETTER_RESULT*jsbitch.LETTER_COLUMS))) - (jsbitch.MAX_ROWS_IN_LETTER_RESULT*jsbitch.LETTER_COLUMS)+1);
 	 var n2=((pg*((jsbitch.MAX_ROWS_IN_LETTER_RESULT*jsbitch.LETTER_COLUMS))));
 	 var n3=jsbitch.replaceAll(s.beskjed,",","");
 	 if(n2>n3) 
 	   n2=n3;
 	 
 	 jsbitch.setLeftEdge(n1<=1);
 	 jsbitch.setRightEdge(n2>=n3);
 	 
 	 jsbitch.pagecb(
	   ["#letterprevious", $("#letter_pgno").val()=="0"], 
	   ["#letternext",n2==n3], function() {
	 		$("#lettercount").html(n1 + "-" + n2 + " av " + s.beskjed);
	 		if(callback) callback(n1,n2,n3);  
	  });	
 	});
 },
 setLeftEdge : function(s) {
 	$("#reachedleftedge").val(s);
 },
 isLeftEdge : function() {
 	return $("#reachedleftedge").val();
 },
 setRightEdge : function(s) {
 	$("#reachedrightedge").val(s);
 },
 isRightEdge : function() {
 	return $("#reachedrightedge").val();
 },
 ax : function(dat, callback) {
 	$.ajax({
	 type: "GET",
	 url: "ax.php",
	 data: dat,
	 success: function(msg){
	 	eval(msg);
	  if(callback) callback(skjellsordboken);
	 }
	});
 },
 add : function(word, callback) {
 	if(word.length <= 2) {
 	 if(callback) callback({
 	  svar : 102,
 	  beskjed : "Vi legger ikke inn ord under tre bokstaver."
 	 });	
 	} else
 		if(this.trim(word).indexOf(' ')>0) {
 		 if(callback) callback({
 	    svar : 103,
 	    beskjed : "Vi legger ikke inn flere ord samtidig."
 	   });
 	} else {
 	 this.ax("type=add&ord=" + encodeURIComponent(word), function(s) {
 		if(callback) callback(s);
 	 });
 	}
 },
 initcalendar : function(callback) { 
	 $("#calendar").empty();
	 cale = Zapatec.Calendar.setup({
	  step              : 1,
		range             : [2009.03, Dates.YM],
		flat              : "calendar",
    flatCallback      : function(cal) {
		 if(cal.dateClicked) {
			 jsbitch.bydate(cal.date.print("%Y-%m-%d"));
		 }
		},
		weekNumbers       : false,
		firstDay          : 0,
		noHelp						: true,
		dateStatusFunc 		: function (date) {
			return (date.print("%Y-%m-%d") < "2009-03-18") || (date.print("%Y-%m-%d") > Dates.YMD);
		}
	 });
	 
	 if(callback) {
	 	callback(cale.date.print("%Y-%m-%d"));
	 }
 },
 search : function(word, callback) {
 	this.ax("type=search&highlight=true&ord=" + encodeURIComponent(word), function(s) {
 		if(callback) callback(s);
 	});
},
 bydate : function(d, keepInfoPad) {
 	
 	this.ax("type=bydate&date=" + d, function(s) {
 		var sp=s.dato.split(".");
 		sp[0]=(" "+sp[0]).replace(" 0","").replace(" ","");//fix on weird bug
 		//cale.setDate(new Date(parseInt(sp[2]),(parseInt(sp[1])-1),parseInt(sp[0])));
 		$("#wordsbydate").fadeOut("fast", function() {
  		$("#header").html("<img src=\"gfx/loader.gif\"/>").html("<span>" + s.funnet + "</span> nye skjellsord den " + s.dato);
  		$("#words").empty();
  		$.each(s.svar, function(i, val) {
  			$("#words").append("<p class=\"" + val[0] + "\" style=\"" + (i>0 ? "color:#b6b6b6" : "font-size:14px;color:#707070;")+ "\">"+val[0] + (val[1]=="1" ? jsbitch.DESCRIPTION_IMAGE : "") + "</p>");
  			$("#words p").eq(i).click(function() {
  				jsbitch.showInfoPad(val[0], function() {
  					jsbitch.bydate(d,true);//to update the list behind the scene.
  				});
  			});
  		});
  		if(!keepInfoPad)
  			jsbitch.hideInfoPad();
  		$(this).fadeIn("fast");
  	});
  });
 },
 trim : function(str) {
	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
 },
 hideInfoPad : function() {
 	 $("#worddesc").fadeOut("fast", function() {
 	 	$("#wordsbydate").fadeIn("fast", function() {
 	 		$("#worddesc").html("<img src=\"gfx/loader.gif\"/>");
 	 	});
 	 });
 },
 showInfoPad : function(word, callback) {
 	word=word.replace("<strong>","").replace("</strong>","");
 		$("#worddesc").html("<img src=\"gfx/loader.gif\"/>");
 		$("#wordsbydate").fadeOut("fast", function() {
 		$("#worddesc").fadeIn("fast", function() {
 			$(this).animate({opacity:1.0}, 10, function() { 
 			
 			jsbitch.ax("type=single&ord=" + encodeURIComponent(word), function(s) {
		 	  $("#worddesc").fadeOut("fast", function() {
		 	  $("#worddesc").html(
		 	  	"<p class=\"majorheader\" style=\"float:left;\">" + s.beskjed + "</p>" +
		 	  	(_delete ? "<a href=\"#\" id=\"delete_" + word + "\" class=\"delete\" style=\"font-size:10px;\">Slett</a>" : "") +
		 	  	"<a href=\"#\" id=\"closeinfopad\">Lukk</a>" +
		 	  	"<br/><br/>" +
		 	  	"<div class=\"ingress\" style=\"float:left;\"><div id=\"txt\">" + s.svar + "</div>" +
		 	  	"<a href=\"#\" id=\"editdesc\">[oppdater beskrivelse]</a></div>" +
		 	  	"<div id=\"editdesctxtcontainer\" style=\"display:none;float:left;\">" +
		 	  	" <textarea id=\"editdesctxt\">" + jsbitch.replaceAll(s.svar,"<br/>","\n") + "</textarea>" + 
		 	  	" <input id=\"updatedesc\" type=\"submit\" value=\"Oppdater\"/>" +
		 	  	"</div>").fadeIn("fast");
		 		 $("#worddesc #closeinfopad").click(function() {
		 			$("#worddesc").fadeOut("fast", function() {
		 				jsbitch.hideInfoPad();
		 			});
		 			return false;
		 		});
		 		$("#editdesc").click(function() {
		 			jsbitch.showDescTxtContainer(true);
		 		});
		 		$("#updatedesc").click(function() {
		 			jsbitch.updateDescription(s.beskjed, jsbitch.replaceAll($("#editdesctxt").val(),"\n","<br/>"), function() {
		 				if(callback) callback();
		 			});
		 		});
		 		$("#worddesc").fadeIn("fast");
		 		$(".delete").click(function() {
		 			jsbitch.ax("type=deletewrdd&ord=" + encodeURIComponent($(this).attr("id").replace("delete_","")), function(s) {
		 				$("."+s.svar).css("color","red");
		 				$("#worddesc").fadeOut("fast", function() {
		 					jsbitch.hideInfoPad();
		 				});
		 			});
		 	 	 });
		 	  });
			 });
  		});
 		});
  });
 },
 showDescTxtContainer : function(doShow) {
 	if(doShow)
 		$("#editdesctxtcontainer").fadeIn("fast");
 	else 
 		$("#editdesctxtcontainer").fadeOut("fast");
 },
 updateDescription : function(word, desc, callback) {
 	//$("#editdesctxtcontainer").html("<img src=\"gfx/loader.gif\"/>");
 	jsbitch.ax("type=updatedesc&ord=" + encodeURIComponent(word) + "&desc=" + encodeURIComponent(desc), function(s) {
 		$("#worddesc .ingress #txt").html(jsbitch.replaceAll(s.svar,"\n","<br>"));
 		if(callback) callback();
 		jsbitch.showDescTxtContainer(false);
 	});
 }
};

var d=new Date();
var Dates = {
 YMD : (d.getFullYear() + "-" + (((d.getMonth()+1)+"").length==1 ? "0"+(d.getMonth()+1) : d.getMonth()+1) + "-" + ((d.getDate()+"").length==1 ? "0"+d.getDate() : d.getDate()))
};

