gbl = { methods : [], lang : false, classes : {} };
init = { classes : {} }

/* Ensure required class is loaded */
function method_ok(id){
	
	if (gbl.methods.indexOf(id) > -1) return true;
	return false;

}

function obj_ok(el){
	
	//	Return true if object exists
	if ($$(el)[0]) return true;
	return false;
	
};

function required_class(cls){
	
	if ($chk(gbl.classes[cls])){ return true; };
	
	return false;
	
};

function get_classes(){

	$$('script[type=text/javascript]').each(function(el,i){
		//	Ignore inline scripting.
		if (!el.get('src')) return;
		
		//	Get source url.
		var src = el.get('src');
		
		//	Isolate the filename location.
		var i0 = src.lastIndexOf('/')+1
		var i1 = src.lastIndexOf('.')
		
		//	Substring of the file name.
		var filename = src.substring(i0,i1);

		//	Try to initialize.
		try {
			
			//	Initialize the class, if available.
			gbl.classes[filename].init();
			
		} catch(err) { 
			
			//	Add the class object if it doesn't exist
			gbl.classes[filename] = new Object() };
		
	});	
	
	
}

/*
 * commentData
 * Author: James Padolsey
 */
 
var commentData = (function(){
    	
    var getAllComments = function(context) {
        
            var ret = [],
                node = context.firstChild;
            
            if (!node) { return ret; }
            
            do {
                if (node.nodeType === 8) {
                    ret[ret.length] = node;
                }
                if (node.nodeType === 1) {
                    ret = ret.concat( getAllComments(node) );
                }
            } while( node = node.nextSibling );
            
            return ret;
            
        },
        cache = [0],
        expando = 'data' + +new Date(),
        data = function(node) {
            
            var cacheIndex = node[expando],
                nextCacheIndex = cache.length;
     
            if(!cacheIndex) {
                cacheIndex = node[expando] = nextCacheIndex;
                cache[cacheIndex] = {};
            }
     
            return cache[cacheIndex];
        
        };
    
    return function(context) {
        
        context = context || document.documentElement;
            
        if ( data(context) && data(context).commentJSON ) {
            return data(context).commentJSON;
        }
    
        var comments = getAllComments(context),
            len = comments.length,
            comment, cData;
            
        while (len--) {
            comment = comments[len];
            cData = comment.data.replace(/\n|\r\n/g, '');
            if ( /^\s*?\{.+\}\s*?$/.test(cData) ) {
                try {
                    data(comment.parentNode).commentJSON = (new Function('return ' + cData + ';'))();
                } catch(e) {}
            }
        }
        
        return data(context).commentJSON || true;
        
    };
    
})();

window.addEvent('domready',function(){		
	//	Plugin checks.
	
	 
	/*var data = commentData($('test')); // <= { someData: 123, other: 'foo' }

	console.log(data.test)*/
	
	//console.log(gbl.methods);
	
	if (method_ok('SiFile')) { SI.Files.stylizeAll() }
	if ($defined(window.jQuery)) jQuery.noConflict(); // Required for WYMeditor :(
	
	/*if ($$('.feedback')){
		
		$$('.feedback')[0].addEvent('click',function(e){
			e.stop();
		
			//console.log('1');
			GSFN.feedback('http://getsatisfaction.com/sayyeah/feedback/topics/new?display=overlay&style=idea', tab_options);

		});
	}*/
	
	if ($('sitewide_search')){
	
		var input = $('sitewide_search')
		var desc = input.get('title');
	
		input.addEvent('focus',function(){
										
			if (desc == input.get('value')){
			
				input.removeClass('faded');
				input.set('value','');
		
			}
		
		});
		
		input.addEvent('blur',function(){						
			if (desc == input.get('value') || input.get('value') == ''){
			
				input.addClass('faded');
				input.set('value',desc);
			
			}
		});	
		
		input.fireEvent('blur');
		
	};

	//	###
	//	#
	//	#	Public Classes
	//	#
	//	###
	
	//	Comment & login
	if (method_ok('CheckUser')) { new CheckUser({'container':$('login_to_comment')}); }
	
	//	Vote
	if (method_ok('Vote')) { new Vote({'els':$$('.score')}) }
	
	//	Shrink article to 1 paragraph on load
	if (method_ok('ConcatArticle')) { new ConcatArticle({ 'els' : $$('div#entries div.content') }) };
	
	//	###
	//	#
	//	#	Management Classes
	//	#
	//	###
	
	//	Ajax response handler.
	if (method_ok('ValidateResponse')) new ValidateResponse();
	
	if (method_ok('UploadBinary') && $(document.body).hasClass('obj_uploaded')) new GrabBinary();	
	if (method_ok('UploadBinary') && $$('form#upload_binary input[name=file_token]')[0]) new AutomaticUpload({ 'event_el' : $$('form#upload_binary input[name=file_token]')[0]});
	
	if (method_ok('StorySource')) new StorySource({ 'event_el' : $('article_title') });
	if (method_ok('SlideEvents')) { new SlideEvents({ 'target' : $$('.trash_slider'), 'execute_at' : 13, 'on_execute' : function(el){
	
		var action = el.retrieve('target').get('name')
		var relation = el.retrieve('target').get('rel')
		
		gbl.form_tools.send_form(action,relation);
																																 
	}}) }
	
	//	Add an Event
	
	//if (method_ok('Events') && $('event_calendar') && $$('a.event')[0]) new ShowEvent({ target : $('event_calendar'), els : $$('a.event') });
	if (method_ok('Events') && $('filter_events')) new ToggleEventList({ els : $('filter_events').getElements('a') });
	if (method_ok('Events') && $('new_event') && $$('input[name=duplicate_event]')[0]) new DuplicateEvent({ target : $('new_event'), button : $$('input[name=duplicate_event]')[0] });

	//	Auto Upload File upon Selection
	if (method_ok('UploadImage') && obj_ok('.file')) var img_upload = new UploadImage({ 'els' : $$('.file') });

	
	
		
	if (method_ok('Comments') && ($('post_a_comment') || $('login_to_comment'))) new CommentReply({ 'els' : $$('a.reply'), target_form : $('post_a_comment') || $('login_to_comment') });
	
	if (method_ok('Comments') && $$('.edit_comment')[0]){ new EditComment({ 'els' : $$('.edit_comment')}); }
	
	if (method_ok('Comments') && $('post_a_comment')){
	
		new LoggedInReply({ 'comment' : $('post_a_comment').getElement('textarea[name=set_content]') });
		
	}
	
	//	Moderate Comments
	if ($$('div[name=unapproved_items]')[0] && method_ok('Moderator')) gbl.moderator = new Moderator({ 'els' : $$('div[name=unapproved_items]')[0].getElements('div.unapproved'), 'counter' : $('count') })
	
	
	if (method_ok('Organize') && obj_ok('#manage_categories')) {
			
		gbl.organize_categories = new Organize(
		{	 module : 'blog_group',
			container : $$('ul.group'),
			els : 'li.child',
			handle : 'span.move'
		});				
		
		gbl.organize_groups = new Organize(
		{	module : 'blog_group',
			container : $$('#manage_categories'),
			els : 'ul.group',
			handle : 'li.parent span.move'
		});
		
		gbl.edit_category = new EditCategory({
			module : 'blog_group',
			els : $('manage_categories').getElements('ul.group li')
		 });
		
		gbl.add_category = new AddCategory(
		{	'el' : $('add_a_category'),
			'target': $('manage_categories'),
			'module' : 'blog_group'
		});
	};
	
	//	###
	//	#
	//	#	Global Events & Listeners
	//	#
	//	###
	gbl.events = {
	
		upload_headline_image : function(){
			
			<!--console.log('begin upload');-->
			
		},
	
		headline_image : function(attr){
		
		
			if ($$('.headline_image')[0]) $$('.headline_image')[0].dispose();	
			
			var image_bundle = '<input type="hidden" name="set_image" value="{token}"/>'
			
			var image_container = new Element('div',{ 'class' : 'headline_image', 'style' : 'background-image:url('+attr.src+')' }).set('html',image_bundle.substitute(attr)).inject($('friendly_url'),'after');
			
			if (!$$('a[name=remove_header_image]')[0]) {
				var remove = new Element('a', { 'name' : 'remove_header_image', 'class' : 'remove_image' }).set('text','Remove Image').inject($('image_upload'),'after');
			
				remove.addEvent('click',function(){ $$('.headline_image')[0].dispose(); this.dispose(); });
			}
		},
		
		wymeditor : function(attr){
				var img = new Element('img',{'src' : attr.src, 'id' : attr.token, 'height' : attr.height, 'width' : attr.width });
				$$('input[name=obj_src]')[0].set('value',attr.src); },
		
		get_overlay : function(attr){
			if (method_ok('Overlay')){			
				if (!gbl.overlay) gbl.overlay = new Overlay({ size : [200,200] });
				gbl.overlay.set_styling('report');
				
				return gbl.overlay
			}; },
		
		hide_iframe : function(){ if ($(document.body).getElement('iframe')) $(document.body).getElement('iframe').setStyle('display','none') }	
	
	}
	//	Event listeners
	window.addEvent('headline_image',gbl.events.headline_image.bind(this));
	window.addEvent('get_overlay',gbl.events.get_overlay.bind(this));
	window.addEvent('wymeditor',gbl.events.wymeditor.bind(this));
	window.addEvent('begin_upload',gbl.events.upload_headline_image.bind(this));
	
	if ($$('a[name=remove_header_image]')[0]) $$('a[name=remove_header_image]')[0].addEvent('click',function(){ $$('.headline_image')[0].dispose(); this.dispose(); });
	
	//	###
	//	#
	//	#	Login Redirection
	//	#
	//	#	If this is a login form, inject a parameter to redirect the url to the originating source after login.
	//	#
	//	###

	var page_loc = function(){
		
		var path = window.location.pathname.toString()
		var qs = window.location.search.toString()
	
		var is_redirected = qs.indexOf('redirect=') ? qs.substring(qs.indexOf('redirect=')+9,qs.length) : false;
		
		//if ($$('input[name=inherit_redirect]')[0]) return $$('input[name=inherit_redirect]')[0].get('value');
		if (path.indexOf('/login') > -1 && is_redirected==false) return '/'
		
		var logout = qs.indexOf('?logout=1') > -1 ? qs.indexOf('?logout=1') : qs.length;
		
		return path+""+qs.substring(0,logout);
	}
	
	if (window.location.pathname.toString() != '/login'){
		if ($$('input[name=redirect]')) {

			$$('input[name=redirect]').each(function(el,i){
			
			el.set('value',page_loc());
			
			})

		}
	}
	
	//if ($('login_form')) 
	//	if ($$('input[name=redirect]')[0])
	//var redirect = new Element('input',{'type':'text','name':'redirect','value':page_loc()}).inject($('login_form','top'))
	
	if ($$('.btn_login')[0]) $$('.btn_login')[0].set('href','/login?redirect='+page_loc());
	
	$$('a[href=/login]').each(function(el){
	
		el.set('href','/login?redirect='+page_loc());

	})
	
	
	
	
	//	Global Messaging
	gbl.message = new GrowlMessage();
	
	get_classes();
});