var App = {
	Models:{},
	Collections:{},
	Views:{},
	Contacts:null,
	Directory: null,
	ContactPane: null
};

pageLayoutOptions = {
	name                 : "pageLayout",
	defaults__fxName    : 'none',
	resizeWithWindowDelay: 250,
	north__paneSelector  : "#charter-net-header",
	north__size          : 85,
	center__paneSelector : "#application",
	center__size         : '100%',
	spacing_open         : 0,
	spacing_closed       : 0,
	center__childOptions : {
		name                : "appLayout",
		resizable           : false,
		slidable            : false,
		closable            : false,
		north__paneSelector : "#primary-tab-buttons",
		center__paneSelector: "#primary-tab-panes",
		north__size         : 39,
		center__size        : '100%',
		spacing_open        : 0,
		spacing_closed      : 0,
		center__onresize    : $.layout.callbacks.resizeTabLayout
	}
};

emailLayoutOptions = {
	name                : "emailLayout",
	defaults__fxName    : 'none',
	slidable            : false,
	triggerEventsOnLoad : true,
	resizeWithWindow    : true,
	north__resizable    : false,
	west__resizable     : false,
	north__closable     : false,
	west_closable       : false,
	spacing_open        : 0,
	spacing_closed      : 0,
	triggerEventsOnLoad : true,
	north__size         : 78,
	west__size          : 230,
	center__onresize    : $.layout.callbacks.resizeTabLayout,
	center__childOptions: {
		name                : "messageLayout",
		defaults__fxName    : 'none',
		resizeable          : true,
		slidable            : false,
		closable            : true,
		center__initHidden  : true,
		east__initHidden    : true,
		west__initHidden    : false,
		west__size          : '100%',
		spacing_open        : 0,
		spacing_closed      : 0,
		east__childOptions  : {
			name                : "composeMessageLayout",
			defaults__fxName    : 'none',
			resizable           : false,
			slidable            : false,
			closable            : false,
			north__paneSelector : "#compose-tab-buttons",
			center__paneSelector: "#compose-tab-panes",
			north__size         : 51,
			center__size        : '100%',
			spacing_open        : 0,
			spacing_closed      : 0,
			center__onresize    : $.layout.callbacks.resizeTabLayout
		},
		east__onresize_end          : function (pane, $pane, paneState, paneOptions){
				emailPaneLayout.center.children.messageLayout.sizePane(pane,'100%');
			},
		west__onresize_end      : toggleEmailListView
	}
}

contactsLayoutOptions = {
	name                : "contactsLayout",
	defaults__fxName    : 'none',
	triggerEventsOnLoad : true,
	resizeWithWindow    : true,
	north__resizable    : false,
	west__resizable     : false,
	north__closable     : false,
	west_closable       : false,
	spacing_open        : 0,
	spacing_closed      : 0,
	triggerEventsOnLoad : true,
	north__size         : 78,
	west__size          : 230	
}

settingsLayoutOptions = {
	name                : "settingsLayout",
	defaults__fxName    : 'none',
	triggerEventsOnLoad : true,
	resizeWithWindow    : true,
	west__resizable     : false,
	west_closable       : false,
	spacing_open        : 0,
	spacing_closed      : 0,
	triggerEventsOnLoad : true,
	west__size          : 230
}

var pageLayout, emailPaneLayout, contactsPaneLayout, settingsPaneLayout,
    messagePaneLayout;

function openComposeMessagePane()
{
	emailPaneLayout.center.children.messageLayout.center.pane.hide();
	emailPaneLayout.center.children.messageLayout.west.pane.hide();

	emailPaneLayout.center.children.messageLayout.close('west');
	emailPaneLayout.center.children.messageLayout.close('center');

	emailPaneLayout.center.children.messageLayout.sizePane('east','100%');
	emailPaneLayout.center.children.messageLayout.open('east');
	setEmailButtonBarState('compose');

}

function resetEmailListPane()
{
	messagePaneLayout.close('center');
	messagePaneLayout.hide('center');
	messagePaneLayout.center.pane.hide();

	messagePaneLayout.close('east');
	messagePaneLayout.hide('east');
	messagePaneLayout.east.pane.hide();

	messagePaneLayout.open('west');
	messagePaneLayout.sizePane('west','100%');

	// don't have ttime to figure out this nonsense but this hack
	// should be investigated...
	messagePaneLayout.west.state.autoResize = true;

	$("#email-list-header").show();
	setEmailButtonBarState('default');
	resetEmailListResizeButton();
	$('#tabular-email-list :checked').prop('checked',false).parents('tr').removeClass('active');
}

function setEmailButtonBarState(state)
{
	/*
	 * TODO: REFACTOR, these switch values can be classes of the element
	 * determining the elements display
	 */

	var buttons;
	switch(state)
	{
		case 'single-checkbox':
			buttons = {
				'get-mail-button':true,
				'sort-mail-dropdown-button':true,
				'mark-mail-dropdown-button':true,
				'more-mail-dropdown-button':true,
				'reply-mail-button':true,
				'replyall-mail-button':true,
				'forward-mail-button':true,
				'send-mail-button':false,
				'attach-mail-button':false,
				'save-draft-mail-button':false,
				'delete-mail-button':true,
				'help-mail-button':true
			};
			break;
		case 'multi-checkbox':
			buttons = {
				'get-mail-button':true,
				'sort-mail-dropdown-button':true,
				'mark-mail-dropdown-button':true,
				'more-mail-dropdown-button':true,
				'reply-mail-button':false,
				'replyall-mail-button':false,
				'forward-mail-button':false,
				'send-mail-button':false,
				'attach-mail-button':false,
				'save-draft-mail-button':false,
				'delete-mail-button':true,
				'help-mail-button':true
			};
			break;
		case 'compose':
			buttons = {
				'get-mail-button':true,
				'sort-mail-dropdown-button':false,
				'mark-mail-dropdown-button':false,
				'more-mail-dropdown-button':false,
				'reply-mail-button':false,
				'replyall-mail-button':false,
				'forward-mail-button':false,
				'send-mail-button':true,
				'attach-mail-button':true,
				'save-draft-mail-button':true,
				'delete-mail-button':false,
				'help-mail-button':true
			};
			break;
		default:
			buttons = {
				'get-mail-button':true,
				'sort-mail-dropdown-button':true,
				'mark-mail-dropdown-button':false,
				'more-mail-dropdown-button':false,
				'reply-mail-button':false,
				'replyall-mail-button':false,
				'forward-mail-button':false,
				'send-mail-button':false,
				'attach-mail-button':false,
				'save-draft-mail-button':false,
				'delete-mail-button':false,
				'help-mail-button':true
			};
	}

	for(var btn in buttons)
	{
		var key = "#" + btn;
		(buttons[btn])? $(key).show() : $(key).hide();
	}
}

function autoResizeEmailList(e)
{
	var width = 35;
	var drctn = 'right';
	var opdir = 'left';
	var tabls = '-210px';

	if( $(this).hasClass('auto-resize-button-right') )
	{
		width = 268;
		drctn = 'left'
		opdir = 'right';
		tabls = '0px';
	}

	messagePaneLayout.sizePane('west',width);
	

	$(this)
		.removeClass( ('auto-resize-button-'+opdir) )
		.addClass( ('auto-resize-button-'+drctn) );

}

function resetEmailListResizeButton()
{	
	$('#mail-list-auto-resizer')
		.removeClass('auto-resize-button-right')
		.addClass('auto-resize-button-left');
}


function toggleEmailListView(pane, $pane, paneState, paneOptions)
{
	// reset the message-items left margin
	$('#tabular-email-list').css('margin-left',0);

	// TODO: this 268 is going to be hard to find
	if(paneState.innerWidth > 268 )
	{
		$('#tabular-email-list .multi-column-view').show();
		$('#tabular-email-list .two-column-view').hide();
		$('#email-list-header').show();
	} else {
		
		if( paneState.innerWidth < 268 ){
			$('#tabular-email-list').css('margin-left','-208px');
		}

		$('#tabular-email-list .multi-column-view').hide();
		$('#tabular-email-list .two-column-view').show();
		$('#email-list-header').hide();
	}
}


$(function(){
	pageLayout = $('body').layout( pageLayoutOptions );

	pageLayout.center.pane
		.tabs({
			// activate: $.layout.callbacks.resizeTabLayout
			activate: function(evt,ui){
				var tabLayout = $(ui.newPanel).data("layout");
				if( tabLayout ){
					tabLayout.resizeAll();
				}

				if(ui.newTab.prop('id') === 'email-tab'){
					$("#email-account-dropdown-button").show();
					$("#email-search-dropdown-button").show();
				} else {
					$("#email-account-dropdown-button").hide();
					$("#email-search-dropdown-button").hide();
				}
			}
		});

	
	pageLayout.center.children.appLayout.resizeAll();

	emailPaneLayout    = $('#email-pane').layout( emailLayoutOptions );
	contactsPaneLayout = $('#contacts-pane').layout( contactsLayoutOptions );
	settingsPaneLayout = $('#settings-pane').layout( settingsLayoutOptions );
	messagePaneLayout  = emailPaneLayout.center.children.messageLayout;

	var composeTabs = emailPaneLayout.center.children.messageLayout.east.pane
		.tabs({
			activate: $.layout.callbacks.resizeTabLayout
		});

	emailPaneLayout.center.children.messageLayout.resizeAll();

	composeTabs.delegate( "span.tab-close-ctrl","click",function(){
		var panelId = $(this).closest("li").remove().prop('aria-controls');
		$( "#" + panelId ).remove();
		composeTabs.tabs("refresh");
	})

	// Associate drop down menus and buttons
	var blurTimer;
	var blurTimerAbandoned = 200;

	$('.dropdown-menu').menu({
		blur: function(e, ui){ 

			blurTimer = setTimeout(function(){
				$('.dropdown-menu-button').removeClass('active');
				$('.dropdown-menu').hide();
			},blurTimerAbandoned)
		},
		focus: function(e,ui){
			clearTimeout(blurTimer);
		}
	});

	// Align the right sides of the advanced search dropdown menu
	$('#email-search-dropdown-button').prop('data-align-side','right');

	// Set the button bar to its default state
	setEmailButtonBarState('default');

	// Open the compose message pane
	$('#compose-mail-button').click( openComposeMessagePane );


	// Open the message display panel
	// but first stop propagation on checkbox click preventing the 
	// click from bubbling up/down and triggering a message-item click
	$('#tabular-email-list td.email-list-checkbox-column input[type="checkbox"]').click(function(e){
		e.stopPropagation();
		var totalList  = $('#tabular-email-list td.email-list-checkbox-column').length;
		var numChecked = $('#tabular-email-list td.email-list-checkbox-column :checked').length;

		if(numChecked === 0){
			resetEmailListPane();
		} else if(numChecked === 1) {
			setEmailButtonBarState('single-checkbox');
		} else if( numChecked > 1) {
			setEmailButtonBarState('multi-checkbox');
		}

		// reflect in the header if all of in list are checked
		var chkHeader = (totalList===numChecked) ? true : false;
		$('#email-list-checkbox-select-all').prop('checked',chkHeader);

		// add/remove active depending on check state
		$(this).prop('checked') ? $(this).closest('tr').addClass('active') : $(this).closest('tr').removeClass('active');
		
	});

	// Open the message display panel
	$('.message-item').click(function(e){
		emailPaneLayout.center.children.messageLayout.open('center');
		emailPaneLayout.center.children.messageLayout.center.pane.show();
		emailPaneLayout.center.children.messageLayout.sizePane('west',268);
		// ensure that this item is the only item with a checked check
		// box
		$(this).addClass('active').find(':checkbox').prop('checked',true);
		$(this).siblings().removeClass('active').find(':checked').prop('checked',false);
		setEmailButtonBarState('single-checkbox');
		$("#email-list-header").hide();
	});

	// Close the message display panel
	$('#message-display-pane-close-button').click( resetEmailListPane );

	// Imap folder buttons reveal #mail-list pane
	$('.imap-folder-button').click(function(e){
		$('.imap-folder-button').removeClass('active');
		$(this).addClass('active');
		resetEmailListPane()
	});

	$('#email-list-checkbox-select-all').click(function(e){
		var checked = $(this).prop('checked');
		var chkitms = $('td.email-list-checkbox-column input[type="checkbox"]');
		chkitms.prop('checked',!checked);
		chkitms.click();
	});

	$('#mail-list-auto-resizer').click( autoResizeEmailList );

	// transform textareas into editors
	$('textarea.rte').ckeditor({toolbar:'Basic'});

	$('#spinner').remove();

	App.Contacts = new App.Collections.Contact();

	$.each(Fixture.contacts,function(i,contact){
		App.Contacts.add(contact);
	});

	App.Directory = new App.Views.Directory({
		el: $('#contacts-list-pane')
	});

	App.Directory.render();

	App.Contacts.on('add remove sort', function(){ App.Directory.render() });

	App.ContactPane = new App.Views.ContactPane({
		$el : $('#contacts-pane'),
		collection : App.Contacts
	});

});