var baseURL=$('meta[name="base_url"]').attr('content');
var token_key=$('#token_key').val();

var $ckfield = CKEDITOR.replace( 'ckfield' );
var $modal_ckfield = CKEDITOR.replace( 'modal-ckfield' );

$ckfield.on('change', function() {
	$ckfield.updateElement();
});

$modal_ckfield.on('change', function() {
	$modal_ckfield.updateElement();
});

$(document).on("change", "#check", function () {
	if($(this).prop("checked") == true){
		$('#testimony').slideDown();
	}
	else if($(this).prop("checked") == false){
		$('#testimony').slideUp();
	}
});

$(document).on("change", "#modal_check", function () {
	if($(this).prop("checked") == true){
		$('#modal_testimony').slideDown();
	}
	else if($(this).prop("checked") == false){
		$('#modal_testimony').slideUp();
	}
});

$("#addForm").validate({

	rules:
		{
			date:
				{
					required: true,
				},
			portfolio_title:
				{
					required: true,
				},
			company_name:
				{
					required: true,
				},
			company_address:
				{
					required: true,
				},
			content:
				{
					required: true,
				},
			contact_person:
				{
					required: true,
				},
			contact_person_post:
				{
					required: true,
				},
			testimonial:
				{
					required: true,
				}
		},

	messages:
		{
			date:
				{
					required:  "Please choose a date",
				},
			portfolio_title:
				{
					required:  "Please type portfolio title",
				},
			company_name:
				{
					required: "Please type company name",
				},
			company_address:
				{
					required: "Please type company address",
				},
			content:
				{
					required: "Please write details about this portfolio",
				},
			contact_person:
				{
					required:  "Please type reviewer's name",
				},
			contact_person_post:
				{
					required:  "Please type reviewer's designation",
				},
			testimonial:
				{
					required:  "Please type reviewer's testimony",
				},
		},

	submitHandler: function(form) {

		$('.submit_button').css('cursor', 'wait');
		$('.submit_button').attr('disabled', true);

		$.ajax({
			url: baseURL + "newPortfolioEntryProcess",
			type: 'POST',
			data: $('#addForm').serialize(),
			dataType:'json',
			success: function(res) {
				swal({
					title: res.response,
					type: res.type,
					timer: 1500,
					showConfirmButton: false,
					customClass: 'swal-height'
				});

				if (res.type=='success')
				{
					$('.open').trigger('click');
					$("#addForm").trigger("reset");
					CKEDITOR.instances['ckfield'].setData("");
					portfolioTable.ajax.reload();
				}


				$('.submit_button').css('cursor', 'pointer');
				$('.submit_button').removeAttr('disabled');

			}
		});
	},                                                // Do not change code below
	errorPlacement: function(error, element)
	{
		error.insertAfter(element.parent());
	}

});

var portfolioTable = $('#portfolioTable').DataTable( {
	"processing": true,
	"serverSide": true,
	"deferRender": true,
	"ajax":{
		"url": baseURL + "dataHandling/getPortfolioData",
		"type": "POST",
		data: function(d) {
			d.csrf_medisave_secured = token_key;
		}
	},

	"columns": [
		null,
		{ "className": ""},
		{ "className": ""},
		{ "className": ""},
		{ "className": ""},
		{ "className": ""},
		{ "className": ""},
		{ "className": "center",searchable: false,orderable: false },
	],
	"autoWidth": false,


	"columnDefs": [ {
		"targets": -1,
		"data": null,
		"defaultContent": "<td align='center'><a href='#full_width_modal_parent' role='button' id='details' class='btn btn-primary btn-xs small_btn' title='Details' data-toggle='modal'><i class='fa fa-bars'></i> View</a> </td></td> "
	},
		{
			targets: 5,
			render: function ( data, type, row ) {
				var color = 'black';
				if (data == 'Not Publish') {
					color = 'red';
				}
				if (data == 'Published') {
					color = 'green';
				}
				return '<span style="color:' + color + '">' + data + '</span>';
			}
		}
	],

	"aLengthMenu": [
		[10, 25, 50, -1],
		[10, 25, 50, "All"]
	],
	// set the initial value
	"iDisplayLength": 10,
	"bFilter" : true,
	"bLengthChange": true,
	"bInfo": true,
	"bPaginate": true,
	"aaSorting": [[ 0, "asc" ]],

} );

$('#portfolioTable tbody').on( 'click', '#details', function () {
	var data = portfolioTable.row( $(this).parents('tr') ).data();
	$('#modal_portfolio_id_picture').val(data[13]);
	$('#modal_portfolio_id').val(data[13]);
	CKEDITOR.instances['modal-ckfield'].setData(data[9]);
	$('#modal_date').val(data[1]);
	$('#modal_portfolio_title').val(data[2]);
	$('#modal_company_name').val(data[3]);
	$('#modal_company_address').val(data[4]);
	$('#modal_contact_person').val(data[7]);
	$('#modal_contact_person_post').val(data[8]);
	$('#modal_testimonial').val(data[10]);
	$('#modal_status').val(data[6]);

	if(data[11]=='TRUE'){
		$('#modal_testimony').show();
		$('#modal_check').prop( "checked", true );
	}
	else{
		$('#modal_testimony').hide();
		$('#modal_check').prop( "checked", false );
	}

	if(data[12]!=null){
		var imageData=data[12];
	}
	else{
		var imageData='image.png';
	}
	var image="<img src='"+baseURL+"/assets/img/portfolio/"+imageData+"' width='120px'/>";
	$('#modal_image').html(image);
} );


$uploadCrop = $('#upload-demo').croppie({
	enableExif: true,
	viewport: {
		width: 550,
		height: 360,
		type: 'rectangle'
	},
	boundary: {
		width: 560,
		height: 370,
	}
});

$('#upload').on('change', function () {
	var reader = new FileReader();
	reader.onload = function (e) {
		$uploadCrop.croppie('bind', {
			url: e.target.result
		}).then(function(){
			console.log('jQuery bind complete');
		});
	}
	reader.readAsDataURL(this.files[0]);
});

$('.upload-result').on('click', function (ev) {

	$('.upload-result').css('cursor', 'wait');
	$('.upload-result').attr('disabled');

	$uploadCrop.croppie('result', {
		type: 'canvas',
		size: 'viewport'
	}).then(function (resp) {
		var portfolio_id=$('#modal_portfolio_id_picture').val();
		$.ajax({
			url: baseURL + "dataHandling/addPortfolioPicture",
			type: "POST",
			data: {"image":resp,"portfolio_id":portfolio_id,"csrf_medisave_secured": token_key},
			dataType: 'json',
			success: function (data) {
				var response_brought = data.response.indexOf('Picture Added successfully');
				if (response_brought != -1)
				{
					swal({
						title: "Picture Added Successfully",
						type: "success",
						timer: 1500,
						showConfirmButton: false,
						customClass: 'swal-height'
					});
					$("#updateLogo").trigger("reset");
					$('#full_width_modal_parent').modal('hide');
					portfolioTable.ajax.reload();
				}

				$('.upload-result').css('cursor', 'pointer');
				$('.upload-result').removeAttr('disabled');
			}
		});
	});
});

$("#updateForm").validate({

	rules:
		{
			date:
				{
					required: true,
				},
			portfolio_title:
				{
					required: true,
				},
			company_name:
				{
					required: true,
				},
			company_address:
				{
					required: true,
				},
			content:
				{
					required: true,
				},
			contact_person:
				{
					required: true,
				},
			contact_person_post:
				{
					required: true,
				},
			testimonial:
				{
					required: true,
				},
			status:
				{
					required: true,
				}
		},

	messages:
		{
			date:
				{
					required:  "Please choose a date",
				},
			portfolio_title:
				{
					required:  "Please type portfolio title",
				},
			company_name:
				{
					required: "Please type company name",
				},
			company_address:
				{
					required: "Please type company address",
				},
			content:
				{
					required: "Please write details about this portfolio",
				},
			contact_person:
				{
					required:  "Please type reviewer's name",
				},
			contact_person_post:
				{
					required:  "Please type reviewer's designation",
				},
			testimonial:
				{
					required:  "Please type reviewer's testimony",
				},
			testimonial:
				{
					required:  "Please select a status",
				},
		},

	submitHandler: function(form) {

		$('.update_button_2').css('cursor', 'wait');
		$('.update_button_2').attr('disabled', true);

		$.ajax({
			url: baseURL + "portfolioEditProcess",
			type: 'POST',
			data: $('#updateForm').serialize(),
			dataType:'json',
			success: function(res) {
				swal({
					title: res.response,
					type: res.type,
					timer: 1500,
					showConfirmButton: false,
					customClass: 'swal-height'
				});

				if (res.type=='success')
				{
					CKEDITOR.instances['modal-ckfield'].setData("");
					$("#updateForm").trigger("reset");
					$('#full_width_modal_parent').modal('hide');
					portfolioTable.ajax.reload();
				}


				$('.update_button_2').css('cursor', 'pointer');
				$('.update_button_2').removeAttr('disabled');

			}
		});
	},                                                // Do not change code below
	errorPlacement: function(error, element)
	{
		error.insertAfter(element.parent());
	}

});
