


//////////////////////////
// Encodable-Standard:
//////////////////////////

var data = new Array(); /* for storing small amounts of data globally (for DOM changes, etc) */

function $(id) { return document.getElementById(id); }

function get_int(value) { var n = parseInt(value); return n == null || isNaN(n) ? 0 : n; }

function setCookie(name, value, hours_to_live, path, domain, secure) {
  var expireDate = "";
  if(hours_to_live)
  {
    expireDate = (new Date((new Date()).getTime() + hours_to_live*3600000)).toGMTString();
  }

  var curCookie = name + "=" + escape(value) +
	((hours_to_live) ? "; expires=" + expireDate : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
	document.cookie = curCookie;
}

function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} else
		begin += 2;
	var end = document.cookie.indexOf(";", begin);
	if (end == -1)
		end = dc.length;
	return unescape(dc.substring(begin + prefix.length, end));
}

function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" + 
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

function schedule_onload_action(newfunc)
{
	var already_scheduled = window.onload;
	if(typeof window.onload != 'function')
	{
		window.onload = newfunc;
	}
	else
	{
		window.onload = function()
		{
			already_scheduled();
			newfunc();
		}
	}
}

function get_selection()
{
	var sel = null;
	if (content.getSelection)
	{
		sel = content.getSelection();
	}
	else if (document.selection)
	{
		sel = document.selection.createRange();
	}
	return sel;
}

function getStyle(el,styleProp) // based on free PPK code.
{
	var x = document.getElementById(el);
	var y = null;
	if (x.currentStyle)
		y = x.currentStyle[styleProp];
	else if (window.getComputedStyle)
		y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);

	if(!y)
	{
		styleProp = convertStyleToCamel(styleProp);

		if (x.currentStyle)
			y = x.currentStyle[styleProp];
		else if (window.getComputedStyle)
			y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
	}

	return y;
}

function getStyleRaw(el,styleProp) // remove "px" from sizes, etc.
{
	var style = getStyle(el,styleProp);
	if(style)
		return style.replace(/px$/,'');
	else
		return 0;
}

function convertStyleToCamel(propertyName)
{
	function lowerToHyphenUpper(match)
	{
		return match.toUpperCase();
	}
	propertyName = propertyName.replace(/-(w)/g, lowerToHyphenUpper);
	return propertyName.replace(/-/g, '');
}

// Developed by Robert Nyman, http://www.robertnyman.com
// Code/licensing: http://code.google.com/p/getelementsbyclassname/
//	
var getElementsByClassName = function (className, tag, elm){
	if (document.getElementsByClassName) {
		getElementsByClassName = function (className, tag, elm) {
			elm = elm || document;
			var elements = elm.getElementsByClassName(className),
				nodeName = (tag)? new RegExp("\b" + tag + "\b", "i") : null,
				returnElements = [],
				current;
			for(var i=0, il=elements.length; i<il; i+=1){
				current = elements[i];
				if(!nodeName || nodeName.test(current.nodeName)) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	else if (document.evaluate) {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = "",
				xhtmlNamespace = "http://www.w3.org/1999/xhtml",
				namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
				returnElements = [],
				elements,
				node;
			for(var j=0, jl=classes.length; j<jl; j+=1){
				classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
			}
			try	{
				elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
			}
			catch (e) {
				elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
			}
			while ((node = elements.iterateNext())) {
				returnElements.push(node);
			}
			return returnElements;
		};
	}
	else {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = [],
				elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
				current,
				returnElements = [],
				match;
			for(var k=0, kl=classes.length; k<kl; k+=1){
				classesToCheck.push(new RegExp("(^|\s)" + classes[k] + "(\s|$)"));
			}
			for(var l=0, ll=elements.length; l<ll; l+=1){
				current = elements[l];
				match = false;
				for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
					match = classesToCheck[m].test(current.className);
					if (!match) {
						break;
					}
				}
				if (match) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	return getElementsByClassName(className, tag, elm);
};


//////////////////////////
// Encodable-CMS:
//////////////////////////

function submit_post_to_CMS()
{
	var error = '';
	if($('cms_post_body') && !$('cms_post_body').value)
		error = "Please enter some page content.";
	else if($('cms_author_field') && !$('cms_author_field').value)
		error = "Please enter your name.";
	else if($('cms_subject_field') && !$('cms_subject_field').value)
		error = "Please enter a subject.";
	else if($('cms_pageaddress_field') && !$('cms_pageaddress_field').value)
		error = "Please enter the page address.";

	if(error)
		alert(error);
	else
		$('cms_posting_form').submit();
}

function toggleSpellcheck(newstate)
{
	setCookie('spellcheck', newstate, 99999);
	location.reload();
}

function ebtextbold()
{
	//var field	= document.getElementById("cms_post_body");
	//var start	= field.selectionStart
	//var end	= field.selectionEnd;
	//var len	= field.length;
	//var text	= field.value.substring(start, end);
	//field.value	= field.value.substring(0,start) + '[b]' + text + '[/b]' + field.value.substring(end,len);
	//field.focus();
	//return false;

	var input = prompt("Enter the text that should be bolded:", "your text here");
	if(input)
		document.getElementById("cms_post_body").value += ' [b]' + input + '[/b]';
}

function ebtextitalic()
{
	var input = prompt("Enter the text that should be italicized:", "your text here");
	if(input)
		document.getElementById("cms_post_body").value += ' [i]' + input + '[/i]';
}

function ebtextunderline()
{
	var input = prompt("Enter the text that should be underlined:", "your text here");
	if(input)
		document.getElementById("cms_post_body").value += ' [u]' + input + '[/u]';
}

function ebtextquote()
{
	document.getElementById("cms_post_body").value += "\n[quote=\"name of author goes here\"]\ntext of quote goes here\n[/quote]\n";
}

function ebinslink()
{
	var text = document.getElementById("cms_post_body");
	var linkURL = prompt("Enter the URL (address) for the link:", "http://");
	var linktext = prompt("Enter the text for the link:", "your text here");
	var num = 1;
	while(text.value.indexOf('][' + num + ']') != -1)
		num++;
	if(linktext && linkURL)
		text.value += ' [' + linktext + '][' + num + '] ' + "\n\n" + '[' + num + ']: ' + linkURL + "\n";
}

function ebinsobject(obtype)
{
	var text = document.getElementById("cms_post_body");
	var input = '';
	var tag = '';
	if(obtype == 'file')
	{
		input = prompt("Enter the text for the link to the file:", "your text here");
		tag = '[[file="' + input + '"]]';
	}
	else
	{
		// we use double-brackets only during the posting process, not during storage.
		tag = "[[" + obtype + "]]";
	}
	var showed_warning = 0;
	if(text.value.indexOf("[" + obtype) != -1)
		showed_warning = 1;
	text.value += "\n" + tag + "\n";
	if(!showed_warning)
		alert("Inserting the " + obtype + " tag now; you will be prompted to upload your " + obtype + " at the end of the posting process.");
}


//////////////////////////
// Encodable-Other:
//////////////////////////




var _startX = 0;            // mouse starting positions
var _startY = 0;
var _offsetX = 0;           // current element offset
var _offsetY = 0;
var _dragElement;           // needs to be passed from on_mouse_down to on_mouse_move
var _oldZIndex = 0;         // we temporarily increase the z-index during drag
var encdebug = null;

var draggerWidth	= 0;
var draggerHeight	= 0;

function init_drag_drop()
{
	if($('textbox_resizer'))
	{
		draggerWidth  = $('textbox_resizer').offsetWidth;
		draggerHeight = $('textbox_resizer').offsetHeight;
	}

	//document.onmousedown = on_mouse_down;
	var draghandles = getElementsByClassName("dragger");
	for(i=0; i<draghandles.length; i++)
		draghandles[i].onmousedown = on_mouse_down;

	//document.onmouseup = on_mouse_up;
	//encdebug = $("encdebug");
}

function on_mouse_down(e)
{
	if(!e) var e = window.event;
	var target = e.target != null ? e.target : e.srcElement;

	if(encdebug)
	{
		//encdebug.innerHTML = target.className.match(/dragger/)
		//	? 'draggable element clicked' 
		//	: 'NON-draggable element clicked';
	}

	// in IE, left click == 1; in Firefox, left click == 0.
	//
	// Also don't bother checking the class because we're only setting on_mouse_down
	// on elements with the proper class in the first place.
	//
	//if((e.button == 1 && window.event != null || e.button == 0) && target.className.match(/dragger/))
	//
	if((e.button == 1 && window.event != null || e.button == 0))
	{
		// grab the mouse position
		_startX = e.clientX;
		_startY = e.clientY;

		// grab the clicked element's position
		_offsetX = get_int(target.offsetLeft);
		_offsetY = get_int(target.offsetTop);

		if(encdebug)
			encdebug.innerHTML = '(' + _offsetX + ', ' + _offsetY + ')';   

		// bring the clicked element to the front while it is being dragged
		_oldZIndex = target.style.zIndex;
		target.style.zIndex = 10000;

		// we need to access the element in on_mouse_move
		_dragElement = target;

		// tell our code to start moving the element with the mouse
		document.onmousemove = on_mouse_move;
		document.onmouseup = on_mouse_up;

		// cancel out any text selections
		document.body.focus();

		// prevent text selection in IE
		document.onselectstart = function () { return false; };
		// prevent IE from trying to drag an image
		target.ondragstart = function() { return false; };

		// prevent text selection (except IE)
		return false;
	}
}

function on_mouse_move(e)
{
	if(!e) var e = window.event;

	var left = _offsetX + e.clientX - _startX;
	var top  = _offsetY + e.clientY - _startY;

	_dragElement.style.left = left + 'px';
	_dragElement.style.top  = top + 'px';

	var wrapperWidth  = left + draggerWidth;
	var wrapperHeight = top + draggerHeight;

	$('pftextbox').style.width  = wrapperWidth + 'px';
	$('pftextbox').style.height = wrapperHeight + 'px';

	// TODO: determine why these are all off by one:
	var textareaWidth  = wrapperWidth - getStyleRaw('pftextbox','border-left-width') - getStyleRaw('pftextbox','border-right-width') - getStyleRaw('cms_post_body','padding-left') - getStyleRaw('cms_post_body','padding-right') + 1;
	var textareaHeight = wrapperHeight - getStyleRaw('pftextbox','border-top-width') - getStyleRaw('pftextbox','border-bottom-width') - getStyleRaw('cms_post_body','padding-top') - getStyleRaw('cms_post_body','padding-bottom') + 1;
	var controlsWidth  = wrapperWidth - getStyleRaw('pfcontrols','border-left-width') - getStyleRaw('pfcontrols','border-right-width') + 2;

	$('pfcontrols').style.width  = controlsWidth + 'px';
	$('cms_post_body').style.width  = textareaWidth + 'px';
	$('cms_post_body').style.height = textareaHeight + 'px';


	if(encdebug)
	{
		//encdebug.innerHTML = '(' + _dragElement.style.left + ', ' + dragElement.style.top + ')';
		//encdebug.innerHTML += 'wrapperWidth=' + wrapperWidth + ', wrapperHeight=' + wrapperHeight;
		//encdebug.innerHTML += '<br><br>' + 'textareaWidth=' + textareaWidth + ', textareaHeight=' + textareaHeight;
	}
}

function on_mouse_up(e)
{
	if (_dragElement != null)
	{
		_dragElement.style.zIndex = _oldZIndex;

		// we're done with these events until the next on_mouse_down
		document.onmousemove = null;
		document.onmouseup = null;
		document.onselectstart = null;
		_dragElement.ondragstart = null;

		// this is how we know we're not dragging      
		_dragElement = null;

		if(encdebug)
			encdebug.innerHTML = 'mouse up';
	}
}







function init_textarea_resizer()
{
	if(!(   $("cms_post_body") && $("pftextboxes") && $("textbox_resizer")   ))
		return;

	//$("textbox_resizer").
}



function autofill_human_test()
{
	//var htfield = document.getElementById("fcht2");
	//if(htfield)
	//{
	//	htfield.value = '236721';
	//}

	// Must use a loop, in case there are multiple forms on the same page, each with its
	// own human test, such as on the blog preview page, where one form lets you submit
	// the final post and a second form lets you modify and re-preview the post.
	var i = 0;
	while(theform = document.forms[i++])
	{
		var htfield = theform.elements['fcht2'];
		if(htfield)
		{
			htfield.value = '236721';
		}
	}
}




schedule_onload_action(init_textarea_resizer);
schedule_onload_action(init_drag_drop);
schedule_onload_action(autofill_human_test);


