
//Bring up the appointment setup popup
function appointment_display(compsid, empsid, usersid, curpage,aptsid){
	scrollTo(0,0);
	if($('#set_an_appointment').html()!=""){
		$('#back_div2').fadeIn('slow');
		$('#set_an_appointment').show();
	}else{
		$('#set_an_appointment').html('<br/><img src="../images/ajax-loader.gif" />').show();
		$.post("ajax/appointments.php", { show:'firstcall',compsid:compsid,empsid:empsid,usersid:usersid,curpage:curpage,aptsid:aptsid},
		function(data){	
			$('#back_div2').fadeIn('slow');
			$('#set_an_appointment').html(data);
		});	
	}
}

//find client as user types into the form field this is only for the appointment setup popup, when viewed by Employees and Companies (works just like find_clients() inside autopopulate.js
function appt_find_clients(){
	var	x = $('#appt_client_search').val();
	if(x!='' && x!= undefined){
		$("#appt_select_client_drop").html('Loading...').fadeIn("slow");
		$.post("ajax/appointments.php", {show:'search_clients', find: x},
		function(data){
			$("#appt_select_client_drop").html(data);
		});
	}else{
		$('#appt_select_client_drop').fadeOut("slow");
	}
}

//find company as user types into the form field this is only for the appointment setup popup when viewed by a Client
function appt_find_companies(){
	var	x = $('#appt_company_search').val();
	if(x!='' && x!= undefined){
		$("#appt_select_company_drop").html('Loading...').fadeIn("slow");
		$.post("ajax/appointments.php", {show:'search_companies', find: x},
		function(data){
			$("#appt_select_company_drop").html(data);
		});
	}else{
		$('#appt_select_company_drop').fadeOut("slow");
	}
}

//update client details display (used in company and employee views)
function appt_update_client_details(clientsid){
	if(clientsid>'0'){
		$.post("ajax/appointments.php", {show:'update_client_details', clientsid: clientsid},
		function(data){
			clear_appt_selections();
			$("#appt_client_info_section").html(data);
		});
	}
}
//update company details display (only used in client view)
function appt_update_company_details(companysid){
	if( companysid>'0'){
		$.post("ajax/appointments.php", {show:'update_company_details', companysid:  companysid},
		function(data){
			$("#appt_client_info_section").html(data);
		});
	}
}
//update service area display (used when selecting a company when logged in as a client)
function appt_update_service_area(){
	var companysid = $("#appt_selected_company").val();
	if(companysid>'0'){
		$.post("ajax/appointments.php", {show:'update_service_area', companysid: companysid},
		function(data){
			if(data!='' && data!=undefined){
				if(data=='fail') alert("This Company does not have any Employees with active Services. Please select another company.");
				else{
					appt_update_company_details(companysid);
					clear_appt_selections();
					$("#appt_service_area_section").html(data);
				}
			}
		});
	}
}
//update selected user field with contact sid based on company and client, creates new contact if needed. (used when selecting a company when logged in as a client)
function appt_update_user_contact(){
	var companysid = $("#appt_selected_company").val();
	if(companysid>'0'){
		$.post("ajax/appointments.php", {show:'update_user_contact', companysid: companysid},
		function(data){
			if(data!='' && data!=undefined){
				$("#appt_selected_user").val(data);
			}
		});
	}
}



//generates new rows of services and employee dropdowns.
function additional_service(){ 
	if($("#appt_selected_user").val()>'0' && $("#appt_selected_company").val()>'0'){
		if($("#appt_servs_section > div:visible").size() < 5){
			var cnt = parseInt($("#appt_servs_section div:last-child").attr('id'));
			var nucnt = cnt+1;
			if(isNaN(nucnt)) nucnt=1;
			$("#appt_serv_hidden").clone().appendTo("#appt_servs_section").show().attr("id",nucnt+"_srvrow");	
		}else alert("You cannot add more than 5 service selections.");
	}else{
		if($("#appt_selected_user").val()=='') alert("You must select a Client before you can continue.");
		else alert("You must select a Company before you can continue.");		
	}
} 

//additional service rows, update service after emp selection.
function update_service_from_emp(emp, service, parentid){
	var sel_srvs='';
	$(".appt_servs:visible").each(function(){
		if($(this).val()>'0' && $(this).val()!= service && $(this).next().val()==emp) sel_srvs = sel_srvs+$(this).val()+'|';
	});
	$.post("ajax/appointments.php", { show:'updt_serv_from_emp',emp:emp,srv:service,sel_srvs:sel_srvs},
	function(data){
		if(data!='' && data!=undefined){
			var arr = data.split('|');
			if(arr[0]!='') $('#'+parentid+' .appt_servs').html(arr[0]);
			if(arr[1]!='') $('#'+parentid+' .appt_emps').html(arr[1]);
		}
	});
}

//additional service rows, update emps after service selection.
function update_emp_from_service(service, emp, parentid){ 
	$.post("ajax/appointments.php", { show:'updt_emp_from_serv',emp:emp,srv:service},
	function(data){
		if(data!='' && data!=undefined){
			var arr = data.split('|');
			if(arr[0]!='') $('#'+parentid+' .appt_emps').html(arr[0]);		
			if(arr[1]!='') $('#'+parentid+' .appt_servs').html(arr[1]);
		}
	});
}

//Grabs the time block for the selected service and provider and passes it to update the main time selector.
function appt_add_time_block(parentid){
	//alert(parentid);
	$('#'+parentid+' .appt_add_srv').attr("disabled",true);
	if($("#appt_selected_user").val()>'0'){
		var srv = $('#'+parentid+' .appt_servs').val();
		var emp = $('#'+parentid+' .appt_emps').val();
		var cli = $("#appt_selected_user").val();
		if(srv=='0' || emp=='0'){
			alert("You must select both a Service and a Provider in order to select the time.");
			$('#'+parentid+' .appt_add_srv').attr("disabled",false);
		}else{
			//alert(emp+'-'+srv+'-'+cli);
			$.post("ajax/appointments.php", { show:'add_time_selector',emp:emp,srv:srv,cli:cli},
			function(data){
				appt_show_time_blocks('#'+parentid+' .appt_add_srv');
				$('#'+parentid+' .appt_add_srv').val("Remove").click(function(){ $('#'+parentid).hide(); clear_appt_selections(cli,emp,srv); });	
				$('#'+parentid+' .appt_emps, #'+parentid+' .appt_servs').attr("disabled",true);
			});
		}
	}else{
		alert("You must select a Client before you can continue.");
		$('#'+parentid+' .appt_add_srv').attr("disabled",false);
	}
}

//Show the time blocks based on session selections
function appt_show_time_blocks(buttonid){
	var thedate = $("#appt_date").val();
	$.post("ajax/appointments.php", { show:'show_selections', thedate:thedate},
		function(data){
			//alert(data);
			$('#appt_time_selector').html(data);
			if(buttonid!=undefined)$(buttonid).attr("disabled",false);
			return true;
		});
	return false;
}
//Update time block based on sub selection
function appt_update_time_block(ekey,vtot,ckey){
	var thedate = $("#appt_set_date_"+ekey).val();
	$.post("ajax/appointments.php", { show:'update_time_block', thedate:thedate, ekey:ekey, vtot:vtot, ckey:ckey},
		function(data){
			$('#appt_setter_'+ekey).html(data);
		});
}

//Clear the selections for appointments. Without parameters it clears all.
function clear_appt_selections(cli,emp,srv){
	$.post("ajax/appointments.php", { show:'clear_selections',cli:cli,emp:emp,srv:srv},
		function(data){
			//alert(data);	
			if(cli==undefined && emp==undefined && srv==undefined){
				$("#appt_servs_section div:not('#appt_serv_hidden,#1_srvrow')").remove();
				$("#1_srvrow .appt_emps, #1_srvrow .appt_servs").attr('disabled',false);
				$('#1_srvrow .appt_add_srv').val("Set Time").unbind('click').bind('click',(function(){ appt_add_time_block('1_srvrow'); }));	
			}else{
				$(".appt_emps").each(function(){
					if($(this).val()==emp){
						if($(this).prev().val()==srv) $(this).closest("div").remove();
					}			
				});
			}
			$('#appt_appointment_info').html('After you select your times the appointment details will appear here.');		
			appt_show_time_blocks();
		});
}

//Update appointment details once a time selection has been made.
function update_appointment_details(myemps){
	var emparr = myemps.split("|");
	var appt_data = '';	
	var fail='';
	for(var i in emparr){
    	var the_emp = emparr[i];
    	if(the_emp!='' && the_emp!=undefined){
    		if($("#appt_set_date_"+the_emp).val()!='' && $("#appt_time_"+the_emp).val()!='' && $("#appt_set_date_"+the_emp).val()!=null && $("#appt_time_"+the_emp).val()!=null){
    			appt_data = appt_data+'---'+the_emp+'|'+$("#appt_set_date_"+the_emp).val()+'|'+$("#appt_time_"+the_emp).val();
    		}else fail='1';
    	}
	}
	
	if(fail=='1'){
		alert("You must select a date and time for each employee's appointment in order to continue.\nPlease remove any selections for which you cannot select a time.");
	}else{
		$.post("ajax/appointments.php", { show:'update_appointment_block', appt_data:appt_data},
			function(data){
				if(data=='overlap'){
					alert("Your selected times may not overlap one another. \nPlease select different times for each of your appointments.");
					data = 'After you select your times the appointment details will appear here.';
				}
				$('#appt_appointment_info').html(data);				
			});
	}
}

function appt_complete_appointment(empsids){
	var emparr = empsids.split("|");
	var appt_data = '';	
	for(var i in emparr){
    	var the_emp = emparr[i];
    	if(the_emp!='' && the_emp!=undefined){
    		appt_data = appt_data+'---'+the_emp+'|'+$("#appt_dur_hr_"+the_emp).val()+'|'+$("#appt_dur_m_"+the_emp).val()+'|'+$("#appt_note_"+the_emp).val()+'|'+$("#appt_set_date_"+the_emp).val();
    	}
	}
	if(confirm("Please verify your appointment setup before continuing.\n\nIf you are sure, press OK to set the appointment.")){
		$.post("ajax/appointments.php", { show:'complete_appointment', appt_data:appt_data},
			function(data){
				$('.appointment_sub_boxes,#appt_service_area_section,#appt_time_selector_section').fadeOut('slow');
				$('#appt_appointment_info').css({'width':'570px'}).show().html(data);
				$('#appointment_client_area_top').css({'margin-top':'8px','width':'912px'}).html('Appointment Setup Complete!');
				$('#appt_client_info_section').css({'width':'906px'});
				$('.appt_appointment_area_section').css({'width':'560px'});
				$('.appt_appointment_area_top').css({'width':'560px'});
				$('#appt_detail_head').css({'margin-right':'284px'});
				$('#appt_client_info input').hide();
				
			});
	}
}
//$("#calendar_display").html();

//For the address books
function appt_showappts(usid, type, csid ) {
	$.post("ajax/appthistory.php", { u: usid, type:type, sid: csid },
			function(data) {
				$('#right_div').html(data).show();
				$('dl.accordian').trigger('load');
				$('#tab_future').click();
			}, 'html'
	);
}
//For cancelling appointments on addressbook page.
function appt_showappts_action(type, sid, data) {
	if (type == 'cancel' && (data == "" || data == undefined)) {
		if ((data = prompt('Reason for cancellation?')) == null) return false;
		$('#dt'+sid+', #dd'+sid).detach();
	}
	$.post("ajax/appthistory.php", { a: sid, type: type, d: data },
			function(data){	
				if(type=='arrival') {
					alert('Appointment Updated.');
					$('#shwmp_'+sid).css('background', data);
				}
	});
	return true;
}

//MAIN CALENDAR POPUP

//Bring up the appointment setup popup
function calendar_display(compsid, empsid, curpage,curtime){
	scrollTo(0,0);
	$('#calendar_display').html('<br/><img src="../images/ajax-loader.gif" />').show();
	$.post("ajax/calendar.php", { show:'firstcall',compsid:compsid,empsid:empsid,curpage:curpage,curtime:curtime},
	function(data){	
		$('#back_div2').fadeIn('slow');
		$('#calendar_display').html(data);
	});	
}
//Switch between employee views on calendar popup
function cal_emp_switch(sid,name){
	$(".hideincal,.shwmp").hide();
	$("#apptfor_label").html(name);
	$("#caldate_header_foremp,#emp_tables,.e_"+sid).show();
	$(".emp_cols").not(".cred").removeClass('cal_block_avail');
	$(".emp_cols").each(function(){
		if($(this).hasClass("ea_"+sid))
			$(this).addClass('cal_block_avail');
	});
}

//Switch to View All on calendar view.
function cal_menu_all(){
	$(".hideincal").hide();
	$("#apptfor_label").html("All Employees");
	$("#caldate_header_forall,#employees_table").show();
	$(".cal_emps").css("color","#fff");
	$(".emp_cols").each(function(){
		if(!!$(this).attr('class').match(/\bea_/))
			$(this).addClass('cal_block_avail');
	});
	update_positions();
	$(".shwmp").show();
}

//When you click on an employee name in cal
function cal_empclick(obj, sid, name) {
	cal_emp_switch(sid, name);
	$('.cal_emps').css('color', '#fff');
	$(obj).css('color', '#000');
	update_positions();
	$(".shwmp_"+sid).show();
}

//move the appointment blocks
function update_positions(){
	setTimeout(function(){
		$('.shwmp').each(function(){
			var pos = $(this).parent().position();
			$(this).css({'margin-top':(pos.top+1)+'px','margin-left':pos.left+'px'});
		});
	},200);
}

//Display appointment details from calendar view.
function show_appointment(apptsid){	
	$('#appointment_detail_display').html('<br/><img src="../images/ajax-loader.gif" />').show();
	$.post("ajax/appointments.php", { show:'show_appointment',apptsid:apptsid},
	function(data){	
		$('#back_div2').fadeIn('slow');
		$('#appointment_detail_display').html(data);		
	});	
}

function appt_cancel(aptsid){
	if(!confirm("Are you sure you want to cancel this appointment?")) return false;
	if (appt_showappts_action('cancel', aptsid)) {
		alert("Your Appointment has been Cancelled.");
		$("#shwmp_"+aptsid).remove();
		$('#appointment_detail_display').html('').fadeOut("slow");
	}
}
function appt_contact_comment_edit(contactsid){
	if($("#appt_contact_comment").val()==''){
		alert("You should enter a comment to edit it.");
	}else{
		$.post("ajax/appointments.php", { show:'update_contact_comment',contactsid:contactsid, comment:$("#appt_contact_comment").val()},
		function(data){	
			alert("Contact Comment Updated");
		});
	}
}
function appt_durations_edit(apptsid){
	$.post("ajax/appointments.php", { show:'update_appt_duration',apptsid:apptsid },
	function(data){	
		$("#appt_total_duration").html(data);
	});
}
function appt_update_set_duration(apptsid){
	var hr = $("#appt_dur_hr").val();
	var min = $("#appt_dur_min").val();
	if(hr=='0' && min=='00') alert("You must select a duration greater than 0.");
	else{
		$.post("ajax/appointments.php", { show:'set_appt_duration',apptsid:apptsid,hr:hr, min:min },
		function(data){	
			if(data=='done'){
				alert("Appointment Duration Updated.");
				show_appointment(apptsid);
			}else alert("An unexpected error occurred, please reload the page and try again.");
		});
	}
}

function appt_reschedule(apptsid, skip){
	if(!confirm('Rescheduling this appointment will delete your current appointment. If you are sure you want to reschedule this appointment, click OK.')) return false;
	appt_showappts_action('cancel', apptsid, 'Cancelled in order to Reschedule.');
	if(skip=='' && skip==undefined) {
		$("#shwmp_"+apptsid).remove();
		$('#appointment_detail_display').html('').fadeOut("slow");
	}
	hidediv();
	appointment_display('','','','',apptsid);
	return true;
}
//End appointment details on calendar view.

function employee_appt_history(emp_sid){	
	$.post("ajax/appthistory.php", { show:'employee_appt_history',emp_sid:emp_sid },
		function(data){	
			$("#appt_history_"+emp_sid).html(data);
		});
}
