<?php
/********************************************************************************* 
 *  This file is part of Sentrifugo.
 *  Copyright (C) 2015 Sapplica
 *   
 *  Sentrifugo is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Sentrifugo is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Sentrifugo.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  Sentrifugo Support <support@sentrifugo.com>
 ********************************************************************************/

if($this->ermsg == 'nocategory')
{
?>
	<div class="ml-alert-1-info m1-info-set"><div class="style-1-icon info"></div>Category not found.</div>
<?php
}
else if($this->ermsg == 'invalidUrl')
{
?>
	<div class="ml-alert-1-info m1-info-set"><div class="style-1-icon info"></div>Invalid URL</div>
<?php
}
else
{
 sapp_Global::generateClientValidations($this->form);
?>
<link rel="stylesheet" href="<?php echo MEDIA_PATH?>css/screen.css">
<script type="text/javascript" src="<?php echo MEDIA_PATH;?>js/jquery.uploadfile.min.js"></script>
<link rel="stylesheet" type="text/css" href="<?php echo MEDIA_PATH; ?>css/uploadfile.css" />

<script type="text/javascript" src="<?php echo MEDIA_PATH;?>js/jquery.prettyPhoto.js"></script>
<link rel="stylesheet" type="text/css" href="<?php echo MEDIA_PATH; ?>css/prettyPhoto.css" />
<form name="<?php echo $this->form->getName(); ?>" id="<?php echo $this->form->getId(); ?>" method="POST" action='<?php echo $this->form->getAction();?>' onsubmit="return validateUploadDoc();">
	<div class="total-form-controller">
		<div class="new-form-ui ">
			<label class="required">Document</label>
			<div class="division"><?php echo $this->form->document_name;?>
			<span class="errors" id="errors-document_name">
				<?php if(isset($this->msgarray['document_name'])){?>
					<?php echo $this->msgarray['document_name'];?>
				<?php }?>
			</span>
			</div>
		</div>
		<div class="new-form-ui ">
			<label class="required">Category</label>
			<div class="division"><?php echo $this->form->category_id; ?>
				<span class="errors" id="errors-category_id">
					<?php if(isset($this->msgarray['category_id'])){?>
						<?php echo $this->msgarray['category_id'];?>
					<?php }?>
				</span>
				<?php  if(!empty($this->popConfigPermission) && in_array('category',$this->popConfigPermission)) { ?>	
					<span class="add-coloum" onclick="displaydeptform('<?php echo BASE_URL.'categories/addnewcategory' ?>','Category');"> Add Category</span>			
				<?php } ?>
			</div>
		</div> 
		<div class="new-form-ui textareaheight">
			<label>Description</label>
			<div class="division"><?php echo $this->form->description; ?></div>
		</div>
		<div class="new-form-ui ">
			<label>Version</label>
			<div class="division">
				<?php echo $this->form->document_version; ?>
				<span class="errors" id="errors-document_version">
					<?php if(isset($this->msgarray['document_version'])){?>
						<?php echo $this->msgarray['document_version'];?>
					<?php }?>
				</span>
			</div>
		</div>
		<div class="new-form-ui-1" id="pd_attachment" style="width:300px;">
			<label class="required">
				Select Document
				<img src="<?php echo MEDIA_PATH;?>images/help.png" title="Allowed file extensions: doc, docx, pdf" class="tooltip">
			</label>	
			<div class="division">
				<span class="upload-attachment uploadbutsel" id="fileupload"><b class="sprite upload-icon" style="cursor:pointer;">Upload Document</b></span>
				<?php 
				if(isset($this->msgarray['file_original_names']) && $this->msgarray['file_original_names'] != '')
				{
					$org_files = explode(',', $this->msgarray['file_original_names']);
					$new_files = explode(',', $this->msgarray['file_new_names']);
					$path = POLICY_DOC_PATH; 
					
					for($i = 0; $i<count($org_files);$i++)
					{
						$strFileName = (strlen($org_files[$i]) > 30)?(substr($org_files[$i],0,28)."..."):$org_files[$i];
						
						echo '<div class="ajax-file-upload-statusbar" id="x_file_'.$i.'">
							<div class="ajax-file-upload-filename" style="width:auto;padding:0 20px 0 20px;">'.$strFileName.'</div>
							<div class="ajax-file-upload-red" onclick=deleteImages(this,"'.$org_files[$i].'","'.$new_files[$i].'","x_file_'.$i.'") style=""><span class="ajax-file-upload-red" style=""><i class="fa fa-times-circle"></i></span></div>';
						echo '</div>';
					}
				}
				?>
			</div>
			<div id="loaderimgprofile" style="display:none; margin-left: 124px; top: 26px;">
				<img src="<?php echo $this->baseUrl("public/media/images/loaderwhite_21X21.gif");?>" style="width:21px; height: 21px; float: none; "/>
			</div>
			<span id="errors-doc_attachment" class="errors">
			<?php if(isset($this->msgarray['doc_attachment'])){
					echo $this->msgarray['doc_attachment'];
				}
			?>
			</span>
		</div>
		<input type="hidden" name="file_original_names" id="file_original_names" value="<?php if(isset($this->file_original_names)){ echo $this->file_original_names;}?>">
		<input type="hidden" name="file_new_names" id="file_new_names" value="<?php if(isset($this->file_new_names)){echo $this->file_new_names;}?>">
		<input type="hidden" name="redirectUrl" id="redirectUrl" value="<?php echo $this->redirectUrl; ?>">
	</div>
    	<div class="new-form-ui-submit">
		<?php echo $this->form->submit; ?>
		<button onclick="window.history.go(-1);" id="Cancel" name="Cancel" type="button" >Cancel</button>
	</div>

	</div>

</form>
<div id="categoriesContainer"  style="display: none; overflow: auto;">
	<div class="heading">
		<a href="javascript:void(0)">
		<img src="<?php echo $this->baseUrl().'/public/media/';?>images/close.png" name="" align="right"
			border="0" hspace="3" vspace="5" class="closeAttachPopup"
			style="margin: -24px 8px 0 0;"> </a>
	</div>
		<iframe id="categoriesCont" class="business_units_iframe" frameborder="0"></iframe>
</div>

<script type="text/javascript">

$(document).ready(function(){

	<?php if($this->data['id']){?>
		$("a[rel^='prettyPhoto']").prettyPhoto({social_tools : '', deeplinking: false});
	<?php }?>

});
function validateUploadDoc()
{
	var file_original_names = $.trim($('#file_original_names').val());
	var documentName = $.trim($('#document_name').val());
	var frm_categoryId = $.trim($('#category_id').val());

	var returnVal = true;
	if(file_original_names == ''){
		$('.ajax-file-upload-error').remove();
		$('#errors-doc_attachment').html('Please upload document');
		returnVal = false;
	}
	if(!documentName)
	{
		$('#errors-document_name').html('Please enter document');
		returnVal = false;
	}
	if(!frm_categoryId)
	{
		$('#errors-category_id').html('Please select category');
		returnVal = false;
	}
	if(returnVal) $.blockUI({ width:'50px',message: $("#spinner").html() });
	return returnVal;
}
$("#fileupload").uploadFile({
	url:base_url+"/policydocuments/uploaddoc",
	fileName: "myfile",
    allowedTypes:"doc,docx,pdf",	
    returnType:"json",
    formData: {},
    maxFileSize:2*1024*1024, // Maximum allowed file size: 2MB
    maxFileCount:1,
    showFileCounter:false,
    showDelete:true,
    showAbort: false,
    showDone:false,
    showCancel: false,
    uploadButtonClass:'upload-attachment',
    dragDrop:false,
    //deletelStr:'x',
    deletelStr:'<i class="fa fa-times-circle"></i>',
    dynamicFormData: function () {
        return {};
    },
    onSelect:function(files)
    {
    	$("#errors-doc_attachment").html('');
	$("#fileupload_error").remove();
    	$("#loaderimgprofile").show();
    	var existing = $('#file_original_names').val();
    	var existingArray = new Array();
    	var uploading_file_name = files[0].name; 
    	
	if(navigator.userAgent.match(/msie/i) == 'MSIE')
    		uploading_file_name = uploading_file_name.replace(/C:\\fakepath\\/i, '');

	if (existing.length > 0) {
    		existingArray = existing.split(',');
    	}
    	
    	for(var i = 0; i < files.length; i++)
		{    	
    		var uploading_file_name = files[i].name;
    		uploading_file_name = uploading_file_name.replace(/[^a-zA-Z0-9.]+/gi, '_');
        	var comma = uploading_file_name.indexOf(',');
	    	if (comma !== -1){
	    		$('#fileupload').after('<div class="errors upload_error_x" id="fileupload_error">Comma( , ) not allowed in file names.</div>');
	    		$("#loaderimgprofile").hide();
	    		return false;
	    	}

	    	// Hide loader when uploaded file is not in allowed file types
	    	file = uploading_file_name.toLowerCase(),
            extension = file.substring(file.lastIndexOf('.') + 1);
	    	allowedExtensions = new Array("doc","docx","pdf");
	    	if ($.inArray(extension, allowedExtensions) == -1) {
	    		$("#loaderimgprofile").hide();
            } 

	    	// Hide loader when uploaded file size is more than 2 MB
	    	if (files[i].size > 2*1024*1024) {
	    		$("#loaderimgprofile").hide();
	    	}
            
    	}
    	
    	if(files.length > 1 || (existingArray.length + files.length) > 1){
    		$('#fileupload').after('<div class="errors upload_error_x" id="fileupload_error">Maximum allowed files are: 1</div>');
    		$("#loaderimgprofile").hide();
            return false;
    	}
    },
    onSuccess:function(files,data,xhr)
    {
	$("#errors-doc_attachment").html('');
	$("#fileupload_error").remove();
    	$('.ajax-file-upload-error').not(':eq(0)').hide();
    	$(".ajax-file-upload-progress").hide();
    	if(navigator.userAgent.match(/msie/i) == 'MSIE')
    	{     
			var c = $('.ajax-file-upload-filename:first').html();
			var d = c.replace(/C:\\fakepath\\/i, '');
			$('.ajax-file-upload-filename:first').html(d);
    	}
    	$('#file_original_names').val(($('#file_original_names').val())?($('#file_original_names').val()+','+data.filedata.original_name):data.filedata.original_name);
    	$('#file_new_names').val(($('#file_new_names').val())?($('#file_new_names').val()+','+data.filedata.new_name):data.filedata.new_name);
    	$("#loaderimgprofile").hide();
    },
    deleteCallback: function(data,pd)
    {
	$('div#fileupload_error').remove();	
	if(data){
    		$("#loaderimgprofile").show();
	    	$.post(base_url+"/policydocuments/deletedocument/format/json",{op: "deletetemp", doc_new_name: data.filedata.new_name},
			        function(resp, textStatus, jqXHR)
			        {
		        		if(textStatus == 'success')
		        		{
				    		var x_original_files = $('#file_original_names').val().split(',');
				    		var x_new_files = $('#file_new_names').val().split(',');
	
				    		var org_index = x_original_files.indexOf(data.filedata.original_name);
				    		if (org_index !== -1) {
				    			x_original_files.splice(org_index, 1);
				    		    org_data = x_original_files.join(',');
				    		    $('#file_original_names').val(org_data);
				    		}

				    		var new_index = x_new_files.indexOf(data.filedata.new_name);
				    		if (new_index !== -1) {
				    			x_new_files.splice(new_index, 1);
				    		    new_data = x_new_files.join(',');
				    		    $('#file_new_names').val(new_data);
				    		}
		        		}
                    	//$.unblockUI();
			        });
	    	pd.statusbar.hide();
	    	$("#loaderimgprofile").hide();
    	}
    }   
});


</script>
<?php
}
?>
<script type="text/javascript">
$(document).ready(function(){

	/**
	** to handle menu issue for policydocuments - START
	**/
	var category_id = <?php echo (isset($this->category_id)? $this->category_id : 0); ?>;
	if(category_id)
		selected_obj = $("li[menu-url='<?php echo BASE_URL ;?>policydocuments/id/"+category_id+"']"); 
	else
		selected_obj = $("li[menu-url^='<?php echo BASE_URL ;?>categories']"); 

	parent_div = selected_obj.attr("parent-div"); 

	if(parent_div == undefined) parent_div = 'div_mchilds_1';	

	selected_obj.addClass("active_menu_class");
	$('.'+parent_div).addClass("selected_menu_class");
	$('.'+parent_div).show();

	parent_menu_selected(selected_obj);

	//removing of class for selected child menu
	$(".side-menu-selected").removeClass("side-menu-selected");
	//end of removing of class for selected child menu

	//to add selected class for selected child menu
	if(parent_div != "dummy" && category_id !='')
	    selected_obj.find("a").addClass("side-menu-selected");

	/**
	** to handle menu issue for policydocuments - END
	**/
});

function deleteImages(event,original_name,new_name,div_id)
{
	$('div#fileupload_error').remove();	
	$("#loaderimgprofile").show();
	
	$.post(base_url+"/policydocuments/deletedocument/format/json",{op: "delete", doc_new_name: new_name},
    function(resp, textStatus, jqXHR)
    {
		if(textStatus == 'success')
		{
			// Update photo gallery by removed attachment
			$("#photo_gallery").html(resp);
			$("a[rel^='prettyPhoto']").prettyPhoto({social_tools : '', deeplinking: false});
			
			$('#'+div_id).remove();
			
    		var x_original_files = $('#file_original_names').val().split(',');
    		var x_new_files = $('#file_new_names').val().split(',');

    		var org_index = x_original_files.indexOf(original_name);
    		if (org_index !== -1) {
    			x_original_files.splice(org_index, 1);
    		    org_data = x_original_files.join(',');
    		    $('#file_original_names').val(org_data);
    		}

    		var new_index = x_new_files.indexOf(new_name);
    		if (new_index !== -1) {
    			x_new_files.splice(new_index, 1);
    		    new_data = x_new_files.join(',');
    		    $('#file_new_names').val(new_data);
    		}

			// Remove 'Click to view' button when there are no attachments
			if (x_original_files.length == 0) {
				$("a.click_view_link_class").remove();
			}
		}
		$("#loaderimgprofile").hide();
    });
	
}
</script>
<style>

      .ajax-file-upload-red {
        cursor: pointer;
        float: right;
        margin-top: 8px;
    }
   
</style>
