/*
*
* Copyright (c) 2007 Andrew Tetlaw
* 
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* * 
*
*
* FastInit
* http://tetlaw.id.au/view/javascript/fastinit
* Andrew Tetlaw
* Version 1.4.1 (2007-03-15)
* Based on:
* http://dean.edwards.name/weblog/2006/03/faster
* http://dean.edwards.name/weblog/2006/06/again/
* Help from:
* http://www.cherny.com/webdev/26/domloaded-object-literal-updated
* 
*/

var FastInit = {
	onload : function() {
		if (FastInit.done) { return; }
		FastInit.done = true;
		for(var x = 0, al = FastInit.f.length; x < al; x++) {
			FastInit.f[x]();
		}
	},
	addOnLoad : function() {
		var a = arguments;
		for(var x = 0, al = a.length; x < al; x++) {
			if(typeof a[x] === 'function') {
				if (FastInit.done ) {
					a[x]();
				} else {
					FastInit.f.push(a[x]);
				}
			}
		}
	},
	listen : function() {
		if (/WebKit|khtml/i.test(navigator.userAgent)) {
			FastInit.timer = setInterval(function() {
				if (/loaded|complete/.test(document.readyState)) {
					clearInterval(FastInit.timer);
					delete FastInit.timer;
					FastInit.onload();
				}}, 10);
		} else if (document.addEventListener) {
			document.addEventListener('DOMContentLoaded', FastInit.onload, false);
		} else if(!FastInit.iew32) {
			if(window.addEventListener) {
				window.addEventListener('load', FastInit.onload, false);
			} else if (window.attachEvent) {
				return window.attachEvent('onload', FastInit.onload);
			}
		}
	},
	f:[],done:false,timer:null,iew32:false
};

/*@cc_on @*/
/*@if (@_win32)
FastInit.iew32 = true;
document.write('<script id="__ie_onload" defer src="' + ((location.protocol == 'https:') ? '//0' : 'javascript:void(0)') + '"><\/script>');
document.getElementById('__ie_onload').onreadystatechange = function(){if (this.readyState == 'complete') { FastInit.onload(); }};
/*@end @*/
FastInit.listen();


/**--------------------------------------------------------------------------*/ 
// EXTENSIONS TO PROTOTYPE
/**--------------------------------------------------------------------------*/ 

// Extension to Ajax allowing for classes of requests of which only one (the latest) is ever active at a time 
// - stops queues of now-redundant requests building up / allows you to supercede one request with another easily. 
 
// just pass in onlyLatestOfClass: 'classname' in the options of the request 
 
Ajax.currentRequests = {}; 
 
Ajax.Responders.register({ 
    onCreate: function(request) { 
        if (request.options.onlyLatestOfClass && Ajax.currentRequests[request.options.onlyLatestOfClass]) { 
            // if a request of this class is already in progress, attempt to abort it before launching this new request 
            try { Ajax.currentRequests[request.options.onlyLatestOfClass].transport.abort(); } catch(e) {} 
        } 
        // keep note of this request object so we can cancel it if superceded 
        Ajax.currentRequests[request.options.onlyLatestOfClass] = request; 
    }, 
    onComplete: function(request) { 
        if (request.options.onlyLatestOfClass) { 
            // remove the request from our cache once completed so it can be garbage collected 
            Ajax.currentRequests[request.options.onlyLatestOfClass] = null; 
        } 
    } 
}); 


/**--------------------------------------------------------------------------*/ 
// Site wide functions
/**--------------------------------------------------------------------------*/
 
function popUp(URL, theWidth, theHeight) {
	day = new Date();
	id = day.getTime();
	var left = (screen.width - theWidth) / 2;
	var top = (screen.height - theHeight) / 2;
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width="+theWidth+",height="+theHeight+",left="+left+",top="+top+"');");
}

function load_ad(name, width, height, rating, div) {
	$(div).innerHTML = '<iframe src="/ad/' + rating + '/' + width + '/' + height + '/' + name + '" width=' + width + ' height=' + height + ' scrolling=no frameborder=0 marginwidth=0 marginheight=0></iframe>';
}

function load_ad2(div, width, height, ad_id) {
	$(div).innerHTML = '<iframe src="/ad:'+ad_id+'" width="'+width+'" height="'+height+'" scrolling=no frameborder=0 marginwidth=0 marginheight=0></iframe>';
}


function dSelect(element, className) {	
	if( $(element).hasClassName(className) ){
		$(element).removeClassName(className);
	} else {
		$(element).addClassName(className);
	}
}

function setCookie(name, value, expire_minutes) {
	var date = new Date();
	if(!expire_minutes) {
		date.setTime(date.getTime()+(2592000000));
	} else {
		date.setMinutes(date.getMinutes()+expire_minutes);
	}
    document.cookie = name + "=" + escape(value) + "; expires=" + date.toGMTString() + "; path=/; domain=.todaysbigthing.com;";
}


function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	
	for(var i=0; i<ca.length; i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	
	return null;
}

function toggle_class(className) {
	document.getElementsByClassName(className).each(
		function(elm) {
			if(Element.visible(elm)) {
				elm.style.display ='none';
			} else {

				elm.style.display = '';
			}
		});
}


function hide_class(className) {
	var elms = document.getElementsByClassName(className);
	
	for(var x = 0, cnt=elms.length; x<cnt; x++) {
		elms[x].style.display = 'none';
	}
}


function show_class(className) {
	document.getElementsByClassName(className).each(
		function(elm) {
			if(Element.visible(elm)) {
				elm.style.display ='';
			}
		}
	);
}

function toggle_element_hide_class_select_element(element, className) {
	var elm = $(element);
	var elm_link = $(element + '_link');
	var status = elm.style.display;
	
	hide_class(className);

	//change background color to none
	var elm_links = document.getElementsByClassName(className + '_link');
	for(var x = 0, cnt=elm_links.length; x<cnt; x++) {
		elm_links[x].style.backgroundColor = '';
	}

	
	if(status == '') {
		elm.style.display ='none';
	} else {
		elm.style.display = '';
		elm_link.style.backgroundColor = '#FBEC5D';
	}

		
}


function toggle_element_hide_class(element, className) {
	var elm = $(element);
	var status = elm.style.display;
	
	hide_class(className);
	
	if(status == '') {
		elm.style.display ='none';
	} else {
		elm.style.display = '';
	}
}
/**--------------------------------------------------------------------------*/ 
// Jument Communicator
/**--------------------------------------------------------------------------*/ 
var Jument = {};
Jument.ajax = Class.create({
	initialize: function(params) {
		this.response_data = '';
		this.params = {};
		
		this.params = params;
		
		if(this.params.options == undefined) {
			this.params.options = {};
		}
		
		this.request();
	},
	
	request: function() {
		this.show_loader();
		
		this.params.options.method = this.params.options.method ? this.params.options.method : 'post';
		
		if(this.params.form) {
			if(this.params.options.parameters == undefined) {
				this.params.options.parameters = Form.serialize(this.params.form);
			} else {
				this.params.options.parameters = this.params.options.parameters.concat('&', Form.serialize(this.params.form));
			}
		}
		
		if(!this.params.url) alert('AJAX: Requires URL');
		if(this.params.debug) console.log('url: %o \npars: %o', this.params.url, pars);
		
		// prep the onComplete function. Add on the hide_loader function
		if(!this.params.options.onComplete) {
			var onComplete = function() { this.hide_loader(); }.bind(this);
		} else if(this.params.onComplete instanceof Array) {
			var funtions = "";
			for(i=0; i < this.params.options.onComplete.length; i++) {
				functions += "this.params.options.onComplete["+i+"]();";
			}
			var onComplete = function(){ eval(functions); this.hide_loader(); }.bind(this);
		} else {
			var func = this.params.options.onComplete;
			var onComplete = function() { func(); this.hide_loader(); }.bind(this);
		}
		
		this.params.options.onComplete = onComplete;
		
		if(this.params.div) {
			new Ajax.Updater(this.params.div, this.params.url, this.params.options);
		} else {
			this.params.options.onSuccess = this.params.options.onSuccess ? this.params.options.onSuccess : this.response;
			new Ajax.Request(this.params.url, this.params.options);
		}
	},
	
	response: function(r) {
		eval('this.response_data = '+r.responseText);

		if(this.response_data.debug) {
			console.log(this.response_data);
			console.log(this.response_data.javascript.replace(/;/, "\n"));
		}
	
		if(this.response_data.javascript) eval(this.response_data.javascript); 
	},
	
	show_loader: function() {
		var loader;
		if (loader = $(this.params.loader)) loader.show();
		document.body.style.cursor = "wait";
	},
	
	hide_loader: function() {
		var loader;
		if (loader = $(this.params.loader)) loader.hide();
		document.body.style.cursor = "default";
	}
});

Jument.submit_form = Class.create({
	initialize: function(url, frm, btn, xpars) {		
		this.submit_form(url, frm, btn, xpars);
	},
	submit_form: function(url, frm, btn, xpars) {
		var btn = $(btn);
		var original_btn_value = btn.value;
		btn.value = 'Please wait...';
		btn.disabled = true;
		
		var pars;
		if(xpars != undefined) pars += '&' + xpars;
		
		new Jument.ajax({
			url: url,
			form: frm,
			options: {
				parameters: pars,
				onFailure: function() { alert('An error occurred. Please try again.'); },
				onComplete: function() { btn.disabled = false; btn.value = original_btn_value; }
			}
		});
	}
});



/*********************************************************************************/
/*********************************** FOOTER EFFECTS ******************************/
/*********************************************************************************/
function toggle_fade(elm1, elm2){
	
	if ( $(elm1).style.display=='none' ) {
	
		switch_fade(elm1, elm2);
	
	} else {
	
		switch_fade(elm2, elm1);
	
	}

}

function switch_fade(show, hide) {

	new Effect.Fade(hide, {duration: 0.5});
	new Effect.Appear(show, {duration: 0.5});

}

/*********************************************************************************/
/*********************************** FACEBOOK ************************************/
/*********************************************************************************/
function fbs_click() {
	u = location.href;
	t = document.title;
	void(window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=no,width=626,height=436'));
	return false;
}



/************************************/
	// AD SKIN
	/************************************/
    ad_skin = {
				
		ad_container: 'skin',
		leaderboard_container: 'top_leaderboard_container',
		body1: 'skin_body',
		loaded: false,
		color_threshold: 10066329,	// #999999
	
		load: function(bg_ad_image, redirect_url, color) {

			Element.addClassName($$('body')[0], 'has-skin');
	
			if(typeof(this.onclick) == 'function') {
				this.stopObserver();
			}
			
			this.loaded = true;
			Element.setStyle(this.ad_container, { background: color + ' url('+bg_ad_image+') top center no-repeat', cursor: 'pointer' });	
			
			this.onclick = function(e) {
				if (e.target) {
					targ = e.target;
				} else if(e.srcElement) {
					targ = e.srcElement;
				}
				
				if(targ.id == this.ad_container || targ.id == this.leaderboard_container) {
					window.open(redirect_url);
				}
			}.bind(this);
			
			if (redirect_url!='') {
				Event.observe(this.ad_container, 'click', this.onclick ); 
			} else {
				$(this.ad_container).style.cursor = 'default';	
			}
		},
	
		body: function(body_image, color, repeat ) {
			
			if(body_image!=''){
				Element.setStyle(this.body1, {background: color+' url('+body_image+') top center '+(repeat ? repeat : 'repeat-x') });
			} else {
				Element.setStyle(this.body1, {background: color});
			}

		},
		
		stopObserver: function() {
			Event.stopObserving(this.ad_container, 'click', this.onclick);
		}
	}; //** END AD SKIN

function chmediabar(site) {
	if(!$('chmedia-links')) {
		var iframe = new Element('iframe', { src: 'http://www.collegehumor.com/chmediabar/?site=' + site, scrolling: 'no', 'frameborder': '0', id: 'chmedia-links' });
		Element.insert($$('body')[0], { top: iframe });
	}
}