// GLOBAL objects
var Workshops;
var ajaxOpts;
var ajaxLoginOptions;
var accountDOMOpts;
var emailshareDOMOpts;

 try {
  document.execCommand("BackgroundImageCache", false, true);
} catch(e) {}

function twitterWorkshopsCallback(twitters){
  var statusHTML = [];
  for (var i=0; i<twitters.length; i++){
	    var username = twitters[i].user.screen_name;
	    var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
	      return '<a href="'+url+'">'+url+'</a>';
	    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
	      return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
	    });
    	var created_date = twitters[i].created_at.split(" ");
    	var dateString = created_date[1]+' '+created_date[2]+', '+created_date[5];
	    var date = new Date(dateString);
	    statusHTML.push('<p>'+status+'<br /><em>'+formatDate(date,'MMM d, yyyy')+' via '+twitters[i].source+'</em></li>');
  }
  document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');

}



// GLOBAL dom ready
jQuery(function($) {
	$("#ws-header").bind("fb_parse",function(){FB.XFBML.parse();}); //Event needed for design app
	// GLOBAL ajaxify options
	ajaxOpts = {
		attribute: 'subject', // New semantic element attribute for every element in HTML5
		buttons: 'button[type=submit], input[type=submit], input[type=image]',  // jQuery selector for buttons
		submit: { // events to be carried out onclick/submit
			disable: {  // disable any inputs (form only)
				selector: 'buttons',
				className: 'disabled'
			},
			message: { text: false },
			waiting: { // if nothing happens after timeout * 1000 ms, update the message and re-enable the buttons
				timeout: 30, // seconds
				message: 'It looks like there was a problem with the request, please try again.',
				className: 'error',
				callback: function() {
					$(this.update).children().css({opacity:1}).filter('.ajax-loader').remove();
					alert('It looks like there was a problem with the request, please try again.');
				}
			},
			callback: function() {
				if(typeof tinyMCE == 'object') tinyMCE.triggerSave();
				tinyMCE.execCommand('mceRemoveControl', false, 'national-submission-content');
				
			}
		},
		// jQuery AJAX options
		dataType: 'html',
		beforeSend: function() {
			$(this.update).css({position:'relative'}).children().css({opacity:0.5}).end().append('<div class="ajax-loader"><br /></div>');
		},
		success: function(data) {
			var o = this; var e = $(this.update);
			e.append('<div class="__loaded__" style="display:none;">'+$.trim(data)+'</div>');
			var loaded = $('.__loaded__', e); var imgs = $('img', loaded);
			o.displayNewContent = function(){
				e.html(loaded.html());
				o.keepLive();
				o.customCommands();
			};
			if( !imgs.size() ) {
				o.displayNewContent();
			} else {
				var imgs_loaded = 0;
				imgs.load(function() {
					imgs_loaded++;
					if( imgs_loaded == imgs.size() ) o.displayNewContent();
				});
			}
		},
		complete: function(req, success) {
			$('.ajax-loader', $(this.update)).remove();
		},
		keepLive: function() {
			Workshops.init( $(this.update) );
			jQuery("div.comment-aside div.comment-author-vcard ").elastictext({width:83});
			if($(this.update).find(".social_icons").length){
				FB.XFBML.parse();
				$('a.email_share').openDOMWindow(emailshareDOMOpts);
			}
			if($(this.update).find(".comment-form-box").length){
				$('a.accountDOMWindow').openDOMWindow(accountDOMOpts);
			}
			
			
		},
		customCommands:function(){}  //overwrite with any specific functionality needed for a particular ajaxify request
	};
	
	// GLOBAL Login
	ajaxLoginOptions = {
		attribute: 'subject', // New semantic element attribute for every element in HTML5
		buttons: 'button[type=submit], input[type=submit], input[type=image]',  // jQuery selector for buttons
		submit: { // events to be carried out onclick/submit
			disable: {  // disable any inputs (form only)
				selector: 'buttons',
				className: 'disabled'
			},
			message: { text: false },
			waiting: { // if nothing happens after timeout * 1000 ms, update the message and re-enable the buttons
				timeout: 10, // seconds
				message: 'It looks like there was a problem with the request, please try again.',
				className: 'error',
				callback: function() {
					$(this.update).children().css({opacity:1}).filter('.ajax-loader').remove();
					alert('It looks like there was a problem with the request, please try again.');
				}
			},
			callback: function() {
				if(typeof tinyMCE == 'object') tinyMCE.triggerSave();
			}
		},
		// jQuery AJAX options
		dataType: 'html',
		beforeSend: function() {
			$(this.update).css({position:'relative'}).children().css({opacity:0.5}).end().append('<div class="ajax-loader"><br /></div>');
		},
		success: function(data) {
			control=data.substr(0,13);
			if(control=="login-success"){
				data=data.replace(control,"");
				this.update="#ws-header-2";			
			}			
			var o = this; var e = $(this.update);
			e.append('<div class="__loaded__" style="display:none;">'+$.trim(data)+'</div>');
			var loaded = $('.__loaded__', e); var imgs = $('img', loaded);
			o.displayNewContent = function(){
				e.html(loaded.html());
				o.keepLive();
				o.customCommands();
			};
			if( !imgs.size() ) {
				o.displayNewContent();
			} else {
				var imgs_loaded = 0;
				imgs.load(function() {
					imgs_loaded++;
					if( imgs_loaded == imgs.size() ) o.displayNewContent();
				});
			}
		},
		complete: function(req, success) {
			$('.ajax-loader', $(this.update)).remove();
		},
		keepLive: function() {
			Workshops.init( $(this.update) );
			$('a.ajaxify-login,form.ajaxify-login', $(this.update)).ajaxify(ajaxLoginOptions);
		},
		customCommands:function(){
			if(this.update=="#ws-header-2"){
				if($("#DOMWindow a.closeDOMWindow").length>0) $("#DOMWindow a.closeDOMWindow").click();
			}
		}
	};
	
	// Back to top Link
	if($("#ws-container").length){
		var w = Math.round($("#ws-container").outerWidth()+$("#ws-container").offset().left);
		$("#back_to_top").css({"left":(w+30)+"px"}).show();
		$("#back_to_top a").click(function(){ $("html,body").animate({scrollTop:0},"normal"); });
	}
	

	emailshareDOMOpts={
						overlay: 1,
						overlayColor: '#000',
						width: 760,
						height: 353,
						positionType: 'centered', 
						eventType: 'click',
						windowBGColor: '#000',
						windowHTTPType: 'get',
						windowSource: 'ajax', 
						windowPadding: 0, 
						loader: 1, 
						//loaderImagePath: '<?php echo base_url().'images/ajax-loader.gif'; ?>',
						loaderWidth: 16, 
						loaderHeight: 11,
						modal: 1,
						functionCallBeforeOpen: function() {
							jQuery('#DOMWindow').append('<a class="closeDOMWindow" href="#">Close</a>');
							
						},
						functionCallAfterOpen: function() {
							jQuery('a.ajaxify, form.ajaxify').ajaxify(ajaxOpts);
						}
					};
	
			$('a.email_share').openDOMWindow(emailshareDOMOpts);
	
	
	// GLOBAL main application object
	Workshops = {
		/**
		 * Initiate functionality based on the specified context element.
		 *
		 * @param mixed context Can be a dom element, or jQuery object.
		 * @return void
		 */
		init: function( context ) {
			if(!context) context = document;
						
			// Generic ajaxify links and forms
			$('a.ajaxify, form.ajaxify', context).ajaxify(ajaxOpts);
			
			// Search input
			$('input.search_input', context).data('fillerText', 'SEARCH');
			// Comment textarea
			$('textarea.comment-form-text', context).data('fillerText', 'WRITE YOUR COMMENT HERE...'); // Change ... to &hellip;
			
			// All inputs and text areas with some fillerText
			$(':input', context).focus(function() {
				if($(this).val().toUpperCase() == $(this).data('fillerText') ) $(this).val(''); 
			}).blur(function() {
				if( $(this).data('fillerText') && $.trim($(this).val()) == '' ) $(this).val(this.defaultValue);
			});
			
			// Char Counters
			if($(':input').length){
			$('textarea[maxlength], input[maxlength]', context).maxlength().bind('charsleft',function(e){
				var counter = jQuery('#'+jQuery(this).attr('id')+'-counter', context);
				counter.html(e.charsLeft+' Characters Left');
			});
			}
		}
	}
	// Initiate from the document
	Workshops.init();
});
