// +---------------------------------------------------------------------------+
// | Geeklog Autosave 1.0.2                                                    |
// +---------------------------------------------------------------------------+
// | Copyright (C) 2009 mystral-kk - geeklog AT mystral-kk DOT net             |
// +---------------------------------------------------------------------------+
// |                                                                           |
// | 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.           |
// |                                                                           |
// +---------------------------------------------------------------------------+

if (typeof Core == "undefined") {
	throw "Class 'Geeklog.autosave' needs 'Core' library.  Please load 'Core' library in advance.  Aborted.";
}

var Geeklog;
if ((typeof Geeklog == "undefined") || (typeof Geeklog != "object")) {
	Geeklog = {};
}

/**
* "Geeklog.autosave" object and "Geeklog.autosave.interval" object are
* defined in 'functions.inc'.
*/

// For debugging with Firebug
Geeklog.autosave.debug = false,

// API key (DO NOT CHANGE THIS!)
Geeklog.autosave._apikey = "fb50911fa748e31b76145505a4541655";

// Names (not IDs) of target elements (<textarea> and <input> fields)
Geeklog.autosave._targets = {
	"article": {
		"sid": null,
		"uid": 0,
		"draft_flag": false,
		"tid": null,
		"title": null,
		"show_topic_icon": true,
		"introtext": null,
		"bodytext": null,
		"postmode": "plaintext"
	},
	
	"staticpages": {
		"sp_id": null,
		"sp_uid": 0,
		"sp_title": null,
		"sp_content": null,
		"postmode": "html"
	}
};

// Currently, either "article" or "staticpages"
Geeklog.autosave._type = null;

// Handle of interval timer
Geeklog.autosave._timer = null;

// Print a log message to Firebug console
Geeklog.autosave._log = function(str)
{
	if (Geeklog.autosave.debug && (Geeklog.autosave.debug === true)
	 && (typeof console != "undefined")) {
		var d = new Date();
		console.log(d.toUTCString() + ": " + str);
	}
};

// Show a message when content was saved
Geeklog.autosave.showMessage = function(msg)
{
// 	var x = 0;
// 	var y = 0;
	var body = document.body;
	var box  = document.createElement("div");
	var text = document.createTextNode(msg);
	
// 	if (typeof window.scrollX != "undefined") {
// 		// for FF, Safari
// 		x = window.scrollX + 10;
// 		y = window.scrollY + 10;
// 	} else if (typeof window.screenLeft != "undefined") {
// 		// for IE, Opera
// 		alert("window.screenTop: " + window.screenTop);
// 		x = window.screenLeft + 10;
// 		y = window.screenTop + 10;
// 	} else 	if (typeof document.body.scrollLeft != "undefined") {
// 		// for IE, Opera
// 		x = body.scrollLeft + 10;
// 		y = body.scrollTop + 10;
// 	}
	
	box.id = "Geeklog_autosave_message";
	box.setAttribute("visibility", "hidden");
	box.appendChild(text);
	body.insertBefore(box, body.childNodes[0]);
	Core.addClass(box, "autosave");
// 	box.style.setAttribute("left", x + "px");
// 	box.style.setAttribute("top", y + "px");
	box.setAttribute("visibility", "");
	
	window.setTimeout(
		function() {
			box.setAttribute("visibility", "hidden");
			body.removeChild(box);
		},
		2 * 1000
	);
}

// Return the content of FCKeditor editor window
Geeklog.autosave._getFCKeditorContent = function(name)
{
	var content = "";
	
	if (typeof window.FCKeditorAPI != "undefined") {
		var oEditor = window.FCKeditorAPI.GetInstance(name);
		
		try {
			content = oEditor.GetXHTML(true);
		} catch (e) {}
	}
	
	return content;
}

// Return the tag with a given name
Geeklog.autosave._getTag = function(name)
{
	var tags = document.getElementsByName(name);
	
	return (tags.length === 0) ? false : tags[0];
}

// Return the value of an HTML tag with a given name
Geeklog.autosave._fetchContent = function(name)
{
	var tag = Geeklog.autosave._getTag(name);
	var retval = false;
	
	if (tag !== false) {
		if (tag.type == "checkbox") {
			retval = (tag.checked) ? 1 : 0;
		} else {
			retval = tag.value;
			
			if (Geeklog.autosave._getTag("postmode").value === "adveditor") {
				// Advanced editor mode
				if (Geeklog.autosave._type === "article") {
					if (name === "introtext") {
						retval = Geeklog.autosave._getFCKeditorContent("introhtml");
					} else if (name === "bodytext") {
						retval = Geeklog.autosave._getFCKeditorContent("bodyhtml");
					}
				} else if (Geeklog.autosave._type === "staticpages") {
					if (name === "sp_content") {
						retval = Geeklog.autosave._getFCKeditorContent("sp_content");
					}
				}
			}
		}
	}
	
	return retval;
};
	
// Copy the value of HTML tags and return the number of valid tags
Geeklog.autosave._saveContents = function() {
	var nValidNames = 0;
	
	for (var name in Geeklog.autosave._targets[Geeklog.autosave._type]) {
		var content = Geeklog.autosave._fetchContent(name);
		if (content !== false) {
			nValidNames ++;
			Geeklog.autosave._targets[Geeklog.autosave._type][name] = content;
		}
	}
	
	return nValidNames;
};
	
// Return data for posting
Geeklog.autosave._preparePostParams = function()
{
	var result = "apikey=" + Geeklog.autosave._apikey
			   + "&type=" + Geeklog.autosave._type;
	
	for (var name in Geeklog.autosave._targets[Geeklog.autosave._type]) {
		result += "&" + name + "=" + encodeURIComponent(Geeklog.autosave._targets[Geeklog.autosave._type][name]);
	}
	
	return result;
};
	
// Update interval timer
Geeklog.autosave.update = function()
{
	var nValidNames = Geeklog.autosave._saveContents();
	
	/**
	* In case of a story, if "sid" field is NULL or if both "title" and
	* "introtext" fields are NULL, we don't save the story.
	*/
	if (Geeklog.autosave._type == "article") {
		if ((Geeklog.autosave._targets[Geeklog.autosave._type]["sid"] === "")
		 || ((Geeklog.autosave._targets[Geeklog.autosave._type]["title"] === "")
			&& (Geeklog.autosave._targets[Geeklog.autosave._type]["introtext"] === ""))) {
			nValidNames = 0;
		}
	}
	
	if (nValidNames > 0) {
		if (!Core.Ajax({
				url: Geeklog.siteURL + "/admin/plugins/autosave/autosave.php",
				method: "post",
				params: Geeklog.autosave._preparePostParams(),
				onSuccess: function(e) {
					if (/<error>0<\/error>/.test(e.responseText)) {
						Geeklog.autosave._log("autosave.update() succeeded.");
						Geeklog.autosave.showMessage("Saved automatically.");
					} else {
						var temp = /<message>(.*)<\/message>/m.exec(e.responseText);
						Geeklog.autosave._log("autosave.update() failed.  Error msg: " + temp["1"]);
					}
				},
				onFailure: function(e) {
					Geeklog.autosave._log("autosave.update() failed.");
				}
			})) {
			Geeklog.autosave._log("Core.Ajax failed in Geeklog.autosave.update().");
		}
	} else {
		Geeklog.autosave._log("autosave.update(): no content to save.");
	}
};
	
// Clear interval timer
Geeklog.autosave.clear = function()
{
	if (Geeklog.autosave._timer !== null) {
		window.clearInterval(Geeklog.autosave._timer);
		Geeklog.autosave._timer = null;
	}
};
	
// Initialize autosave feature
Geeklog.autosave.init = function()
{
	var uri = window.location.href;
	
	if ((uri.indexOf("story.php") > 0) && (uri.indexOf("mode=edit") > 0)) {
		Geeklog.autosave._type = "article";
	} else if ((uri.indexOf("staticpages/index.php") > 0)
	 && (uri.indexOf("mode=edit") > 0)) {
		Geeklog.autosave._type = "staticpages";
	} else {
		Geeklog.autosave._type = null;
	}
	
	if ((Geeklog.autosave._type !== null) 
	 && (Geeklog.autosave._saveContents() > 0)) {
		if ((Geeklog.autosave.interval < 1) || (Geeklog.autosave.interval > 19)) {
			Geeklog.autosave.interval = 10;
		}
		
		if (Geeklog.autosave.debug) {
			// Save every 5 seconds
			Geeklog.autosave.timer = window.setInterval(Geeklog.autosave.update, 5 * 1000);
		} else {
			Geeklog.autosave.timer = window.setInterval(Geeklog.autosave.update, 60 * 1000 *  Geeklog.autosave.interval);
		}
		Core.addEventListener(window, "unload", Geeklog.autosave.clear);
		Geeklog.autosave._log("Geeklog.autosave initialized.");
	} else {
		Geeklog.autosave._log("Geeklog.autosave not initialized.");
	}
};

Core.start(Geeklog.autosave);

