addEvent(window, "load", klinks);

var currKanji = false;
var currData = false;
var currEvent = false;
var currSpan =false;
var currMissed = false;

function klinks()
{
	if (!document.getElementsByTagName) return;
    spans = document.getElementsByTagName("span");
    for (ti=0;ti<spans.length;ti++) {
        thisSpan = spans[ti];
        if (((' '+thisSpan.className+' ').indexOf("klook") != -1) ) {
        
        	addEvent(thisSpan,'click',klookup);
        }
    }

}


function klookup(e)
{
	if (!e) var e = window.event;
	var span = (window.event) ? e.srcElement : e.target;
	var kchar = span.innerHTML;
	currEvent = e;
	
	tt_Hide(true);
	tip(span,'Loading kanji information ... ',true);
	sendAjax(kchar,span);

}

function sendAjax(thechar,thespan)
 {
 
	currSpan = thespan;
	//alert(escape(thechar));
  	var myAjax = new Ajax.Request(
		'index.php?page=quiz/klookup.php', 
		{
			method: 'get', 
			parameters: 'kanji='+thechar, 
			onComplete: processElements,
			onFailure: function() { alert('failure!'); }
		});
      
  }
  

  
  function getSingle(el,name)
  {	
 // 	alert('getting: '+name+' from '+el);
  	if( el.getElementsByTagName(name)[0] )
  		return el.getElementsByTagName(name)[0].firstChild.data; 
  	else
  		return false;
  }
  
  function processElements(xml)
  {
	if( xml.responseText == null )
	{
		tt_Hide(true);
		return;
	}

	jsonarr = jsonArr(xml);
//alert(xml.responseText);
	thespan = currSpan;
	if( jsonarr['definition'] )
	{

		kanji = jsonarr['kanji'];//getSingle(elem,'kanji');
	  //	alert('kanji: '+kanji);
		definition = jsonarr['definition'];//getSingle(elem,'definition');
		onstr = ( !jsonarr['on'] ) ? '' : "<div><u>On-yomi</u>: "+jsonarr['on']+"</div>";
		kunstr = ( !jsonarr['kun'] ) ? '' : "<div><u>Kun-yomi</u>: "+jsonarr['kun']+"</div>";
	
		nolocal = ( jsonarr['nolocal'] ) ? '<div style="font-size:10px">No vocab was found in these textbooks. These are from a dictionary.</div>' : '';
	
		tangos = jsonarr['tangos'];
		
		ffstr = "<div>"+jsonarr['firstfound']+"</div>";
		
		sod = ( jsonarr['sod'] ) ? "<br><div><u>Stroke order diagram</u><br>"+jsonarr['sod']+"<br><span class='little'>This stroke order diagram used under this <a href='http://www.kanjicafe.com/license.htm'>License</a></span></div>" : '';
		
		
	  
		inner = "<div class='innerborder' onclick='tt_Hide(true)'><div class='fright xbox lnk'>X</div><div class='fleft' style='border: 1px solid black; font-size: 36px; padding: 3px; margin: 3px'>"+kanji+"</div>"+
		"<div><u>Definition</u>: "+definition+"</div>"+onstr+kunstr+ffstr+"<div class='clear'><br><u>Vocab containing this kanji</u>:<div class='deflist'>"+nolocal+tangos+sod+"</div><div class='center' style='font-size:11px'>(click anywhere in box to close)</div></div>";
	}
	else
	{
		inner = "<div class='innerborder' onclick='tt_Hide(true)'><div class='fright xbox lnk'>X</div><div class='fleft' style='border: 1px solid black; font-size: 36px; padding: 3px; margin: 3px'>"+jsonarr['kanji']+"</div><div class='clear'>No information was found for this kanji!</div><div class='center' style='font-size:11px'>(click anywhere in box to close)</div></div>";
	
	}
	
   tt_Hide(true);
   tip(thespan,inner,true);
   return;

  }
  
  
  function loadCat(el)
  {
  	catid = el.value;
  	
  	//turn off old cat
  	inputs = Form.getInputs($('createsched'),'','category');
  	for( x = 0; x < inputs.length; x++ )
  	{
  		if( $('optbox_'+inputs[x].value) )
  			$('optbox_'+inputs[x].value).className = 'rhidden';
  		//if( inputs[x].checked )
  		//	return inputs[x].value;
  	}
  	if( $('optbox_'+catid) )
  		$('optbox_'+catid).className = 'left';
  	sendCOptions();
  }
  
  function formVal(fid,vname)
  {
  	return Form.getInputs($(fid),'',vname)[0].value;
  }
  
  function formRVal(fid,vname)
  {
  	inputs = Form.getInputs($(fid),'',vname);
  	for( x = 0; x < inputs.length; x++ )
  	{
  		if( inputs[x].checked )
  			return inputs[x].value;
  	}
  	return false;
  }
  

  function sendOptions()
  {
  	if( opt_ids.length == 0 )
  		return;
  	//send request
 
 	if( location.href.indexOf('custom_create') != -1 ) //special case, redirect
 	{
 		sendCOptions();
 		return;
 	}
 
  	
  	 args = ['category_id='+document.getElementById('category_id').value];
    for(i = 0; i < opt_ids.length; i++ )
    {
    	//alert(opt_ids[i]+"|"+document.getElementById(opt_ids[i]));
    	if( document.getElementById(opt_ids[i]).value == '' )
   		{
   			$('lessonblock').innerHTML = '';
   			$('optionsblock').innerHTML = '';
   			$('oinstruct').className = 'shown';
   			$('hajimeru').className = 'rhidden';
    		return;
    	}
    	args[args.length] = opt_ids[i]+"="+document.getElementById(opt_ids[i]).value;
    }
    $('loadlesson').className = '';
    $('lessonblock').innerHTML = '';
   	//$('optionsblock').innerHTML = '';
   			
    var myAjax = new Ajax.Request(
			'index.php?page=quiz/olookup', 
			{
				method: 'get', 
				parameters: args.join('&'), 
				onComplete: processOptions,
				onFailure: function() { alert('failure!'); }
			});
  		//alert('my ajax, yay');
  }
  
  function jsonArr(response)
  {
  	firstPos = response.responseText.indexOf('{');
	if( firstPos != 0 )
	{
		res = response.responseText.substr(firstPos);
	}
	else
		res = response.responseText;
	//alert('about to parse');
  	return JSON.parse(res);
  }
  
  function processOptions(response)
  {
  	//	alert('process');
  	
  		if( $('loadlesson') )
  			$('loadlesson').className = 'rhidden';
  		if( opt_ids.length == 0 )
  			return;
  		
  		//alert('pOptions');
  	//	$('subfooterl').innerHTML = window.location.href;
		
  		jsonarr = jsonArr(response);
  		//alert('got jsonarr');
  		//return;
  		if( jsonarr['error'] )
  			alert('bad lessons!');
  		else
  		{	
  			//this sets up the actual lesson block;
  			$('lessonblock').innerHTML = jsonarr['olessons'];	

  			//now, we have to insert the lessons
  			olessonblock = jsonarr['olessonarr'].split("\n");

  			olessonbox = $('lessonbox');
  			


			if( olessonbox.hasChildNodes() )
				olessonbox = olessonbox.firstChild;
				
			base = false;
  			
  			for( i = 0; i < olessonblock.length; i++)
  			{
  				if( base == false )
  					base = document.createElement('tr');
  					
  				vals = olessonblock[i].split("|"); //lid, title, numkanji, if fourth, then custom
  				custom = vals.length == 4;

  					
  				firsttd = document.createElement('td');
  				checkbx = document.createElement('input');
  				checkbx.type = 'checkbox';
  				checkbx.name = 'lesson_'+vals[0];
  				checkbx.id = 'lesson_'+vals[0];
  				firsttd.appendChild(checkbx);
  				base.appendChild(firsttd);
  				sectd = document.createElement('td');
  				ael = document.createElement('a');
  				ael.href = "index.php?page=quiz/kanji_list&setid="+vals[0];
  				ael.innerHTML = vals[1];
  				breaker = document.createElement('br');
  				spanner = document.createElement('span');
  				spanner.className = 'little';
  				spanner.innerHTML = "("+vals[2]+" words)";
  				sectd.appendChild(ael);
  				sectd.appendChild(breaker);
  				sectd.appendChild(spanner);
  				base.appendChild(sectd);


  				if( !custom || vals[3] == 4 )
				{

					olessonbox.appendChild(base);

					base = false;

				}

  			}

  			
  			if( base != false )
  				olessonbox.appendChild(base);

  		}


  		if( jsonarr['options'] )
  		{
			$('oinstruct').className = 'rhidden';
  			$('optionsblock').innerHTML = jsonarr['options'];
  			
  			$('hajimeru').className = 'shown';
  		}
  		//alert(location.href);
  		if( location.href.indexOf('custom_create') != -1 ) 
  		{
  			//array('yay');
  			//alert(lessonSet);
  			for( x = 0; x < lessonSet.length; x++ )
  			{
  				
  				if( $('lesson_'+lessonSet[x]) )
  					$('lesson_'+lessonSet[x]).checked = 'checked';
  			
  			}
  			lessonSet = [];
  		}

  }
  



function make_visible() {
	document.getElementById('ans').className = 'displayed';
	document.getElementById('ans_text').className = 'displayed';
	document.getElementById('linker').className = 'rhidden';
	document.getElementById('linker').blur();
	for(x=0; x < 5; x++)
		if(document.getElementById('radio'+x))
			document.getElementById('radio'+x).className = 'rdisplayed';
}

function highlight(index,id)
{
	document.getElementById(index+'_'+id).className = 'highlight';
	//alert(k+'_'+document.getElementsByName(csel)[0].value);
	//document.getElementById(cid).className = '';
	sel = document.getElementById(index+'_selected');
	if( sel.value != '' && sel.value != id )
		document.getElementById(index+'_'+sel.value).className = '';
	sel.value = id;
}

function build(index)
{
	oh = document.getElementById(index+'_ohira').value;
	ok = document.getElementsByName(index+'_kanji')[0].value;
	hlen = oh.length;
	kbuild = hbuild = pbuild = '';
	if( ok.length > 0 )
	{
		for( x= ok.length-1; x >= 0; x-- )
		{
			//alert(ok.substr(x-1,x));
			if( ok.substr(x,1) == oh.substr(hlen-1,1) ) //back end of hira
			{
				//kbuild = kbuild + ok.substr(x-1,x);
				pbuild = oh.substr(hlen-1,1) + pbuild;
				hlen--;
			}
			else
				break;
		}
		
		kbuild = ok.substr(0,x+1);
		hbuild = oh.substr(0,hlen);
		document.getElementsByName(index+'_kanji')[0].value = kbuild;
		document.getElementsByName(index+'_hira')[0].value = hbuild;
		document.getElementsByName(index+'_post')[0].value = pbuild;
		//alert('kbuild: ['+kbuild+'] hbuild: ['+hbuild+'] pbuild: ['+pbuild+']');
	}
	else
		document.getElementsByName(index+'_hira')[0].value = oh;
}

function loadcorrect(el)
{
	document.getElementById('correction').className = 'rdisplayed'; 
	el.className = 'rhidden';
	self.location.href='#correct';
}


function addEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
// By Scott Andrew
{
  if (elm.addEventListener){
    elm.addEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.attachEvent){
    var r = elm.attachEvent("on"+evType, fn);
    return r;
  } 
} 

function removeEvent(elm,evType,fn,useCapture)
{
	if (elm.removeEventListener){
    elm.removeEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.detachEvent){
    var r = elm.detachEvent("on"+evType, fn);
    return r;
  }

}

/* This notice must be untouched at all times.

wz_tooltip.js    v. 3.25

The latest version is available at
http://www.walterzorn.com
or http://www.devira.com
or http://www.walterzorn.de

Copyright (c) 2002-2003 Walter Zorn. All rights reserved.
Created 1. 12. 2002 by Walter Zorn (Web: http://www.walterzorn.com )
Last modified: 21. 4. 2004

Cross-browser tooltips working even in Opera 5 and 6,
as well as in NN 4, Gecko-Browsers, IE4+, Opera 7 and Konqueror.
No onmouseouts required.
Appearance of tooltips can be individually configured
via commands within the onmouseovers.

This program is free software;
you can redistribute it and/or modify it under the terms of the
GNU General Public License as published by the Free Software Foundation;
either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License
at http://www.gnu.org/copyleft/gpl.html for more details.
*/

///////// DON'T CHANGE ANYTHING BELOW THIS LINE /////////////////////
var tt_obj,
tt_objW = 0, tt_objH = 0,  // width and height of tt_obj
tt_objX = 0, tt_objY = 0,
tt_offX = 0, tt_offY = 0,
xlim = 0, ylim = 0,        // right and bottom borders of visible client area
tt_above = false,          // true if T_ABOVE cmd
tt_wait = false,
tt_vis = false,            // tooltip visibility flag
tt_dwn = false,            // true while tooltip below mousepointer
tt_u = 'undefined',
tt_sticky = false;
mouse_x = mouse_y = 0;
var par_x = false, par_y = false, par_w = false, par_h = false;

var tt_db = (document.compatMode && document.compatMode != 'BackCompat')? document.documentElement : document.body? document.body : null,
tt_n = navigator.userAgent.toLowerCase();

// Browser flags
var tt_op = !!(window.opera && document.getElementById),
tt_op6 = tt_op && !document.defaultView,
tt_ie = tt_n.indexOf('msie') != -1 && document.all && tt_db && !tt_op,
tt_n4 = (document.layers && typeof document.classes != "undefined"),
tt_n6 = (!tt_op && document.defaultView && typeof document.defaultView.getComputedStyle != "undefined"),
tt_w3c = !tt_ie && !tt_n6 && !tt_op && document.getElementById;

tt_n = '';

var tempStage = true;


function tt_Int(t_x)
{
	var t_y;
	return isNaN(t_y = parseInt(t_x))? 0 : t_y;
}

function tt_EvX(t_e)
{
	var t_y = tt_Int(t_e.pageX || t_e.clientX || 0) +
		tt_Int(tt_ie? tt_db.scrollLeft : 0) +
		tt_offX;
	if (t_y > xlim) t_y = xlim;
	var t_scr = tt_Int(window.pageXOffset || (tt_db? tt_db.scrollLeft : 0) || 0);
	if (t_y < t_scr) t_y = t_scr;
	return t_y;
}


function tt_EvY(t_e)
{
	var t_y = tt_Int(t_e.pageY || t_e.clientY || 0) +
		tt_Int(tt_ie? tt_db.scrollTop : 0);
	if (tt_above) 
	{
		//debug('case 1');
		t_y -= (tt_objH + tt_offY - (tt_op? 31 : 15));
	}
	else if (t_y > ylim || !tt_dwn && t_y > ylim-24)
	{
		//debug('case 2');
		t_y -= (tt_objH + 25);
		tt_dwn = false;
	}
	else
	{
		//debug('case 3');
		t_y += tt_offY;
		tt_dwn = true;
	}
	return t_y;
}


function tt_ReleasMov()
{
	if (document.onmousemove == tt_Move)
	{
		if (document.releaseEvents) document.releaseEvents(Event.MOUSEMOVE);
		document.onmousemove = null;
	}
}

function tt_GetDivW(el)
{
	if ( el )
		return (
			el.style.pixelWidth? el.style.pixelWidth
			: el.offsetWidth
		);
	else
		return (
			tt_obj.style.pixelWidth? tt_obj.style.pixelWidth
			: tt_obj.offsetWidth
		);
}


function tt_GetDivH(el)
{
	if ( el )
		return (
			el.style.pixelHeight? el.style.pixelHeight
			: el.offsetHeight
		);
	else
		return (
			tt_obj.style.pixelHeight? tt_obj.style.pixelHeight
			: tt_obj.offsetHeight
		);
}


function tt_SetDivPos(t_x, t_y)
{
	var t_i = tt_obj.style || tt_obj;
	var t_px = (tt_op6 || tt_n4)? '' : 'px';
	t_i.left = (tt_objX = t_x) + t_px;
	t_i.top = (tt_objY = t_y) + t_px;
}


function tt_ShowDiv(t_x)
{
	if (tt_n4) tt_obj.visibility = t_x? 'show' : 'hide';
	else tt_obj.style.visibility = t_x? 'visible' : 'hidden';
	tt_vis = t_x;
}


function tip(el,txt,sticky)
{
	if( !tt_obj || !tt_sticky || ( tt_sticky && sticky ) )
	{
		var tipobj=document.all? document.all["ttip"] : document.getElementById? document.getElementById("ttip") : "";
		tipobj.style.width = '';
		tt_sticky = ( sticky == true ) ? true : false;
		tipobj.innerHTML = txt;
		el.onmouseout = omo;
		tt_Show(txt,tipobj,el);
	}
}


function omo(e)
{
	if (!e) var e = window.event;
	var tg = (window.event) ? e.srcElement : e.target;
//	alert('this is the source: '+tg);
	if (tg != curr_el) 
	{
	//	alert('source-target inner: '+tg.innerHTML);
	//	alert("moving from self to self"+ tg.toString());
		//return;
	}
	var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
	//alert('this is source '+tg+' and where I started: '+reltg);
	//on tables, when you move off of a td cell, it goes to the table elemnt (of which the row is inside)
	if( reltg )
	{	
		while (reltg != curr_el && reltg.nodeName != 'BODY')
		{
			//alert("moving from self to inner node");
			//alert('to element '+reltg.innerHTML);
			reltg= reltg.parentNode
		}
	//	alert('this is the highest I got: '+reltg);
		if (reltg == curr_el) return;
		// Mouseout took place when mouse actually left layer
		// Handle event
	}
	tt_Hide();
}

curr_el = false;
function tt_Show(t_e, t_obj,el)
{
	curr_el = el;
	if (tt_obj) tt_Hide();
	var t_mf = document.onmousemove || null;
	if (window.dd && (window.DRAG && t_mf == DRAG || window.RESIZE && t_mf == RESIZE)) return;
	var t_uf = document.onmouseup || null;
	if (t_mf && t_uf) t_uf(t_e);

	par_h = tt_GetDivH(el);
	par_w = tt_GetDivW(el);
	thepos = getPosition(el);
	par_top = thepos[1];
	par_left = thepos[0];
	
	tt_obj = t_obj;
	if (tt_obj)
	{
		tt_dwn = !(tt_above = false);
		tt_objW = tt_GetDivW();
		if( tt_objW > 600 )
		{
			newwidth = '600px';
		}
		else
		{
			newwidth = parseInt(tt_objW)+'px';
		}


		if( tt_ie )
			tt_obj.style.width = newwidth;

		tt_objH = tt_GetDivH();
		tt_offX = 8;
		tt_offY = 19;
		if (tt_op) tt_offY += 21;



		xlim = tt_Int((tt_db && tt_db.clientWidth)? tt_db.clientWidth : window.innerWidth) +
			tt_Int(window.pageXOffset || (tt_db? tt_db.scrollLeft : 0) || 0) -
			tt_objW -
			(tt_n4? 21 : 0) - 30;
		ylim = tt_Int(window.innerHeight || tt_db.clientHeight) +
			tt_Int(window.pageYOffset || (tt_db? tt_db.scrollTop : 0) || 0) -
			tt_objH - tt_offY;

		t_e = window.event || t_e;
		
		if( tt_sticky )
		{
			xlim = tt_Int((tt_db && tt_db.clientWidth)? tt_db.clientWidth : window.innerWidth) -
			
			(tt_n4? 21 : 0) - 30;
		ylim = tt_Int(window.innerHeight || tt_db.clientHeight)  -
			 tt_offY;
		
			xoffset = tt_Int(window.pageXOffset || (tt_db? tt_db.scrollLeft : 0) || 0);
			yoffset = tt_Int(window.pageYOffset || (tt_db? tt_db.scrollTop : 0) || 0);
			dbox = $('debugbox');
			if( typeof dbox != 'undefined' ) 
			{
			//	dbox.innerHTML = xlim+"|"+xoffset+"|"+tt_GetDivW();
			}
			xpos = xoffset + (xlim - tt_GetDivW())/2;
			ypos = yoffset + (ylim - tt_objH)/2;
		//alert();
			////xpos = ( mouse_x + 15 + tt_objW < xlim ) ? mouse_x+15 : mouse_x - tt_objW-15;
			//ypos = ( mouse_y + 15+ tt_objH < ylim ) ? mouse_y+15 : mouse_y - tt_objH-15;
			tt_SetDivPos(xpos, ypos);
			tt_ShowDiv(true);
		}
		else
		{
			//debug('not sticky');
			tt_SetDivPos(tt_EvX(t_e), tt_EvY(t_e));
			tempStage = true;

		}
		//debug('left: '+tt_obj.style.left+", top: "+tt_obj.style.top);
		
		//tt_ShowDiv(true);


		if (document.captureEvents) document.captureEvents(Event.MOUSEMOVE);
		document.onmousemove = tt_Move;
	}

}

function getPosition(theElement) 
{ 
 var positionX = 0; 
 var positionY = 0; 

 while (theElement != null) 
 { 
	//alert('adding for '+theElement);
   positionX += theElement.offsetLeft; 
   positionY += theElement.offsetTop; 
   theElement = theElement.offsetParent; 
 } 

 return [positionX, positionY]; 
}

function debug(aMsg) {
   setTimeout(function() { throw new Error("[debug] " + aMsg); }, 0);
} 

function grabCoords(ev)
{
	mouse_x = (tt_ie) ? event.clientX + document.body.scrollLeft : ev.pageX;
	mouse_y = (tt_ie) ? event.clientY + document.body.scrollTop : ev.pageY;
}

function tt_Move(t_ev)
{
	if (!tt_obj || tt_sticky ) return;
	var t_e = t_ev || window.event;

	xpos = tt_EvX(t_e);
	ypos = tt_EvY(t_e);
	if( xpos < par_left || xpos > par_left+par_w || ypos < par_top-20 || ypos > par_top+par_h+20 )
	{
		tt_Hide(true);
		//alert('out of bounds xpos '+xpos+' par_left '+par_left+' par_w '+par_w+' ypos '+ypos+' par_top '+par_top+' par_h '+par_h);
		return;
	}

	tt_SetDivPos(xpos,ypos);
	if( tempStage )
	{
		tt_ShowDiv(true);
		tempStage = false;
	}
}


function tt_Hide(force)
{
//	alert('tt_hide');

	curr_el = false;
	if (window.tt_obj)
	{
		if (window.tt_rdl) window.clearTimeout(tt_rdl);
		if( !tt_sticky || tt_sticky && force == true)
		{
			tt_ShowDiv(false);
			tt_SetDivPos(-tt_objW, -tt_objH);
			tt_obj = null;
			if (typeof window.tt_upFunc != tt_u) document.onmouseup = window.tt_upFunc;

			tt_ReleasMov();
		}
	}
}

/*
 * Kills an event's propagation and default action
 */
function knackerEvent(eventObject) {
    if (eventObject && eventObject.stopPropagation) {
        eventObject.stopPropagation();
    }
    if (window.event && window.event.cancelBubble ) {
        window.event.cancelBubble = true;
    }
    
    if (eventObject && eventObject.preventDefault) {
        eventObject.preventDefault();
    }
    if (window.event) {
        window.event.returnValue = false;
    }
}

document.onmousemove = tt_Move;
document.onmousedown = grabCoords;