/*****************************************************************
	File:   	blog.js
	Author:	barclay loftus
	
	Copyright (c) 2003-2007, barclay loftus (barclay@distinctpixel.org)
	
	This file is provided "as is" with no expressed or implied warranty.
	The author accepts no liability if it causes any damage whatsoever.
	This code is free and may be used in any way you desire. If the source code in 
	this file is used in any commercial application then a simple email would be 
	nice.
	
	$LastChangedDate: 2007-08-31 14:05:17 -0700 (Fri, 31 Aug 2007) $
	$Rev:$
	$Author:$
	
****************************************************************/

/*****************************************************************
*  setupIndexPage()
****************************************************************
*/
function setupIndexPage() {
	bgImageSelect();
}

/*****************************************************************
*  bgImageSelect()
*  Sets the background image for the page. 
****************************************************************
*/
function bgImageSelect() {
	var imageStyles = new Array();
	imageStyles[0] = "dancing";
	imageStyles[1] = "shoe";
	imageStyles[2] = "sky";
	imageStyles[3] = "canyon";
	
	// get the current index from the cookie; 
	// we're going to walk through the array linearly. 
	var imgIndex = eval(getCookie("bgImageStyle"));
	
	if(imgIndex>=imageStyles.length || imgIndex=="" || imgIndex==null){
		imgIndex=0;
	}
	setCookie("bgImageStyle", imgIndex + 1);
	
	// now let's set the elements to the new classname
	document.getElementById("innerContainer").className = imageStyles[imgIndex];
	document.getElementById("innerEntry").className = imageStyles[imgIndex];
	document.getElementById("entryControls").className = imageStyles[imgIndex];
}

function historyPop(){
	var h = document.historyForm.historySelect.value;
	var qs; 
	var n;

	if(h.indexOf(",") != -1){
		qs="history";
	} else {
		qs="id";
	}
	
	if(h==null || h.length < 1) {
		//wait... we might do something else here...
		//n= "/?";
	} else {
		a = h.split(",");
		n = "/entries/history/" + a[1] + "/" + a[0];
		//alert(n);
		document.location = n;
	}
}

function searchHighlight(obj, searchStr){
	var searchAry 	= new Array();
	searchAry  		= cleanSearchStr(searchStr);
	for (var i=0; i<searchAry.length; i++){
		if(searchAry[i].toLowerCase() != "and" && searchAry[i].toLowerCase() != "or") {
			wordhighlight(obj, searchAry[i]);
		}
	}
}

function cleanSearchStr(searchStr){
	var badChars 	= ".,='|*";
	var charAry 	= new Array;
	var searchAry 	= new Array;
	badChars 		= badChars + '";';
	charAry 		= badChars.split("");

	for(var i=0; i< charAry.length; i++)
		searchStr = searchStr.replace(charAry[i], "");
	
	// replace the +'s and 	trim the string
	//
	searchStr = searchStr.replace("+", " ");
	searchStr = Trim(searchStr);
	
	// split it, and return the array...
	//
	return searchStr.split(" ");
}

function wordhighlight(aSourceObject, aWords){
	// Extract HTML Tags
	//
	regexp		= /<[^<>]*>/ig;
	vHTMLArray 	= aSourceObject.innerHTML.match(regexp);
	
	// Replace HTML tags
	//
	vStrippedHTML = aSourceObject.innerHTML.replace(regexp,"$!$");

	//alert(vStrippedHTML);

	// Replace search words
	//
	regexp	= new RegExp ("(" + aWords + ")", "gi");
	vTemp 	= vStrippedHTML.replace(regexp,'<span class="search_highlight">$1</span>');
	
	// Now, let's re-insert HTML back
	//
	for(var i=0;vTemp.indexOf("$!$") > -1;i++)
		vTemp = vTemp.replace("$!$", vHTMLArray[i]);
	
	aSourceObject.innerHTML = vTemp;
}

function LTrim(str) {
   var whitespace = new String(" \t\n\r");
   var s = new String(str);

   if (whitespace.indexOf(s.charAt(0)) != -1) {
      // We have a string with leading blank(s)...
      var j=0, i = s.length;
      // Iterate from the far left of string until we
      // don't have any more whitespace...
      while (j<i && whitespace.indexOf(s.charAt(j)) != -1)
         j++;
      s = s.substring(j, i);
   }
   return s;
}

function RTrim(str){
   var whitespace = new String(" \t\n\r");
   var s = new String(str);

   if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
      var i = s.length - 1;       // Get length of string
      while (i>=0 && whitespace.indexOf(s.charAt(i)) != -1)
         i--;
      s = s.substring(0, i+1);
   }
   return s;
}

function Trim(str) {
	if (str.length > 1) {
		var newStr = RTrim(LTrim(str));
		//alert(newStr);
		return newStr;
	} else {
		//alert("returning nothing...");
		return "";
	}
}

function setCookie(name, value, expires, path, domain, secure)
{
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

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));
}

// -------------------------------------------------------------------
// validateComment()
//   The basic JS validation for comments. 
// -------------------------------------------------------------------
//
function validateComment() {
	// TODO
}

// -------------------------------------------------------------------
// Globals
// -------------------------------------------------------------------
//
var gDubug		= false;
var gDebugMsg	= "";
var gStartTime;
var gScreenX;
var gScreenY;


function Common() {
	gScreenX = document.body.clientWidth;
	gScreenY = document.body.clientHeight;	
	
	// if the document is shorter, grab the window size...
	//
	if (gScreenY < window.innerHeight){gScreenY = window.innerHeight;} 
	
	_DEBUG("Common(): Screen size is :" + gScreenX + "x" + gScreenY);
}

// -------------------------------------------------------------------
// getObj()
//   The quirksmode DHTML micro api 
// Arguments:
//	 name - the name of the element. 
// -------------------------------------------------------------------
//
function getObj(name) {
	if (document.getElementById) {
		this.obj		= document.getElementById(name);
		this.style		= document.getElementById(name).style;
	} else if (document.all) {
		this.obj		= document.all[name];
		this.style		= document.all[name].style;
	} else if (document.layers) {
		this.obj		= document.layers[name];
		this.style		= document.layers[name];
	}
	this.ClassName		= this.obj.className;
	this.AddClass		= function(className) {AddCssClass(this.obj, className);}
	this.RemoveClass	= function(className) {RemoveCssClass(this.obj, className);}
	this.id				= name;
	this.GetOpacity		= function()  {GetOpacityOfElement(this.obj)};
	this.SetOpacity		= function(p) {SetOpacityOfElement(this.obj, p);}
}

// -------------------------------------------------------------------
// GetOpacityOfElement()
//   Gets an int value (0-100) that represent's an element's opacity 
// Arguments:
//	 el - the element to examine. 
// -------------------------------------------------------------------
//
function GetOpacityOfElement(el) {
	// first, let's try and get the "filter" value from IE
	//
	if (el.style.filter) {
		var filterStr = el.style.filter;
		if (filterStr == null || filterStr == "") {
			_DEBUG("GetOpacityOfElement(): No opacity declared in " + el.id + ", returning 100");
			SetOpacityOfElement(el, 100);
			return 100;
		}
		
		var ary = filterStr.split("=");
		var op	= parseInt(ary[1].substring(0, ary[1].length -1));
		_DEBUG("GetOpacityOfElement(): Returning opacity: " + el.id + " is: " + op);
		return op;
	
	// otherwise, let's use the mozilla/safari "opacity" value
	//
	} else {
		var opacityStr 	= el.style.opacity || el.style.MozOpacity ||  el.style.KhtmlOpacity;
		if (opacityStr == null || opacityStr == "") {
			_DEBUG("GetOpacityOfElement(): No opacity declared in " + el.id + ", returning 100");
			SetOpacityOfElement(el, 100);
			return 100;
		}
		
		var op = opacityStr * 100;
		_DEBUG("GetOpacityOfElement(): Returning opacity: " + el.id + " is: " + op);
		return op;
	}
}

// -------------------------------------------------------------------
// SetOpacityOfElement()
//   Sets the opacity of an object using an int value (0-100) 
// Arguments:
//	 e - the element to examine. 
//	 percent - an int, (0-100) that represents the opacity value to set
// -------------------------------------------------------------------
//
function SetOpacityOfElement(e, percent) {
	_DEBUG("SetOpacityOfElement(): Setting opacity of " + e.id + " to " + percent);
	e.style.filter 		= "alpha(opacity=" + percent + ")";
	e.style.opacity 	= percent/100;
	e.style.MozOpacity	= percent/100;
	e.style.KhtmlOpacity= percent/100;	
}

// -------------------------------------------------------------------
// createInput()
//   Creates HTML input elements since IE is broken 
// Arguments:
//	 type - the type of input to create
//   id - the HTML id of the new element.
// -------------------------------------------------------------------
//
function CreateInput(type, id) {
	var element = null;

	// First try the IE way; if this fails then use the standard way
	//
	try {
		element		= document.createElement("<input type=\"" + type + "\" id=\""+id+"\" name=\"" + id + "\">");
	// Probably failed because we’re not running on IE, so do it the normal way
	//
	} catch (e) {
		element		= document.createElement("input");
		element.id  = id;
		element.name= id;
		element.setAttribute("type", type);
	}
	return element;
}

// -------------------------------------------------------------------
// focus()
// Arguments:
//   id :  id of the element
// -------------------------------------------------------------------
//
function focusThis(id) {
	var e = document.getElementById(id);
	e.focus();
}

// -------------------------------------------------------------------
// GetElementsLeftPosition()
//   Gets the x coordinate for a given element
// Arguments:
//	 obj - the HTML element.
// -------------------------------------------------------------------
//
function GetElementsLeftPosition(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	} else if (obj.x)
		curleft += obj.x;
	return curleft;
}

// -------------------------------------------------------------------
// GetElementsTopPosition()
//   Gets the y coordinate for a given element
// Arguments:
//	 obj - the HTML element.
// -------------------------------------------------------------------
//
function GetElementsTopPosition(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	} else if (obj.y)
		curtop += obj.y;
	return curtop;
}

// -------------------------------------------------------------------
// GetOffsetTop()
//   Gets the height for a given element
// Arguments:
//	 obj - the HTML element.
// -------------------------------------------------------------------
//
function GetOffsetTop(obj) {
	var cur = 0;
	if(obj.offsetParent) {		
		while(obj.offsetParent) {
			cur += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}		
	return cur;
}

// -------------------------------------------------------------------
// AddEvent()
//   Attaches an event listener to an object. 
//	 This isn't a 100% reliable method, but for simple elements 
//   (anchors, and what not) it should work fine. 
// Arguments:
//	 element - the HTML element to attach the event listener to
///	 mozillaEvent - the name of the eventLister for mozilla and safari
//   ieEvent - the name of the stupid IE event 
//	 f - 
// -------------------------------------------------------------------
//
function AddEvent(element, mozillaEvent, ieEvent, f) {

	// mozilla
	//
	if (navigator.userAgent.toLowerCase().indexOf("msie")==-1) {
		element.addEventListener(mozillaEvent,f, false);
	}
	// ie
	//
	else {
		element.attachEvent(ieEvent,f);
	}
}

// -------------------------------------------------------------------
// RemoveCssClass()
//   Removes a CSS class from an HTML element. 
// Arguments:
//	 element - the element with the class to remove
//	 className - the className to remove
// -------------------------------------------------------------------
//
function RemoveCssClass(element, className) {
	var regExStr = Trim(className) + "\\b";
	if (element.className.indexOf(className) != -1) {
		element.className = element.className.replace(new RegExp(regExStr), "");
	}
}

// -------------------------------------------------------------------
// AddCssClass()
//   Adds a CSS class from an HTML element. 
// Arguments:
//	 element - the element
//	 className - the className to add
// -------------------------------------------------------------------
//
function AddCssClass(element, className) {
	var newClassStr = " " + className;
	if (element.className.indexOf(className) == -1) {
		element.className += newClassStr;
	}
}

// -------------------------------------------------------------------
// _DEBUG()
//   Allows you to make trace statements in js
// Arguments:
//	 message: printf, baby, printf. 
// -------------------------------------------------------------------
//
function _DEBUG(message) {
	if (gDubug) {
		var dbgBox;
		var output = _DEBUGFormatMessage(message);
		if (!document.getElementById("debugOutput")) {
			if (!document.getElementById("dbg")) {
				gDebugMsg = output + gDebugMsg;
			} else {
				dbgBox = document.createElement("textarea");
				dbgBox.setAttribute("id", "debugOutput");
				//dbgBox.setAttribute("style", "width: 700px; height:200px;");
				dbgBox.style.height = "150px";
				dbgBox.style.width  = "700px";
				dbgBox.value = _DEBUGFormatMessage("Creating debug output window") + gDebugMsg;
				document.getElementById('dbg').appendChild(dbgBox);
			}
		} else {
			dbgBox = document.getElementById("debugOutput");
			dbgBox.value = output + dbgBox.value;
		}
	}
}

// -------------------------------------------------------------------
// _DEBUGFormatMessage()
//   formats the debug statements. 
// Arguments:
//	 message: printf, baby, printf. 
// -------------------------------------------------------------------
//
function _DEBUGFormatMessage(message) {
	if (gStartTime == null) {gStartTime = new Date();}
	var now			= new Date();
	var dateDiff	= now - gStartTime;
	var output		= "" + now.getHours() + ":" + now.getMinutes() + ":"	+ now.getSeconds() + " " + now.getMilliseconds() + " : " + message + " (" + dateDiff + "ms)\n";
	return output;
}

_DEBUG("Completed loading Common.js...");
