/*WP Ajax Edit Script
--Created by Ronald Huereca
--Created on: 03/28/2007
--Last modified on: 04/02/2007
--Relies on Prototype somewhat
Classnames referenced in here for the Author are:
	editAuthor (default)
	editableAuthor (Shows it can be edited)
	textAuthor (When the author field is being edited)
Classnames referenced in here for the Comment are:
	editComment (default)
	editableComment (Shows it can be edited)
	textComment (When the comment field is being edited)
	
	Copyright 2007  Ronald Huereca  (email : ron alfy [a t ] g m ail DOT com)

    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 for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

var wpAjaxAec = new AjaxEditComments;

//Called when the page has finished loading
function AjaxEditComments_init() { 
	wpAjaxAec.wpAjaxMakeEdit();
	wpAjaxAec.PluginURL = document.getElementById('editBlogUrl').value + '/wp-content/plugins/wp-ajax-edit-comments';
}
//Class AjaxEditComments
function AjaxEditComments() { 
	this.CommentAuthorName = "editAuthor";
	this.CommentClassName = "editComment";
	this.EditCommentAuthorName = "editableAuthor"; //not edible author :)
	this.EditCommentClassName = "editableComment";
	this.TextAuthorClassName = "textAuthor";
	this.TextCommentClassName = "textComment";
	this.PluginURL = '';
	
	//Methods
	this.wpAjaxEdit = wpAjaxEdit;
	this.wpAjaxMakeEdit = wpAjaxMakeEdit;
	this.wpAjaxShowAsEditable = wpAjaxShowAsEditable;
	this.wpAjaxShowAsUnEditable = wpAjaxShowAsUnEditable;
	this.wpAjaxAuthorSave = wpAjaxAuthorSave;
	this.wpAjaxEditCancel = wpAjaxEditCancel;
	this.wpAjaxCommentSave = wpAjaxCommentSave;
	this.wpAjaxLoadCommentComplete = wpAjaxLoadCommentComplete;
	this.wpAjaxLoadCommentFailure = wpAjaxLoadCommentFailure;
	this.wpAjaxSaveCommentComplete = wpAjaxSaveCommentComplete;
	this.wpAjaxSaveCommentFailure = wpAjaxSaveCommentFailure;
	this.wpAjaxSaveAuthorComplete = wpAjaxSaveAuthorComplete;
	this.wpAjaxSaveAuthorFailure = wpAjaxSaveAuthorFailure;
	this.wpAjaxMakeAjaxPost = wpAjaxMakeAjaxPost;
	this.wpAjaxBuildAjaxRequest = wpAjaxBuildAjaxRequest;
	this.wpAjaxMakeAjaxRequest = wpAjaxMakeAjaxRequest;
	
}
//Scans the spans and divs for a specific class and sets events to make them editable
function wpAjaxMakeEdit() {
		
	//Make the Author portions editable
	var spans = document.getElementsByTagName('span');
	for (var i = 0; i < spans.length; i++) {
		if (spans[i].className == this.CommentAuthorName) {
			var id = spans[i].id;
			 spans[i].onmouseover = this.wpAjaxShowAsEditable.wpAjaxbindAsEventListener(this, spans[i]);
			 spans[i].onmouseout = this.wpAjaxShowAsUnEditable.wpAjaxbindAsEventListener(this, spans[i]);
			 spans[i].onclick = this.wpAjaxEdit.wpAjaxbindAsEventListener(this, spans[i]);
		}
	}
	var divs = document.getElementsByTagName('div');
	//Make the comment portions editable
	for (var i = 0; i < divs.length; i++) {
		if (divs[i].className == this.CommentClassName) {
			var id = divs[i].id;
			 divs[i].onmouseover = this.wpAjaxShowAsEditable.wpAjaxbindAsEventListener(this, divs[i]);
			 divs[i].onmouseout = this.wpAjaxShowAsUnEditable.wpAjaxbindAsEventListener(this, divs[i]);
			 divs[i].onclick = this.wpAjaxEdit.wpAjaxbindAsEventListener(this, divs[i]);
		}
	}	
}
//Saves the Author Data to the Database
//evt - The event object
//obj1 - The element to show saved information
//obj2 - The element to retreive saved information
//display - The display type of object 1
//saveButton - The save button to disable
function wpAjaxAuthorSave(evt, obj1, obj2, display, saveButton) {
	//Retrieve the url
	var myObj = this;
	var url = document.getElementById(obj1.id + "_URL");
	var author = document.getElementById(obj1.id + "_author");
	saveButton.value = "Saving...";
	saveButton.disabled = "true";
	if (url == undefined || author == undefined) { saveButton.value = "Saving Author Failed"; return; }
	urlValue = url.value;
	authorValue = author.value;
	
	var url = this.PluginURL + '/php-includes/AjaxEditComments.php';
	var pars = 'SaveAuthorCommentId=' + obj1.id + '&AuthorURL=' + encodeURIComponent(urlValue) + '&AuthorName=' + encodeURIComponent(authorValue);
	this.wpAjaxMakeAjaxPost("myObj.wpAjaxSaveAuthorComplete", false, url, pars, obj1, obj2, display, saveButton, myObj);

}
//Saves the comment data to the database
//evt - The event object
//obj1 - The element to show saved information
//obj2 - The element to retreive saved information
//display - The display type of object 1
//saveButton - The save button
function wpAjaxCommentSave(evt, obj1, obj2, display, saveButton) {
	//Retrieve the textarea
	var myObj = this;
	var textarea = document.getElementById(obj1.id + "_edit");
	if (textarea == undefined) { return; } //todo error
	saveButton.value = "Saving...";
	saveButton.disabled = "true";
	
	var url = this.PluginURL + '/php-includes/AjaxEditComments.php';
	var pars = 'SaveCommentId=' + obj1.id + '&SaveContent=' + encodeURIComponent(textarea.value);
	this.wpAjaxMakeAjaxPost("myObj.wpAjaxSaveCommentComplete", false, url, pars, obj1, obj2, display, saveButton, myObj);
}
//Cancels an edit
//evt - The event object
//obj1 - The element to show
//obj2 - The element to destroy
//display - The display type of object 1
function wpAjaxEditCancel(evt, obj1, obj2, display) {
	var objParent = obj2.parentNode;
	objParent.removeChild(obj2);
	obj1.style.display = display;
}
//Allows the comment and author areas to be editable
//evt - The event object
//obj - The element that caused the event
function wpAjaxEdit(evt, obj) {
	var myObj = this;
	if (obj.tagName.toLowerCase() == "span") {
		//Create a new span element to replace the author span
		var newSpan = document.createElement('span');
		newSpan.className = this.TextAuthorClassName;
		newSpan.id = this.TextAuthorClassName + obj.id;

		//if url and name both return zero matches, use innerHTML as is.
		var url = obj.innerHTML.match(/href=\"([^"]*)\"/i);
		if (url == undefined) {
			url = obj.innerHTML.match(/href=\'([^']*)\'/i)
		}
		if (url == undefined) {
			url = '';
			name = obj.innerHTML;
		} else {
			url = url[1];
			name = obj.innerHTML.match(/>([^<]*)<\/a>/i)[1];
		}
		var authorInputBox = '<label for="' + obj.id + '_URL">URL: </label><input type="text" class="authorURL" id="' + obj.id + '_URL" value="' + url + '" /><label for="' + obj.id + '_author"> Name: </label><input type="text" id="' + obj.id + '_author" class="authorInput" value=\'' + name + '\' />&nbsp;&nbsp;';
		var authorButtons = '<input type="button" value="Save" id="' + obj.id + '_saveAuthor" /> or <input type="button" value="Cancel" id="' + obj.id + '_cancelAuthor" />';
		newSpan.innerHTML = authorInputBox + authorButtons;
		
		//Hide the old span and show the new one
		obj.style.display = "none";
		obj.parentNode.insertBefore(newSpan, obj);
		//Save button
		var saveButton = document.getElementById(obj.id + '_saveAuthor');
		var cancelButton = document.getElementById(obj.id + '_cancelAuthor');
		saveButton.onclick = this.wpAjaxAuthorSave.wpAjaxbindAsEventListener(this, obj, newSpan, "inline", saveButton);
		cancelButton.onclick = this.wpAjaxEditCancel.wpAjaxbindAsEventListener(this, obj, newSpan, "inline");
	} else if (obj.tagName.toLowerCase() == "div") {
			var newDiv = document.createElement('div');
			newDiv.className = this.TextCommentClassName;
			newDiv.id = this.TextCommentClassName + obj.id;
			//Create the input box and buttons
			var textarea = '<textarea id="' + obj.id + '_edit" name="' + obj.id + '">Loading comment...</textarea>';
			var commentButtons = '<p><input type="button" value="Save" id="' + obj.id + '_saveComment" /> or <input type="button" value="Cancel" id="' + obj.id + '_cancelComment" /></p>';
			
			//Load the comment
			var url = this.PluginURL + '/php-includes/AjaxEditComments.php';
			var pars = 'GetCommentId=' + obj.id;
			this.wpAjaxMakeAjaxPost("myObj.wpAjaxLoadCommentComplete", false, url, pars, obj.id, myObj);
			
			

			newDiv.innerHTML = textarea + commentButtons;
			//Hide the old span and show the new one
			obj.style.display = "none";
			obj.parentNode.insertBefore(newDiv, obj);
			
			//Save button
			var saveButton = document.getElementById(obj.id + '_saveComment');
			var cancelButton = document.getElementById(obj.id + '_cancelComment');
			saveButton.onclick = this.wpAjaxCommentSave.wpAjaxbindAsEventListener(this, obj, newDiv, "block", saveButton);
			cancelButton.onclick = this.wpAjaxEditCancel.wpAjaxbindAsEventListener(this, obj, newDiv, "block");
	} else { 
		return true; //Just in case I suppose
	}
	return false;
}

//Changes the classname of the span/div so that it appears editable
function wpAjaxShowAsEditable(evt, obj) {
	if (obj.className == this.CommentAuthorName) {
		obj.className = this.EditCommentAuthorName;
	} else if ( obj.className == this.CommentClassName) {
		obj.className = this.EditCommentClassName;
	}
}
//Changes the classname of the span/div so that it appears uneditable
function wpAjaxShowAsUnEditable(evt, obj) {
	if (obj.className == this.EditCommentAuthorName) {
		obj.className = this.CommentAuthorName;
	} else if ( obj.className == this.EditCommentClassName) {
		obj.className = this.CommentClassName ;
	}
}

function wpAjaxLoadCommentComplete(t, id) {
	var textBox = document.getElementById(id + "_edit");
	if (textBox == undefined) {
		//nothing to do so we return
		return;
	}
	
	if (t == 0) {
			textBox.value = "Load comment failed";
			return;
	}
	//todo time out
	textBox.value = t;
}
function wpAjaxLoadCommentFailure(t, id) {
	var textBox = document.getElementById(id + "_edit");
	if (textBox == undefined) {
		//nothing to do so we return
		return;
	}
	
	if (t == 0) {
			textBox.value = "Load comment failed.";
			return;
	}
}
function wpAjaxSaveAuthorComplete(t, obj1, obj2, display, saveButton) {
	if (obj1 == undefined || obj2 == undefined || saveButton == undefined) { 
		return;
	}
	if (t == 0) {
			saveButton.value = "Save Author Failed";
			return;
	}

	//todo time out
	obj1.innerHTML = t;
	obj1.style.display = display;
	var p = obj2.parentNode;
	p.removeChild(obj2); 
}
function wpAjaxSaveAuthorFailure(t, saveButton) {
	if (saveButton == undefined) { return; }
	saveButton.value = "Save Author Failed";
}
function wpAjaxSaveCommentComplete(t, obj, obj2, display, saveButton) {
	if (obj == undefined || obj2 == undefined || saveButton == undefined) { return; }
	
	if (t == 0) { 
		saveButton.value = "Save Comment Failed";
		return;
	}
	

	//todo time out
	obj.innerHTML = t;
	obj.style.display = display;
	var p = obj2.parentNode;
	p.removeChild(obj2);
}
function wpAjaxSaveCommentFailure(t, id, saveButton) {
	if (saveButton == undefined) { return; }
	saveButton.value = "Save Author Failed";
}
function wpAjaxBuildAjaxRequest( callback, retXML, ignoreStatus ) {
    var http_request = false;
		var myObj = this;

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        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 ) {

        if( retXML ) {
            evalString = '(http_request.responseXML';
        }
        else {
            evalString = '(http_request.responseText';
        }

        if( arguments.length == 4 ) {
            args = arguments[3];

            for( var i = 0; i < args.length; i++ ) {
                evalString += (',args[' + i + ']');
            }
        }

        evalString += ')';

        http_request.onreadystatechange = function() {
            if (http_request.readyState == 4) {
                if( ignoreStatus || http_request.status == 200 ) {
                    eval(callback + evalString);
                }
            }
        }
    }

    return http_request;
}
//This code was originally in Expand Comments - The function names have been changed to prevent naming conflicts
// buildAjaxRequest is inspired by www.sitepoint.com/article/take-command-ajax
// which is taken from other various tuts. Sharing is caring.
// For documentation's sake, callback is a function that takes
// a single argument. This argument holds what is returned from
// the server, as XML of retXML is true, or as Text if not
// buildAjaxRequest will also look to see if there is a third
// argument, which should be an array of more arguments.
// This array is expanded, and when the callback is called,
// It will be given this list of arguments
/*
 * wpAjaxMakeAjaxRequest will form a GET request from the server.
 * Any arguments past the first 3 will be sent to the callback
 */
function wpAjaxMakeAjaxRequest(callback, retXML, url) {
    args = [];
    for( i = 3; i < arguments.length; i++ ) {
        args.push( arguments[i] );
    }

    http_request = this.wpAjaxBuildAjaxRequest(callback, retXML, false, args);

    /* This RANDOM query is so the page isn't cached */
    url += "&RANDOM=" + (Math.random() * Date.parse(new Date()))
    http_request.open('GET', url, true);
    http_request.send(null);
}

/*
 * wpAjaxMakeAjaxPost will form a POST request to the server.
 * params should be a properly formatted line (id=3&submit=true)
 * Any arguments past the first 4 will be sent to the callback
 */
function wpAjaxMakeAjaxPost(callback, retXML, url, params) {

    args = [];
    for( i = 4; i < arguments.length; i++ ) {
        args.push( arguments[i] );
    }
    http_request = this.wpAjaxBuildAjaxRequest(callback, retXML, false, args);

    http_request.open("POST", url, true);
    http_request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
    http_request.send(params);

    return false;
}
//Credit: Simon Willison 2004
//From: http://simon.incutio.com/archive/2004/05/26/addLoadEvent
//Function names changed to prevent naming conflicts
function wpAjaxaddLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}
//Adds a load event to make the link to resize the page visible
wpAjaxaddLoadEvent(function() {
	if (document.getElementById && document.getElementsByTagName) {
		AjaxEditComments_init();
	}
	
});