$.namespace('AdminManageusers');

AdminManageusers = $.klass({
	initialize: function (config) {

		var that = this;
		// hack to ge level menu to display properly with float left.
		// Its basicly a dummy toolbar with the same CSS under the real toolbar
		//this.toolbarunder = $('<div class="toolbar2 clearfix"><\/div>')
		//	.appendTo(this.element);

		this.toolbarmaster = $('<div class="toolbar clearfix"><\/div>')
			.appendTo(this.element)
			.attach(AdminManageusers.Toolbar, {
				grid: config.grid,
				store: config.store
		});
	}

});



/**
 * The manage user toolbar, consisting of user selection tools
 */
AdminManageusers.Toolbar = $.klass({
	initialize: function (config) {
		var that = this;
		
		this.selectme = $('<div><\/div>')
			.appendTo(this.element)
			.attach(AdminManageusers.Toolbar.Selectme, {
				toolbar: this,
				grid:config.grid,
				store: config.store
			});

		this.level = $('<div><\/div>')
			.appendTo(this.element)
			.attach(AdminManageusers.Toolbar.Level, {
				toolbar: this,
				grid:config.grid,
				store: config.store
			});

		this.element.children().click(function(){
			$(this).siblings().each(function(){return $(this).firstAttached(AdminManageusers.Toolbar.Item).hide();});
		});
		
	}
});
/**
 * A superclass for toolbar items expecting to be passed the document in config.
 */
AdminManageusers.Toolbar.Item = $.klass({
	initialize: function (config) {
		/* hack so that firstAttached will return the field attached to an element */
		if (!AdminManageusers.Toolbar.Item.instances) {
			AdminManageusers.Toolbar.Item.instances = [];
		}
		AdminManageusers.Toolbar.Item.instances.push(this);
	},
	show:function(){},
	hide:function(){}
});

AdminManageusers.Toolbar.Selectme = $.klass(AdminManageusers.Toolbar.Item, {
	initialize: function ($super, config) {
		
		var that = this;
			
		var sm = config.grid.getSelectionModel();
		
		var grid = config.grid;

		var store = config.store;

		var v = grid.getView();
		
		var groups = [];

		var subjects = [];

		var messages = [];

		this.toolbar = $('<div><\/div>');

		this.element.append(that.toolbar); 
	
		this.userfiltering = $('<div class="userfiltering clearfix"><\/div>')
			.append($('<div class="dropdown">Select users from group: <\/div>'))
			.appendTo(that.toolbar);

		this.checkboxgrid = $('<div class="checkboxgrid clearfix"><\/div>')
			.appendTo(that.toolbar);

		this.bigcontainer = $('<div id="bigcontainer" style="display: none;" ><\/div>')
			.appendTo(that.element);

		this.tabcontainer = $('<div id="tabcontainer"><\/div>')
			.appendTo(that.bigcontainer);

		this.sidepanelcontainer = $('<div id="sidepanelcontainer"><b>The following people will receive this email:<b\/><\/div>')
			.appendTo(that.bigcontainer);

		this.tabnav = $('<ul id="tabnav"><\/ul>')
			.appendTo(that.tabcontainer);

		this.tabdiv = $('<div id="tabdiv"><\/div>')
			.appendTo(that.tabcontainer);

		// All Tab
		$('<li id="tab-nav-All"><a href="#tab-All">Selected<\/a><\/li>').appendTo(that.tabnav);

		$('<div id="tab-All" class="All tabtogglediv"><\/div>')
			.append($('<div class="email-forms" id="email-form-All"><\/div>')
			.append($('<tr><td><label for="id_subject_All">Subject:<\/label><\/td><td><input type="text" id="id_subject_All" name="subject" ><\/td><\/tr>'))
			.append($('<tr><td colspan="2"><textarea id="msgme_All" name="message" cols="43" rows="10"><\/textarea><\/td><\/tr>'))
			.append($('<tr><td colspan="2"><p class="help-manage-users"><\/p><\/td><\/tr>')))
			.appendTo(that.tabdiv);

		$('#id_subject_All').val("Subject here");
		$('#msgme_All').text("Enter the body of your email here");

		$('<div id="sidepanel-All" class="sidepanel"><\/div>')
				.append('<div style="visibility:hidden;">space<\/div>')
				.appendTo(that.sidepanelcontainer);
		
		$.get(window.location.pathname, {
			c: randomString(20),
			getdata:''
			},function(data){
				var groups = data.groups;
				var subjects = data.subjects;
				var messages = data.messages;

				for (var i = 0; i < groups.length; i++) {

					// Create tab for each group
					$('<li id="tab-nav-'+groups[i]+'" class="tabtoggle"><a href="#tab-'+groups[i]+'">'+groups[i]+'<\/a><\/li>').appendTo(that.tabnav);
					// remove table from here as well
					$('<div id="tab-'+groups[i]+'" class="'+groups[i]+' tabtogglediv"><\/div>')
					.append($('<div class="email-forms" id="email-form-'+groups[i]+'"><\/div>')
					.append($('<tr><td><label for="id_subject_'+groups[i]+'">Subject:<\/label><\/td><td><input type="text" id="id_subject_'+groups[i]+'" name="subject" ><\/td><\/tr>'))
					.append($('<tr><td colspan="2"><textarea id="msgme_'+groups[i]+'" name="message" cols="43" rows="10"><\/textarea><\/td><\/tr>'))
					.append($('<tr><td colspan="2"><p class="help-manage-users"><\/p><\/td><\/tr>')))
					.appendTo(that.tabdiv);

					// Load messages & subjects
					$('#id_subject_'+groups[i]).val(subjects[i]);
					$('#msgme_'+groups[i]).val(messages[i]);				
				

					// Side panels

					$('<div id="sidepanel-'+groups[i]+'" class="sidepanel"><\/div>')
						.append('<div style="visibility:hidden;">space<\/div>')
						.appendTo(that.sidepanelcontainer);

					// Create checkboxes on the toolbar for every group
					$('<input type="checkbox" class="'+groups[i]+' groupcheckbox" value="'+groups[i]+'" >'+groups[i]+'<\/input>')
						.click(function (e) {
							//e.preventDefault();
							var groups2 = "";

							var levellist = "";
							
							for (var j = 0; j < groups.length; j++) {

								if ($("."+groups[j]).attr('checked')) {
									groups2 = groups2 + groups[j] +',';
									//groups2.push(groups[j]);
								}
								  
							}

							$(".levelcheckbox:checked").each(function(i,el){
								levellist = levellist + $(el).val() + ',';
   					
							});

							var emaillist = [];
							var rec2select = [];

							var store2 = grid.getStore();

							$.get(window.location.pathname, {
								c: randomString(20),
								emaillist:'',
								groups:groups2,
								endswith:$(".endswith:text").val(),
								levels:levellist
								},function(data){
									emaillist = data.emaillist;
									//globalemaillist = data.emaillist;
									store2.each(function (record) {
									for (x in emaillist) {
										if (emaillist[x][0] == record.data.email) {
											rec2select.push(record);
											emaillist.splice(x,1);
											break;
										}
									}
								});
								sm.selectRecords(rec2select);
								var myselect = sm.getSelected();
								if (myselect) { 
									v.focusRow(store.indexOf(myselect));
								}										
							}, 'json');						
											
						})
						.appendTo(that.checkboxgrid);
			
				} //end for loop

				$(".email-forms").wrapInner("<table><\/table>");

				$(".help-manage-users").append('<div>Include these <b>keywords<\/b> in your message and they will be<\/div>')
							.append('<div>replaced by the corresponding values: <\/div>')
							.append('<div><b>USERNAME<\/b> will be replaced by the recipients username <\/div>')
							.append('<div><b>FIRSTNAME<\/b> will be replaced by the recipients firstname <\/div>')
							.append('<div><b>LASTNAME<\/b> will be replaced by the recipients lastname <\/div>')
							.append('<div><b>LEVEL<\/b> will be replaced by the recipients level in a competition <\/div>')
							.append('<div><b>REFERENCE-ID<\/b> will be replaced by the recipients reference-id <\/div>');
				

				$('<input type="checkbox" class="allc groupcheckbox" value="all" >All<\/input>')
					.click(function (e) {
						if ($(".allc").attr('checked')) {
							sm.selectAll();
							$(".groupcheckbox").attr({checked:'checked'});
						}
						else {
							sm.clearSelections();
							$(".groupcheckbox").attr({checked:''});
						}
					})
					.appendTo(that.checkboxgrid);

				this.endswith = $('<div class="endswith">Search: <\/div>')
					.appendTo(that.toolbar);

				this.endswith = $('<input class="endswith" align="left" type="text" size="10" value=""><\/input>')
					.keyup(function (e) {
						if (this.value != this.pdataentered) {
	
							var endswith = this.value;
	
							if (this.waitforme) {
	
								clearTimeout(this.waitforme);
							}
	
							this.waitforme = setTimeout(function (e) {
							
								var groups2 = "";

								var levellist = "";
								
								for (var j = 0; j < groups.length; j++) {
	
									if ($("."+groups[j]).attr('checked')) {
										groups2 = groups2 + groups[j] +',';
									}
									  
								}
	
								$(".levelcheckbox:checked").each(function(i,el){
									levellist = levellist + $(el).val() + ',';
								});

								var emaillist = [];
								var rec2select = [];
	
								var store2 = grid.getStore();
	
								$.get(window.location.pathname, {
									c: randomString(20),
									emaillist:'',
									groups:groups2,
									endswith:endswith,
									levels:levellist
									},function(data){
										emaillist = data.emaillist;
										//globalemaillist = data.emaillist;
										store2.each(function (record) {
										for (x in emaillist) {
											if (emaillist[x][0] == record.data.email) {
												rec2select.push(record);
												emaillist.splice(x,1);
												break;
											}
										}
									});
									sm.selectRecords(rec2select);
									var myselect = sm.getSelected();
									if (myselect) { 
										v.focusRow(store.indexOf(myselect));
									}										
								}, 'json');	
								
							}, 200);
	
							this.pdataentered = this.value;
						}
				
					})
					.appendTo(that.toolbar);
													
			}, 'json');
			
	
			$super(config);
	}				
		
});


/**
 * A superclass for dropdown-style toolbar items.
 */
AdminManageusers.Toolbar.Dropdown = $.klass(AdminManageusers.Toolbar.Item, {
	initialize: function ($super, settings) {
		$super(settings);
		var that = this;
		
		this.settings = $.extend({hideDelay:500, showDelay:1500}, settings);

		this.link = $('> a.dropdown', this.element)
			.click(function (e) {
				e.preventDefault();
				if (that.menu.is(':visible')) {
					that.hide();
				} else {
					that.show();
				}
			})
			.blur(function (e) {
					// Commented out the following, prevents menus from closing when element clicked
					//that.hide();
				});				
		this.menu = $('> ul.dropdown', this.element)
			.hide()
			.css({
				top: this.link.position().top + this.link.outerHeight(),
				right: $('#document').innerWidth() - this.link.position().left - this.link.outerWidth() - 2
				//right: $('#document').innerWidth() - this.link.offset().left - this.link.position().left - this.link.outerWidth()
			});
			
		this.element
			.hover(function () {			
				if (that.$timer) {
					clearTimeout(that.$timer);
					that.$timer = undefined;
				}
			}, function() {
				if (that.$timer) {
					clearTimeout(that.$timer);
					that.$timer = undefined;
				}
				if (that.menu.is(':visible')) {
					that.$timer = setTimeout(function() {
						that.hide();
						that.$timer = undefined;
					}, that.settings.hideDelay);
				}
			});

	},
	show: function(){
		this.link.addClass('expanded');
		this.menu.slideDown(500);
	}, 
	hide: function(){
		var that = this;
		this.menu.slideUp(1000,function () {
			that.link.removeClass('expanded');
		});
	}
});
/**
 * Toolbar item for Level selection.
 */

AdminManageusers.Toolbar.Level = $.klass(AdminManageusers.Toolbar.Dropdown, {
	initialize: function ($super, config) {
		var that = this;

		var sm = config.grid.getSelectionModel();
		
		var grid = config.grid;

		var store = config.store;

		var items = $('<ul class="dropdown"><\/ul>');

		var v = grid.getView();

		$.get(window.location.pathname, {
			c: randomString(20),
			getlevels:''
			},function(data){

				for (var i = 0; i < data.levels.length; i++) { 
					$('<li><a><input type="checkbox" class="levelcheckbox" value="'+data.levels[i]+'">'+data.levels[i]+'</input><\/a><\/li>')
						.click(function (e) {
							
							var groups2 = "";

							var levellist = "";

							$(".groupcheckbox:checked").each(function(i,el){
								groups2 = groups2 + $(el).val() + ',';
   					
							});

							$(".levelcheckbox:checked").each(function(i,el){
								levellist = levellist + $(el).val() + ',';
   					
							});
							
							var emaillist = [];
							var rec2select = [];

							var store2 = grid.getStore();

							$.get(window.location.pathname, {
								c: randomString(20),
								emaillist:'',
								groups:groups2,
								endswith:$(".endswith:text").val(),
								levels:levellist
								},function(data){
									emaillist = data.emaillist;
									//globalemaillist = data.emaillist;
									store2.each(function (record) {
									for (x in emaillist) {
										if (emaillist[x][0] == record.data.email) {
											rec2select.push(record);
											emaillist.splice(x,1);
											break;
										}
									}
								});
								sm.selectRecords(rec2select);
								var myselect = sm.getSelected();
								if (myselect) { 
									v.focusRow(store.indexOf(myselect));
								}
								
																		
							}, 'json');
							
						})
						.appendTo(items);
				}	// end for	
				
				//v.focusRow(15);
							
		}, 'json');		

		this.element
			.addClass('levels dropdown')
			.append('<a title="Levels" href="#" class="dropdown">Levels<\/a>')
			.append(items);

		$super(config);
	}
});

