/**
 * Autosave jQuery plugin
 *
 * Copyright (c) 2008 Rik Lomas (rikrikrik.com)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
;(function(j$) {
	j$.fn.autosave = function(options) {
		var opts = j$.extend({}, j$.fn.autosave.options, options);
		j$.fn.autosave.options = opts;
		var ev = false;
		var doSave = false;
		var ti = 0;
		var ci = 0;
		var ri = 0;

		function setEvents ()
		{
			j$( j$.fn.autosave.options.saving ).hide();
			
			j$( j$.fn.autosave.options.autosave ).click(function () {
				j$.fn.autosave.go();
				return false;
			});
			
			j$( j$.fn.autosave.options.restore ).click(function () {
				j$.fn.autosave.restore();
				return false;
			});
			
			j$( j$.fn.autosave.options.removeCookies ).click(function () {
				j$.fn.autosave.removeAllCookies();
				return false;
			});
		
//			j$(window).unload(function () {
//				j$.fn.autosave.go();
//				return true;
//			});
		
			setInterval(function () {
				if (doSave) {
					j$.fn.autosave.go();	
					doSave = false;
				} 
			}, j$.fn.autosave.options.interval);
			ev = true;
		}
		
		return this.filter(':text, :radio, :checkbox, select, textarea').each(function () {
			if (j$(this).is(':text, textarea')) {
				j$.fn.autosave.values.text[ti] = this;
				j$(this).keyup(function () {
					doSave = true;
				});
				ti++;
			} else if (j$(this).is('select')) {
				j$.fn.autosave.values.text[ti] = this;
				j$(this).change(function () {
					doSave = true;
				});
				ti++;
			} else if (j$(this).is(':checkbox')) {
				j$.fn.autosave.values.check[ci] = this;
				j$(this).click(function () {
					doSave = true;
				});
				ci++;
			} else {
				j$.fn.autosave.values.radio[ri] = this;
				j$(this).click(function () {
					doSave = true;
				});
				ri++;
			}
		
			if (!ev) { setEvents(); }
		});
	};

	j$.fn.autosave.values = {
		'text': {},
		'check': {},
		'radio': {}
	};

	j$.fn.autosave.options = {
		'autosave': '.autosave',
		'restore': '.autosave_restore',
		'removeCookies': '.autosave_removecookies',
		'saving': '.autosave_saving',
		'interval': 2000,
		'unique': '',
		'uniquePathKey': '',
		'onBeforeSave': function () { },
		'onAfterSave': function () { },
		'onBeforeRestore': function () { },
		'onAfterRestore': function () { },
		'cookieCharMaxSize': 400,
		'cookieExpiryLength': 90
	};

	j$.fn.autosave.go = function () {
		
		j$.fn.autosave.options.onBeforeSave();
		
		var m = j$.fn.autosave.values;
		var u = j$.fn.autosave.options.unique;
		
		function saveCookie (i, j, content)
		{
			j$.cookie('autosave_'+i, content, { expires: j$.fn.autosave.options.cookieExpiryLength, path:'/' });
		}

		function removeBiggerCookies (i)
		{
			var j = 1;
			while (j$.cookie('autosave_'+u+i+'_'+j) !== null && j < 2)
			{
				j$.cookie('autosave_'+u+i+'_'+j, null);
			}
		}
	
		for (i in m.text)
		{
			var content;
			var j = 0;
		
			content = j$(m.text[i]).val();
			size = content.length;
		
			if (size < j$.fn.autosave.options.cookieCharMaxSize)
			{
				removeBiggerCookies(i);
				saveCookie(j$(m.text[i]).attr('name'), 0, content);
			}
			else
			{
				removeBiggerCookies(i);
				saveCookie(j$(m.text[i]).attr('name'), j, content.substr(0, j$.fn.autosave.options.cookieCharMaxSize));
//				for (var k = 0; k < size; k += j$.fn.autosave.options.cookieCharMaxSize)
//				{
//					saveCookie(j$(m.text[i]).attr('name'), j, content.substr(k, j$.fn.autosave.options.cookieCharMaxSize));
//					if (j == 1) break;
//					j += 1;
//				}
			}
		}
	
		var cookiecheck = '';
		for (i in m.check)
		{
			if (j$(m.check[i]).attr('checked')) {
				j$.cookie(
					'autosave_'+j$(m.check[i]).attr('name'), 
					j$(m.check[i]).val(), 
					{ expires: j$.fn.autosave.options.cookieExpiryLength, path:'/' }
				);
			}
		}

		var cookieradio = '';
		for (i in m.radio)
		{
			if(j$(m.radio[i]).is(':checked'))
			{
				j$.cookie(
					'autosave_'+j$(m.radio[i]).attr('name'), 
					j$(m.radio[i]).val(), 
					{ expires: j$.fn.autosave.options.cookieExpiryLength, path:'/' }
				);
			}
		}
	
		j$.fn.autosave.saving(); 
		
		j$.fn.autosave.options.onAfterSave();
		
	};

	j$.fn.autosave.removeAllCookies = function () {

		var u = j$.fn.autosave.options.unique;
	
		for (var i = 0; i < 40; i++)
		{
			var j = 0;
			while (j$.cookie('autosave_'+u+i+'_'+j) !== null && j < 2)
			{
				j$.cookie('autosave_'+u+i+'_'+j, null);
				j += 1;
			}
		}
	
		j$.cookie('autosave_'+u+'_check', null);
		j$.cookie('autosave_'+u+'_radio', null);
	};

	j$.fn.autosave.saving = function () {
		j$( j$.fn.autosave.options.saving ).show().fadeTo(1000, 1).fadeOut(500);
	};
	
})(jQuery);
