/* ******************** */
// [ GLOBAL VARIABLES ] //
/* ******************** */

var jsLib = {
	jqueryPlugins 	: '/gbl/js/jQueryPlugins',
	validatePath	: '/gbl/js/jQueryPlugins/validate/1.8.1',
	tinyMCEPath		: '/gbl/js/tinyMCE/3.4-jquery'
};
jsLib = $.extend(jsLib, {
	fastConfirm		: jsLib.jqueryPlugins + '/fastConfirm/2.1.1/jquery.fastconfirm.js', //http://blog.pierrejeanparra.com/jquery-plugins/fast-confirm/
	fastConfirmCSS	: jsLib.jqueryPlugins + '/fastConfirm/2.1.1/jquery.fastconfirm.css',
	jquery			: '//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js', //http://jquery.com/
	jqueryLocal 	: '/gbl/js/jquery/1.6.1/jquery.min.js',
	jqueryUI 		: 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js', //http://jqueryui.com/
	jqueryUITheme 	: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/themes/redmond/jquery-ui.css',
	jNotify			: jsLib.jqueryPlugins + '/jNotify/1.1.00/jquery.jnotify.min.js', //http://www.givainc.com/labs/jnotify_jquery_plugin.htm
	jNotifyCSS		: jsLib.jqueryPlugins + '/jNotify/1.1.00/css/jquery.jnotify.css',
	metadata		: jsLib.jqueryPlugins + '/metadata/2.1/jquery.metadata.min.js',// http://docs.jquery.com/Plugins/Metadata
	meioMask		: jsLib.jqueryPlugins + '/meioMask/1.1.3/jquery.meio.mask.min.js', //http://www.meiocodigo.com/projects/meiomask/
	tinyMCE			: jsLib.tinyMCEPath + '/jquery.tinymce.js', //http://tinymce.moxiecode.com/
	tmpl			: jsLib.jqueryPlugins + '/tmpl/1.0.0b/jquery.tmpl.min.js', //https://github.com/jquery/jquery-tmpl
	jLabel			: jsLib.jqueryPlugins + '/jLabel/1.3/jquery.jlabel.min.js', //http://www.wduffy.co.uk/jlabel/
	uniForm			: '/gbl/css/uniForm/1.5/js/uni-form.jquery.min.js', //http://sprawsm.com/uni-form/
	uniFormCSS		: root + '/includes/css/uni-form.css',
	validate		: jsLib.validatePath + '/jquery.validate.min.js' //http://bassistance.de/jquery-plugins/jquery-plugin-validation/
});


/* ********************* */
// [ Utility Functions ] //
/* ********************* */

$('#navigation li:last a:has(span)').html($('#navigation li:last span').html())

// Utility: Table Utilities
$('.result:not(.ignore),.data tr').each(function(i){
	var $this = $(this);
	if($this.parents('.results,.data').hasClass('ignore')) return; 
	
	$this.click(function(e){
		var _l=$('a:not(.del):first', this);
		if(_l.length) window.location=_l.attr('href'); return false; 
	})
	.css({'cursor':'pointer'});
});
		
// Utility: Form Utilities
$('button[href]:not(.del,.fastConfirm)').click(function(){window.location=$(this).attr('href');});


/* *********** */
// [ Plugins ] //
/* *********** */

// Plugin: Message Box Notice
var applyMessageBox = function(){
	if(!messageBoxArray.length) return;
	
	yepnope({
		load	: [jsLib.jNotify,
				   jsLib.jNotifyCSS],
		complete: function(){		
			$.each(messageBoxArray, function(i,v){
				var $this = $.extend({message:'', type:'notice'}, v);
				$.jnotify($this.message, {
					type	: $this.type, 
					delay	: 5000,
					sticky	: (/error|warning/i).test($this.type)? true : false
				});
			});
		}
	});
}();

// Plugin: jLabel - inline labels
var applyJLabel = function(){
	var $this = $('.label');
	if(!$this.length) return;
	
	yepnope({
		load	: [jsLib.jLabel],
		complete: function(){		
			$this.jLabel({opacity:0});
			$this.each(function(){
				var $$this = $(this);
				//setTimeout(function(){$$this.jLabel()}, 1000);
				//$$this.prev('label').css('display','');
			});
		}
	});
}();

// Plugin: Server Side Column Sorting
var applyColumnSort = function(){
	var $this = $('table.results');
	if(!$this.length) return;
	
	yepnope({
		load	: jsLib.query,
		complete: function(){
			var c = ($.query.get('c') != 'undefined' && $.query.get('c').length)? $.query.get('c') : $('th:[alt]:first', $this).attr('alt');
			var d = (Boolean($.query.get('d')))? 1 : 0;

			if ($.query.get('c').length == 0 && typeof colOrderDefault != 'undefined') c = colOrderDefault;	
			if ($.query.get('d').length == 0 && typeof colOrderDesc != 'undefined') d = Boolean(colOrderDesc);
			
			$('.results:first th[alt >= ]')
			.addClass('header')
			.click(function(){
				d = (d)?0:1;
				if(c != $(this).attr('alt')) d=0;	
				c = $(this).attr('alt');										
				if(typeof colOrderSubmit != 'undefined') colOrderSubmit(c, d); 
				else window.location = $.query.set('c', c).set('d', d);
			})
			.append($('<span class="icon carat-2-n-s" style="float:right;"></span>'));
			
			$('.results:first th:[alt='+c+']').addClass((d)? 'headerSortUp' : 'headerSortDown');	
			$('.headerSortUp span:first').removeClass('carat-2-n-s').addClass('carat-1-n');
			$('.headerSortDown span:first').removeClass('carat-2-n-s').addClass('carat-1-s');
		}
	});
}();

// Plugin: _datePick() - Setup '.date' input fields with a date picker
var applyDatepicker = function(selector){
	var selector = selector || $('document');
	var $this = $('input.date:not(.hasDatepicker),input.datetime:not(.hasDatepicker)', selector);
	if(!$this.length) return true;
	
	yepnope({
		load	: [jsLib.jqueryUI, 
			   	   jsLib.timePicker, 
			       jsLib.jqueryUITheme],
		complete: function(){
				$this.each(function(){
					var $this = $(this);
					var $options = {
						buttonImageOnly: true,
						ampm		: true,
						timeFormat	: 'hh:mm TT',
						stepMinute	: 5,
						buttonText 	: '',
						showOn		: 'both',
						showAnim	: 'slideDown',
						hideAnim	: 'slideUp'};

					if ($this.hasClass('datetime')) $this.datetimepicker($options);		
					else $this.datepicker($options);		
					
					$this.after(
						$('<img>')
						.attr({'src': root + '/includes/img/calendar.png'})
						.addClass('trigger')
						.css({'margin-left':3, 'vertical-align':'middle'})
						.click(function(){$this.datepicker('show')})
					);
				});
				$('input.date,input.datetime,img.trigger').click(function(){
					var $this=$(this).is('input')? $(this) : $(this).siblings('input.date:first');
					var $options = {
						minDate:($this.hasClass('max') ? $this.parents('form:first').find('.min:first').val() : null),
						maxDate:($this.hasClass('min') ? $this.parents('form:first').find('.max:first').val() : null)	
					};
					
					if ($this.hasClass('datetime')) $this.datetimepicker('option', $options);		
					else $this.datepicker('option', $options);
				});
			}			
	});
};	
applyDatepicker(document);

// Plugin: Fast Confirm
var applyFastConfirm = function(){
	var $this = $('.fastConfirm');
	if(!$this.length) return;
		
	yepnope({
		load	: [jsLib.fastConfirm,
			       jsLib.metadata,
		           jsLib.fastConfirmCSS],
		complete: function(){		
			$this.click(function(e){
				var $this = $(this);
				e.preventDefault();
				e.stopPropagation();
				var metadata = {
					position : ($this.parents('table:first').hasClass('results'))? 'right' : 'top',
					onProceed: function(trigger){ if(!$(trigger).is('[href]')) return; window.location = $(trigger).attr('href'); }
				};
				$this.fastConfirm($.extend(metadata, $this.metadata()));
				return false;
			});
		}
	});
}();

// Plugin: uniForm
var applyUniForm = function(){
	var $this = $('.uniForm');
	if(!$this.length) return true;
	
	yepnope({
		load	: [jsLib.uniForm,
			  	   jsLib.uniFormCSS],
		complete: function(){
			$('.checkboxContainer').click(function(e){e.stopPropagation(); $this=$(this).find(':checkbox,:radio'); $this.focus().trigger('click');});
			$('.checkboxContainer :checkbox, .checkboxContainer :radio').click(function(e){e.stopPropagation();});	
			if($('input.focus').length) $('input.focus:first').focus();		
		}			
	});
}();	

// Plugin: validate
var loadValidatorOptions = {};
var applyValidate = function(){
	var $this = $('form:not(.ignore)');
	if(!$this.length) return;

	yepnope({
		load	: [jsLib.metadata,
			 	   jsLib.validate,
				   jsLib.validatePath + '/validationLibrary.js',
				   jsLib.uniForm,
				   jsLib.uniFormCSS], 
		complete: function(){													   
			if(typeof loadValidators !== 'undefined') loadValidators();
			
			$.validator.setDefaults({ 
				errorClass: 'errorField', 
				errorElement: 'p', 
				errorPlacement: function(error, element) { 
					error.prependTo(element.parents('div.ctrlHolder'))
				},
				highlight: function(element,errorClass) {
					$(element).parents('div.ctrlHolder').addClass('error');
				},
				unhighlight: function(element,errorClass) {
					$(element).parents('div.ctrlHolder').removeClass('error');
				}
			});
			
			$this.each(function(){
				var validatorOptions = $.extend({ignore: '.ignore,button'}, loadValidatorOptions);
				$(this).uniform(); 
				$(this).validate(validatorOptions);				
			});	
			
			$('input.focus:first').focus();
		}
	});
}();

// Plugin: Field Masks
var applyFieldMask = function(){
	var $this = $('input.dateMask,input.phoneMask,input.moneyMask,input.decimalMask');
	if(!$this.length) return;
	
	yepnope({
		load	: jsLib.meioMask,
		complete: function(){
			$('input.dateMask').setMask('99/99/9999');
			$('input.phoneMask').setMask('999-999-9999');
			$('input.moneyMask').setMask({mask:'99.999,999,999,999', type:'reverse', defaultValue:'000'});
			$('input.decimalMask').setMask({mask:'99.999999999999', type:'reverse', defaultValue:'000'});
		}
	});
}();
