//This file contains all ccTiddly's plugins that would not exist in standalone version
//The plugins were moved from inside the code to an extra js file is because:
//	1/ allow for caching 
//	2/ ease in reading the code and updating
//	3/ load quicker?
//	4/ avoid overwriting functions that are also used by other plugins (such as saveTiddler)

/////////////////////////////////////////////////////////misc config/////////////////////////////////////////////////
/***
!!!Changing the default options
***/
config.options.chkHttpReadOnly = false;    //make it HTTP writable by default
config.options.chkSaveBackups = false;    //disable save backup
config.options.chkAutoSave = false;    //disable autosave
config.options.chkUploadStoreArea = false;    //use to define whether to upload storeArea when saveChanges is pressed

//config.shadowTiddlers.AdvancedOptions: "<<option chkGenerateAnRssFeed>> GenerateAnRssFeed\n<<option chkOpenInNewWindow>> OpenLinksInNewWindow\n<<option chkSaveEmptyTemplate>> SaveEmptyTemplate\n<<option chkToggleLinks>> Clicking on links to tiddlers that are already open causes them to close\n^^(override with Control or other modifier key)^^\n<<option chkHttpReadOnly>> HideEditingFeatures when viewed over HTTP\n<<option chkForceMinorUpdate>> Treat edits as MinorChanges by preserving date and time\n^^(override with Shift key when clicking 'done' or by pressing Ctrl-Shift-Enter^^\n<<option chkConfirmDelete>> ConfirmBeforeDeleting\nMaximum number of lines in a tiddler edit box: <<option txtMaxEditRows>>\nFolder name for backup files: <<option txtBackupFolder>>\n",
//add uploadstorearea option to allow user to upload all content in storearea when saveChanges is triggered
//config.shadowTiddlers.AdvancedOptions = "<<option chkUploadStoreArea>> UploadStoreArea\n" + config.shadowTiddlers.AdvancedOptions;

/***
!!!Put SiteTitle to webpage title
***/
//window.title = convertUnicodeToUTF8((wikifyPlain("SiteTitle") + " - " + wikifyPlain("SiteSubtitle")).htmlEncode());

/////////////////////////////////////////////////////////remove isDirty popup dialog/////////////////////////////////////////////////

window.confirmExit = function()
{
	hadConfirmExit = true;		//confirm exit since ccT save "on the fly"
}

/////////////////////////////////////////////////////////change title/////////////////////////////////////////////////
window.cct_main = window.main
window.main = function()
{
	window.cct_main();
	//	var newSiteTitle = convertUnicodeToUTF8((wikifyPlain("SiteTitle") + " - " + wikifyPlain("SiteSubtitle")).htmlEncode());
	//document.title = "aa"+convertUnicodeToUTF8((wikifyPlain("SiteTitle") + " - " + wikifyPlain("SiteSubtitle")).htmlEncode());
	document.title=(wikifyPlain("SiteTitle") + " - " + wikifyPlain("SiteSubtitle")).htmlEncode();
}
//document.title="test";
/////////////////////////////////////////////////////////save Tiddler/////////////////////////////////////////////////

TiddlyWiki.prototype.cct_saveTiddler = TiddlyWiki.prototype.saveTiddler;
TiddlyWiki.prototype.saveTiddler = function(title,newTitle,newBody,modifier,modified,tags)
{
	var tiddler = this.fetchTiddler(title);
	//if minorupdate is used, it is possible that a tiddler is accidentally overwrite by another due to collision detection is done via modified date
	if( modified == undefined )
	{
		if(tiddler)
		{
			modified = tiddler.modified;
		}else{
			modified =  new Date();
		}
	}
	var omodified = modified;
	if(tiddler)
	{
		omodified = tiddler.modified; // get original modified date
	}

	tiddler = store.cct_saveTiddler(title,newTitle,newBody,modifier,modified,tags);
document.forms.invisiForm.msg.value = "saveTiddler";
document.forms.invisiForm.oldtitle.value = title;
document.forms.invisiForm.title.value = newTitle;
document.forms.invisiForm.body.value = newBody;
document.forms.invisiForm.modifier.value = modifier;
document.forms.invisiForm.omodified.value = omodified.convertToYYYYMMDDHHMM();
document.forms.invisiForm.modified.value = modified.convertToYYYYMMDDHHMM();
document.forms.invisiForm.tags.value = tiddler.getTags().htmlEncode();		//change suggested by Bram for support of comma separated tags
//document.forms.invisiForm.tags.value = tags;
document.forms.invisiForm.submit();

	clearMessage();
	displayMessage("Tiddler saved");

	return tiddler;
}

/////////////////////////////////////////////////////////removeTiddler/////////////////////////////////////////////////
TiddlyWiki.prototype.cct_removeTiddler = TiddlyWiki.prototype.removeTiddler;
TiddlyWiki.prototype.removeTiddler = function(title)
{
	store.cct_removeTiddler(title);
	document.forms.invisiForm.msg.value = "removeTiddler";
	document.forms.invisiForm.title.value = title;
	//document.forms.invisiForm.modifier.value = config.options.txtUserName;
	document.forms.invisiForm.submit();
}
/////////////////////////////////////////////////////////saveChanges/////////////////////////////////////////////////
window.cct_genRss = function ()
{
	document.forms.invisiForm.msg.value = "rss";
	document.forms.invisiForm.body.value = generateRss();
	document.forms.invisiForm.submit();
}

window.cct_uploadStore = function ()
{
	document.forms.invisiForm.msg.value = "upload";
	document.forms.invisiForm.body.value = allTiddlersAsHtml();
	document.forms.invisiForm.submit();
}


window.saveChanges = function ()
{
	clearMessage();
	var cct_msg = "";
	
	//set delay in saveChanges to allow auto generating RSS/upload store area
	//otherwise it skips generating RSS, possibly because iframe is not ready
	
	// Save Rss
	if(config.options.chkGenerateAnRssFeed)
	{
		setTimeout("window.cct_genRss ()",config.options.txtTimeDelay);
		cct_msg = cct_msg+"Rss generated and saved\n";
	}
	
	//saveChanges (upload the whole storearea)
	if( config.options.chkUploadStoreArea )
	{
		setTimeout("window.cct_uploadStore ()",2*config.options.txtTimeDelay);
		cct_msg = cct_msg+"storeArea uploaded";
	}
	
	if( config.options.chkGenerateAnRssFeed===false && config.options.chkUploadStoreArea===false )
	{
		displayMessage("Nothing happened since option not enabled. Please see AdvanceOptions.");
	}
	else
	{
		displayMessage(cct_msg);
	}
}

/////////////////////////////////////////////////////////password functions/////////////////////////////////////////////////
//used to create login password field. Passwords are encrypted with MD5
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////onChangeOption
//config.macros.option.cct_onChangeOption = config.macros.option.onChangeOption;
config.macros.option.onChangeOption = function(e)
{
	var opt = this.getAttribute("option");
	var elementType,valueField;
	if(opt)
	{
		switch(opt.substr(0,3))
		{
			case "txt":
				elementType = "input";
				valueField = "value";
				break;
			case "chk":
				elementType = "input";
				valueField = "checked";
				break;
			case "pas":
				elementType = "input";
				valueField = "value";
				break;
		}
		if( opt.substr(0,3) == "pas" )
		{
			config.options[opt] = hex_md5(this[valueField]);
		}else{
			config.options[opt] = this[valueField];
		}
		saveOptionCookie(opt);
		var nodes = document.getElementsByTagName(elementType);
		for(var t=0; t<nodes.length; t++)
		{
			var optNode = nodes[t].getAttribute("option");
			if(opt == optNode)
				nodes[t][valueField] = this[valueField];
		}
	}
	return(true);
};
/*
config.macros.option.cct_onChangeOption = config.macros.option.onChangeOption;
config.macros.option.onChangeOption = function(e)
{
	var opt = this.getAttribute("option");
	var elementType,valueField;
	if(opt)
	{
		switch(opt.substr(0,3))
		{
			case "pas":
				elementType = "input";
				valueField = "value";
				break;
			case "txt":
				config.macros.option.cct_onChangeOption(e);
				return (true);
				break;
			case "chk":
				return(config.macros.option.cct_onChangeOption(e));
				return (true);
				break;
		}
		config.options[opt] = hex_md5(this[valueField]);
		saveOptionCookie(opt);
		var nodes = document.getElementsByTagName(elementType);
		for(var t=0; t<nodes.length; t++)
		{
			var optNode = nodes[t].getAttribute("option");
			if(opt == optNode)
				nodes[t][valueField] = this[valueField];
		}

	}

	return(true);
};*/

//////////////////////////////////////////////////option handler
config.macros.option.handler = function(place,macroName,params)
{
	var opt = params[0];
	if(config.options[opt] == undefined)
		return;
	var c;
	switch(opt.substr(0,3))
	{
		case "txt":
			c = document.createElement("input");
			c.onkeyup = this.onChangeOption;
			c.setAttribute("option",opt);
			c.size = 15;
			place.appendChild(c);
			c.value = config.options[opt];
			break;
		case "chk":
			c = document.createElement("input");
			c.setAttribute("type","checkbox");
			c.onclick = this.onChangeOption;
			c.setAttribute("option",opt);
			place.appendChild(c);
			c.checked = config.options[opt];
			break;
		case "pas":
			c = document.createElement("input");
			c.setAttribute("type","password");
			c.onkeyup = this.onChangeOption;
			c.setAttribute("option",opt);
			c.size = 15;
			place.appendChild(c);
			//c.value = config.options[opt];
			c.value = "";		//this is such that the md5 hash wont appear in the password box
			break;
	}
};

//////////////////////////////////////////////////loadOptionsCookie
window.loadOptionsCookie = function()
{
	if(safeMode)
		return;
	var cookies = document.cookie.split(";");
	for(var c=0; c<cookies.length; c++)
	{
		var p = cookies[c].indexOf("=");
		if(p != -1)
		{
			var name = cookies[c].substr(0,p).trim();
			var value = cookies[c].substr(p+1).trim();
			switch(name.substr(0,3))
			{
				case "txt":
					config.options[name] = DecodeCookie(value);//convert from UTF-8 to unicode
					break;
				case "chk":
					config.options[name] = value == "true";
					break;
				case "pas":
					config.options[name] = unescape(value);//does not require decode because it is MD5 hash
					break;
			}
		}
	}
};

//////////////////////////////////////////////////saveOptionCookie
window.saveOptionCookie = function(name)
{
	var c = name + "=";
	var t = "; expires=Fri, 1 Jan 2038 12:00:00 UTC; path=/";

	switch(name.substr(0,3))
	{
		case "txt":
			c += EncodeCookie(config.options[name].toString());//convert from unicode to UTF-8
			break;
		case "chk":
			c += config.options[name] ? "true" : "false";
			break;
		case "pas":
			c += (EncodeCookie(config.options[name].toString()));
			if( config.macros.option.passwordTime!=0 ) //if not using default time, calculate new time
			{
				var date = new Date();
				date.setTime(date.getTime()+config.macros.option.passwordTime*60000);
				t = "; expires="+date.toGMTString()+"; path=/";
			}
		break;
	}
	c += t;
	document.cookie = c;
};

//////////////////////////////////////////////////Reload config file
/***
!!!Reload config file
uncomment it to enable
require variables defined by this time
***/
//window.loadOptionsCookie();

/////////////////////////////////////////////////////////encode and decode cookies///////////////////////////////////////////////////
//functions provided by BramChen
function EncodeCookie(s)
{
	//return escape(manualConvertUnicodeToUTF8(s));
	return escape(manualConvertUnicodeToUTF8(s));
}

function DecodeCookie(s)
{	s=unescape(s);
	var re = /&#[0-9]{1,5};/g;
	return s.replace(re, function($0) {return(String.fromCharCode(eval($0.replace(/[&#;]/g,""))));});
}

/////////////////////////////////////////////////////////MD5 functions/////////////////////////////////////////////////
//obtained from  http://pajhome.org.uk/crypt/md5
///////WARNING: does not work with UTF-8 character at the moment, seem to use different algorithm to PHP ones 
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//variables
config.macros.option.passwordHexcase = 0; //hex output format. 0 - lowercase; 1 - uppercase
config.macros.option.passwordChrsz = 8; //bits per input character. 8 - ASCII; 16 - Unicode

//md5 function
window.hex_md5 = function(s) { return binl2hex(core_md5(str2binl(s), s.length * config.macros.option.passwordChrsz));}

//Calculate the MD5 of an array of little-endian words, and a bit length
window.core_md5 = function (x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }
  return Array(a, b, c, d);

}


//These functions implement the four basic operations the algorithm uses.
window.md5_cmn = function (q, a, b, x, s, t)
{
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
window.md5_ff = function (a, b, c, d, x, s, t)
{
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
window.md5_gg = function (a, b, c, d, x, s, t)
{
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
window.md5_hh = function (a, b, c, d, x, s, t)
{
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
window.md5_ii = function (a, b, c, d, x, s, t)
{
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

//Add integers, wrapping at 2^32. This uses 16-bit operations internally
//to work around bugs in some JS interpreters.
window.safe_add = function (x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

//Bitwise rotate a 32-bit number to the left.
window.bit_rol = function (num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}


//Convert a string to an array of little-endian words
// If config.macros.option.passwordChrsz is ASCII, characters >255 have their hi-byte silently ignored.
window.str2binl = function (str)
{
  var bin = Array();
  var mask = (1 << config.macros.option.passwordChrsz) - 1;
  for(var i = 0; i < str.length * config.macros.option.passwordChrsz; i += config.macros.option.passwordChrsz)
    bin[i>>5] |= (str.charCodeAt(i / config.macros.option.passwordChrsz) & mask) << (i%32);
  return bin;
}

//Convert an array of little-endian words to a hex string.
window.binl2hex = function (binarray)
{
  var hex_tab = config.macros.option.passwordHexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
  }
  return str;
}
