var http_request, puzzid, puzztimeout=30;
var PuzzCAPTCHA_initialized = false;

if (!Array.prototype.indexOf){
	Array.prototype.indexOf = function(elt /*, from*/){
		var len = this.length;
		var from = Number(arguments[1]) || 0;
		from = (from < 0) ? Math.ceil(from) : Math.floor(from);
		if(from < 0){
			from += len;
		}
		for(; from < len; from++){
			if(from in this && this[from] === elt){
				return from;
			}
		}
		return -1;
	}
}

function URLencode(sStr) {
	return escape(sStr).replace(/\+/g, '%2B').replace(/\"/g,'%22').replace(/\'/g, '%27').replace(/\&/g, '%26');
}

function applyEvent(theObj, theEvent, theFunction){
	if(window.addEventListener){ // Mozilla, Netscape, Firefox
		theObj.addEventListener(theEvent, theFunction, false);
	}else{ // IE
		theObj.attachEvent('on' + theEvent, theFunction);
	}
}

function removeEvent(theObj, theEvent, theFunction){
	if(window.addEventListener){ // Mozilla, Netscape, Firefox
		theObj.removeEventListener(theEvent, theFunction, false);
	}else{ // IE
		theObj.detachEvent('on' + theEvent, theFunction);
	}
}

function makeRequest(url) {
	if (window.XMLHttpRequest) { // Mozilla, Safari, etc.
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {
			}
		}
	}
	if (!http_request) {
		return false;
	}
	http_request.onreadystatechange = function(){handleResponse()};
	http_request.open('GET', url, true);
	http_request.send(null);
	return true;
}

function handleResponse(){
	if(http_request.readyState == 4){

		var xmldoc = http_request.responseXML;
		var ret = xmldoc.getElementsByTagName('puzzcaptcha').item(0);
		var errNum = ret.getElementsByTagName('errNum').item(0).firstChild.data;
		var errDesc = ret.getElementsByTagName('errDesc').item(0).firstChild.data;
		var pre_approved = ret.getElementsByTagName('pre_approved').item(0).firstChild.data;
		puzzid = ret.getElementsByTagName('puzzid').item(0).firstChild.data;
		var tlimit = ret.getElementsByTagName('tlimit').item(0).firstChild.data;
		var passed = ret.getElementsByTagName('passed').item(0).firstChild.data;
		var answer = ret.getElementsByTagName('answer').item(0).firstChild.data;
		msgblock = document.getElementById("capinstr");

		if(passed != "true"){
			puzzCAPTCH_reset();
			//insert the 4 image bits
			pdrop0 = document.getElementById("puzzdrop0");
			img0 = document.createElement("img");
			img0.setAttribute("id", "cpuzza");
			img0.setAttribute("src", "/wordpress/wp-content/plugins/puzzcaptcha/puzzbits/" + puzzid + "a.png");
			img0.className = "puzzimg";
			pdrop0.appendChild(img0);

			pdrop1 = document.getElementById("puzzdrop1");
			img1 = document.createElement("img");
			img1.setAttribute("id", "cpuzzb");
			img1.setAttribute("src", "/wordpress/wp-content/plugins/puzzcaptcha/puzzbits/" + puzzid + "b.png");
			img1.className = "puzzimg";
			pdrop1.appendChild(img1);

			pdrop2 = document.getElementById("puzzdrop2");
			img2 = document.createElement("img");
			img2.setAttribute("id", "cpuzzc");
			img2.setAttribute("src", "/wordpress/wp-content/plugins/puzzcaptcha/puzzbits/" + puzzid + "c.png");
			img2.className = "puzzimg";
			pdrop2.appendChild(img2);

			pdrop3 = document.getElementById("puzzdrop3");
			img3 = document.createElement("img");
			img3.setAttribute("id", "cpuzzd");
			img3.setAttribute("src", "/wordpress/wp-content/plugins/puzzcaptcha/puzzbits/" + puzzid + "d.png");
			img3.className = "puzzimg";
			pdrop3.appendChild(img3);

			if(errNum!=errNum){ //reserved
			}

			initPuzzCAPTCHA();

			document.getElementById("puzzwayouter").style.display = "block";
			document.getElementById("puzzouter").style.display = "block";
			document.getElementById("puzzcaptcha_form").style.display = "block";
			document.getElementById("puzzcaptcha_input").focus();
			if(answer!="" && passed == "false"){
				msgblock.innerHTML = "<br />Incorrect, please try again:<br />";
				msgblock.style.color = "#FF0000";
				document.getElementById("puzzcaptcha_input").value = "";
			}else if(passed.substring(0,7)=="expired"){
				msgblock.innerHTML = "<br />We're sorry, but the PuzzCAPTCHA code you entered " + passed + " Please try again:<br />";
				msgblock.style.color = "#FF0000";
				document.getElementById("puzzcaptcha_input").value = "";
			}
		}else{ // captcha validated
			try{
				var cformc = document.getElementById("commentformclone");
			}catch(e){
			}
			if(cformc){
				msgblock.style.color = "#7CB88F";
				msgblock.innerHTML = "<br /><strong>Success!</strong><br />";

				try{
					var cform = document.getElementById("commentform");
				}catch(e){
				}
				if(cform){
					var evalue;
					for (i=0; i < cform.elements.length; i++) {
						ele = cform.elements[i];
						etype = ele.getAttribute("type");
						if((ele.tagName=="INPUT" && etype.toLowerCase() != "submit") || ele.tagName=="TEXTAREA"){
							evalue = ele.value;
							eid = ele.getAttribute("id");
							if(eid!=null && eid!=""){
								//alert(eid + "clone");
								cele = document.getElementById(eid + "clone");
								cele.value = evalue;
							}
						}
					}
				}

				var puzzid_input = document.createElement("input");
				puzzid_input.setAttribute("type", "hidden");
				puzzid_input.setAttribute("value", puzzid);
				puzzid_input.setAttribute("name", "puzzid");
				cformc.appendChild(puzzid_input);
				var puzzans_input = document.createElement("input");
				puzzans_input.setAttribute("type", "hidden");
				puzzans_input.setAttribute("value", answer);
				puzzans_input.setAttribute("name", "puzzans");
				cformc.appendChild(puzzans_input);
				cformc.submit();
			}
		}
	}else{
		//alert('There was a problem with the request. ReadyState:' + http_request.readyState);
	}
}

function dropPuzz(idOfDraggedItem,targetId,x,y){
	var targetObj = document.getElementById(targetId);
	var targetNum = targetId.charAt(8);
	var sourceObj = document.getElementById(idOfDraggedItem);
	//grab the existing image
	var currPuzz = document.getElementById(puzzOrder[targetNum]);
	//figure out where the dropped item came from
	sourceNum = puzzOrder.indexOf(sourceObj.getAttribute("id"));
	var swapTo = document.getElementById("puzzdrop" + sourceNum);
	//swap em
	swapTo.appendChild(currPuzz);
	targetObj.appendChild(sourceObj);
	//update the array
	puzzOrder[sourceNum] = puzzOrder[targetNum];
	puzzOrder[targetNum] = idOfDraggedItem;
}

function initPuzzCAPTCHA(){
	var dragDropObj = new DHTMLgoodies_dragDrop();
	dragDropObj.addSource('cpuzza',true, true, true, "puzzouter");
	dragDropObj.addSource('cpuzzb',true, true, true, "puzzouter");
	dragDropObj.addSource('cpuzzc',true, true, true, "puzzouter");
	dragDropObj.addSource('cpuzzd',true, true, true, "puzzouter");
	dragDropObj.addTarget('puzzdrop0','dropPuzz');
	dragDropObj.addTarget('puzzdrop1','dropPuzz');
	dragDropObj.addTarget('puzzdrop2','dropPuzz');
	dragDropObj.addTarget('puzzdrop3','dropPuzz');
	dragDropObj.init();
}

function make_puzzdiv(){
		divOuter = document.createElement("div");
		divOuter.className = "puzzouter";
		divOuter.setAttribute("id", "puzzouter");
		divOuter.style.display = "none";
		pdrop0 = document.createElement("div");
		pdrop0.setAttribute("id", "puzzdrop0");
		divOuter.appendChild(pdrop0);
		pdrop1 = document.createElement("div");
		pdrop1.setAttribute("id", "puzzdrop1");
		divOuter.appendChild(pdrop1);
		pdrop2 = document.createElement("div");
		pdrop2.setAttribute("id", "puzzdrop2");
		divOuter.appendChild(pdrop2);
		pdrop3 = document.createElement("div");
		pdrop3.setAttribute("id", "puzzdrop3");
		divOuter.appendChild(pdrop3);
		return divOuter;
}

function grabCommentForm(){
	//reassign the comment form action, if it exists
	try{
		var cform = document.getElementById("commentform");
	}catch(e){
	}
	if(cform){
		var cformc = cform.cloneNode(true);
		cformc.setAttribute("id", "commentformclone");
		cformc.style.display = "none";
		for (i=0; i < cformc.elements.length; i++) {
			ele = cformc.elements[i];
			etype = ele.getAttribute("type");
			if(ele.tagName=="INPUT" && etype.toLowerCase() == "submit"){
				ele.parentNode.removeChild(ele);
			}else{
				var oldid = ele.getAttribute("id");
				ele.setAttribute("id", oldid + "clone");
			}
		}
		cform.parentNode.appendChild(cformc);
		cform.onsubmit=function(){return false;};
		applyEvent(cform, "submit", preSubmit);

		divWayOuter = document.createElement("div");
		divWayOuter.className = "puzzwayouter";
		divWayOuter.setAttribute("id", "puzzwayouter");
		divWayOuter.style.display = "none";
		cform.parentNode.insertBefore(divWayOuter, cform);

		divOuter = make_puzzdiv();
		divWayOuter.appendChild(divOuter);
		capForm = document.createElement("div");
		capForm.setAttribute("id", "puzzcaptcha_form");

		capFormF = document.createElement("form");
		capFormF.onsubmit=function(){return false;};
		applyEvent(capFormF, "submit", capValidate);

		capInstr = document.createElement("span");
		capInstr.setAttribute("id", "capinstr");
		var puzz_instr = "<br />Rearrange the pieces, solve the puzzle, and enter the word it shows below ";
		puzz_instr += "within <span id='puzz_tout'>" + puzztimeout + "</span> seconds:<br />";
		capInstr.innerHTML = puzz_instr;
		capFormF.appendChild(capInstr);

		capTB = document.createElement("input");
		capTB.setAttribute("type", "text");
		capTB.setAttribute("size", "12");
		capTB.setAttribute("name", "puzzcaptcha_input");
		capTB.setAttribute("id", "puzzcaptcha_input");
		capFormF.appendChild(capTB);

		capBut = document.createElement("input");
		capBut.setAttribute("type", "submit");
		capBut.setAttribute("value", "Continue");
		capBut.setAttribute("id", "puzzcaptcha_button");
		capFormF.appendChild(capBut);

		capUndInstr = document.createElement("span");
		capUndInstr.setAttribute("id", "capundinstr");
		capUndInstr.innerHTML = "<br /><em>Note: puzzle is not case sensitive.</em><br />";
		capFormF.appendChild(capUndInstr);

		capForm.appendChild(capFormF);
		capForm.style.display = "none";
		cform.parentNode.insertBefore(capForm, cform);
	}
}

function capValidate(){
	var pci = document.getElementById("puzzcaptcha_input");
	if(pci.value==""){
		return false;
	}
	makeRequest("/wordpress/wp-content/plugins/puzzcaptcha/puzzgen.php?a=ver&pc=" + puzzid + "&ans=" + URLencode(pci.value));
}

function puzzCAPTCH_reset(){
	po = document.getElementById("puzzouter");
	pwo = document.getElementById("puzzwayouter");
	divOuter = make_puzzdiv();
	po.parentNode.removeChild(po);
	pwo.appendChild(divOuter);
	puzzOrder = ["cpuzza", "cpuzzb", "cpuzzc", "cpuzzd"];
}

function preSubmit(){
	if(!PuzzCAPTCHA_initialized){
		var cform = document.getElementById("commentform");
		cform.style.display = "none";
		makeRequest("/wordpress/wp-content/plugins/puzzcaptcha/puzzgen.php");
		PuzzCAPTCHA_initialized = true;
	}
}

//initial assignment of image pieces
var puzzOrder = ["cpuzza", "cpuzzb", "cpuzzc", "cpuzzd"];
