$(document).ready(function()  {
	
  $(".tree").treeTable();	
	$('#association-dialog').dialog({autoOpen:false, bgiframe:true, modal:true, draggable:false, resizable:false, width:800, height:650});
	$('#association-dialog').dialog('option', 'buttons', { "Cancel": function() { $(this).dialog("close"); } });
	
	$('#setup-dialog').dialog({autoOpen:false, bgiframe:true, modal:true, draggable:false, resizable:false, width:400, height:400});
	$('#setup-dialog').dialog('option', 'buttons', { "Save": 
			function() { 
				
				// take care a few form elements
				$('#setup-data-pane').hide();		
				$('#setup-processing-error').html("").hide();
				// set the HTML, then show the message...
				$('#setup-processing-changes').html( processingChangesHTML() ).show();		
			
				 // sumit the data
				 $.getJSON("/index.cfm/do/manageenrollment.saveUserTypeSetup", {userid:$('#userid').val(), usertypeid:$('#usertypeid').val(), acctusertypeid:$('#acctusertypeid').val(), internalid:$('#internalid').val(), username:$('#username').val(), password:$('#password').val()},function(data){
				 	// if the result was returned as a success
					if(data.success == 'true'){
						//reload the associations now
						reloadUserAssociationsGrid($('#userid').val());
						// close the dialog window
						$('#setup-dialog').dialog('close');	
					}else{
						// there was an error....display it						
						// there was an error with the data supplied, so swap the data display back around and show the user the message...
						$('#setup-processing-changes').html("").hide();
						$('#setup-processing-error').html(data.returnHTML).show();
						$('#setup-data-pane').show();		
					}
			  });
	 		} 
	 });
	 
	 $('#setup-dialog').bind('dialogclose', function(event, ui) {
  	//alert('closed');
		// dialog back to the default
		$('#setup-data-pane').show();
		$('#setup-processing-changes').html("").hide();
		$('#setup-processing-error').html("").hide();
	});
	 
	$('#delete-dialog').dialog({autoOpen:false, bgiframe:true, modal:true, draggable:false, resizable:false, width:400, height:400});
	$('#delete-dialog').dialog('option', 'buttons', { 
		"Cancel": function() { $(this).dialog("close"); }, 
		"Delete": 
			function() { 	
			
				// take care a few form elements
				$('#delete-data-pane').hide();		
				$('#delete-processing-error').html("").hide();
				// set the HTML, then show the message...
				$('#delete-processing-changes').html( processingChangesHTML() ).show();
				
				 // sumit the data
				 $.getJSON("/index.cfm/do/manageenrollment.deleteAssociation", {userid:$('#userid').val(), usertypeid:$('#usertypeid').val(), acctusertypeid:$('#acctusertypeid').val(), termID:$('#termID').val(), itemID:$('#itemID').val()},function(data){
				 	// if the result was returned as a success
					if(data.success == 'true'){
						//reload the associations now
						reloadUserAssociationsGrid($('#userid').val());
						// close the dialog window
						$('#delete-dialog').dialog('close');	
					}else{
						// there was an error....display it						
						// there was an error with the data supplied, so swap the data display back around and show the user the message...
						$('#delete-processing-changes').html("").hide();
						$('#delete-processing-error').html(data.returnHTML).show();
						$('#delete-data-pane').show();		
					}
			  });
	 		} 
	 });
	 
	 $('#delete-dialog').bind('dialogclose', function(event, ui) {
		// dialog back to the default
		$('#delete-data-pane').show();
		$('#delete-processing-changes').html("").hide();
		$('#delete-processing-error').html("").hide();
	});
	 
	$('#modify-dialog').dialog({autoOpen:false, bgiframe:true, modal:true, draggable:false, resizable:false, width:400, height:320});
	$('#modify-dialog').dialog('option', 'buttons', { 
		"Cancel": function() { $(this).dialog("close"); },
		"Save Changes": 
			function() { 	
			
				// take care a few form elements
				$('#modify-data-pane').hide();		
				$('#modify-processing-error').html("").hide();
				// set the HTML, then show the message...
				$('#modify-processing-changes').html( processingChangesHTML() ).show();
				
				 // sumit the data
				 $.getJSON("/index.cfm/do/manageenrollment.modifyAssociation", {userid:$('#userid').val(), usertypeid:$('#usertypeid').val(), acctusertypeid:$('#acctusertypeid').val(), termID:$('#termID').val(), itemID:$('#itemID').val(),acctSecurityTypeID:$('#acctSecurityTypeID').val(),newtermID:$('#newtermID').val()},function(data){
				 	// if the result was returned as a success
					if(data.success == 'true'){
						//reload the associations now
						reloadUserAssociationsGrid($('#userid').val());
						// close the dialog window
						$('#modify-dialog').dialog('close');	
					}else{
						// there was an error....display it						
						// there was an error with the data supplied, so swap the data display back around and show the user the message...
						$('#modify-processing-changes').html("").hide();
						$('#modify-processing-error').html(data.returnHTML).show();
						$('#modify-data-pane').show();		
					}
			  });
	 		} 
		 });
		 
	$('#modify-dialog').bind('dialogclose', function(event, ui) {
		// dialog back to the default
		$('#modify-data-pane').show();
		$('#modify-processing-changes').html("").hide();
		$('#modify-processing-error').html("").hide();
	});
	
	
	$('#email-login-dialog').dialog({autoOpen:false, bgiframe:true, modal:true, draggable:false, resizable:false, width:700, height:600});
	
	 
	
	// bind the functions to the userAssociation grid
	bindAssociationGridFunctions();
	
	// when the term is changed....
	$('#term-id').change(function(){
		
		// get the tree for the term
		$(function () { 
			$("#tree-pane").tree({
				data : { 
					async : true,
					opts : {
						method : "GET",
						url : "/index.cfm/do/trees.surveyleveltree"
					}
				}
			,
			ui:{
					theme_path	: "/assets/css/treetheme/style.css",	// Path to the theme CSS file - if set to false and theme_name is not false - will lookup jstree-path-here/themes/theme-name-here/style.css
					theme_name	: "default"// if set to false no theme will be loaded
				},
				callback : {
					beforedata	: function(NODE,TREE_OBJ) { // PARAMETERS PASSED TO SERVER
						return { 
								ParentItemID : $(NODE).attr("id") || 0, 
								termid : $('#term-id').val(),
								rand : Math.floor(Math.random()*11) // this will ensure there is no caching going on....
								} 
							} 
				},
				rules	: {
					multiple	: false,	// FALSE | CTRL | ON - multiple selection off/ with or without holding Ctrl
					drag_copy	: false	// FALSE | CTRL | ON - drag to copy off/ with or without holding Ctrl
				},
			plugins : { 
					contextmenu : { 
						items : {
							// get rid of the remove item
							remove : false,
							create : false,
							rename : false,
							// add an item of our own
							my_act : {
								label	: "Add Access", 
								icon	: "", // you can set this to a classname or a path to an icon like ./myimage.gif
								visible	: function (NODE, TREE_OBJ) { 
									// this action will be disabled if more than one node is selected
									if(NODE.length != 1) return 0; 
									// this action will not be in the list if condition is met
									if(TREE_OBJ.get_text(NODE) == "Child node 1") return -1; 
									// otherwise - OK
									return 1; 
								}, 
								action	: function (NODE, TREE_OBJ) { 
									// send the request out... and populate the associations grid
									//console.log($(NODE).attr("id"))
									// load the information for this item....	
								$.get('/index.cfm/do/manageenrollment.addAssociation', {itemid:$(NODE).attr("id"), acctusertypeid:$('#association-dialog').data('acctUserTypeID')}, function(html){
										// Append the HTML to the table...
										$('#associations-pane table tbody').append(html)
										// unbind all
										$('.association-remove').unbind('click');										
										// bind the remove event...
										$('.association-remove').click(function() {
											$(this).parent().parent().remove();
											// now if there are no more associations....hide the table..
											if($('#associations-pane table tbody tr').length == 0){
												$('#associations-pane').hide();
											}
										});										
										$('#associations-pane').show();
										
									
									});	
										
								},
								separator_before : true
							}
						}
					}
				}
			});
		});	
			
		
		
		$('#association-dialog').dialog('option', 'buttons', { "Save Associations": function() { 
					$('#processing-error').html("").hide();
					$('#tree-pane').hide();
					$('#associations-pane').hide();
					// set the HTML, then show the message...
					$('#processing-changes').html( processingChangesHTML() ).show();	
					
					$('#association-acctusertypeid').val($('#association-dialog').data('acctUserTypeID'));
					$('#association-termid').val($('#term-id').val());
					$('#association-userid').val($('#userid').val());
					$('#association-usertypeid').val($('#usertypeid').val());
					
					$('#tree-drill-form').ajaxSubmit({dataType:'json', success:function(responseText, statusText){
						//console.log(responseText)
						// once saved...reload the grid on the main page....
						if (responseText.success == 'true') {
						  // reload the userAssociationGrid
						  reloadUserAssociationsGrid($('#userid').val());
							// now close the window
							$('#association-dialog').dialog('close');
							$('#associations-pane table tbody tr').remove();
							$('#associations-pane').hide();
						}else{
							// there was an error with the data supplied, so swap the data display back around and show the user the message...
							$('#processing-changes').html("").hide();
							$('#processing-error').html(responseText.returnHTML).show();
							$('#tree-pane').show();		
							$('#associations-pane').show();
						}
							
							
						}
					
					}); 
					
				}
			});	
		
		$('#tree-pane').show();
	});
	
	$('#association-dialog').bind('dialogclose', function(event, ui) {
  	//alert('closed');
		// dialog back to the default
		$('#term-id').val("");
		$('#tree-pane').html("").hide();
		$('#processing-changes').html("").hide();
		$('#association-dialog').removeData('acctUserTypeID');
		$('#association-dialog').dialog('option', 'buttons', { "Cancel": function() { $(this).dialog("close"); } });
	});
	
});

// reloadGridData
function reloadUserAssociationsGrid(userid){
	$.get('/index.cfm/do/manageenrollment.userAssociationsGrid', {userid:userid}, function(html){
		//set the html of the new grid
		$('#user-associations-grid').html(html);
		// b/c the HTML was updated, rebind the functions for the grid
		bindAssociationGridFunctions();
	});
}

// binds the functions to the association grid
function bindAssociationGridFunctions(){
	
	// add the functions to the association link
	$('.add-association-link').click(function(){
		// attach the acctUserTypeID to the dialog data structure...
		$('#association-dialog').data('acctUserTypeID', $(this).attr('id'));
		$('#usertypeid').val($('#' + $(this).attr('id') + '-usertypeid').val());
		$('#term-id').val("");
		$('#association-dialog').dialog('open');
	});
		
	// add the functions to the setup link
	$('.setup-level-link').click(function(){
		var acctUserTypeID = $(this).attr('id');
		// attach the acctUserTypeID to the dialog data structure...
		$('#setup-dialog').data('acctUserTypeID', $(this).attr('id'));
		$('#usertypeid').val($('#' + acctUserTypeID + '-usertypeid').val());
		$('#acctusertypeid').val(acctUserTypeID);
		$('#internalid').val($('#' + acctUserTypeID + '-internalid').val());
		$('#username').val($('#' + acctUserTypeID + '-username').val());
		$('#password').val($('#' + acctUserTypeID + '-password').val());
		
		$('#password-field').show().val("");
		// check the auth method, if it is plugin, then we need to hide the username and password fields.
		if($('#' + acctUserTypeID + '-authMethodID').val() != 'UsernameandPassword'){
			$('#username-field').hide().val("");
			$('#password-field').hide().val("");
		}else{
			$('#username-field').show().val("");
			$('#password-field').show().val("");
		}
		
		$('#setup-dialog').dialog('open');
	});	
	
	// add the functions to the delete link
	$('.association-delete-link').click(function(){
		var acctUserTypeID = $(this).attr('id');
		var itemID = $(this).attr('itemID');
		var termID = $(this).attr('termID');
		
		$('#usertypeid').val($('#' + acctUserTypeID + '-usertypeid').val());
		$('#acctusertypeid').val(acctUserTypeID);
		$('#termID').val(termID);
		$('#itemID').val(itemID);
		$('#delete-dialog').dialog('open');
	});
		
	// add the functions to the modify link
	$('.association-modify-link').click(function(){
		var acctUserTypeID = $(this).attr('id');
		var itemID = $(this).attr('itemID');
		var termID = $(this).attr('termID');
		
		$('#usertypeid').val($('#' + acctUserTypeID + '-usertypeid').val());
		$('#acctusertypeid').val(acctUserTypeID);
		$('#termID').val(termID);
		$('#itemID').val(itemID);
		
		//Get the AcctUserType
		$.getJSON("/index.cfm/do/manageenrollment.AcctSecurityType", {userTypeID:$('#usertypeid').val(),itemID:$('#itemID').val(),termID:$('#termID').val()},function(data){
			var acctSecurityTypeID = data.acctSecurityTypeID;
			
			for(var i=0;i<document.getElementById('acctSecurityTypeID').options.length;i++) {
				if(document.getElementById('acctSecurityTypeID').options[i].value == acctSecurityTypeID) {
					document.getElementById('acctSecurityTypeID').options.selectedIndex = i;
				}
			}
		});
		for(var i=0;i<document.getElementById('newtermID').options.length;i++) {
			if(document.getElementById('newtermID').options[i].value == $('#termID').val()) {
				document.getElementById('newtermID').options.selectedIndex = i;
			}
		}
		
		
		$('#modify-dialog').dialog('open');
	});
	
	$('.email-login-link').click(function(){
		
		var acctUserTypeID = $(this).attr('id');
		$('#usertypeid').val($('#' + acctUserTypeID + '-usertypeid').val());
		$('#usertypename').val($('#' + acctUserTypeID + '-usertypename').val());
		$('#email').val($('#' + acctUserTypeID + '-email').val());
		$('#acctusertypeid').val(acctUserTypeID);
		$('#to_email').html($('#' + acctUserTypeID + '-email').val());
		
		
		var iframe_location = $(location).attr('protocol') + '//' + $(location).attr('host') + '/index.cfm/do/Communication.EmailUserLogin/acctUserTypeID/' + acctUserTypeID + '/usertypename/' + $('#' + acctUserTypeID + '-usertypename').val() + '/email/' + $('#' + acctUserTypeID + '-email').val() + '/usertypeid/' + $('#' + acctUserTypeID + '-usertypeid').val();

		
		$('#email-login-dialog').html('<iframe id="email-login-body" width="650" height="1000" marginWidth="0" marginHeight="0" frameBorder="0" scrolling="no" /><div id="loading" style="display:none;" />').dialog('open');
		$("#email-login-body").attr("src",iframe_location);
		
		$('#email-login-dialog').dialog('open');
	});
}

/******* START: General functions *******/

	// returns the ajaxLoaderHTML
	function ajaxLoaderHTML(){
		return '<div align="center" style="margin-top:3em;"><img src="/assets/icons/ajax-loader.gif" border="0" /></div>'
	}
	
	// returns the processingChangesHTML
	function processingChangesHTML(){
		return '<div align="center" style="margin-top:3em;">Processing changes....</div>'
	}
	
	function closeEmailDialog() {
		$('#email-login-dialog').dialog("close");
	}

/******* END: General Functions *******/