//------------------------------------------------------[TG]
// Public: JS
//------------------------------------------------------[TG]

// Admin Object ----------------------------------------[TG]
var ADM = {
	CheckChildren: function() {
		var ParentStatus = this.checked;
		$('input', $(this).parent()).each(function() {
			this.checked = ParentStatus;
		});
	},
	ToggleChildren: function(Event) {
		Event.stopPropagation();

		if (typeof(this.Display) == 'undefined')
			this.Display = true;

		if ($('img', $(this).parent())[0].src.indexOf('plus') > 0)
			$('img', $(this).parent())[0].src = $('img', $(this).parent())[0].src.replace('plus', 'minus');
		else
			$('img', $(this).parent())[0].src = $('img', $(this).parent())[0].src.replace('minus', 'plus');

		var ParentDisplay = this.Display = (this.Display) ? false : true;
		$('> ul > li', $(this).parent()).each(function() {
			$(this).css('display', (ParentDisplay) ? 'none' : '');
		});
	},
	ClickToClose: function(Event) {
		var Parent = $(this).parent();
		$(this).remove();
		if (!Parent.children().length)
			Parent.remove();
	},
	HidePanel: function(PanelName) {
		var Side = (PanelName == 'ADM_Help') ? 'Left' : 'Right';
		var Panel = $('.' + PanelName);

		if (Panel.css('display') == 'none') {
			Panel.show();
			$('.ADM_Section').addClass('ADM_Open' + Side);
			$('.' + PanelName + 'Closed').hide();
		} else {
			Panel.hide();
			$('.' + PanelName + 'Closed').show();
			$('.ADM_Section').removeClass('ADM_Open' + Side);
			
		}
		var Page = location.href.substr(0, ((location.href.indexOf('?') != -1) ? location.href.indexOf('?') : location.href.length));
		$.cookie(Side + Page, (Panel.css('display') == 'none') ? 'Hide' : 'Show');
	},
	ChangeStatusHandler: function(Event, ItemID, NewStatus, Type, ProcessPage){
		var div = this;
		PostParams = {};
		PostParams['Action'] 		= 'StatusUpdate';
		PostParams['Status'] 		= NewStatus;
		PostParams['RequestType']	= 'AJAX';
		PostParams['Type']			= Type;
		PostParams[Type+'ID'] 		= ItemID;
		
		if(arguments[5] != null && typeof(eval(arguments[5])) == 'function'){
			div.callback = eval(arguments[5]);
		}

		$.get(ProcessPage, PostParams, function(Response){
			if(!Response.match(/success/)) {
				$(div).html('Error');
				return false;
			}
			$('img', $(div).parent()).each(function() {
				$(this).attr('src', $(this).attr('src').replace('.on.', '.off.'));
			});
			var img = $('img:first', $(div).siblings('a[title=\''+NewStatus+'\']'));
			img.attr('src', img.attr('src').replace('.off.', '.on.'));
			$(div).html(NewStatus);

			if(div.callback){
				div.callback(div);
			}
		});
		
		return false;
	}
};
//------------------------------------------------------[TG]

// On Ready --------------------------------------------[TG]
$(document).ready(function() {

	// Current Page without Query String
	var Page = location.href.substr(0, ((location.href.indexOf('?') != -1) ? location.href.indexOf('?') : location.href.length));

	// Show or Hide Help
	var HelpPanel = $('.ADM_Help');
	if (HelpPanel[0]) {
		$('h2:first', HelpPanel[0]).append('<a href="#" class="ADM_Close" title="click to hide panel" onclick="javascript: ADM.HidePanel(\'ADM_Help\'); return false;"><img src="' + PATH.IMG + '/ADM/btn.close_left.gif" border="0" class="ADM_MouseOverable" /></a>');
		
		if (!$.cookie('Left' + Page) || $.cookie('Left' + Page) == 'Show')
			$('.ADM_Section').addClass('ADM_OpenLeft');
		else {
			HelpPanel.hide();
			$('.ADM_HelpClosed').show();
		}
	}

	// Show or Hide Controls
	var ControlsPanel = $('.ADM_Controls');
	if (ControlsPanel[0]) {
		$('h2:first', ControlsPanel[0]).append('<a href="#" class="ADM_Close" title="click to hide panel" onclick="javascript: ADM.HidePanel(\'ADM_Controls\'); return false;"><img src="' + PATH.IMG + '/ADM/btn.close_right.gif" border="0" class="ADM_MouseOverable" /></a>');

		if (!$.cookie('Right' + Page) || $.cookie('Right' + Page) == 'Show')
			$('.ADM_Section').addClass('ADM_OpenRight');
		else {
			ControlsPanel.hide();
			$('.ADM_ControlsClosed').show(); 
		}
	}

	// Put Cursor in First Text Field on all Forms
	if ($('.ADM_Form:first :text:first'))
		$('.ADM_Form:first :text:first').focus();

	// Make Center Content have rounded base
	$('.ADM_Section:eq(0)').append('<div class="ADM_SectionFoot"><div></div></div>');

	// Attach Events
	if ($('.ADM_Permissions')[0]) {
		$('.ADM_Permissions input').click(ADM.CheckChildren);
		$('.ADM_Permissions span').click(ADM.ToggleChildren);
		$('.ADM_Permissions img').click(ADM.ToggleChildren);
	}

	// Close Messages
	$('.MSG_Error').click(ADM.ClickToClose);
	$('.MSG_Success').click(ADM.ClickToClose);
	
	// Roll Overs
	$('.ADM_MouseOverable').hover(
		function() {
			$(this).attr('src', $(this).attr('src').replace('.gif', '.over.gif') );
		},
		function() {
			$(this).attr('src', $(this).attr('src').replace('.over.gif', '.gif') );
		}
	);
	
	$('.ADM_Listing td.ADM_Status div').bind('StatusChange', ADM.ChangeStatusHandler);

	

});
//------------------------------------------------------[TG]

// Image Library ---------------------------------------[MN]
var Essence_ImageLibrary = function(){ 
	var This = {
		Image_Clear: function( InputID ) {
			$( '#'+ InputID ).val( '' );
			$( '#'+ InputID +'_Image' ).attr( 'src', PATH.IMG +'/addimg.gif' );
		},
		Image_Insert: function( URL, Data, Settings ){
			var RelativeURL = '/'+ URL.replace( /\.\.\//g, '' );

			$( 'form[name='+ Settings.target_form +']' ).find( 'input[name=Thumb_'+ Settings.target_elements +']' ).val( Data.custom.thumbnail_url );
			var Input_URL = $( 'form[name='+ Settings.target_form +']' ).find( 'input[name='+ Settings.target_elements +']' );
				Input_URL.val( RelativeURL );
				Input_URL.parents( 'td:first' ).find( '.ADM_AssetImage' ).attr( 'src', RelativeURL );
		}
		,AssetIDGetPath: '/assetid.get'
		/**	To Use this Just make an 
			img   id="INPUTINAME_Image" replaced bu the new image
			input  id="INPUTINAME" = replaced by the assetID
		**/
		,CustomAssetIDInsert : function(URL,Data,Settings){
			var RelativeURL = '/'+ URL.replace( /\.\.\//g, '' );
			var ThumbURL = Data.custom.thumbnail_url;
			var TargetID = Settings.target_elements;

			// max_wid and max_height limit
			if (Settings.max_width && Settings.max_width < Data.custom.width){
				alert('The image you selected has exceeded the maximum dimensions.');
				return false;
			}
			if (Settings.max_height && Settings.max_height < Data.custom.height){
				alert('The image you selected has exceeded the maximum dimensions.');
				return false;
			}

			// min_width and min_height limit
			if (Settings.min_width && Settings.min_width > Data.custom.width){
				alert('The image you selected is smaller than the minimum dimension.');
				return false;
			}
			if (Settings.min_height && Settings.min_height > Data.custom.height){
				alert('The image you selected is smaller than the minimum dimension.');
				return false;
			}

			// Get The AssetID
			$.post(PATH['Admin'] + This.AssetIDGetPath + '/',{'Thumb_ImagePath':ThumbURL,'ImagePath':RelativeURL},
				function(data){
					$('#' + TargetID).val(data);
					$('#' + TargetID + '_Image').attr('src',RelativeURL);
			});
			return true;
		}
	};
	return This; 
};
//------------------------------------------------------[MN]

// TinyMCE ---------------------------------------------[MN]
tinyMCE.init( {
	mode : 'none',
	theme : 'advanced',
	content_css : "/css/v1/ADM/admin.css",
	plugins : 'paste,imagemanager,table',
	theme_advanced_buttons1 : 'bold,italic,underline,|,bullist,numlist,|,outdent,indent,|,justifyleft,justifyright,justifycenter,justifyfull,|,forecolor,backcolor,|,link,unlink',
	theme_advanced_buttons2 : 'pastetext,pasteword,|,cut,copy,paste,pastetext,pasteword,insertimage,media,code,removeformat,|,tablecontrols',
	theme_advanced_buttons3 : '',
	apply_source_formatting : false,
	imagemanager_insert_template : '<img src="{$url}" />',
	relative_urls : false
} );
//------------------------------------------------------[MN]


// Constructors ----------------------------------------[MN]
var IMG = new Essence_ImageLibrary();
//------------------------------------------------------[MN]

//Check/Uncheck all checkboxes -------------------------[LB]
function CheckBoxStatus(GroupName, ControllerName, ElAttribute) {
	var CheckedStatus = true;

	ElAttribute = (ElAttribute) ? ElAttribute : 'name';

	$('input[' + ElAttribute + '~=' + GroupName + ']').each(function() {
		if ($(this).attr('checked') === false) {
			CheckedStatus = false;
		}
	});
	$('#' + ControllerName).attr('checked', CheckedStatus);
}
//------------------------------------------------------[LB]

// Event Delegation ------------------------------------[TN]
jQuery.delegate = function(Rules) {
	return function(e) {
		var Target = $(e.target);
		for (var Selector in Rules)
			if (Target.is(Selector)) return Rules[Selector].apply(this, $.makeArray(arguments));
	}
}
//------------------------------------------------------[TN]