/* 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() };
		
	});	
	
	
}

window.addEvent('domready',function(){		
	//	Plugin checks.
	if (method_ok('SiFile')) { SI.Files.stylizeAll() }
	if ($defined(window.jQuery)) jQuery.noConflict(); // Required for WYMeditor :(
	
	/*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('Tagline')) new Tagline({ 'event_el' : $$('#tagline div.current_tagline')[0], 'target_el' : $$('#tagline div.change_tagline')[0] });
	if (method_ok('Tags')) new Tags({ 'event_el' : $$('#tags div.current_tags')[0], 'target_el' : $$('#tags div.change_tags')[0] });
	if (method_ok('SetURL')) new SetURL({ 'event_el' : $('friendly_url') });
	if (method_ok('FormTools') && obj_ok('#tools')) gbl.form_tools = new FormTools({ 'container' : $('tools'), 'el' : '.btn_tools'});
	if (method_ok('FormTools') && obj_ok('#publication')) gbl.form_tools = new FormTools({ 'container' : $('publication'), 'el' : 'a.button' })
	
	
	//	Add an Event
	if ($$('select[name*=start]') && $$('input[name=set_start]')[0] && method_ok('Events')) var start_date = new SetDate({targets:$$('select[name*=start]'),setter:$$('input[name=set_start]')[0]});
	if ($$('select[name*=end]') && $$('input[name=set_end]')[0] && method_ok('Events')) var end_date = new SetDate({targets:$$('select[name*=end]'),setter:$$('input[name=set_end]')[0]});
	
	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('ComboList') && obj_ok('.combo_list')) gbl.combo_list = new ComboList({ container : $$('.combo_list')[0] })
	
	if (method_ok('Dates') && $$('*[name*=date]') && $$('input[name=set_publish]')[0]) {
		var toggle_date = new SetDateToggle({ 'event_el' : $$('.current_publication_date')[0], 'target_el' : $$('.change_publication_date')[0] });
		gbl.set_date = new SetDate({ 'targets' : $$('input[type=text][name*=date], select[name*=date]'), 'setter' : $$('input[name=set_publish]')[0], 'current_date' : $$('input[name=current_date]')[0] });
	};
		
	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());
	
	//	Global Messaging
	gbl.message = new GrowlMessage();
	
	get_classes();
});