var uplooad = {};
var ajaxRequest = {};
var toCompleter = {};
var dateCompleter = {};
var clientCompleter = {};
var projectPanelOpen = false;

window.addEvent('domready',function(){
	/* The password box */
	var passwordHdSlider = new Fx.Slide('password_hd',{duration: 50});
	var passwordBdSlider = new Fx.Slide('password_bd',{duration: 250});
	
	/* If there is no value in the from field, hide the password box */
	if($('display_password_field').getValue() == false){
		$('password').disabled = true;
		passwordHdSlider.hide();
		passwordBdSlider.hide();
	}
	
	function hidePasswordField(){
		$('password').disabled = true;
		passwordBdSlider.slideOut().chain(function(){
			passwordHdSlider.slideOut();
		});
	}
	
	function showPasswordField(){
		$('password').disabled = false;
		passwordHdSlider.slideIn().chain(function(){
			passwordBdSlider.slideIn();
		});
	}
	
	if($('project_id')){
		/* Select Project Box */
		$('project_slider').slider = new Fx.Slide('project_slider',{duration: 250});
		if($('project_slider').hasClass('hide')){
			$('project_slider').slider.hide();
			$('project_slider').removeClass('hide');
		}
		
		/* Create Project Box */
		$('new_project_hd').slider = new Fx.Slide('new_project_hd',{duration: 50});
		$('new_project_bd').slider = new Fx.Slide('new_project_bd',{duration: 250});
		$('new_project_hd').slider.hide();
		$('new_project_bd').slider.hide();
		$('new_project_hd').removeClass('hide');
		$('new_project_bd').removeClass('hide');
	
		$('create_new_project').addEvent('click',function(){ showProjectPanel(); });
		$('cancel_create_new_project').addEvent('click',function(){ hideProjectPanel(); });
		$('save_new_project').addEvent('click',function(){
			ajaxRequest.request('{"controller":"project","action":"create","callBack":"createProjectResponse","owner":"'+$('from').getValue()+'","name":"'+$('project_name').getValue()+'","client":"'+$('project_client').getValue()+'","description":"'+$('project_description').getValue()+'"}');
		});
	}
	
	
	/* When bluring the from field, figure out if we need to display the password field. Also set the options for the toCompleter */
	$('from').addEvent('blur',function(){
		toCompleter.options.postData.from = this.getValue();
		ajaxRequest.request('{"controller":"place_order","do":"check_account","from":"'+$('from').getValue()+'"}');
	});
	
	/* When bluring the password field, put the password in the toCompleter options so it can authenticate the user to get their contacts */
	$('password').addEvent('blur',function(){
		toCompleter.options.postData.password = this.getValue();
		ajaxRequest.request('{"controller":"account/login","action":"login","callBack":"loginRepsonse","email":"'+$('from').getValue()+'","password":"'+$('password').getValue()+'"}');
	});

	/* Adjust the layout */
	$('right_panel').style.height = $('apps').getSize().size.y - 6 + 'px';
	$('instructions').lastChild.style.height = $('apps').getSize().size.y - 150 + 'px';

	/* Hack for IE6, turn off rounded borders on tool tip windows */
	if(window.ie6){
		$$('.tool-title, .tool-text').each(function(el){
			el.style.background = '';
			el.style.backgroundColor = '#000';
		});
	}

	/* Initialize the to autocompleter */
	toCompleter = new Autocompleter.Ajax.Json($('to'), '/controller.php', {
		className: ($('type').getValue() == 'projectlink' ? 'blue' : ($('type').getValue() == 'orderlink' ? 'purple' : ($('type').getValue()=='invoicelink' ? 'green' : ($('type').getValue()=='doclink' ? 'orange' : ''))))+' autocompleter-choices',
		postData: {"controller":"to_autocompleter","from":$('from').getValue(),"password":$('password').getValue()}
	});
	
	if($('date_due')){
		dateCompleter = new Autocompleter.Ajax.Json($('date_due'), '/controller.php', {
			className: ($('type').getValue() == 'projectlink' ? 'blue' : ($('type').getValue() == 'orderlink' ? 'purple' : ($('type').getValue()=='invoicelink' ? 'green' : ($('type').getValue()=='doclink' ? 'orange' : ''))))+' autocompleter-choices',
			postData: {"controller":"date_autocompleter"}
		});
	}
	
	if($('project_id')){
		clientCompleter = new Autocompleter.Ajax.Json($('project_client'), '/controller.php', {
			className: ($('type').getValue() == 'projectlink' ? 'blue' : ($('type').getValue() == 'orderlink' ? 'purple' : ($('type').getValue()=='invoicelink' ? 'green' : ($('type').getValue()=='doclink' ? 'orange' : ''))))+' autocompleter-choices',
			postData: {"controller":"client_autocompleter","from":$('from').getValue(),"password":$('password').getValue()}
		});
	}
	
	/* Initialize the AJAX Request Object */
	// var ajaxRequest = new Ajax("/controllers/place_order.php",{
	ajaxRequest = new Ajax("/controller.php",{
		onRequest: function(){
			// hide all the error marks
			$$('.error_mark').each(function(e){
				e.addClass('hide');
			});
		},
		onComplete: function(r){
			var r = Json.evaluate(r);
			if(r.callBack){
				// If a callback was specified, execute it
				eval(r.callBack)(r);
			}
			if(r.error || r.warning){
				// Show the error mark for the inputs that have issues
				r.elements.each(function(e){
					$(e+'_error_mark').removeClass('hide');
				});
				// Focus on the first errored out input
				if($(r.elements[0]) && $(r.elements[0]).focus){
					$(r.elements[0]).focus();
				}
				
				if(r.error_message){
					// Alert the error message
					alert(r.error_message);
					$('status').setHTML(r.error_message);
				}else if(r.warning_message){
					$('status').setHTML(r.warning_message);
				}
			}
		},
		onSuccess: function(){ },
		onStateChange: function(){ },
		onFailure: function(){ alert('Request Failed. Please try again later.'); }
	});

	/* Initialize the Uploader */
	uplooad = new FancyUpload($('file'), {
		url: false,
		swf: '/swf/Swiff.Uploader.swf',
		multiple: true,
		queued: true,
		types: ($('type').getValue() == 'doclink' ? null : {'Documents (*.pdf, *.doc, *.xls)': '*.pdf; *.doc; *.xls'}),
		limitSize: false,
		limitFiles: false,
		createReplacement: null,
		instantStart: false,
		allowDuplicates: false,
		optionFxDuration: 250,
		container: $('swfContainer'),
		container: null,
		queueList: 'upload_queue',
		onComplete: Class.empty,
		onError: function(){ },
		onCancel: Class.empty,
		onAllComplete: submitTransaction
	});

	if(new Array('orderlink','invoicelink','doclink').contains($('type').getValue())){
		if(Swiff.getVersion() < 8){
			uplooad.use = false;
			$('order_form').target = 'upload_frame';
		}else if(Swiff.getVersion() == 10){
			uplooad.use = false;
			$('order_form').target = 'upload_frame';
			$('flashwarn').style.display = 'block';
		}else{
			uplooad.use = true;
		}
	}else{
		uplooad.use = false;
	}

	/* Setup all events and declare functions used by ajax callBacks */
	
	/* 1: Send Form data for validation on the server */
	$('send_it').addEvent('click',startValidation);

	
	/* Application Descriptions */
	$('app_summary').style.opacity = 1;
	$('app_summary').style.display = 'block';
	$('app_summary').opacityChange = new Fx.Style('app_summary', 'opacity',{duration:500});
	$$('ul.app_tabs li').each(function(li){
		var myText = li.title;
		li.removeProperty('title');
		
		// Save the classes for mouseleave/enter events
		li.classes = li.className.split(' ');

		li.addEvent('mouseenter',function(){
			// Remove the selected class from the other tabs
			$$('ul.app_tabs li').each(function(li){
				li.removeClass(li.classes[0]+'_selected');
			});
			
			// For browsers that dont support :selected
			li.addClass(li.classes[0]+'_selected');
			
			// Set the summary text
			$('app_summary').setHTML(myText);
			
		});
	});
	$$('ul.app_tabs').addEvent('mouseleave',function(){
		// Look at all the tabs and find the one that was selected in the beginning
		$$('ul.app_tabs li').each(function(li){
			if(li.classes[1]){
				li.fireEvent('mouseenter');
				li.addClass(li.classes[1]);
			}
		});
	})
	
	/* Instructions/Tool Tips for the form inputs */
	$('instructions').style.opacity = 0;
	$('instructions').style.display = 'block';
	var opacityChange = new Fx.Style('instructions', 'opacity',{duration:500});
	$('order_input_list').addEvent('mouseenter',function(){
		opacityChange.stop();
		opacityChange.start(0,.99);
	});
	$('order_input_list').addEvent('mouseleave',function(){
		opacityChange.stop();
		opacityChange.start(1,0);
	});
	
	$$('.input_list li').each(function(el){
		var myTitle;
		var myText;
	
		if(el.title){
			var dual = el.title.split('::');
			if(dual.length > 1){
				myTitle = dual[0].trim();
				myText = dual[1].trim().replace(/\r/g,"\n").replace(/\n/g,"<br/><br/>");
				myText = myText;
			}else{
				myTitle = '';
				myText = el.title;
			}
			el.addEvent('mouseenter',function(){
				$($('instructions').lastChild).setHTML('<h1>'+myTitle+'</h1>'+myText); // Double $() for IE7
			});
			el.addEvent('mouseleave',function(){
				$($('instructions').lastChild).setHTML(); // Double $() for IE7
			});
	
			el.removeProperty('title');
		}
	});
});

/* 1: Send Form data for validation on the server */
function startValidation(){
	if(projectPanelOpen){
		alert('Please either Save the new Project or Cancel');
		$('status').setHTML('Please either Save the new Project or Cancel');
		$('project_panel_open_error_mark').removeClass('hide');
		$('save_new_project').focus();
		return false;
	}
	
	if(new Array('orderlink','invoicelink','doclink').contains($('type').getValue())){
		if(window.uplooad.use && uplooad.nextFile() == -1){
			alert('Please click "Browse Files" and select some files to upload.');
			$('status').setHTML('Please click "Browse Files" and select some files to upload.');
			return false;
		}
	}
	
	
	$('status').setHTML('Sending Details...');
	// Clear out already sent files
	if(uplooad.use){
		uplooad.clearList();
	}
	
	ajaxRequest.request($('order_form').toJsonString());
}

/* 2: The form validated, Upload files */
function startUpload(){
	$('status').setHTML('Uploading Files...');
	if(uplooad.use){
		uplooad.upload();
	}else{
		$('order_form').submit();
	}
}

/* 3: The files uploaded, Submit the transaction */
function submitTransaction(){
	$('status').setHTML('Submitting Transaction...');
	ajaxRequest.request('{"controller":"place_order","do":"submit_transaction","type":"'+$('type').getValue()+'","tid":"'+$('tid').getValue()+'"}');
}

/* 4. Everything worked out, Provide some feedback */
function showConfirmation(r){
	showStatusPanel();
	$('result').setHTML(r.upload_result);
	$('status').setHTML('Done!');
	if(!uplooad.use && $('type').getValue()!='projectlink'){
		$('order_form').reset();
	}
	if(r.unconfirmed){
		alert('We just sent you an email with a confirmation link which will activate your account.');
	}
}

/* This function gets called by the iFrame after the upload completes when NOT using fancyupload */
function checkUpload(){
	var result = Try.these(
			function() {return window.frames['upload_frame'].document.body.innerHTML;},
			function() {return $('upload_frame').document.body.innerHTML;}
		);
	try{
		var response = eval(result);
		if(response.error){
			alert('Error: '+response.error_message);
			$('status').setHTML('Error: '+response.error_message);
		}else if(response.success){
			submitTransaction();
		}
	}catch(e){
		alert('Error: Could not determine the result of the upload.');
		$('status').setHTML('Error: Could not determine the result of the upload.');
	}
	
}

function hideProjectPanel(){
	projectPanelOpen = false;
	$('new_project_bd').slider.slideOut().chain(function(){
		$('new_project_hd').slider.slideOut();
	});
}
function showProjectPanel(){
	projectPanelOpen = true;
	$('new_project_hd').slider.slideIn().chain(function(){
		$('new_project_bd').slider.slideIn();
	});
}

function loginRepsonse(r){
	if(r.success){
		if($('project_id')){
			ajaxRequest.request('{"controller":"project","action":"get_list","callBack":"createProjectResponse","owner":"'+$('from').getValue()+'"}');
		}
	}
}

// Adds a newly created project
function createProjectResponse(r){
	if(r.success){
		// IE is a steaming pile
		if(window.ie){
			$('project_id').outerHTML = '<select id="project_id" name="project_id"><option></option>'+r.project_options+'</select>';
		}else{
			$('project_id').setHTML('<option></option>' + r.project_options);
		}
		
		$('project_slider').slider.slideIn();
		hideProjectPanel();
		$('project_name').value = '';
		$('project_client').value = '';
		$('project_description').value = '';
	}
}

/* Error handler */
function displayError(r){
	
}

function showStatusPanel(){
	var mySlide = new Fx.Slide('right_panel_content',{duration: 250}).slideOut().chain(function(){
		$('overview').addClass('hide');
		$('result').removeClass('hide');
		this.slideIn();
	});
}