// JavaScript Document
function lookUpWord(word){
	$.msgbox({
		height:600, 
		width:550, 
		title:'Look up a word',
		type:'iframe', 
		content:'dict.php?kw='+encodeURI(word)
	});		
}

function reloadNumOfRecited(){ 

	$("td[class=td_recited]")
		.html('<img src="images/loading.gif" height="15">')
		.load("ajax/numOfRecited.php",'');
		
}

function reloadNumOfMywords(){ 

	$("td[class=td_mywords]")
		.html('<img src="images/loading.gif" height="15">')
		.load("ajax/numOfMyWords.php",'');
		
}

function reloadNumOfWordlib(){ 

	$("td[class=td_wordlib]")
		.html('<img src="images/loading.gif" height="15">')
		.load("ajax/numOfWordLib.php?"+Math.random(),'');
		
}

function loadWordshow(word,fn){
	
	fn = fn || function(){};
	if( $("#wordlist_main li").length>0 )
		$("#wordshow")
			.html('<img src="images/loading1.gif" align="absmiddle"> Loading...')
			.load("ajax/wordShow.php",'word='+word,fn);
	else
		$("#wordshow")
			.html('Please import words first!<br /><a href="help.php#h2" target="_blank">How to import words?</a>');
		
}

function loadWordlist(page,fn,noMark){ 
	
	noMark = noMark || 0;
	fn = fn || function(){};

	$("#wordlist")
		.html('<img src="images/loading1.gif" align="absmiddle"> Loading...')
		.load("ajax/wordList.php", 'cat='+cat+'&page='+page+'&nm='+noMark, fn);
				
}

function initWordshow(){
	
	$("#prev_word").unbind('click').click(function(){
		if($("#wordlist_main li").length > 0)
			if($("#wordlist_main li.lihover").is(":first-child")){
				if(parseInt($("#page").val()) <= 1)
					$.msgbox({
						content:"This is the first word!",
						closeAfter: 5
					});
				else
					loadWordlist(
						parseInt($('#page').val()) - 1,
						initWordlist, 1
					);					
			} else 
				liClick($("#wordlist_main li.lihover").prev());
	});
	
	$("#next_word").unbind('click').click(function(){
		if($("#wordlist_main li").length > 0)
			if($("#wordlist_main li.lihover").is(":last-child")){
				if(parseInt($("#page").val()) >= parseInt($("#total_page").val()))			
					$.msgbox({
						content:"This is the last word!",
						closeAfter: 5
					});
				else 
					loadWordlist(
						parseInt($('#page').val()) + 1,
						initWordlist, 1
					);					
			} else 
				liClick($("#wordlist_main li.lihover").next());
	});

	$(".dict_main_content a[href$=\#]")
		.click(function(){
			lookUpWord($(this).html());	
		});
		
	$("#report_questions").click(function(){
		$.msgbox({
			height:500, 
			width:500, 
			title:'Report errors',
			content: 'reportErrors.php?kw='+$(".word").html(),
			type:'iframe'
		});											  
	});
	
	$("#lookup_in_dict").click(function(){
		lookUpWord($(".word").html());									
	});
	
	$("#dlt_from_my").click(function(){
		if( confirm('Sure to remove this word from my word book? \n' +
				  	'If you\'ve recognized this word,\n' +
					'you may just rate it to 3 starts\n' +
					'as you set words have 3 stars hidden in word book.\n') ){
			$.get(
				"ajax/removeMyword.php",
				'kw='+$(".word").html(),
				function(){
					reloadNumOfMywords();
					removeLi($("#wordlist_main li.lihover"));
				}
			)
		}								 
	});
		
	$("#edit_my_word").toggle(
							  
		function(){       //editable
			
			$("#edit_my_word img").attr({"src":"images/edit1.gif","title":"Submit!"});
			
			$(".pronounce").html('<input id="wordpron" name="wordpron" value="'
								 	+ $('.pronounce')
								 		.html()
										.substring(1,$('.pronounce').html().length-1)
								 	+ '" class="inputbox1 pronounce" />'
								 );
			
			meaningss = $(".dict_main_content").eq(0).html();
			meanings = meaningss.split(/\<br\s?\/?\>/gi);
			mean_edit = '';
			
			for(var i=0; i<meanings.length-1; i++){
			
				mean_edit += meanings[i].replace(
				
					/\<span class=\"?red\"?\>(.*?)\.?\<\/span\>\s*(.*?)\;/i,
					'<div>' +
						'<input class="inputbox1" name="wordpos[]" value="$1" size=3 />' +
						'<input class="inputbox1" name="wordmean[]" value="$2" size=40 />' + 
					 	(i ? ' <input type=button class="inputbtn" name="dlt_wordmean" value=" - " />' : '') +
					 	(!i ? ' <input type=button class="inputbtn" id="add_wordmean" value=" + " />' : '') +
					'</div>\n'
					
				);
				
			}
			
			mean_edit += meanings[meanings.length-1].replace(/\<span class=\"?catagory\"?\>CATAGORY: (.*?)\<\/span\>\<span class=\"?tag\"?\>TAG: (.*?)\<\/span\>/i,
				'<span class="catagory">CATAGORY: ' +
					'<input class="inputbox1" id="wordtype" name="wordtype" value="$1" style="width:120px;" />' +
				'</span>' +
				'<span class="tag">TAG: Seperate by comma(,)' +
					'<input class="inputbox1" id="wordtag" name="wordtag" value="$2" size=25 />' +	
				'</span>');
			
			$(".dict_main_content").eq(0).html(mean_edit);
			
			wordmemo = $(".dict_main_content").eq(1).html();
			wordmemo = '<textarea class="textarea" id="wordmemo" name="wordmemo" rows=6 cols=80 >'
						+ wordmemo + '</textarea>';
			$(".dict_main_content").eq(1).html(wordmemo);
			
			wordder =  $(".dict_main_content").eq(2).html();
			wordder = '<textarea class="textarea" id="wordder" name="wordder" rows=6 cols=80 >'
						+ wordder + '</textarea>';
			$(".dict_main_content").eq(2).html(wordder);
			
			worden =  $(".dict_main_content").eq(3).html();
			worden = '<textarea class="textarea" id="worden" name="worden" rows=6 cols=80 >'
						+ worden + '</textarea>';
			$(".dict_main_content").eq(3).html(worden);
			
			wordexp =  $(".dict_main_content").eq(4).html();
			wordexp = '<textarea class="textarea" id="wordexp" name="wordexp" rows=6 cols=80 >'
						+ wordexp + '</textarea>';
			$(".dict_main_content").eq(4).html(wordexp);
			
			$("#wordpron").yinbiao();		
			$("#wordtype").ecombo(wordtypes);
			$("#wordtag").suggestTag("ajax/suggestTag.php");
			
			$("#add_wordmean").click(function(){
				$(this).parent().parent().children("div:last").after(
					'<div>' +
						'<input class="inputbox1" name="wordpos[]" value="" size=3 />' +
						'<input class="inputbox1" name="wordmean[]" value="" size=40 />' + 
					 	' <input type=button class="inputbtn" name="dlt_wordmean" value=" - " />' +
					'</div>\n'
				);			
				
			});
			
			$("input[name=dlt_wordmean]").live('click',function(){
				$(this).parent().remove();											 
			});
			
		},
		
		function(){   //submit edit
		
			$("#edit_my_word img")
				.attr("src","images/yes.gif")
				.fadeOut(1000)
				.fadeIn(1500);
				
			wordposs = [];
			wordmeans = [];
			str_wordpos = '';
			str_wordmean = '';
			
			$("input[name^=wordpos]").each(function(){
			
				wordposs.push($(this).val());
				
			});
			
			$("input[name^=wordmean]").each(function(){
			
				wordmeans.push($(this).val());
				
			});
			
			for(var i=0; i<wordposs.length; i++){
			
				if(wordposs[i] != '' && wordmeans[i] != ''){
				
					str_wordpos += wordposs[i]+';';
					str_wordmean += wordmeans[i]+';';
					
				}
				
			}
			
			$.post(
				"ajax/updateMyWord.php",
				{ 	word 		: $(".word").html(),
					wordpron 	: '['+$("#wordpron").val()+']',
					wordpos 	: str_wordpos,
					wordmean	: str_wordmean,
					wordexp		: $("#wordexp").val(),
					wordder		: $("#wordder").val(),
					worden		: $("#worden").val(),
					wordtag		: $("#wordtag").val(),
					wordtype	: $("#wordtype").val(),
					wordmemo	: $("#wordmemo").val() 
				},
				function(){
				
					loadWordshow(
						$(".word").html(),
						initWordshow
					);
					
				});
		}
		
	);
	
	var familiarity = $("#rateDiv").html();
	
	$("#rateDiv")      // ready for rating, wordshow
		.empty()
		.rate({
			  rated : familiarity,
			  ratePage : 'ajax/rateWord.php?word=' + $(".word").html(),
			  rateAfterEvent : function(r){
				  var $li = $("#wordlist_main li.lihover");
				  var $rateStar = $li.children("span")
									.children("a.star")
									.eq(r-1);
				  $rateStar       // make wordlist show the same rate
				  	.addClass("star_yes")
					.prevAll()
					.addClass("star_yes")
					.end()
					.nextAll()
					.removeClass("star_yes");
				  
				  if(r==3){ 
					  reloadNumOfRecited(); 
					  if(hide3Stars) removeLi($li); 
				  }
			  }
		});
}

function liClick($li){    // select word

	$li
		.prevAll()
		.removeClass("lihover")
		.end()
		.nextAll()
		.removeClass("lihover");
		
	$li.addClass("lihover");
	
	$("#this_word").val($li.children("input[type=hidden]").val());
	
	loadWordshow(
		$li.children("a").html(),
		initWordshow
	);
	
}

function removeLi($li){ 
  	
	if($li.children("input[type=hidden]").val() == $("#this_word").val()){
		if($li.is(":last-child")) 
			liClick($li.prev());
		else 
			liClick($li.next());
	}
	
	if($.trim($li.children("a").html()).toLowerCase() == $.trim($("#gotoMark").text().split(":")[1]).toLowerCase()){
		$("#markIt").click();    // if the recored removed is bookmark
	}
	
	$li.css("background-color","red").fadeOut();
						
}

function initWordlist(){ 
	
	$(".whichlist a img[src*=first]").click(function(){
		loadWordlist(1, initWordlist, 1);	
	});
	
	$(".whichlist a img[src*=previous]").click(function(){
		loadWordlist(
			parseInt($('#page').val()) - 1,
			initWordlist, 1
		);	
	});
	
	$(".whichlist a img[src*=next]").click(function(){
		loadWordlist(
			parseInt($('#page').val()) + 1,
			initWordlist, 1
		);	
	});
	
	$(".whichlist a img[src*=last]").click(function(){
		loadWordlist(
			parseInt($('#total_page').val()),
			initWordlist, 1
		);	
	});
	
	$(".this_page").blur(function(){ 
		if( /[0-9]+/.test($(this).val)
			&& $(this).val()*1 >= 1 
			&& $(this).val()*1 <= $('#total_page').val()*1 )
			//&& parseInt($(this).val()) != parseInt($("#page").val()) )  // refresh not allowed
			loadWordlist(
				$(this).val(),
				initWordlist, 1
			);		
	});
	
	$("#wordlist_main li").hover(
	
		function(){ $(this).addClass("lihover") },
		
		function(){ 
			if( $(this).children("input[type=hidden]").val() != $("#this_word").val() )
				$(this).removeClass("lihover");
		}

	);
	
	$("#wordlist_main li").click(function(){
		liClick( $(this) );	
	});
	
	var $select_li;
	
	$("#wordlist_main li").each(function(){
										 
		var wordid = $(this).children("input[type=hidden]").val();
		var word = $(this).children("a").html();
		
		if($("#this_word").val() == wordid) 
			$select_li = $(this);
			
		var familiarity = $(this).children("span").html();
		var $li = $(this);
		
		$li.children("span")
			.empty()
			.rate({   // wordlist
				  rated : familiarity,
				  ratePage : 'ajax/rateWord.php?word=' + word,
				  rateAfterEvent :	function(r){
					  
					  					if(r==3){											
											reloadNumOfRecited(); 
											if(hide3Stars) removeLi($li);
										}

										if(wordid == $("#this_word").val()) {
											loadWordshow( word, initWordshow );	
										}
										
									}
			});
	}); 
	
	if(!$select_li) $select_li = $("#wordlist_main li").eq(0);
	
	liClick($select_li);
	
	$("#markIt").click(function(){
		if( $(".td_mywords").text() > 0 ) {  //prevent initial mark(when one has no words in his book)
			pageOfMark = $("#page").val();
			$(this).next().next("a").html('<img src="images/loading.gif" height="15">').load(
				"ajax/markIt.php",
				"cat="+cat+"&mark="+$("#this_word").val()
			);
		}
	});
	
	$("#gotoMark").click(function(){
		loadWordlist( pageOfMark, initWordlist );						  
	});

};
