/* ---------------------------
   ---- ELEMENT FUNCTIONS ----
   --------------------------- */

/* Quick Get Element By ID */
function $(obj) {
	var to_get = document.getElementById(obj);
	if( to_get )
		return to_get;
}

/* Get Elements By ClassName */
function getElementsByClassName(oElm, strTagName, strClassName){
    var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    for(var i = 0, oElement; oElement = arrElements[i]; i++){
        if(oRegExp.test(oElement.className))
            arrReturnElements.push(oElement);
    }
    return (arrReturnElements)
}

/* Add Class Name to Element */
function addClassName (elem, className) {
    removeClassName (elem, className);
    elem.className = (elem.className + " " + className).trim();
}

/* Remove Class Name from Element */
function removeClassName (elem, className) {
    elem.className = elem.className.replace(className, "").trim();
}

/* Check if Element Contains Class Name */
function hasClassName (elem, className ) {
	if( elem.className )
		elem.className.indexOf(className) >= 0 ? has = true : has = false;
	else
		has = false;
	return has;
}


/* Whitespace Checker for DOM */
var wspace = {
	testF : function(elem){
		var wspace = /[^\t\n\r ]/
		if(!wspace.test(elem.data)){ return elem.nextSibling; }else{ return elem; }
	},
	testB : function(elem){
		var wspace = /[^\t\n\r ]/
		if(!wspace.test(elem.data)){ return elem.previousSibling; }else{ return elem; }
	}
}



/* ---------------------------
   ----- EVENT FUNCTIONS -----
   --------------------------- */

/* Add Event Listeners */
function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}
var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();

/* Remove Event Listeners */
function removeEvent( obj, type, fn ) {
	if ( obj.detachEvent ) {
		obj.detachEvent( 'on'+type, obj[type+fn] );
		obj[type+fn] = null;
	} else
		obj.removeEventListener( type, fn, false );
} 
addEvent(window,'unload',EventCache.flush);



/* -------------------------------
   ----- PROTOTYPE FUNCTIONS -----
   ------------------------------- */

/* Trim String Whitespace */
String.prototype.trim = function() {
    return this.replace( /^\s+|\s+$/, "" );
}

/* Merge Two Arrays */
Array.prototype.assCon = function(theArray){
  var retArr = new Array();
  for(var elem in this){
    if(isNaN(elem) && elem!="assCon"){
      retArr[elem] = this[elem];
    }
  }
  for(var elem in theArray){
    if(isNaN(elem) && elem!="assCon"){
      retArr[elem] = theArray[elem];
    }
  }
  return retArr;
}

/* Check if Item is in Array */
Array.prototype.inArray = function(value) {
	for (var i=0; i < this.length; i++) {
		if (this[i] === value)
			return i;
	}
	return false;
};

/* Convert HTML Collections to Actual Arrays */
function $c(array){
	var nArray = [];
	for (var i=0;i<array.length;i++) nArray.push(array[i]);
	return nArray;
}

/* Step through Array */
Array.prototype.iterate = function(func){
	for(var i = 0, e; e = this[i]; i++ ) func(e, i);
}
if (!Array.prototype.each) Array.prototype.each = Array.prototype.iterate;



/* -------------------------------
   ----- COSMETIC FUNCTIONS ------
   ------------------------------- */

/* Repair PNG Files for IE */
function correctPNG() {
	for(var i=0; i<document.images.length; i++) {
		var img = document.images[i]
		var imgName = img.src.toUpperCase()
		if (imgName.substring(imgName.length-3, imgName.length) == "PNG") {
			var imgID = (img.id) ? "id='" + img.id + "' " : ""
			var imgClass = (img.className) ? "class='" + img.className + "' " : ""
			var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
			var imgStyle = "display:inline-block;" + img.style.cssText 
			if (img.align == "left") imgStyle = "float:left;" + imgStyle
			if (img.align == "right") imgStyle = "float:right;" + imgStyle
			if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle		
			var strNewHTML = "<span " + imgID + imgClass + imgTitle
			+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
			+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
			+ "(src=\'" + img.src + "\', sizingMethod='image');\"></span>" 
			img.outerHTML = strNewHTML
			i = i-1
		}
	}
	// Added IE Loads
	rolloversIE.init();
}

/* Show Rollovers for Any Image, including PNG */
var rolloversIE = {
	init : function() {
		var spans = $c(document.getElementsByTagName('span'));
		spans.each( function(span){ rolloversIE.preload(span);} );
	},
	preload : function(e) {
		if( hasClassName(e, 'rollover') ) {
			var img = new Image, filter = e.style.filter;
			var src = filter.substring( filter.indexOf("src='") + 5, filter.indexOf("',"));
			img.src = src.substring(0, src.length - 4) + '_over' + src.substring(src.length - 4, src.length);
			addEvent(e,'mouseover',rolloversIE.show);
			addEvent(e,'mouseout',rolloversIE.hide);
		}
	},
	show : function(e) {
		var filter = this.style.filter;
		var src = filter.substring( filter.indexOf("src='") + 5, filter.indexOf("',"));
		var ext = src.substring(src.length - 4, src.length);
		var name = src.substring(0, src.length - 4);
		this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader" + "(src=\'" + name + '_over' + ext + "\', sizingMethod='image')";
	},
	hide : function(e) {
		var filter = this.style.filter;
		var src = filter.substring( filter.indexOf("src='") + 5, filter.indexOf("',"));
		this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader" + "(src=\'" + src.replace('_over','') + "\', sizingMethod='image')";
	}
}

var rollovers = {
	obj : Object,
	init : function() {
		var overs = $c(document.getElementsByTagName('img'));
		overs.each( function(over){	rollovers.preload(over);} );
	},
	preload : function(e) {
		if( hasClassName(e, 'rollover') ) {
			var img = new Image, src = e.src;
			img.src = src.substring(0, src.length - 4) + '_over' + src.substring(src.length - 4, src.length);
			addEvent(e,'mouseover',rollovers.show);
			addEvent(e,'mouseout',rollovers.hide);
		}
	},
	show : function(e) {
		var ext = this.src.substring(this.src.length - 4, this.src.length);
		var name = this.src.substring(0, this.src.length - 4);
		this.src = name + '_over' + ext;
	},
	hide : function(e) {
		this.src = this.src.replace('_over','');
	}
}
   
/* Add a PNG "Frame" to any image */
function pngFrame(dir) {
	for( var i = 0, img; img = document.getElementsByTagName('img')[i]; i++ ) {
		if( img.className.indexOf('frame') > -1 ) {
			img.style.background = "url(" + img.src + ")";
			img.src = png_frame;
		}
	}
}

/* Sidebar Navigation Inputs */
var navsideFocus = {
	init: function() {
		var navside = $('navside');
		if( navside )
			var inputs = getElementsByClassName(navside,'input','bg');
		if( inputs )
			for( var i = 0, input; input = inputs[i]; i++ ) {
				addEvent(input,'focus',this.show);
				addEvent(input,'blur',this.hide);
			}
	},
	show : function() {
		addClassName(this,'focus');
	},
	hide : function() {
		removeClassName(this,'focus');
	}
}


/* ----------------------------
   -------- SEARCH FORM -------
   ---------------------------- */
var sitesearch = {
	init : function() {
		var input = $('searchinput');
		if( input ) {
			addEvent(input,'focus',this.active);
			addEvent(input,'blur',this.off);
		}
	},
	active : function() {
		if( this.value == 'Enter Search Keyword')
			this.value = '';
	},
	off : function() {
		if( this.value == '' )
			this.value = 'Enter Search Keyword';
	}
}
addEvent(window,'load',function(){ sitesearch.init(); });


/* ---------------------------
   --- USABILITY FUNCTIONS ---
   --------------------------- */

/* Deactivate "#" Dummy Links */
function linkBreaker() {
	for( var i = 0, a; a = document.getElementsByTagName('a')[i]; i++ ) {
		var to_go = a.getAttribute('href');
		switch(to_go) {
			case "#nogo" :
			case "#" :
				a.onclick = function(){ return false; }; break;
		}
	}
}

/* Open Links (with class="out") in a New Window */
function outLinks(){
	var outs = getElementsByClassName(document,'a','out');
	for( var i = 0, out; out = outs[i]; i++ ) {
		out.target = "_blank";
	}
}

/* Smooth Scroll Back to Top */
function backToTop() {
    var x1 = x2 = x3 = 0;
    var y1 = y2 = y3 = 0;

    if (document.documentElement) {
        x1 = document.documentElement.scrollLeft || 0;
        y1 = document.documentElement.scrollTop || 0;
    }

    if (document.body) {
        x2 = document.body.scrollLeft || 0;
        y2 = document.body.scrollTop || 0;
    }

    x3 = window.scrollX || 0;
    y3 = window.scrollY || 0;

    var x = Math.max(x1, Math.max(x2, x3));
    var y = Math.max(y1, Math.max(y2, y3));

    window.scrollTo(Math.floor(x / 2), Math.floor(y / 2));

    if (x > 0 || y > 0)
        window.setTimeout("backToTop()", 25);
}

/* Window Popups By Class Name (class="popup ###x###") */
var popWindows = {
	id : 0,
	init: function() {
		var links = getElementsByClassName(document,'a','popup');
		this.id = Math.ceil(Math.random()*10);
		for( var i = 0, lnk; lnk = links[i]; i++ ) {
			addEvent(lnk,'click',popWindows.run);
			lnk.onclick = function(){ return false; }
		}
	},
	run : function(e) {
		var dimensions = this.className.match(/[0-9]{1,3}x[0-9]{1,3}/) + '';
		var width = dimensions.split('x')[0], height = dimensions.split('x')[1];
		width = width * 1; height = height * 1;
		var page = window.open("" + this.href + "",id,'width=' + width + ', height=' + height);
	}
}

/* Account Settings Form */
var accountChange = {
	ajaxFile : 0,
	output : Object,
	form : Object,
	button : Object,
	save : Object,
	cancel : Object,
	fields : ['current_pw','password1','password2'],
	init : function() {
		this.ajaxFile = 'pages/account.ajax.php';
		this.button = $('settings_button');
		this.form = $('account_settings');
		this.output = $('settings_output');
		this.cancel = $('settings_cancel');
		this.save = $('settings_save');
		
		if( this.button )
			addEvent(this.button,'click',this.toggle);
		if( this.save )
			addEvent(this.save,'click',this.adjust);
		if( this.cancel )
			addEvent(this.cancel,'click',this.doCancel);
	},
	toggle : function(e) {
		if( accountChange.form.style.display == 'none' || !accountChange.form.style.display )
			accountChange.form.style.display = 'block';
		else
			accountChange.form.style.display = 'none';
	},
	doCancel : function(e) {
		for( var i = 0, field; field = accountChange.fields[i]; i++ ) {
			field.value = '';
		}
		accountChange.form.style.display = 'none'
	},
	adjust : function(e) {
		var args = 'current=' + $('current_pw').value + '&new1=' + $('password1').value + '&new2=' + $('password2').value;
		
		var opt = {
			method: 'post',
			postBody: args,
			onLoading : function(t) {	accountChange.output.innerHTML = 'Loading...';	},
			onSuccess: function(t) {
				if( t.responseText == 'Settings saved!' )
					accountChange.doCancel();
				accountChange.output.innerHTML = '<p>' + t.responseText + '</p>';
			},
			on404: function(t) {	accountChange.output.innerHTML = t.statusText	},
			onFailure: function(t) {	accountChange.output.innerHTML = 'Error ' + t.status + ' -- ' + t.statusText;	}
		}
		new Ajax.Request(accountChange.ajaxFile,opt);
	}
}

/* Go To URL */
function goTo(url) {
	window.location.href = url;
}

/* Manage Cookies */
var cookies = {
	set : function(name, value, expires, path, domain, secure ) {
		var today = new Date();
		today.setTime( today.getTime() );
		if ( expires )
			expires = expires * 1000 * 60 * 60 * 24;
		var expires_date = new Date( today.getTime() + (expires) );
		document.cookie = name+'='+escape( value ) +
			( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
			( ( path ) ? ';path=' + path : '' ) +
			( ( domain ) ? ';domain=' + domain : '' ) +
			( ( secure ) ? ';secure' : '' );
	},
	get : function(name) {
		var start = document.cookie.indexOf( name + "=" );
		var len = start + name.length + 1;
		if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
			return null;
		}
		if ( start == -1 ) return null;
		var end = document.cookie.indexOf( ';', len );
		if ( end == -1 ) end = document.cookie.length;
		return unescape( document.cookie.substring( len, end ) );
	},
	remove : function(name, path, domain) {
		if ( cookies.get( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
	}
}


/* ---------------------------
   ------ AJAX FUNCTIONS -----
   --------------------------- */

function ahah(url, target, delay) {
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
  	try {
		req = new ActiveXObject("Msxml2.XMLHTTP");
	} catch(e) {
		try {
			req = new ActiveXObject("Microsoft.XMLHTTP");
		} catch(e) {
			req = false;
		}
	}
  }
  if (req != undefined) {
    req.onreadystatechange = function() {ahahDone(url, target, delay);};
    req.open("GET", url, true);
    req.send("");
  }
}  

function ahahDone(url, target, delay) {
  if (req.readyState == 4) { // only if req is "loaded"
    if (req.status == 200) { // only if "OK"
      document.getElementById(target).innerHTML = req.responseText;
    } else {
      document.getElementById(target).innerHTML="ahah error:\n"+req.statusText;
    }
    if (delay != undefined) {
       setTimeout("ahah(url,target,delay)", delay); // resubmit after delay
	    //server should ALSO delay before responding
    }
  }
}



/* ---------------------------
   ------ LOAD FUNCTIONS -----
   --------------------------- */

if( navigator.userAgent.indexOf('MSIE') > 0 )
	addEvent(window,'load',correctPNG);		// Fix Transparent PNGs for IE
addEvent(window,'load',outLinks);			// Open Links in a New Window
addEvent(window,'load',pngFrame);			// Apply PNG Frame to Images
addEvent(window,'load',popWindows.init);	// Open pop-up windows by class
addEvent(window,'load',rollovers.init);		// Add Rollovers to Images
addEvent(window,'load',function(){ accountChange.init() });		// Account settings for subscribers
addEvent(window,'load',function(){ navsideFocus.init() });
