/***************************************
Copyright (c) 2008, Jeffrey Davis
all rights reserved.
***************************************/
//var requestURI="./simulate.php";
var requestURI="/WordRakeWS/WordRake";
//var requestURI="/WordRakeWS/WordRake.php";

window.onload=function(){loadRake();};

var wr=null;


/** need the separtion so the call doesn't get munged by the loss of scope thru the event model **/
function rake(){
$('step1action').hide();
if(WordRake.results!=null)
	WordRake.results=null;
$('approveall').checked=false;

wr.rakeDoc($('diagrake'));
}


var WordRake = function() {};
WordRake.prototype = {
		defaults: {requestURI: "localhost"},
		wrInput:null,
		results:null,
		rakeDoc: function(inputElement) {
	//		throw("WordRake.rakeDoc: WordRake object supplied has no rakeDoc(inputString) method");
			this.wrInput=inputElement;
			this.notifyEngine();
				
		},
		rakeStarting:function(){
			throw("WordRake.rakeStarting: WordRake object supplied has no rakeStarting() function");
		},
		rakeComplete:function(){
			throw("WordRake.rakeComplete: WordRake object supplied has no rakeComplete() function");
		},
		setInputElement:function(inputElement){
			this.wrInput=inputElement;
		},
		notifyEngine:function(){
			this.cleanseUserInput(this.wrInput.value);
			wrthis=this;
			wrthis.rakeStarting();
			new Ajax.Request(requestURI,{
			method:'POST',
			parameters: this.wrInput.serialize(true),
			onSuccess:function(transport){wrthis.results = transport.responseText.evalJSON();wrthis.rakeComplete();},
		//	onSuccess:wrthis.rakedResults,
			onFailure:function(){alert("WordRake is currently disabled as we conduct a private beta test.  We apologize for the disappointment");}
			});

		},
		cleanseUserInput:function(strToCleanse)
		{
		var encodedString = '';
		var regLength = strToCleanse.length;
		for (i = 0; i < regLength; i++)
		{
			var curChar = (strToCleanse.charAt(i));
			if (curChar == 'Ò'){ curChar = '"'; }
			if (curChar == 'Ó'){ curChar = '"'; }
			if (curChar == '<'){curChar = '&lt;'; }
			if (curChar == '>'){curChar = '&gt;'; }
			if(strToCleanse.charCodeAt(i)>128){curChar=" ";}
			if(strToCleanse.charCodeAt(i)==12 || strToCleanse.charCodeAt(i)==13){curChar="\x10";}
			encodedString += curChar;
		}
		this.wrInput.value= encodedString;
		},

		fireFailure:function(){
			throw("WordRake.fireFailure:  WordRake object supplied has no fireFailure() method")
		},		
		getResults:function(){
		return this.results;
		}
		
}

DiagRake=function(){}
DiagRake.prototype=new WordRake();
DiagRake.prototype.rakeStarting=rakeStart;//(){return;}
DiagRake.prototype.fireFalilure=function(){return;}
DiagRake.prototype.rakeComplete=gotoStep2;

function rakeStart(){
$('step1action').hide();
$('diagrake').hide();
$('cancel').show();
$('approve').show();
$('checkcontainer').show();
}


function gotoStep2(){
res=wr.getResults();
$('diag_results').appear();
addDiffs();


}

function step2Action(){

}

function addDiffs()
{
	var results=wr.getResults();
	for(var i=0;i<= results.CHANGE.length;i++)
	{
		var res=results.CHANGE[i].BEFORE;		
		if(results.CHANGE[i].HASCHANGE)
		{			
			before=unesc(" ")+unesc(results.CHANGE[i].BEFORE);
			after=unesc(" ")+unesc(results.CHANGE[i].AFTER);
			addText=diffString(before,after );
			addText=addText.replace(/<\/del><del>/g,"");
			addText=addText.replace(/<\/ins><ins>/g,"");
			addText=addText.replace(/<del>/g,"<del class='deletion' >");
			if(!addText.match('%RESULT%'))
				addText=addText.replace(/<ins>/g,"<ins class='insertion''>");
			else
				addText=addText.replace(/<ins>/g,"<ins sid='"+i+"'class='question'>");			
		}else{
		  addText=results.CHANGE[i].BEFORE;
		}
		entry=document.createElement("span");
 		   addText=addText.replace('%RESULT%',"<span class='prompt'>"+results.CHANGE[i].QUERY+"</span>");	
		addText=addText.replace(/  /g,' ');
		entry.innerHTML=addText;
		$('diag_data').appendChild(entry);
	}
	var questions=$$('.question');
	for(var i=0;i<questions.length;i++)
	{
		questions[i].observe('click',question);
	}
	$$('.insertion').each(function(s){s.observe('click',markupSelected)});
	$$('.deletion').each(function(s){s.observe('click',markupSelected)});

	
}

undoctr=0;
undoQueue=new Array();

function markupSelected(e){

if(e.target)
	e=e.target;
a=e.parentNode;
undoctr++;
e.writeAttribute('undoNode',value=undoctr);
 offset=e.cumulativeOffset();
new Effect.Move(e, { x: 0, y: -210, mode: 'absolute',duration:0.2 });
new Effect.Fade(e,{queue:'end',duration:0.1});
if(undoctr>0)
	$('undo').show();
}

function undoLast(e){

allElements =$('diag_data').descendants();
for(i=0;i<allElements.length;i++)
{
		if(allElements[i].getAttribute("undoNode")==undoctr){
		allElements[i].show();
		new Effect.Move(allElements[i], {x: 0, y:0, mode: 'absolute',duration:0.1} );
		allElements[i].removeAttribute('undoNode');
		
	}


}
	undoctr--;
if(e.stop)
e.stop();
}

function question(e){
	evt =e || window.event;
//	target=e.target;
	var showingFlag=false;
	var evtTarget=evt.target || evt.srcElement;
	checknode=evtTarget;
//** here is how we move up the dom tree looking for our lost parent ***/	
	while(checknode.className!='question')
	{
			checknode=checknode.parentNode; //|| checknode.parentELement;
	}		
	checknode.descendants().each(function(s){
		if(s.tagName=="BUTTON"){
			showingFlag=true;
		}
		});
	tname=evtTarget.tagName.toLowerCase();
	if(tname!="button" && tname!="input" && !showingFlag)
	{
	//target=target.parentNode;
	tempElement=new Element("span");
	tempInput= new Element("input");
	tempOk=new Element("button"); //.observe("click",inplaceOK);
	tempOk.innerHTML="Ok";
	tempElement.appendChild(tempInput);
	tempElement.appendChild(tempOk);
	checknode.appendChild(tempElement);
	}
	if(tname=="button"){
		var din=evtTarget.parentNode.getElementsByTagName("input",evtTarget.parentNode)[0];
		sv=din.parentNode;
		if(din.value=="")
			din.value="_____";
		din.parentNode.parentNode.update(din.value);
	//	din.parentNode.parentNode.remove;
			
	}
		e.stop();
}







/** highlight the text on mouseover.  This is done so we can use <a> tags
without that pesky href='#' which would cause a reload.  This also allows
us to use the div wrapper as the event target.
@todo move color off to global variable, so it can be set in one spot.
***/
function hightlight(e){
	if (!e) var e = window.event;
	var tg = (window.event) ? e.srcElement : e.target;
	tg.style.color="#279500";
}
/** lowlight the text on mouseout.  This is done so we can use <a> tags
without that pesky href='#' which would cause a reload.  This also allows
us to use the div wrapper as the event target.
@todo move color off to global variable, so it can be set in one spot.
***/
function lowlight(e){
	if (!e) var e = window.event;
	var tg = (window.event) ? e.srcElement : e.target;
	tg.style.color="#4C4D4D";
}
/**
update the text box when a user selects a new author.
**/
//function authorChanged(e){
//	if (!e) var e = window.event;
//	var tg = (window.event) ? e.srcElement : e.target;
//	$('diagrake').value=speeches[tg.selectedIndex].text;
//}
function authorChanged(e){
var evtTarget=e.target || e.srcElement;
	var it=evtTarget.getAttribute("speech");
	$('diagrake').value=speeches[it].text;
}

/** Temp storage for input box data **/
var rakeInputData=null;

/**
	function to clear out all of the values in the input box. 
**/
function clearRakeBox()
{
//	$('step3').blindUp();
//	$('step1').appear();
	$('diagrake').value="";
	
}

/**
switch back to the original text area, hide the results.
**/
function cancelResults()
{
	$('cancel').hide();
	$('approve').hide();
	$('checkcontainer').hide();
//	$('step3').blindUp();
	$('step1action').appear();
	$('diag_results').fade({duration:0.2});
//	$('diagrake').value="";
 if ( $('diag_data').hasChildNodes() )
{
    while ( $('diag_data').childNodes.length >= 1 )
    {
        $('diag_data').removeChild( $('diag_data').firstChild );       
    } 
}
 $('diagrake').show();
   	
}
/**
switch back to the original text area, hide the results.
**/
function approveResults()
{
results=wr.getResults();
	$('cancel').hide();
	$('approve').hide();
	$('step1action').show();
	$('checkcontainer').hide();
	
	 var re=new RegExp("<.+>","g");
	 //var re=new RegExp(<(.|\n)*?>);
//	$$('.question').each(function(s,index){var resno=s.getAttribute('sid');if(s.firstDescendant().innerHTML==results.CHANGE[resno].QUERY){s.firstDescendant().innerHTML="________";}  });
	$$('.prompt').each(function(s,index){s.update('_________');});
	allElements=$('diag_data').descendants();
	allElements.each(function(s, index) {
			if(s.style.display=="none"){s.remove(); } 
		});
	
	allElements=$('diag_data').childElements();
	//console.log("----->"+$('diag_data').recursivelyCollect('innerHTML'));
	returnString="";
	//.replace(re,"")
	allElements.each(function(s, index){
		str=s.innerHTML.replace(/<(?!\s*p\s*|\w>|\s*\/\s*p\s*>)[^>]+>/gi, "");
		str=str.replace(/<\s*p[^>]+>/gi, "");
	returnString+=str;}
	);
	$('diagrake').value=returnString;
	if ( $('diag_data').hasChildNodes() )
	{
	    while ( $('diag_data').childNodes.length >= 1 )
	    {
	        $('diag_data').removeChild( $('diag_data').firstChild );       
	    } 
	}
	new Effect.Fade('diag_results');
$('diagrake').show();
	}
	

/** Handle html Entities if putting results in an html block
Don't handle them if putting them in a textbox.
**/

function unesc(s) {
    var n = s;
    n = n.replace(/&lt;/g, "<");
    n = n.replace(/&gt;/g, ";");
   n = n.replace(/&quot;/g, "\"");
    n = n.replace(/&apos;/g, "'");
    n = n.replace(/&amp;/g, "&;");

     return n;
}


function underlineQuestions(ques){
return ques;
}

function updateBio(e){
//console.log(e.target);
var evtTarget=e.target || e.srcElement;
var it=evtTarget.getAttribute("speech");
$('bio').update(speeches[it].bio);
}

function approveAll(e){
var evtTarget=e.target || e.srcElement;
if(evtTarget.checked==true)
	$$('.deletion').each(function (s){markupSelected(s);});
else
$$('.deletion').each(function (s){undoLast(s);});

}

function punchDownHelp(){
$('help').style.fontWeight="bolder";
$('help').style.color="#09A100";
}

function unpunchHelp(){
$('help').style.fontWeight="normal";
$('help').style.color="#3CB538";
}
function help(){prompt('if we had a help file, this would be a good time to show it');}

function punchDownPrint(){
$('print').style.fontWeight="bolder";
$('print').style.color="#09A100";
}

function unpunchPrint(){
$('print').style.fontWeight="normal";
$('print').style.color="#3CB538";

}
function wprint(){
$('diagrake').setAttribute('rows',($('diagrake').value.length/100)+2);
window.print();
$('diagrake').setAttribute('rows',15);
}

function punchDownUndo(){
$('undo').style.fontWeight="bolder";
$('undo').style.color="#09A100";
}

function unpunchUndo(){
$('undo').style.fontWeight="normal";
$('undo').style.color="#3CB538";

}



function loadRake(){
 	wr=new DiagRake();
	wr.defaults.requestURI="./simulate.php";
	wr.setInputElement($('diagrake'));
	// Create new options tags based on the speeches
	for(var i=0;i<speeches.length;i++)
	{	
		var li=new Element('li');			
		var author=new Element("span",{'speech': i}).update(speeches[i].author).observe('mouseover',updateBio).observe('click',authorChanged);
		li.appendChild(author);
		$('authorlist').insert(li,{position: top});
	}
	var bioli=new Element('li');
	var bio=new Element("div");
	bio.id='bio';
	bioli.insert(bio);
	$('authorlist').insert(bioli);
	// Set the initial value of the input box.
	$('diagrake').value=speeches[0].text;
	/**
	 Register all of the event handlers... nice.
	 Use prototype registration where we can, traditional where we have to.
	**/
	$('step1action').onmouseover=hightlight;
	$('step1action').onmouseout=lowlight;
	$('step1action').observe("click",rake);
	$('undo').observe("click",undoLast);
	$('cancel').onmouseover=hightlight;
	$('cancel').onmouseout=lowlight;
	$('cancel').observe("click",cancelResults);
	$('approve').observe("click",approveResults);
	$('approve').onmouseover=hightlight;
	$('approve').onmouseout=lowlight;
	$('approveall').observe("click",approveAll);
	$('help').observe("click",help);
	$('help').observe("mousedown",punchDownHelp);
	$('help').observe("mouseup",unpunchHelp);
	$('print').observe("click",wprint);
	$('print').observe("mousedown",punchDownPrint);
	$('print').observe("mouseup",unpunchPrint);
	$('undo').observe("mousedown",punchDownUndo);
	$('undo').observe("mouseup",unpunchUndo);

}





