/*******************************************************
 *	Functions used throughout the osc wizard process.
 *
 *******************************************************/
 
function goToEvent( OSCWizardForm, location ){
 	OSCWizardForm.action = location ;  
 	OSCWizardForm.submit() ;
 
 	return false;
}

function setVehicleFields( OSCWizardForm, DMSVehicleId, customerVehicleId, year, make, makeCode, model, modelCode, mileage ){

	OSCWizardForm.elements['DMSVehicleId'].value = DMSVehicleId ;
	OSCWizardForm.elements['customerVehicleId'].value = customerVehicleId ; 
 	OSCWizardForm.elements['vehicleYear'].value = year ;
 	OSCWizardForm.elements['vehicleMake'].value = make ;
 	OSCWizardForm.elements['vehicleMakeCode'].value = makeCode ;
	if( model ) OSCWizardForm.elements['vehicleModel'].value = model ;
 	if( modelCode ) OSCWizardForm.elements['vehicleModelCode'].value = modelCode ;
 	if( mileage ){
		OSCWizardForm.elements['vehicleMileage'].value = mileage ;
	}else{
		OSCWizardForm.elements['vehicleMileage'].value = 0 ;
	}
}

function setNewVehicleFields(thisForm){
	setVehicleFields(thisForm, "OSC_NEW_VEHICLE", 0, thisForm.newVehicleYear.options[thisForm.newVehicleYear.selectedIndex].value, thisForm.newVehicleMake.options[thisForm.newVehicleMake.selectedIndex].innerHTML, thisForm.newVehicleMake.options[thisForm.newVehicleMake.selectedIndex].value, thisForm.newVehicleModel.options[thisForm.newVehicleModel.selectedIndex].innerHTML, thisForm.newVehicleModel.options[thisForm.newVehicleModel.selectedIndex].value, 0 );
}

function setCustomerVehicleSelector(thisForm, selectedValue){
	setRadioValue(thisForm.customerVehicleSelector, selectedValue);;
}

function initNewVehicleForm(){
	$(":radio[name='customerVehicleSelector']").click(
  		function() {
  			if(this.value == "OSC_NEW_VEHICLE"){
  				$("#addNewVehicle").show("fast");
    		} else{
    			$("#addNewVehicle").hide("fast");
    		}
    		return true;
  		}
  	);
  	
	if( $(":radio[name='customerVehicleSelector']").length == 1 ){
		$(":radio[name='customerVehicleSelector']").attr("checked",true) ;
	}
  	
  	if( $(":radio[name='customerVehicleSelector']:checked").val() !== "OSC_NEW_VEHICLE" ){
  		$("#addNewVehicle").hide();
 	}
}

function setAdvisorName( OSCWizardForm, name ){
 	OSCWizardForm.elements['serviceAdvisorName'].value = name ;
}

function initSelectServicesForm(){
	//	the link to add new custom service describers
	$("#addServiceDescriberLink").click(
  		function() {
		  	//	Add new textarea when customer previously entered custom services comment
			if($("input[name='customServiceDescriptions']").val() != ""){
				var clonedRow = $("table#customServiceDescriptionsTable  tr:last").clone();	
				var defaultExplanationText = "[ENTER DESCRIPTION]";
				
				// clear the value of the copied textarea
				$(":textarea[name='customServiceDescriptionAdder']", clonedRow).val( defaultExplanationText );
				
				$("table#customServiceDescriptionsTable").prepend( clonedRow );
			}

			// Show custum descriptions when user clicks on add custom description
	  		$("#customServiceDescriptions").show();
  		}
  	);

  	//	Show all previously entered custom services comment boxes
	if($("input[name='customServiceDescriptions']").val() != ""){
  		$("#customServiceDescriptions").show();
	}
}

function removeCustomServiceExplanation(removeButton) {
	var deleteDescription = $(removeButton).prev("textarea").val();

	if( confirm( "Delete: " + deleteDescription + "?") ){

		var customDescriptions = $("input[name='customServiceDescriptions']").val().split("|OSC_DESC_DELIM|");

		for(var i = 0; i < customDescriptions.length; i++){
			if(customDescriptions[i] == deleteDescription){ 
				customDescriptions.splice(i,1);
				break;
			}
		}

		$("input[name='customServiceDescriptions']").val( customDescriptions.join('|OSC_DESC_DELIM|') );
		if($("input[name='customServiceDescriptions']").val() != ""){ 
			$(removeButton).parent().parent().remove();
		}else{
			$(removeButton).prev("textarea").html("[ENTER DESCRIPTION]");
			$("#customServiceDescriptions").slideUp("fast");
		}
	}

	// When all custom descriptions are deleted, hide the custom description textarea
	if(thisForm.customServiceDescriptions.value != ""){
		$("#customServiceDescriptions").slideDown("fast");			
		$(":hidden#customServices").val("");
	}
}

function clearCustomServiceExplanation(textArea){
	var defaultExplanationText = "[ENTER DESCRIPTION]";
	
	if( textArea.value == defaultExplanationText ){
		textArea.value = "";
	}
}

function setCustomServiceDescription(thisForm){
	var serviceDescriptionAdder = thisForm.customServiceDescriptionAdder ;
	var i = 0;
	var serviceDescription = "";
	var serviceDescriptions = new Array();
	var oscDelimiter = "|OSC_DESC_DELIM|";

	if(serviceDescriptionAdder.length !== undefined){
		for(i=0; i < serviceDescriptionAdder.length; i++){
			serviceDescriptions[i] = serviceDescriptionAdder[i].value;
		}
		serviceDescription = serviceDescriptions.join( oscDelimiter );
	} else{
		serviceDescription = serviceDescriptionAdder.value;
	}
	thisForm.customServiceDescriptions.value = serviceDescription;

	if(thisForm.customServiceDescriptions.value != ""){
		$(":hidden#customServices").val("OSC_CUSTOM");
	}
}

function setRadioValue(radio, selectedValue){
	if(radio.length !== undefined){
		for(i=0; i<radio.length; i++){
			if(radio[i].value == selectedValue){
				radio[i].checked = true;
			}
		}
	} else{
		radio.checked = (radio.value == selectedValue);
	}
	return true;
}

function getRadioValue(radio){
	var selectedValue = "";
	var i = 0;
	
	if(radio.length !== undefined){
		for(i=0; i<radio.length; i++){
			if(radio[i].checked == true){
				selectedValue = radio[i].value;
			}
		}
	} else{
		if(radio.checked){
			selectedValue = radio.value;
		}
	}
	
	return selectedValue;
} 
/*******************************************************
 *	Appointment calendar for "select_appointment_date" 
 *	view.
 *
 *******************************************************/
 
 // appointment calendar 'class'
 function appointmentDatePicker(){
 	this.selectedDate = "";
 	
 	this.setSelectedDate = function setSelectedDate( selectedDate ){
	 	this.selectedDate = selectedDate;
	 	return true;
	}
 	
	// call to render calendar
	this.renderCalendar = function renderDatePicker(){
		$('#datepicker').datepicker({
			beforeShowDay: isClosed,
   			onSelect: function(date) { 
		    	$("input#appointmentDate").val( date );
		    	reloadAppointments();
		    },
			onChange: function(date) {
		    	$("input#appointmentDate").val( date );
		    	reloadAppointments();
		    },
   			dateFormat: 'mm-dd-yy',
			numberOfMonths: 2,
			minDate: 0, 
   			maxDate: 180,
   			defaultDate: +1
		});

		// set the selected date as being selected in the calendar interface
		$("#datepicker").datepicker("setDate", $.datepicker.parseDate("mm-dd-yy", this.selectedDate) );
	}
}

function reloadAppointments() {
	disableCalendarControls();
	// get value from input
	var date = $("input#appointmentDate").val();
	var days = $("input#days").val();
	var serviceAdvisorId = $("input#serviceAdvisorId").val();
	var recommended = $("input#recommended").attr("checked");

	document.getElementById( 'availableAppointments' ).innerHTML = "<br/><br/>Searching for available appointment times.<br/><br/><img src='/views/core/images/loading.gif'/>";

	$.AjaxCFC({
		url: "/modules/osc/model/ajax/Appointments.cfc",
		useDefaultErrorHandler: false,
		method: "reloadAppointmentDateTimes",
		data: { "date":date, "days":days, "franchiseId":franchiseId(), "serviceAdvisorId":serviceAdvisorId },
		timeout:60000,
		success: function(results) {
			reloadAppointmentDateTimesResp(results);
		}
	});
}

// call back function
function reloadAppointmentDateTimesResp( resp ) {
	enableCalendarControls();
	$("#availableAppointments").transform({
		xsl: "/modules/osc/views/xsl/servicedates.xsl",
		xmlstr: resp,
		complete: function(){
			$("#accordion h4:first").addClass("ui-corner-top");				
			$("#accordion h4:first").removeClass("ui-corner-all");				
			$("div.ui-state-active", $("#accordion h4:first")).html("<span class=\"ui-icon ui-icon-triangle-1-n\"/>");

			$("#accordion h4:first").next().show();

			$("input[name='appointmentDateTime']").each(
				function(){
					var selectedAppointmentId = $("#serviceAdvisorId").val() + '_' + $("#appointmentDate").val() + '_' + $("#appointmentTime").val();
					if( $(this).val() == selectedAppointmentId ){
						$(this).attr('checked','true');
					}
				}
			);
			$("#accordion h4").click(function() {
				if($(this).hasClass("ui-corner-all")){
					$(this).addClass("ui-corner-top");				
					$(this).removeClass("ui-corner-all");
					$("div.ui-state-active", this).html("<span class=\"ui-icon ui-icon-triangle-1-n\"/>");
				}else{
					$(this).addClass("ui-corner-all");				
					$(this).removeClass("ui-corner-top");
					$("div.ui-state-active", this).html("<span class=\"ui-icon ui-icon-triangle-1-s\"/>");
				}
				$(this).next().slideToggle(100);
			});

			$(".additional-hours").click(function(){
				if($(this).html() == "Display additional hours"){
					$(this).html("Hide additional hours" );
				}else{
					$(this).html("Display additional hours" );
				}
				$(this).next("div").slideToggle(90);
			});

		}
	});
}

function setAppointmentDateTime( obj ){
	var appt_info = obj.value.split( "_" );

	var advisorId = appt_info[0];
	var appt_date = appt_info[1];
	var appt_time = appt_info[2];

	$("input#serviceAdvisorId").attr("value",advisorId);
	$("input#appointmentDate").attr("value", appt_date);
	$("input#appointmentTime").attr("value", appt_time);
}

function disableCalendarControls(){
	$("#datepicker").datepicker("disable");
	$("input#backButton").attr("disabled", true);
	$("input#nextButton").attr("disabled", true);
}
function enableCalendarControls(){
	$("#datepicker").datepicker("enable");
	$("input#backButton").attr("disabled", false);
	$("input#nextButton").attr("disabled", false);
} 
 /*******************************************************
 *	forgot password 
 *
 *******************************************************/
function sendPassword( customerEmail, franchiseId ) {
	$("#sendPassword").text("Sending password. Please wait...");
	$("#sendPasswordLink").hide();

	$.AjaxCFC({
		url: "/modules/osc/model/ajax/Appointments.cfc",
		useDefaultErrorHandler: false,
		method: "sendForgottenPassword",
		data: {	
			'customerEmailAddress': customerEmail,  
			'franchiseId': franchiseId },
		timeout:15000,
		success: function(results) {
			sendPasswordResp(results);
		}
	});
}

// call back function for sendPassword
function sendPasswordResp( resp ) {
	if(resp == "true"){
		$("#sendPassword").text("Password sent to " + $("input#emailAddress").val() );	
	} else{
		$("#sendPasswordLink").show();
		$("#sendPassword").text("A user with the email address " + $("input#emailAddress").val() + " was not found." );			 
	}
}

// validation for email address
function isValidEmail(anEmail){
	regEmail = /^[A-Za-z0-9\-_]+(\.[A-Za-z0-9\-_]+)*@([A-Za-z0-9\-_\.]+\.)+[A-Za-z]{2,3}$/i;
	return regEmail.test(anEmail);
}

// ajax call for "forgot password" dialog
function sendModalPassword( franchiseId ) {
	var customerEmail = $("input#forgotPasswordEmail").val();
	if( isValidEmail( customerEmail ) ){
		$("#forgotPasswordStatus").text("Sending password. Please wait...");
		
		$.AjaxCFC({
			url: "/modules/osc/model/ajax/Appointments.cfc",
			useDefaultErrorHandler: false,
			method: "sendForgottenPassword",
			data: {	
				'customerEmailAddress': customerEmail,  
				'franchiseId': franchiseId },
			timeout:15000,
			success: function(results) {
				sendModalPasswordResp(results);
			}
		});
	} else{
		$("#forgotPasswordStatus").text("Please enter a valid email address.");
	}

}

// call back function for sendModalPassword
function sendModalPasswordResp( resp ) {
	if(resp == "true"){
		$("#forgotPasswordStatus").text("Password sent to " + $("input#forgotPasswordEmail").val() );
		$("input#forgotPasswordEmail").val("");
	} else{
		$("#forgotPasswordStatus").text("A user with the email address \"" + $("input#forgotPasswordEmail").val() + "\" was not found." );			 
	}
}

// modal dialog to collect password
function initForgotPasswordDialog(franchiseId){
	$("#forgotPasswordDialog").dialog({ 
		autoOpen: false,
		title: "Forgot Password",
		height: 200,
		resizable: false,
	    modal: true,
	    overlay: { 
	        opacity: 0.8, 
	        background: "white" 
	    },  
	    buttons: { 
	        "Send": function() { 
	            sendModalPassword(franchiseId); 
	        }, 
	        "Close": function() { 
	            $(this).dialog("close"); 
	        } 
	    }
	     
	});
}
function launchForgotPasswordDialog(){
	// fix for ie
	$("#forgotPasswordDialog").show();
	$("#forgotPasswordDialog").dialog('open');	
}


 /*******************************************************
 *	send outlook appointment 
 *
 *******************************************************/
function sendOutlookAppointment( oscWizardForm, franchiseId ) {

	var customerEmail = oscWizardForm.emailAddress.value;
	var serviceAdvisorFullName = oscWizardForm.serviceAdvisorName.value;  
	var serviceAdvisorFirstName = "";
	var serviceAdvisorLastName = "";
	var arServiceAdvisorFullName = "";
	
	if(serviceAdvisorFullName.length){
		arServiceAdvisorFullName = serviceAdvisorFullName.split(" ");
		if(arServiceAdvisorFullName.length > 0){
			serviceAdvisorFirstName = arServiceAdvisorFullName[0];
		}
		if(arServiceAdvisorFullName.length > 1){
			serviceAdvisorLastName = arServiceAdvisorFullName[1];
		}
	}
	
	$("#sendOutlookAppointmentStatus").text("Sending appointment reminder. Please wait...");

	$.AjaxCFC({
		url: "/modules/osc/model/ajax/Appointments.cfc",
		useDefaultErrorHandler: false,
		method: "sendOSCOutlookAppointment",
		data: {	
			'customerEmail' : customerEmail, 
			'franchiseId' : franchiseId, 
			'appointmentDate' : oscWizardForm.appointmentDate.value, 
			'appointmentTime' : oscWizardForm.appointmentTime.value, 
			'vehicleYear' : oscWizardForm.vehicleYear.value,
			'vehicleMake' : oscWizardForm.vehicleMake.value,
			'vehicleModel' : oscWizardForm.vehicleModel.value,
			'serviceAdvisorFirstName' : serviceAdvisorFirstName,
			'serviceAdvisorLastName' : serviceAdvisorLastName
		},
		timeout:15000,
		success: function(results) {
			sendOutlookAppointmentResp(results);
		}
	});
}

// call back function for sendOutlookAppointment
function sendOutlookAppointmentResp( resp ) {
	if(resp == "true"){
		$("#sendOutlookAppointmentStatus").text("Appointment reminder sent to " + $("input#emailAddress").val() );	
	} else{
		$("#sendPassword").text("Unable to send appointment reminder. Please try again." );			 
	}
}

/*******************************************************
*	Loading dialog 
*
*******************************************************/
function launchLoader( message ){
	// set and show the message
	$("#dialogMessage").text(message);
	// fix for autohide in ie (autoOpen=false causes a flicker)
	$("#loaderDialog").show();
	
	// hide the x
	$("#loaderDialog").dialog().parents(".ui-dialog:first").find(".ui-dialog-titlebar-close").hide();
	
	// hide the title bar
	$("#loaderDialog").dialog().parents(".ui-dialog:first").find(".ui-dialog-titlebar").hide();
	$("#loaderDialog").dialog('open');
}
function initLoader(){
	$("#loaderDialog").dialog({ 
		autoOpen: false,
		title: "",
		close: false,
		resizable: false,
		height: 150,
		open: function() {
		  $(document).unbind('keydown.dialog-overlay');
		}, 
		closeOnEscape: false,
	    modal: true,
	    overlay: { 
	        opacity: 0.8, 
	        background: "white" 
	    }  
	});
}