// +---------------------------------------------------------------------------+
// | Geeklog Autosave 1.0                                                      |
// +---------------------------------------------------------------------------+
// | 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 = true,

// 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,
		"title": null,
		"introtext": null,
		"bodytext": null,
		"postmode": "html"
	},
	
	"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);
	}
};
	
// Return the value of an HTML tag with a given name
Geeklog.autosave._fetchContent = function(name)
{
	var tags = document.getElementsByName(name);
	return (tags.length > 0) ? tags[0].value : false;
};
	
// 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();
	
	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.");
					} 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().");
		}
	}
};
	
// 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) {
		Geeklog.autosave._type = "article";
	} else if (uri.indexOf("staticpages/index.php") > 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;
		}
 		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);
