<?php 
$submit_url = $file_name."?page=view&action=$action"; 
$status_submit_url = $file_name."?page=view&name=$name"; 
if($_REQUEST['action'] != 'edit'){
	$appointment_text = $gsi->getDescripByJobId($_REQUEST["job_id"]);
	//$addess = $gsi->getAddressByJobId($_REQUEST["job_id"]);
	
	$addess_n = $gsi->getAddressByJobId($_REQUEST["job_id"]);
	//$jobtypetext = utility::getTableFieldById("job","client_industry","id",$_REQUEST["job_id"]);
	//$jobtypefeild = $gsi->getcrmbaseJobTypeList($jobtypetext);
	//echo $jobtypefeild;
	$secondaddress_ap = utility::getTableFieldById("job","address1","id",$_REQUEST['job_id']);				
	if($jobtypefeild == 'Domestic' or $secondaddress_ap == ''){
		$addess = $gsi->getAddressByJobId($_REQUEST["job_id"]);
	}else{
		$addess = utility::getTableFieldById("job","address1","id",$_REQUEST['job_id']);
	}
} 
$hide_class = "";
if($prospect==1){
	$hide_class = "hide";
}
?>
<div class="box-header" >
	<form action="<?php echo $submit_url;?>" method="post" name="search_form" id="search_form">
		<div class="col-sm-3">
			<!--<label for="Appointment Text" class="control-label">Description</label>-->
			<label for="Notes" class="control-label">Notes</label>
			<textarea class="form-control" rows="4" id="appointment_text" name="appointment_text" required><?php echo stripslashes($appointment_text);?></textarea>
		</div>
		<div class="col-sm-3">
			<div class="staff_member <?=$hide_class?>">
			<label for="Staff Member" class="control-label">Staff Member</label>
			<? 
				$admin_ids = "";
				$sql_for_admin = "SELECT * FROM job_admin_mapping WHERE job_id = $job_id";
				$rs_for_admin = mysqli_query($conn,$sql_for_admin);
				if(mysqli_num_rows($rs_for_admin) > 0){
					while($row_for_admin = mysqli_fetch_assoc($rs_for_admin)){
						$admin_ids .= $row_for_admin["admin_id"].",";
					}
					$admin_ids = substr($admin_ids,0,-1);
				}
				if($admin_ids == ""){
					echo "<br><span style='color:red;' id='span'>No staff member assign to this job. First assign staff member.</span>";
				}else{
					Admin::getAdminList("admin_id",$admin_id,"100%",true,"form-control","required",$admin_ids); 
				}
			?>
			</div>
			<!--<label for="Location" class="control-label">Location</label>
			<input type="text" class="form-control" id="appointment_location" name="appointment_location" value="<?php //echo $appointment_location;?>">-->
		</div>
		<div class="col-sm-2">
			<label for="Appointment Time" class="control-label">Time From</label>
			<div class="bootstrap-timepicker">
				<!--<input type="text" class="form-control timepicker" id="appointment_time" name="appointment_time" value="<?php //echo $appointment_time;?>">-->
				<? utility::getTimeList("appointment_time", $appointment_time, "Time From", "100%");?>
			</div>
			
			<label for="Appointment Time" class="control-label">Time To</label>
			<div class="bootstrap-timepicker">
				<!--<input type="text" class="form-control timepicker" id="appointment_time_to" name="appointment_time_to" value="<?php //echo $appointment_time_to;?>">-->
				<? utility::getTimeList("appointment_time_to", $appointment_time_to, "Time To", "100%");?>
			</div>
			
			<label for="Appointment" class="control-label">Date <? if(!(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit')){ ?>From<? } ?></label>
			<input type="text" class="form-control datepicker" id="appointment_date" name="appointment_date" value="<?php (isset($appointment_date) && $appointment_date !="") ? utility::getFormatedDate($appointment_date) : utility::getFormatedDate(date($config->dateFormat));?>" required>
			
			<? if(!(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit')){ ?>
				<label for="Appointment" class="control-label">Date To</label>
				<input type="text" class="form-control datepicker" id="appointment_date_to" name="appointment_date_to" value="<?php utility::getFormatedDate(date($config->dateFormat));?>" required>
			<? } ?>
		</div>
		<div class="col-sm-4">
			<label for="Addess" class="control-label">Address</label>
			<? 
				//echo $jobtypefeild;
			?>
			<input type="text" class="form-control" id="addess" name="addess" value="<?php echo $addess;?>"><br />
			
			<div style="display:<?=$quotation_area_hide;?>;">
				<!--<div class="form-group">
					<label for="Full Day" class="control-label">Full Day</label><br>
					<input class="flat-red" type="checkbox" id="is_full_day" name="is_full_day" <? //echo ($is_full_day) ? "checked" : ""; ?>>
				</div>-->
				<div class="form-group">
					<input class="flat-red" type="checkbox" id="attended" name="attended" <? echo ($attended) ? "checked" : ""; ?>>&nbsp;&nbsp;<b>Attended</b>
				</div>
				
				<div class="form-group">
					<input class="flat-red" type="checkbox" id="client_not_in" name="client_not_in" <? echo ($client_not_in) ? "checked" : ""; ?>>&nbsp;&nbsp;<b>Client not in</b>
				</div>
				
				<!--<hr />-->
				<div class="form-group">
					<input type="checkbox" class="flat-red quotation_status" id="quotation_accepted" name="quotation_accepted" value="1"  <? echo ($quotation_accepted ==1) ? 'checked':''; ?>>&nbsp;&nbsp;<b>Quotation Accepted</b>						
					<i class="fa fa-check pull-right" id="quotation_accepted_check" style="color:#bad23a;font-size: 20px;display:none;"></i>
					<i class="fa fa-refresh fa-spin pull-right" style="font-size: 20px;display:none;" id="quotation_accepted_refresh"></i>
				</div>
				<div class="form-group">	
					<input type="checkbox" class="flat-red quotation_status" id="quotation_declined" name="quotation_declined" value="1"  <? echo ($quotation_declined ==1) ? 'checked':''; ?>>&nbsp;&nbsp;<b>Quotation Declined</b>
					<i class="fa fa-check pull-right" id="quotation_declined_check" style="color:#bad23a;font-size: 20px;display:none;"></i>
					<i class="fa fa-refresh fa-spin pull-right" style="font-size: 20px;display:none;" id="quotation_declined_refresh"></i>
				</div>
			</div>
			<div style="clear:both;"></div>
			<!--<label for="Notes" class="control-label">Notes</label>
			<textarea class="form-control" rows="4" id="notes" name="notes"><?php //echo stripslashes($notes);?></textarea>-->
		</div>
		<?
				if($common_appointment_id >0 ){					
					$apply_needs_for_other = 0;
					$current_date = date('Y-m-d H:i:s');
					$sel_appoint = "SELECT * FROM appointment WHERE appointment_date >='".$current_date."' AND common_appointment_id='".$common_appointment_id."' AND id!='".$id."'  ";
					$sql_appoint = mysql_query($sel_appoint);
					if(mysql_num_rows($sql_appoint)){
						$apply_needs_for_other = 1;
					}
				}			
			?>
			<?
				if($apply_needs_for_other==1){?>
				<div class="col-sm-3">
					<label for="Apply to coming event" class="control-label">Apply to coming event &nbsp;&nbsp;</label>
					<input type="checkbox" class="flat-red" id="apply_to_coming_event" name="apply_to_coming_event" value="1" checked>
				</div>
				
			<?	}
			?>
		<?if($action == 'insert'){?>
			<div class="col-sm-3">
				<label for="Date of event" class="control-label">Frequency</label>				  
				<? $gsi->getTypeOfAppointmentList("type_of_appointment",$type_of_appointment,"100%",false,"form-control select2","required"); ?>
				<?
				$fre_display = 'block';
				if($type_of_appointment==1){
					$fre_display = 'none';
				}?>
				
				<div class="form-group the_day_options" style="display:<?=$fre_display?>;margin-top:10px">
                  <div class="radio">
                    <label>
                      <input type="radio" name="dayOptions" id="optionsDay" value="day">
						Day	
					  </label>		
					  <label>		
					   <input type="radio" name="dayOptions" id="optionsThe" value="the">
						The
					  </label>
                  </div>
                </div>
				
				<div class="for_monthly " style="display:<?=$fre_display?>;margin-top:10px">
					
					<div class="form-group day_option">
						<label>Day of Month</label>
						<? $gsi->getDayOfMonthList("day_of_month",$day_of_month,"100%",true,"form-control select2 day_of_month"); ?>
					</div>
					
					<div class="the_monthly_option">
						<div class="form-group">
							<label>Week</label>
							<? $gsi->getWeekListForAppointment("week_of_month",$week_of_month,"100%",true,"form-control select2 week_of_month"); ?>
						</div>
						
						<div class="form-group">
							<label>Day</label>
							<? $gsi->getDayOfWeekList("frequency_checklist1",$frequency_checklist,"100%",true,"form-control select2 frequency_checklist1"); ?>
						</div>
					</div>
				</div>
				
				<div class="form-group occurrence" style="display:<?=$fre_display?>">
					<!--<label for="Date of event" class="control-label">Frequency</label>-->
					<div class="" style="padding-top:8px">
						<div style="margin-right:10px;float:left;"><input type="checkbox" id="first_week" class="week_checkbox" name="frequency_checklist[]" value="1" <?php echo ($frequency_checklist=="1")?" checked='checked' ":"";?>/>&nbsp;Mon</div>
						<div style="margin-right:10px;float:left;"><input type="checkbox" id="second_week" class="week_checkbox" name="frequency_checklist[]" value="2" <?php echo ($frequency_checklist=="2")?" checked='checked' ":"";?>/>&nbsp;Tue</div>
						<div style="margin-right:10px;float:left;"><input type="checkbox" id="third_week" class="week_checkbox" name="frequency_checklist[]" value="3" <?php echo ($frequency_checklist=="3")?" checked='checked' ":"";?>/>&nbsp;Wed</div>
						<div style="margin-right:10px;float:left;"><input type="checkbox" id="fourth_week" class="week_checkbox" name="frequency_checklist[]" value="4" <?php echo ($frequency_checklist=="4")?" checked='checked' ":"";?>/>&nbsp;Thu</div>
						<div style="margin-right:10px;float:left;"><input type="checkbox" id="fifth_week" class="week_checkbox" name="frequency_checklist[]" value="5" <?php echo ($frequency_checklist=="5")?" checked='checked' ":"";?>/>&nbsp;Fri</div>
						<div style="margin-right:10px;float:left;"><input type="checkbox" id="sixth_week" class="week_checkbox" name="frequency_checklist[]" value="6" <?php echo ($frequency_checklist=="6")?" checked='checked' ":"";?>/>&nbsp;Sat</div>
						<div style="margin-right:10px;float:left;"><input type="checkbox" id="seventh_week" class="week_checkbox" name="frequency_checklist[]" value="7" <?php echo ($frequency_checklist=="7")?" checked='checked' ":"";?>/>&nbsp;Sun</div>
						<div style="margin-right:10px;float:left;"><input type="checkbox" id="every_week"  name="frequency_checklist[]" value="8" <?php echo ($frequency_checklist=="8")?" checked='checked' ":"";?>/>&nbsp;Every Day</div>
					</div>
				</div>
		
			</div>
			<?}?>
		<!--<div class="col-sm-3">
			<label for="Job" class="control-label">Job</label>
			<? //$gsi->getEnqQuoteJobList("job_id",$job_id,"100%",false); ?>
		</div>-->
		<div style="clear:both;margin-top:5px;"></div>
		<div class="col-sm-3">
			<div style="clear:both;margin-top:23px;"></div>
			<input type="hidden" id="id" name="id" value="<?php echo $id;?>">
			<input type="hidden" id="job_id" name="job_id" value="<?php echo $job_id;?>">
			<input type="hidden" id="query_string" name="query_string" value="<?php echo $query_string;?>">
			<input type="hidden" id="source" name="source" value="<?php echo $source;?>">
			<input type="hidden" id="prospect" name="prospect" value="<?php echo $prospect;?>">
			<button type="submit" name="add_master_data" id="submit_form" class="btn btn-primary"><?=$button_value?>
				<i class="fa fa-refresh fa-spin" style="display:none;" id="page_load_div"></i>
			</button>
		</div>
	</form>
</div>
<style>
label {
    margin-top: 5px;
}
</style>
<script type="text/javascript">
$(function(){
	$('#search_form').submit(function(){
		$("#add_master_data").attr("disabled", true);
		$('#page_load_div').show();
	});
	$("#search_form").on("click","#every_week",function(){
		if($("#every_week:checked").length == 1){
			$('.week_checkbox').prop( "checked", true );
		}else{
			$('.week_checkbox').prop( "checked", false );
		}
	});
	
	$("#search_form").on("change","#type_of_appointment",function(){
		var type_of_appointment = $(this).val();
		
		if(type_of_appointment == 3 || type_of_appointment == 2 ){
			if(type_of_appointment == 2){
				
				$('.the_day_options').show();
				//$('.for_monthly').show();
				$('.occurrence').hide();
			}else{
				$('.occurrence').show();
				$('.the_day_options').hide();
				$('.for_monthly').hide();
				
				$('input[name="dayOptions"]').prop('checked', false);
				$('.week_of_month').select2("val", "");
				$(".frequency_checklist1").select2("val", "");
			}
		}else{
			
			//$('#day_of_week').select2("val", "");
			$('.week_checkbox').prop( "checked", false );
			$('.occurrence').hide();
			$('.for_monthly').hide();
			$(".the_day_options").hide();
			
			$('input[name="dayOptions"]').prop('checked', false);
			$('.week_of_month').select2("val", "");
			$(".frequency_checklist1").select2("val", "");
		}
	});
		
	$("#search_form").on("click", "#optionsDay,#optionsThe",function() {
		$('.for_monthly').show();
		if($(this).val()=='day'){			
			$(".day_option").show();
			$(".the_monthly_option").hide();
			$('.week_of_month').select2("val", "");
			$(".frequency_checklist1").select2("val", "");
		}else{			
			$('.day_of_month').select2("val", "");
			$(".day_option").hide();
			$(".the_monthly_option").show();
		}
	});
	
	function getOrientation(file, callback) {
	  var reader = new FileReader();

	  reader.onload = function(event) {
		var view = new DataView(event.target.result);

		if (view.getUint16(0, false) != 0xFFD8) return callback(-2);

		var length = view.byteLength,
			offset = 2;

		while (offset < length) {
		  var marker = view.getUint16(offset, false);
		  offset += 2;

		  if (marker == 0xFFE1) {
			if (view.getUint32(offset += 2, false) != 0x45786966) {
			  return callback(-1);
			}
			var little = view.getUint16(offset += 6, false) == 0x4949;
			offset += view.getUint32(offset + 4, little);
			var tags = view.getUint16(offset, little);
			offset += 2;

			for (var i = 0; i < tags; i++)
			  if (view.getUint16(offset + (i * 12), little) == 0x0112)
				return callback(view.getUint16(offset + (i * 12) + 8, little));
		  }
		  else if ((marker & 0xFF00) != 0xFF00) break;
		  else offset += view.getUint16(offset, false);
		}
		return callback(-1);
	  };

	  reader.readAsArrayBuffer(file.slice(0, 64 * 1024));
	};
	
	var output_format = null;
	var file_name = null;
	function readFile(evt) {
		$("#page_load_div").show();
		$("#upload_complete").hide();
		var file = evt.target.files[0];
		getOrientation(file, function(orientation) {			
			$("#orientation").val(orientation);
			console.log("orientation : "+orientation);
		 });
		var reader = new FileReader();
	    reader.onload = function(event) {
			var i = document.getElementById("source_image");
			console.log(i);
	            i.src = event.target.result;
	            i.onload = function(){
	                
	                console.log("Image loaded");
	            }
	    };
		output_format = file.name.split(".").pop();
		file_name = file.name;
	    console.log("Filename:" + file.name);
	    console.log("Fileformat:" + output_format);
	    console.log("Filesize:" + (parseInt(file.size) / 1024) + " Kb");
	    console.log("Type:" + file.type);
	    reader.readAsDataURL(file);
		
		//$("#compress").show();
		setTimeout(function(){
			$("#compress").trigger('click');
		},2000);
		
	    return false;
	}
 // compress image
 	$( "#compress" ).click(function() {
        var source_image = document.getElementById("source_image");
        if (source_image.src == "") {
            alert("You must load an image first!");
            return false;
        }

        var quality = 30;
       	
        console.log("process start...");
        console.log("process start compress ...");
	    compressed_image.src = jic.compress(source_image,quality,output_format).src;
		//$("#upload").trigger('click');
		//$("#upload").show();
		$("#upload").trigger('click');
    	
	});
	// upload imange
	$( "#upload" ).click(function() {
        var compressed_image = document.getElementById("compressed_image");
        if (compressed_image.src == "") {
            alert("You must compress image first!");
            return false;
        }

	    var successCallback= function(response){
			var resultObj = jQuery.parseJSON(response);
		    $.each(resultObj.uploadfileArray, function(key,value) {
				
				id = key+1;
				$("<p id='document_p"+id+"'>"+value+"<i class='fa fa-close pull-right document_delete' alt='"+value+"' style='margin-top:3px;color:#3C8DBC;cursor:pointer;'></i></p>").appendTo("#document_div");
			});
			$("#page_load_div").hide();
			$("#upload_complete").show();
			setTimeout(function(){
				$("#upload_complete").hide();
			},2000);	
			console.log("image uploaded successfully! :)");
            console.log(response);       
        }

        var errorCallback= function(response){
            console.log("image Filed to upload! :)");
            console.log(response);
			$("#page_load_div").hide();
			$("#upload_complete").hide();	
        }
		
    	var orientation = $("#orientation").val();
    	console.log("process start upload ...");
    	jic.upload(compressed_image, "<?php echo $siteURL?>/appointment/index?page=ajax_actions&action=upload_image&orientation="+orientation, "file", file_name,successCallback,errorCallback);
    	
    });

	document.getElementById("fileinput").addEventListener("change", readFile, false);
	
	$("#submit_form").click(function(){	
		//if($("#span").text() == "No consultant assign to this job. First assign consultant."){
		var prospect = $("#prospect").val();
		if(prospect!=1){
			if($("#span").text() == "No staff member assign to this job. First assign staff member."){
				alert("First select Consultant");
				return false;
			}
		}
		
	});
	////////////////// DOCUMENT DELETE //////////////////////////////////////
	$("#add_form").on("click",".document_delete",function(){
		if(confirm("Do you want to delete the document?")){
			var document_p_id = $(this).parent().attr("id");
			//alert(document_p_id);
			var document_name = $(this).attr("alt");
			if(document_name != ""){
				var form_data   = {'document_name':document_name};  
				$.ajax({
					async: true,
					type: "POST",
					url: site_url+"/modules/appointment/index.php?page=ajax_actions&action=delete_document",
					data: form_data,
					success: function(result){
						var resultObj = jQuery.parseJSON(result); 
						if(resultObj.status == "success"){
							$("#"+document_p_id).hide();
						}
					}
				});	
			}
		}
	});
	
	$('.quotation_status').on('ifClicked', function(){
		
		$('.quotation_status').iCheck('uncheck');
		$(this).iCheck('check');
		
		if($(this).attr("name") == "quotation_accepted"){
			$("#quotation_accepted_refresh").show();
		}else{
			$("#quotation_declined_refresh").show();
		}
		
		var quotation_status = $(this).attr("name");
		var job_id = $("#job_id").val();
		//alert('aaaaaaaaaaa'+job_id);
		var form_data   = {'job_id':job_id,'quotation_status':quotation_status};       
		$.ajax({
			async: true,
			type: "POST",
			url: site_url+"/modules/appointment/index.php?page=ajax_actions&action=update_quotation",
			data: form_data,
			success: function(r){    
				$("#quotation_accepted_refresh").hide();
				$("#quotation_declined_refresh").hide();
				
				if(r == "quotation_accepted"){
					$("#quotation_accepted_check").show();
					setTimeout(function(){
						$("#quotation_accepted_check").hide();
					},2000);
				}else{
					$("#quotation_declined_check").show();
					setTimeout(function(){
						$("#quotation_declined_check").hide();
					},2000);
				}
			}
		});
	});
	
	////////////////// AJAX UPLOAD //////////////////////////////////////
	var btnUpload=$('#document');
	//$("#document").click(function(){
		//var identification_span_id = $(this).attr("alt");
		var form_data   = {'job_id':'1'};    
		new AjaxUpload(btnUpload, {
			action: '<?php echo $siteURL?>/appointment/index?page=ajax_actions&action=upload_document',
			name: 'uploadfile[]',
			data: form_data,
			onSubmit: function(file, ext){
				if (! (ext && /^(jpg|png|jpeg|pdf|doc|docx|xls|xlsx|csv)$/.test(ext))){ 
					// extension is not allowed 
					alert('Only JPG, PNG, PDF, DOC or DOCX files are allowed');
					return false;
				}
				$("#page_load_div").show();
				$("#upload_complete").hide();
				/* if(confirm("Do you want to upload")){
					$("#page_load_div").show();
					$("#upload_complete").hide();
				}else{
					return false;
				} */
			},
			onComplete: function(file, response){
				var resultObj = jQuery.parseJSON(response); 
				if(resultObj.status == "success"){
					console.log(response);
					$("#page_load_div").hide();
					$("#upload_complete").show();
					setTimeout(function(){
						$("#upload_complete").hide();
					},2000);
					
					$.each(resultObj.uploadfileArray, function(key,value) {
						//alert(key+" "+value);
						id = key+1;
						$("<p id='document_p"+id+"'>"+value+"<i class='fa fa-close pull-right document_delete' alt='"+value+"' style='margin-top:3px;color:#3C8DBC;cursor:pointer;'></i></p>").appendTo("#document_div");
					});
				} else{
					$("#page_load_div").hide();
					$("#upload_complete").hide();
					alert("There is some error to upload file.");
				}
				$("input[name='uploadfile[]']").attr("multiple","multiple");
			}
		});
	//});
	
	$("input[name='uploadfile[]']").attr("multiple","multiple");
});
</script>
<script type="text/javascript" src="<?php echo $siteURL?>/modules/appointment/js/ajaxupload.3.5.js" ></script>
<script type="text/javascript" src="<?php echo $siteURL?>/modules/appointment/js/jic.js" ></script>