function hideRestoreButton() {
	var restorebutton = document.getElementById('restorebutton');
	if (restorebutton) restorebutton.setAttribute("style","display: none;");
}

function restoreOriginalContent() {
	var restorebutton = document.getElementById('restorebutton');
	if (restorebutton) {
		hideRestoreButton();
		var oldcontent = restorebutton.getAttribute("oldcontent");
		if (oldcontent) {
			var textarea = document.getElementById('content');
			if (textarea) {
				textarea.value = oldcontent;
			}
		}
	}
}


function showRestoreButton() {
	var restorebutton = document.getElementById('restorebutton');
	if (restorebutton) restorebutton.setAttribute("style","");
}

function saveOriginalContent() {
	var restorebutton = document.getElementById('restorebutton');
	if (restorebutton) {
		var textarea = document.getElementById('content');
		if (textarea) {
			restorebutton.setAttribute("oldcontent",textarea.value)
		}
		showRestoreButton();
	}
}


var config = {
	// Options that can be set in the options panel and/or cookies
	txtRegexp: "apattern",
	txtReplacement: "apattern2",
	chkCaseInsensitive: true,
	chkDotAll: false,
	chkShown: false
};

String.prototype.trim = function()
{
	var regexpTrim = new RegExp("^\\s*(.*)\\s*$","mg");
	return(this.replace(regexpTrim,"$1"));
}

function srLoadOptionsCookie()
{
	var cookies = document.cookie.split(";");
	for(var c=0; c<cookies.length; c++)
		{
		var currcookie = cookies[c].trim();
		var p = currcookie.indexOf("=");
		if(p != -1)
			{
			var name = currcookie.substr(0,p);
			var value = currcookie.substr(p+1);
			switch(name.substr(0,3))
				{
				case "txt":
					config[name] = unescape(value);
					break;
				case "chk":
					config[name] = value == "true";
					break;
				}
			}
		}
}

function srLoadOptions() {
// 	alert(document.cookie);
	srLoadOptionsCookie();
}

function srSaveOptionCookie(name)
{

	var cd = name + "=";
	switch(name.substr(0,3))
		{
		case "txt":
			cd += escape(config[name].toString());
			break;
		case "chk":
			cd += config[name] ? "true" : "false";
			break;
		}

	var newcookie = "";

	newcookie += cd;

	var cookies = document.cookie.split("; ");
	for(var c=0; c<cookies.length; c++)
		{
		var currcookie = cookies[c].trim();
		var p = currcookie.indexOf("=");
		if(p != -1)
			{
			var lname = currcookie.substr(0,p);
			var lvalue = currcookie.substr(p+1);
			switch(lname.substr(0,3))
				{
				case name:
					break;
				default:
					newcookie += ";" + currcookie;
					break;
				}
			}
		}

	document.cookie = newcookie;
}

function srSaveOptions() {
		config["txtRegexp"] =
			document.getElementById("searchregexp").value;
		config["txtReplacement"] =
			document.getElementById("searchreplacement").value;
		config["chkCaseInsensitive"] = 
			document.getElementById("searchreinsensitive").checked;
		config["chkDotAll"] =
			document.getElementById("searchredotall").checked;
		srSaveOptionCookie("txtRegexp");
		srSaveOptionCookie("txtReplacement");
		srSaveOptionCookie("chkCaseInsensitive");
		srSaveOptionCookie("chkDotAll");

		config["chkShown"] = false;
		if (document.getElementById("srholder").getAttribute("style") == "") {
			config["chkShown"] = true;
		}
		srSaveOptionCookie("chkShown");

// 		alert(document.cookie);
}

function toggleSearchAndReplace() {

	var shown = false;

	var srholder = document.getElementById('srholder');
	if (srholder) {
		if (srholder.getAttribute("style") == "") {
			srholder.setAttribute("style","display: none;");
			}
		else {
			srholder.setAttribute("style","");
			shown = true; }
	} else {
		var textarea = document.getElementById('content');
		var textareaparent = textarea.parentNode;
	
		var srholder = document.createElement("table");
		srholder.setAttribute("id","srholder");
		srholder.setAttribute("align","center");
		srholder.setAttribute("style","");
	
		var srholderrow1 = document.createElement("tr");
		var srholderrow2 = document.createElement("tr");
		var srholdercell1 = document.createElement("td");
		var srholdercell2 = document.createElement("td");
		var srholdercell3 = document.createElement("td");
		srholdercell1.setAttribute("colspan","2");
		srholdercell1.setAttribute("style","white-space: nowrap;");
		srholdercell2.setAttribute("style","white-space: nowrap;");
		srholdercell3.setAttribute("style","white-space: nowrap; text-align: right;");
	
		srholderrow1.appendChild(srholdercell1);
		srholderrow2.appendChild(srholdercell2);
		srholderrow2.appendChild(srholdercell3);
		srholder.appendChild(srholderrow1);
		srholder.appendChild(srholderrow2);
	
		var searchregexp = document.createElement("input");
		searchregexp.setAttribute("type","text");
		searchregexp.setAttribute("name","searchregexp");
		searchregexp.setAttribute("id","searchregexp");
		searchregexp.setAttribute("value",config["txtRegexp"]);
		searchregexp.setAttribute("onblur","srSaveOptions();");
	
		var searchreplacement = document.createElement("input");
		searchreplacement.setAttribute("type","text");
		searchreplacement.setAttribute("name","searchreplacement");
		searchreplacement.setAttribute("id","searchreplacement");
		searchreplacement.setAttribute("value",config["txtReplacement"]);
		searchreplacement.setAttribute("onblur","srSaveOptions();");
	
		var searchreinsensitive = document.createElement("input");
		searchreinsensitive.setAttribute("type","checkbox");
		searchreinsensitive.setAttribute("name","searchreinsensitive");
		searchreinsensitive.setAttribute("id","searchreinsensitive");
		searchreinsensitive.checked = config["chkCaseInsensitive"];
		searchreinsensitive.setAttribute("onclick","srSaveOptions();");
	
		var searchreinsensitivelabel = document.createElement("label");
		searchreinsensitivelabel.setAttribute("for","searchreinsensitive");
		searchreinsensitivelabel.setAttribute("id","searchreinsensitivelabel");
		searchreinsensitivelabel.appendChild(document.createTextNode(" Ignore case "));
	
		var searchredotall = document.createElement("input");
		searchredotall.setAttribute("type","checkbox");
		searchredotall.setAttribute("name","searchredotall");
		searchredotall.setAttribute("id","searchredotall");
		searchredotall.checked = config["chkDotAll"];
		searchredotall.setAttribute("onclick","srSaveOptions();");
	
		var searchredotalllabel = document.createElement("label");
		searchredotalllabel.setAttribute("for","searchredotall");
		searchredotalllabel.setAttribute("id","searchredotalllabel");
		searchredotalllabel.appendChild(document.createTextNode(" Periods match newlines too "));
	
	// 	var srholderbr = document.createElement("br");
	
		var searchbutton = document.createElement("input");
		searchbutton.setAttribute("type","button");
		searchbutton.setAttribute("name","searchbutton");
		searchbutton.setAttribute("id","searchbutton");
		searchbutton.setAttribute("value","Replace");
		searchbutton.setAttribute("onclick","searchAndReplace('content','searchregexp','searchreplacement');");
	
		var restorebutton = document.createElement("input");
		restorebutton.setAttribute("type","button");
		restorebutton.setAttribute("name","restorebutton");
		restorebutton.setAttribute("id","restorebutton");
		restorebutton.setAttribute("value","Undo");
		restorebutton.setAttribute("onclick","restoreOriginalContent();");
		restorebutton.setAttribute("style","display: none;");

		var searchhelplink = document.createElement("a");
		searchhelplink.setAttribute("target","_blank");
		searchhelplink.setAttribute("href","http://rudd-o.com/projects/wp-search-replace/wp-search-replace-usage/");
		searchhelplink.setAttribute("title","Open the quick reference in a new window");
		searchhelplink.appendChild(document.createTextNode("Help!"));
	
	// 	srholderrow1.appendChild(document.createElement("hr"));
		srholdercell1.appendChild(document.createTextNode("Expression: "));
		srholdercell1.appendChild(searchregexp);
		srholdercell1.appendChild(document.createTextNode(" Replacement: "));
		srholdercell1.appendChild(searchreplacement);
	
	// 	srholderp.appendChild(srholderbr);
		srholdercell2.appendChild(searchreinsensitive);
		srholdercell2.appendChild(searchreinsensitivelabel);
		srholdercell2.appendChild(document.createTextNode(" "));
		srholdercell2.appendChild(searchredotall);
		srholdercell2.appendChild(searchredotalllabel);
	
		srholdercell3.appendChild(searchhelplink);
		srholdercell3.appendChild(document.createTextNode(" "));
		srholdercell3.appendChild(searchbutton);
		srholdercell3.appendChild(document.createTextNode(" "));
		srholdercell3.appendChild(restorebutton);
		
	// 	srholder.appendChild(srholderp);
	// 	srholder.appendChild(srholderp2);
	
		textareaparent.insertBefore(srholder,textarea);
		shown = true;
	}

	srSaveOptions();
	return shown;

}

// this function is also copied from Canary Comment
function encodeAForm(sNode) {
	var tvar = "";
	var ctyp = sNode.nodeName ? sNode.nodeName.toLowerCase() : "";
	var etyp = sNode.type ? sNode.type.toLowerCase() : "";
	if( ( ((ctyp=="textarea") || (ctyp=="input")) && (etyp!="radio") && (etyp!="checkbox") && (etyp!="submit") )){
		tvar = encodeURIComponent(sNode.getAttribute("name")) + "=" + encodeURIComponent(sNode.value) + "&";
	}else if((ctyp=="input") && (etyp!="submit")){
		if(sNode.checked){
			tvar = encodeURIComponent(sNode.getAttribute("name")) + "=" + encodeURIComponent(sNode.value) + "&";
		}
	}
	if(sNode.hasChildNodes()){
		for(var temp_count=(sNode.childNodes.length-1); temp_count >= 0; temp_count--){
			tvar += encodeAForm(sNode.childNodes.item(temp_count));
		}
	}
	return tvar;
}

var searchreplacerurl = "<?php echo get_plugin_public_url(); ?>";

function searchAndReplace(textareaid,searchregexpid,searchreplacementid) {

	srSaveOptions();

	var content = document.getElementById(textareaid);
	var regexp = document.getElementById(searchregexpid);
	var replacement = document.getElementById(searchreplacementid);

	var ci = document.getElementById('searchreinsensitive');
	var dotall = document.getElementById('searchredotall');

	var regmod = "";
	if (ci.checked) regmod = regmod + "i";
	if (dotall.checked) regmod = regmod + "s";

	var querystring = encodeAForm(content) + encodeAForm(regexp) + encodeAForm(replacement) + "searchmodifiers=m" + regmod + "&op=searchandreplace";

// 	alert(querystring);
// 	malo();

	var ajax = new sack();
	ajax.encodeURIString = false;
	ajax.requestFile = searchreplacerurl;
	ajax.execute = false;
	ajax.onCompletion = function() {
		saveOriginalContent();
		content.value = ajax.response;
	}
	ajax.runAJAX(querystring);
	return false;

}

function addSRButton() {

	var toolbar = document.getElementById('ed_toolbar');
	var textarea = document.getElementById('content');
	if (toolbar && textarea)
	{
		var theButton = document.createElement('input');
		theButton.type = 'button';
		theButton.value = 'Search/Replace';
		theButton.setAttribute('onclick', 'if (toggleSearchAndReplace()) { document.getElementById("searchregexp").focus() ; }');
		theButton.className = 'ed_button';
		theButton.title = "Search/Replace";
		theButton.id = "ed_SearchReplace";
		toolbar.appendChild(theButton);

		if (config["chkShown"] == true) {
			toggleSearchAndReplace();
		}
	}
}

srLoadOptions();
addSRButton();