var currentProjectId = '';

function validateMailFormFields() {
	var hasError = false;
	var errors = [];
	$("div.error ul", $('#mailDialog')).empty();
	$("div.error", $('#mailDialog')).hide();
	$("label.error, h3.error").removeClass('error');
	
	if (!$("#txtFromEmail").val().length) {
		errors.push("Please enter your email address.");
		$("label[for=txtFromEmail]").addClass('error');
		hasError=true;
	}
	if (!$("#txtName").val().length) {
		errors.push("Please enter your name.");
		$("label[for=txtName]").addClass('error');
		hasError=true;
	}
	
	if (!$("#txtToEmail").val().length) {
		errors.push("Please enter the recipient's email address.");
		$("label[for=txtToEmail]").addClass('error');
		hasError=true;
	}
	
	if (!Recaptcha.get_response().length) {
		errors.push("Please enter the security code.");
		$("#pre_mailCaptcha h3").addClass('error');
		hasError=true;
	}
	if (hasError) {
		for (var i =0; i< errors.length; i++) {
			$("#mailDialog div.error ul").append($("<li>").text(errors[i]));
		}
		$("#mailDialog div.error").show();
		adjustDialogPosition($("#mailDialog").parents(".ui-dialog"));
		
	}
	
	return !hasError;
}

function validateNewRequestFormFields(order) {
	var errorMessages = [];
	$("#projectInfo .errorMessage ul").empty();
	$("#projectInfo .errorMessage").hide();
	$("#projectInfo .error").removeClass('error');
	
	if ($(":radio[name=existingProject]:checked").val() == 0) {
	
		$("#projectInfo .required input:not(.notrequired)" +
			",#projectInfo .required textarea:not(.notrequired)" +
			",#requestInfo .required input:not(.notrequired)" +
			",#requestInfo .required textarea:not(.notrequired)").each(function() {
			if (order && $(this).closest('required').hasClass('notForOrder')) {
				return true;
			}
				
			if ($(this).val() == '') {
				$(this).closest(".required").addClass('error');
				var fieldName = $(this).attr('title');
				errorMessages.push("The " + fieldName.toLowerCase() + " is required");
			}
		});
	
	}
	if (errorMessages.length) {
		for (var i =0; i<errorMessages.length; i++) {
			$("#projectInfo .errorMessage ul").append($("<li>").text(errorMessages[i]));
		}
		$("#projectInfo .errorMessage").show();
		adjustDialogPosition($("#requestDialog").parents(".ui-dialog"));
		return false;
	}
	return true;
}

function validateExistingRequestFormFields() {
	$("#projectInfo .errorMessage ul").empty();
	$("#projectInfo .errorMessage").hide();
	$("#requestDialog .error").removeClass('error');
	var errorMessages = [];
	
	$("label.error").removeClass('error');
	if ($("#requestJob").val() == '') {
		errorMessages.push("Please select a job.");
		$("#requestJob").parents('tr').addClass('error');
		return;
	} 
	
	$("#existingProject .required input:not(.notrequired)"+
		",#existingProject .required textarea:not(.notrequired)" +
		",#requestInfo .required input:not(.notrequired)" +
		",#requestInfo .required textarea:not(.notrequired)").each(function() {
		if ($(this).val() == '') {
			$(this).closest(".required").addClass('error');
			var fieldName = $(this).attr('title');
			errorMessages.push("The " + fieldName.toLowerCase() + " is required");
		}
	});

	if (errorMessages.length) {
		for (var i =0; i<errorMessages.length; i++) {
			$("#projectInfo .errorMessage ul").append($("<li>").text(errorMessages[i]));
		}
		$("#projectInfo .errorMessage").show();
		adjustDialogPosition($("#requestDialog").parents(".ui-dialog"));
		return false;
	}
	return true;
}

function sendMail(data, type) {
	var sendButton=$('.ui-dialog-buttonpane button:first', $('#mailDialog').closest('.ui-dialog'));
	sendButton.addClass('ui-state-disabled');
	sendButton.prop('disabled',true);	
	if (validateMailFormFields()) {
		$.ajax ({		
			data: data,
			success: function(responseData) {
				if (responseData == "Success") {
					$('#mailDialog').dialog('close');
					showAlert('A copy of your ' + type + ' has been sent to "' + data.toEmail + '".', function() {}, "Email Sent");
					$.cookie('fromEmail', data.fromEmail, {path: COOKIE_PATH});
					$.cookie('emailName', data.fromName, {path: COOKIE_PATH});
				} else {
					$("div.error ul", $('#mailDialog')).append($('<li>').html("There was an unknown error sending your email."));	
				}
			},
			error: function(jqXHR, textStatus, errorThrown){
				$("div.error ul", $('#mailDialog')).append($('<li>').html(errorThrown));
				$("div.error", $('#mailDialog')).show();
				adjustDialogPosition($("#mailDialog").parents(".ui-dialog"));
				Recaptcha.reload();
				sendButton.removeClass('ui-state-disabled');
				sendButton.prop('disabled',false);
			}
		});
	//re-enable the button on validation error.
	} else {
		sendButton.removeClass('ui-state-disabled');
		sendButton.prop('disabled',false);
	}
	
}

function getAddressFields() {
	var addressFields = {};
	
	if ($("#mailingAddressId").val() == '' ) {
		$(".mailing_field").each(function() {
			addressFields[$(this).attr('id')] = $(this).val();
		});
		
	} else {
		addressFields['mailingAddressId'] = $("#mailingAddressId").val();
	}
	
	if ($("#billingAddressId").val() == '' ) {
		$(".billing_field").each(function() {
			addressFields[$(this).attr('id')] = $(this).val();
		});
		
	} else {
		addressFields['billingAddressId'] = $("#billingAddressId").val();
	}
	addressFields['sameAddress'] = $("#sameAddressContactForm").is(':checked') ? '1' :'0';
	return addressFields;
}

function contactResearcherExistingProject(projectId, data) {
	var sendButton=$('.ui-dialog-buttonpane button:first', $('#requestDialog').closest('.ui-dialog'));
	sendButton.addClass('ui-state-disabled');
	sendButton.prop('disabled',true);	
	if (validateExistingRequestFormFields()) {
		var addressFields = getAddressFields();
		$.ajax ({		
			data: $.extend({
				action: 'createRequest',
				type: 'existing',
				jobId: $("#requestJob").val(),
				researcherName:  $("#researcherName").val(),
				message: $("#projectMessage").val(),
				title: $("#projectName").val(),
				projectId: projectId == null ? '' : projectId,
				projectDescription: $("#projectDescription").val(),
				masterFormat: $("#projectMasterFormat").val(),
				masterFormatOther: $("#projectMasterFormatOther").val(),
				fedexNumber: $("#fedexNumber").val(),
				dvd: $("#projectDVD").is(':checked') ? '1' : '0',
				deliveryDate: $("#projectDate").val(),
				rights: $("#projectRights").val()
				
			}, addressFields, data),
			success: function(data) {
			
				$('#requestDialog').dialog('close');
				showAlert(
					"Thank you!  Your contact request was sent, and your Historic Films representative will be following up with you.",
					function() {}, 
					"Request Sent"
				);
			
			},
			error: function(jqXHR, textStatus, errorThrown){
				$("#projectInfo .errorMessage ul", $('#requestDialog')).append($('<li>').text(errorThrown));
				$("#projectInfo .errorMessage").show();	
				sendButton.removeClass('ui-state-disabled');
				sendButton.prop('disabled',false);
				adjustDialogPosition($("#requestDialog").parents(".ui-dialog"));
				$("#requestDialog")[0].scrollTop($("#requestDialog")[0].scrollHeight);
			}
		});
	} else {
		sendButton.removeClass('ui-state-disabled');
		sendButton.prop('disabled',false);
		adjustDialogPosition($("#requestDialog").parents(".ui-dialog"));
		$("#requestDialog")[0].scrollTop($("#requestDialog")[0].scrollHeight);
		
	}
}

function contactResearcherNewProject(data, order) {
	var sendButton=$('.ui-dialog-buttonpane button:first', $('#requestDialog').closest('.ui-dialog'));
	sendButton.addClass('ui-state-disabled');
	sendButton.prop('disabled',true);	
	if (validateNewRequestFormFields(order)) {
		var addressFields = getAddressFields();
		$.ajax ({		
			data: $.extend({
				action: 'createRequest',
				type: 'new',
				title: $("#projectName").val(),
				message: $("#projectMessage").val(),
				projectDescription: $("#projectDescription").val(),
				masterFormat: $("#projectMasterFormat").val(),
				masterFormatOther: $("#projectMasterFormatOther").val(),
				fedexNumber: $("#fedexNumber").val(),
				dvd: $("#projectDVD").is(':checked') ? '1' : '0',
				deliveryDate: $("#projectDate").val(),
				rights: $("#projectRights").val()
			},data, addressFields),
			success: function(data) {
			
				$('#requestDialog').dialog('close');
				showAlert(
					"Thank you!  Your contact request was sent, and an Historic Films representative will be following up with you.",
					function() {}, 
					"Request Sent"
				);
			
			},
			error: function(jqXHR, textStatus, errorThrown){
				$("#projectInfo .errorMessage ul", $('#requestDialog')).append($('<li>').text(errorThrown));
				$("#projectInfo .errorMessage").show();
				sendButton.removeClass('ui-state-disabled');
				sendButton.prop('disabled',false);
				adjustDialogPosition($("#requestDialog").parents(".ui-dialog"));
				$("#requestDialog")[0].scrollTop($("#requestDialog")[0].scrollHeight);
			} 
		});
	} else {
		sendButton.removeClass('ui-state-disabled');
		sendButton.prop('disabled',false);
		adjustDialogPosition($("#requestDialog").parents(".ui-dialog"));
		$("#requestDialog")[0].scrollTop($("#requestDialog")[0].scrollHeight);
	}
}

function contactResearcher(data) {
	
	$("#requestDialog .error").removeClass('error');
	$("#projectInfo .errorMessage").hide();
	if ($(":radio[name=existingProject]:checked").val() == 1) {
		contactResearcherExistingProject( currentProjectId, data);
	} else if (data.orderId) {
		contactResearcherNewProject(data,true);
	} else {
		contactResearcherNewProject(data, false);
	}
}

function showMailBinDialog(binId) {

	$('#mailDialog').dialog('option', 'title', 'Email Bin');
	$('#mailDialog .email').show();
	$("#mailDialog p .type").text('bin');
	$("#mailDialog .emailResearcher").unbind().click(function() {
		
		$("#requestDialog #projectMessage").val($("#emailMessage").val());
		$("#mailDialog").dialog('close');
		showContactResearcherBinDialog(binId);
	});
	
	$('#mailDialog').dialog('option', 'buttons',
	{
		"Send Mail": function() {
			var events = [];
			if (binId == currentBinId) {
				count =0;
				$("#clipBin li").each(function() {
					events.push([
						"Share Clip", 
						$(this).hasClass('specialty') ? 'Specialty Collection' : 'Standard Collection', 
						$("h5",$(this)).text()
					]);
			
				});
			
			} else if (binId == displayBinId) {
				$("#binContents li").each(function() {
					events.push([
						"Share Clip", 
						$(this).hasClass('specialty') ? 'Specialty Collection' : 'Standard Collection', 
						$(".tapeId",$(this)).text()
					]);
				});
			}
			trackEvents(events);
			sendMail({
				action: 'mailBin',
				binId: binId,
				toEmail: $("#txtToEmail").val(),
				fromEmail: $("#txtFromEmail").val(),
				fromName: $("#txtName").val(),
				message: $("#emailMessage").val(),
				captchaChallenge: Recaptcha.get_challenge(),
				captchaResponse: Recaptcha.get_response()
			}, 'bin');

		},
		"Cancel": function () {
			$(this).dialog('close');
		}
	});
	$('#mailDialog').parent().css({position:"fixed"}).end().dialog('open');;
}

function showMailClipDialog(tapeId, inOffset, outOffset, title) {
	
	$('#mailDialog').dialog('option', 'title', 'Mail Clip');
	$('#mailDialog .email').show();
	$("#mailDialog p .type").text('clip');
	$("#mailDialog .emailResearcher").unbind().click(function() {
		
		$("#requestDialog #projectMessage").val($("#emailMessage").val());
		showContactResearcherClipDialog(tapeId, inOffset, outOffset, title);
		$("#mailDialog").dialog('close');
	});
	
	$('#mailDialog').dialog('option', 'buttons', {
		"Send Mail": function() {
			var sendButton=$('.ui-dialog-buttonpane button:first', $('#mailDialog').closest('.ui-dialog'));
			sendButton.addClass('ui-state-disabled');
			sendButton.prop('disabled',true);
			trackEvent("Share Clip", 
				$("#videoWindow .specialty").is(':visible') ? 'Specialty Collection' : 'Standard Collection',
				$(".tapeId", $("#videoWindow")).text(), tapeId);
			sendMail({
				action: 'mailClip',
				tapeId: tapeId,
				clipId: currentClipId ? currentClipId : '',
				clipType: currentClipType,
				offsetIn: inOffset,
				offsetOut: outOffset,
				title: title,
				toEmail: $("#txtToEmail").val(),
				fromEmail: $("#txtFromEmail").val(),
				fromName: $("#txtName").val(),
				message: $("#emailMessage").val(),
				captchaChallenge: Recaptcha.get_challenge(),
				captchaResponse: Recaptcha.get_response()
			}, 'clip');
		},
		"Cancel": function () {
			$(this).dialog('close');
		}
	});
	$('#mailDialog').parent().css({position:"fixed"}).end().dialog('open');
}

function showContactResearcherClipDialog(tapeId, inOffset, outOffset, title) {
	
	$('#requestDialog').dialog('option', 'buttons',
	{
		"Send Request": function() {
			trackEvent(
				"Request", 
				$("#videoWindow .specialty").is(':visible') ? 'Specialty Collection' : 'Standard Collection',
				$(".tapeId", $("#videoWindow")).text()
			);
			contactResearcher({
				tapeId: tapeId,
				offsetIn: inOffset,
				offsetOut: outOffset,
				clipTitle: title
			});	
		},
		"Cancel": function () {
			$(this).dialog('close');
		}
	});
	$('#contactAttachNotice').text('The clip you selected will be attached to your message.');
	openRequestDialog();
}

function showContactResearcherBinDialog(binId) {
	
	$('#requestDialog').dialog('option', 'buttons',
	{
		"Send Request": function() {
			
			var	events = [];
			if (binId == currentBinId) {
				count =0;
				$("#clipBin li").each(function() {
					events.push([
						"Request", 
						$(this).hasClass('specialty') ? 'Specialty Collection' : 'Standard Collection', 
						$("h5",$(this)).text()
					]);
			
				});
			
			} else if (binId == displayBinId) {
				$("#binContents li").each(function() {
					events.push([
						"Request", 
						$(this).hasClass('specialty') ? 'Specialty Collection' : 'Standard Collection', 
						$(".tapeId",$(this)).text()
					]);
				});
			}
			trackEvents(events);
			contactResearcher({
				binId: binId
			});
		},
		"Cancel": function () {
			$(this).dialog('close');
		}
	});
	$('#contactAttachNotice').text('The bin you selected will be attached to your message.');
	openRequestDialog();
}

function showContactResearcherOrderDialog(orderId) {
	
	$(".notForOrder").hide();
	
	$.ajax({
		data: {
			action: 'getOrder',
			orderId: orderId
		},
		success: function(data) {
			showOrderProjectInfo($.parseJSON(data));
			$('#requestDialog').dialog('option', 'buttons',
			{
				"Send Request": function() {
					
					contactResearcher({
						orderId: orderId
					});
				},
				"Cancel": function () {
					$(this).dialog('close');
				}
			});
			$('#contactAttachNotice').text('The order you selected will be attached to your message.');
			openRequestDialog();
			$(".ui-dialog-buttonpane button:contains('Send Request')")
			 	.removeAttr('disabled', 'disabled')
			 	.removeClass('ui-state-disabled');
		}
	});
}

function showContactResearcherDialog() {
	
	$('#requestDialog').dialog('option', 'buttons',
	{
		"Send Request": function() {
			contactResearcher({});	
		},
		"Cancel": function () {
			$(this).dialog('close');
		}
	});
	$('#contactAttachNotice').html('Note! If you would like to discuss specific footage you see on the site, close this window and use the <span class="bigToolsStyle">"<img alt="Contact icon" src="template/icon_contact.png">Contact a researcher"</span> buttons you see in the context of clips or bins instead.  Those clips or bins will then be attached to your request.');

	openRequestDialog();

}

function openRequestDialog() {
	if (!isLoggedIn) {
		showAlert("Please sign in or create an account to contact a researcher.", null, "Contact a Researcher");			
	} else {
		$('#requestDialog').parent().css({position:"fixed"}).end().dialog('open');
		$(".ui-dialog-buttonpane button:contains('Send Request')", $("#requestDialog").parent())
			 	.prop('disabled',true)
			.addClass('ui-state-disabled');
	}
}

function showOrderProjectInfo(order) {
	$(".fedexNumber").hide();
	$("#projectDVD").removeAttr('checked');
	$("#projectDate").val('');
	$(".notForOrder").hide();
	
	$(".existingProjectHeader").show();
	$(".newProjectHeader").hide();

	$("#projectMasterFormat").val(order.deliveryFormat);
	if (order.deliveryFormatOther) {
		$(".other").show();
		$("#projectMasterFormatOther").val(order.deliveryFormatOther);
		if (order.deliveryFormat != "Digital file for Download") {
			$("#fedexNumber").show();
		}
	} else {
		$(".other").hide();
		$("#projectMasterFormatOther").val('');
	}
	
	if (order.fedexNumber) {
		$("#fedexNumber").val(order.fedexNumber);
	} else {
		$("#fedexNumber").val('');
	}
	
	
	$("#billingAddressId").val(order.billingAddressId);
	if (order.billingAddressId) {
		showAddress('billing', order.billingAddress);
	} else {
		//clearAddress('billing');
	}
	$("#mailingAddressId").val(order.mailingAddressId);
	if (order.mailingAddressId) {
		showAddress('mailing', order.mailingAddress);
	} else {
		//clearAddress('mailing');
	}
	if (order.mailingAddressId != order.billingAddressId) {
		$("#sameAddressContactForm").removeAttr('checked');
	} else {
		$("#sameAddressContactForm").attr('checked', 'checked');
	}
	$("#projectInfo").show();
}

function showProjectInfo(requestProject) {
	currentProjectId = requestProject.id;
	$(".fedexNumber").hide();
	$("#projectDescription").val(requestProject.projectDescription);
	$("#projectMasterFormat").val(requestProject.masterFormat);
	if (requestProject.masterFormatOther) {
		$(".other").show();
		$("#projectMasterFormatOther").val(requestProject.masterFormatOther);
		if (requestProject.masterFormat != "Digital file for Download") {
			$("#fedexNumber").show();
		}
	} else {
		$(".other").hide();
		$("#projectMasterFormatOther").val('');
	}
	
	if (requestProject.dvd == 1) {
		$("#projectDVD").attr('checked', 'checked');
		$(".fedexNumber").show();
	} else {
		$("#projectDVD").removeAttr('checked');
	}
	if (requestProject.fedexNumber) {
		$("#fedexNumber").val(requestProject.fedexNumber);
	} else {
		$("#fedexNumber").val('');
	}
	if (requestProject.expectedDelivery) {
		$("#projectDate").val(formatDate(requestProject.expectedDelivery, "Y-m-d"));
	} else {
		$("#projectDate").val('');
	}
	$("#projectRights").val(requestProject.rights);
	$("#billingAddressId").val(requestProject.billingAddressId);
	if (requestProject.billingAddressId) {
		showAddress('billing', requestProject.billingAddress);
	} else {
		clearAddress('billing');
	}
	$("#mailingAddressId").val(requestProject.mailingAddressId);
	if (requestProject.mailingAddressId) {
		showAddress('mailing', requestProject.mailingAddress);
	} else {
		clearAddress('mailing');
	}
	if (requestProject.mailingAddressId != requestProject.billingAddressId) {
		$("#sameAddressContactForm").prop('checked', false);
		$("div.mailingAddress").show();
	} else {
		$("#sameAddressContactForm").prop('checked', true);
		$("div.mailingAddress").hide();
	}
	$("#projectInfo").show();
	adjustDialogPosition($("#requestDialog").parents(".ui-dialog"));
}

function clearProjectInfo() {
	currentProjectId =null;
	$(".notForOrder").show();
	$("#projectDescription").val('');
	$("#projectMasterFormat").val("Digital file for Download");
	$(".other").hide();
	$("#projectMasterFormatOther").val('');
	$("#projectDVD").removeAttr('checked');
	$(".fedexNumber").hide();
	$("#fedexNumber").val('');
	$("#projectDate").val('');
	$("#projectRights").val('');
	//clearAddress('billing');
	//clearAddress('mailing');
	$("#sameAddressContactForm").attr('checked', 'checked');
	$("#projectInfo").show();
}

function showAddress(prefix, address) {
	$("#" + prefix + "_streetAddress").val(address.streetAddress);
	$("#" + prefix + "_city").val(address.city);
	$("#" + prefix + "_countryId").val(address.countryId);
	$("#" + prefix + "_regionId").empty();
	$.each(address.country.regions, function(index, value) {
		$("#" + prefix + "_regionId").append($("<option>").attr('value', value.id).text(value.name));
	});
	$("#" + prefix + "_zipcode").val(address.zipcode);
}

function clearAddress(prefix) {
	$("#" + prefix + "_streetAddress").val('');
	$("#" + prefix + "_city").val('');
	$("#" + prefix + "_countryId").val('');
	$("#" + prefix + "_regionId").empty();
	$("#" + prefix + "_zipcode").val('');
}

function setAddressesTodefault() {
	
	function fillIn(prefix) {
		if (userAddress[prefix]) {
			$("#" + prefix + "_name").val(userAddress[prefix].name);
			$("#" + prefix + "_streetAddress").val(userAddress[prefix].streetAddress);
			$("#" + prefix + "_city").val(userAddress[prefix].city);
			$("#" + prefix + "_countryId").val(userAddress[prefix].countryId);
			$("#" + prefix + "_regionId").val(userAddress[prefix].regionId);
			$("#" + prefix + "_zipcode").val(userAddress[prefix].zipcode);
		}
	}
	
	fillIn('billing');
	fillIn('mailing');
	if (userAddress['mailing'] !=  null && userAddress['mailing'].addressId == userAddress['billing'].addressId) {
		$("#sameAddressContactForm").prop('checked', true);
		$("div.mailingAddress").hide();
	}
}

$(document).ready(function() {

	
	$("#mailDialog").dialog({
		autoOpen:false,
		modal: true,
		resizable: false,
		width:480,
		open: function() {
			pauseVideo();
			Recaptcha.destroy();
			Recaptcha.create(recaptchaPublicKey, 
				"mailCaptcha", 
				{
					theme: "clean",
					callback: function() { adjustDialogPosition($("#mailDialog").parents(".ui-dialog")); }
				}
			);
			$("div.error ul", $('#mailDialog')).empty();
			$("div.error").hide();
			$("label.error, h3.error").removeClass('error');
			if (isLoggedIn) {
				$("#mailCaptcha").hide();
			}
			$("#txtFromEmail").val($.cookie('fromEmail') == null ? '' : decodeURIComponent($.cookie('fromEmail')));
			$("#txtName").val($.cookie('emailName') == null ? '' : decodeURIComponent($.cookie('emailName')));
			var sendButton=$('.ui-dialog-buttonpane button:first', $('#mailDialog').closest('.ui-dialog'));
			sendButton.removeClass('ui-state-disabled');
			sendButton.prop('disabled',false);
		
		},
		close: function() {
			$("input,textarea", $(this)).val('');
		}
		
	});
	
	$("#requestDialog").dialog({
		autoOpen:false,
		modal: true,
		resizable: false,
		width:550,
		open: function() {
			adjustDialogPosition($("#requestDialog").parents(".ui-dialog"));
			pauseVideo();

		},
		close: function() {
			$(".clearable", $(this)).val('');
			$("#requestDialog .error").removeClass('error');
			$("#projectInfo .errorMessage").hide();
			$("#existingProject").hide();
			$("#projectInfo").hide();
			$("tr.researcherName").hide();
			$("#researcherName").val('');
			$("#requestJob").val('');
			setAddressesTodefault();
			clearProjectInfo();
			$(".newProjectHeader").hide();
			$(".existingProjectHeader").hide();
			$("#existingProject").hide();
			$("#projectInfo").hide();
			$("#requestDialog :radio").each(function() {
				this.checked= false;
			});
			
			$(".ui-dialog-buttonpane button:contains('Send Request')", $("#requestDialog").parent())
			 	.prop('disabled', true)
			 	.addClass('ui-state-disabled');
			
		}
	});
	
	$( "#projectDate" ).datepicker({
		showOn: 'button',
		buttonImage: 'template/icons/calendar.png',
		buttonImageOnly: true,
		dateFormat: "yy-mm-dd",
		changeMonth: true,
		changeYear: true,
		buttonText: "Open a calendar",
		beforeShow: function() {
			if ($("#ui-datepicker-div").parent().not('.jQueryDatePicker').length) {
				$("#ui-datepicker-div").wrap($("<span>").addClass('jQueryDatePicker'));
			}
		}
	});
	
	$(":radio[name=existingProject]").change(function() {
		
		clearProjectInfo();	
		if ($(this).val() == 1) {
			$("#existingProject").show();
			if ($("#requestJob .realopt").length == 0) {
				$("#requestJob").val(-1);
				$("#requestJob").parents('tr').hide();
				$("tr.researcherName").show();
			}
			
			$(".newProjectHeader").hide();
			$(".existingProjectHeader").show();
			$("#projectInfo").hide();
			
		} else {
			$(".ui-dialog-buttonpane button:contains('Send Request')")
			 	.prop('disabled', false)
			 	.removeClass('ui-state-disabled');
			$("#projectInfo").show();
			$(".newProjectHeader").show();
			$(".existingProjectHeader").hide();
			$("#existingProject").hide();
			$(".projectField").val('');
			$("#requestJob").val('');
			$(".existingProjectHeader .requirementNote").show();
			$("#projectInfo .notRequiredForProject").addClass('required');
			$("#projectInfo .notRequiredForProject").removeClass('notRequiredForProject');
		}
		adjustDialogPosition($(this).parents(".ui-dialog"));
	});
	
	$(".billing_field", $("#requestDialog")).change(function() {
		$("#billingAddressId").val('');
	});
	
	$(".mailing_field", $("#requestDialog")).change(function() {
		$("#mailingAddressId").val('');
	});
	
	$("#sameAddressContactForm").change(function() {
		if ($(this).is(':checked')) {
			$(".mailingAddress").hide();
			adjustDialogPosition($(this).parents(".ui-dialog"));
		} else {
			$(".mailingAddress").show();
			adjustDialogPosition($(this).parents(".ui-dialog"));
		}
	});
	
	$("#requestJob").change(function() {
		if ( $(this).val() == '') {	
			
			clearProjectInfo();
			$("#projectInfo").hide();
			$("tr.researcherName").hide();
			$(".ui-dialog-buttonpane button:contains('Send Request')")
			 	.prop('disabled', true)
			 	.addClass('ui-state-disabled');
			$("#requestDialog").height($("#requestDialog").height() - $("#projectInfo").height());
			adjustDialogPosition($(this).parents(".ui-dialog"));
			return;
		} 
		$(".ui-dialog-buttonpane button:contains('Send Request')")
			.prop('disabled', false)
			.removeClass('ui-state-disabled');
		if ($(this).val() == -1) {
			$("tr.researcherName").show();
			$(".existingProjectHeader .requirementNote").show();
			$("#projectInfo .notRequiredForProject").addClass('required');
			$("#projectInfo .notRequiredForProject").removeClass('notRequiredForProject');
			clearProjectInfo();
			$("#projectInfo").show();
			setAddressesTodefault();
			adjustDialogPosition($(this).parents(".ui-dialog"));
		} else if ($(this).val()) {
			$.ajax({
				data: {
					action: 'getRequestProject',
					jobId: $(this).val()
				},
				success: function(data) {
					$("tr.researcherName").hide();
					$("#projectInfo").show();
					$(".existingProjectHeader .requirementNote").hide();
					$("#projectInfo .required").addClass('notRequiredForProject');
					$("#projectInfo .required").removeClass('required');
					
					if (data) {
						showProjectInfo($.parseJSON(data));
					} else {
						clearProjectInfo();
					}
					adjustDialogPosition($("#requestDialog").parents(".ui-dialog"));
				}
			});
		}
		
	});
	
	$("#projectMasterFormat").change(function() {
		if ($(this).val() == '') {
			$(".other", $(this).parent()).show();
		} else {
			$(".other", $(this).parent()).hide();
		}
		if ($(this).val() != "Digital file for Download") {
			$(".fedexNumber").show();
		} else if (!$("#projectDVD").is(':checked')) {
			$(".fedexNumber").hide();
		}
		adjustDialogPosition($(this).parents(".ui-dialog"));
	});
	
	$("#projectDVD").change(function() {
		if ($(this).is(':checked')) {
			$(".fedexNumber").show();
		} else if ($("#projectMasterFormat").val() == "Digital file for Download") {
			$(".fedexNumber").hide();
		}
	});
	
	$("#mailing_countryId").change(function() {
		if ($(this).val()) {
			getRegions($(this).val(), 'mailing');
		}
	});
	
	$("#billing_countryId").change(function() {
		if ($(this).val()) {
			getRegions($(this).val(), 'billing');
		}
	});
	
});


