var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		"use strict";
		var validator,
			$frmCreateEnquiry = $('#frmCreateEnquiry'),
			$frmUpdateEnquiry = $('#frmUpdateEnquiry'),
			$dialogConfirmation = $("#dialogConfirmation"),
			dialog = ($.fn.dialog !== undefined),
			datepicker = ($.fn.datepicker !== undefined),
			datagrid = ($.fn.datagrid !== undefined),
			validate = ($.fn.validate !== undefined),
			multiselect = ($.fn.multiselect !== undefined),
			chosen = ($.fn.chosen !== undefined),
			spinner = ($.fn.spinner !== undefined),
			tabs = ($.fn.tabs !== undefined),
			$tabs = $("#tabs"),
			tOpt = {
				activate: function (event, ui) {
					$(":input[name='tab_id']").val($(ui.newPanel).prop('id'));
				}
			};
	
		if ($tabs.length > 0 && tabs) {
			$tabs.tabs(tOpt);
		}
		$(".field-int").spinner({
			min: 1
		});
		if (chosen) {
			$("#c_country").chosen();
			$("#client_id").chosen();
		}
		
		if ($frmCreateEnquiry.length > 0 || $frmUpdateEnquiry.length > 0) 
		{
			$frmCreateEnquiry.validate({
				rules: {
					"cc_type":{
						required: function(){
							if($('#payment_method').val() == 'creditcard')
							{
								return true;
							}else{
								return false;
							}
						}
					},
					"cc_num":{
						required: function(){
							if($('#payment_method').val() == 'creditcard')
							{
								return true;
							}else{
								return false;
							}
						}
					},
					"cc_code":{
						required: function(){
							if($('#payment_method').val() == 'creditcard')
							{
								return true;
							}else{
								return false;
							}
						}
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				errorClass: "err",
				wrapper: "em",
				ignore: "",
				invalidHandler: function (event, validator) {
				    if (validator.numberOfInvalids()) {
				    	var index = $(validator.errorList[0].element, this).closest("div[id^='tabs-']").index();
				    	if ($tabs.length > 0 && tabs && index !== -1) {
				    		$tabs.tabs(tOpt).tabs("option", "active", index-1);
				    	}
				    };
				}
			});
			$frmUpdateEnquiry.validate({
				rules: {
					"cc_type":{
						required: function(){
							if($('#payment_method').val() == 'creditcard')
							{
								return true;
							}else{
								return false;
							}
						}
					},
					"cc_num":{
						required: function(){
							if($('#payment_method').val() == 'creditcard')
							{
								return true;
							}else{
								return false;
							}
						}
					},
					"cc_code":{
						required: function(){
							if($('#payment_method').val() == 'creditcard')
							{
								return true;
							}else{
								return false;
							}
						}
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: "",
				invalidHandler: function (event, validator) {
				    if (validator.numberOfInvalids()) {
				    	var index = $(validator.errorList[0].element, this).closest("div[id^='tabs-']").index();
				    	if ($tabs.length > 0 && tabs && index !== -1) {
				    		$tabs.tabs(tOpt).tabs("option", "active", index-1);
				    	}
				    };
				}
			});
		}
		function formatClient (str, obj) {
			return '<a href="index.php?controller=pjAdminClients&action=pjActionUpdate&id='+obj.client_id+'">'+str+'</a>';
		}
		if ($("#grid").length > 0 && datagrid) {
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminEnquiries&action=pjActionUpdate&id={:id}"},
				          {type: "copy", url: "index.php?controller=pjAdminEnquiries&action=pjActionCreate&id={:id}", title: myLabel.copy},
				          {type: "print", target: "_blank", url: "index.php?controller=pjAdminEnquiries&action=pjActionPrint&id={:id}", title: myLabel.print},
				          {type: "delete", url: "index.php?controller=pjAdminEnquiries&action=pjActionDeleteEnquiry&id={:id}"}
						 ],
				columns: [
				          {text: myLabel.date_time, type: "text", sortable: true, width:250},
				          {text: myLabel.client, type: "text", sortable: false, width:120, renderer: formatClient},
				          {text: myLabel.total, type: "text", sortable: true, editable: false, width:70},
				          {text: myLabel.status, type: "select", sortable: true, editable: true, width: 100, options: [
				                                                                                     {label: myLabel.pending, value: "pending"}, 
				                                                                                     {label: myLabel.confirmed, value: "confirmed"},
				                                                                                     {label: myLabel.cancelled, value: "cancelled"}
				                                                                                     ], applyClass: "pj-status"}],
				dataUrl: "index.php?controller=pjAdminEnquiries&action=pjActionGetEnquiry" + pjGrid.queryString,
				dataType: "json",
				fields: ['date', 'c_name', 'total', 'status'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminEnquiries&action=pjActionDeleteEnquiryBulk", render: true, confirmation: myLabel.delete_confirmation},
					   {text: myLabel.exported, url: "index.php?controller=pjAdminEnquiries&action=pjActionExportEnquiry", ajax: false}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminEnquiries&action=pjActionSaveEnquiry&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
		}
				
		$(document).on("focusin", ".datepicker", function (e) {
			var minDate, maxDate,
				$this = $(this),
				custom = {},
				o = {
					firstDay: $this.attr("rel"),
					dateFormat: $this.attr("rev"),
				};
			$(this).datepicker($.extend(o, custom));
		}).on("click", ".pj-form-field-icon-date", function (e) {
			var $dp = $(this).parent().siblings("input[type='text']");
			if ($dp.hasClass("hasDatepicker")) {
				$dp.datepicker("show");
			} else {
				$dp.trigger("focusin").datepicker("show");
			}
			
		}).on("click", ".btn-all", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$(this).addClass("pj-button-active").siblings(".pj-button").removeClass("pj-button-active");
			var content = $grid.datagrid("option", "content"),
				cache = $grid.datagrid("option", "cache");
			$.extend(cache, {
				status: "",
				q: ""
			});
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminEnquiries&action=pjActionGetEnquiry", "created", "DESC", content.page, content.rowCount);
			return false;
		}).on("click", ".btn-filter", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $this = $(this),
				content = $grid.datagrid("option", "content"),
				cache = $grid.datagrid("option", "cache"),
				obj = {};
			$this.addClass("pj-button-active").siblings(".pj-button").removeClass("pj-button-active");
			obj.status = "";
			obj[$this.data("column")] = $this.data("value");
			$.extend(cache, obj);
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminEnquiries&action=pjActionGetEnquiry", "created", "DESC", content.page, content.rowCount);
			return false;
		}).on("submit", ".frm-filter", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $this = $(this),
				content = $grid.datagrid("option", "content"),
				cache = $grid.datagrid("option", "cache");
			$.extend(cache, {
				q: $this.find("input[name='q']").val()
			});
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminEnquiries&action=pjActionGetEnquiry", "created", "DESC", content.page, content.rowCount);
			return false;
		}).on("click", ".pj-button-detailed, .pj-button-detailed-arrow", function (e) {
			e.stopPropagation();
			$(".pj-form-filter-advanced").toggle();
		}).on("submit", ".frm-filter-advanced", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var obj = {},
				$this = $(this),
				arr = $this.serializeArray(),
				content = $grid.datagrid("option", "content"),
				cache = $grid.datagrid("option", "cache");
			for (var i = 0, iCnt = arr.length; i < iCnt; i++) {
				obj[arr[i].name] = arr[i].value;
			}
			$.extend(cache, obj);
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminEnquiries&action=pjActionGetEnquiry", "created", "DESC", content.page, content.rowCount);
			return false;
		}).on("reset", ".frm-filter-advanced", function (e) {
			$(".pj-button-detailed").trigger("click");
		}).on("change", "#payment_method", function (e) {
			switch ($("option:selected", this).val()) {
				case 'creditcard':
					$(".boxCC").show();
					break;
				default:
					$(".boxCC").hide();
			}
		}).on("change", "#bedrooms, #bathrooms", function (e) {
			calculatePrice();
		}).on("click", ".pjCbsExtrasCheckbox, .pjCbsCleaningMaterials", function (e) {
			calculatePrice();
		}).on("click", ".pjCbsSendConfirm", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$dialogConfirmation.data('id', $(this).attr('data-id')).dialog('open');
		}).on("change", "#client_id", function (e) {
			var $pjCbsEditURL = $('#pjCbsEditURL');
			var href = $pjCbsEditURL.attr('data-href');
			if($(this).val() == '')
			{
				$('.clientBox').show();
				$('#c_name').addClass('required');
				$('#c_email').addClass('required');
				$pjCbsEditURL.hide();
				$('#clientInfo').html("").parent().hide();
			}else{
				$('.clientBox').hide();
				$('#c_name').removeClass('required');
				$('#c_email').removeClass('required');
				
				href = href.replace('{ID}', $(this).val());
				$pjCbsEditURL.attr('href', href).show();
				
				var option = $('option:selected', this).attr('data-info');
				$('#clientInfo').html(option).parent().show();
			}
		});
		
		if ($dialogConfirmation.length > 0 && dialog) {
			$dialogConfirmation.dialog({
				autoOpen: false,
				draggable: false,
				resizable: false,
				modal: true,
				width: 645,
				open: function () {
					$dialogConfirmation.html("");
					$.get("index.php?controller=pjAdminEnquiries&action=pjActionConfirmation", {
						"enquiry_id": $dialogConfirmation.data('id')
					}).done(function (data) {
						$dialogConfirmation.html(data);
						validator = $dialogConfirmation.find("form").validate({
							
						});
						$dialogConfirmation.dialog("option", "position", "center");
						attachTinyMce.call(null);
					});
				},
				buttons: (function () {
					var buttons = {};
					buttons[cbsApp.locale.button.send] = function () {
						if (validator.form()) {
							$.post("index.php?controller=pjAdminEnquiries&action=pjActionConfirmation", $dialogConfirmation.find("form").serialize()).done(function (data) {
								$dialogConfirmation.dialog("close");
							})
						}
					};
					buttons[cbsApp.locale.button.cancel] = function () {
						$dialogConfirmation.dialog("close");
					};
					
					return buttons;
				})()
			});
		}
		function attachTinyMce(options) {
			if (window.tinymce !== undefined) {
				tinymce.EditorManager.editors = [];
				var defaults = {
					selector: "textarea.mceEditor",
					theme: "modern",
					width: 610,
					height: 330,
					plugins: [
				         "advlist autolink link image lists charmap print preview hr anchor pagebreak",
				         "searchreplace visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
				         "save table contextmenu directionality emoticons template paste textcolor"
				    ],
				    toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | print preview media fullpage | forecolor backcolor emoticons"
				};
				
				var settings = $.extend({}, defaults, options);
				
				tinymce.init(settings);
			}
		}
		
		function calculateHours()
		{
			var time_per_bedroom = parseInt($('#time_per_bedroom').val(), 10);
			var time_per_bathroom = parseInt($('#time_per_bathroom').val(), 10);
			var bedrooms = $('#bedrooms').val();
			var bathrooms = $('#bathrooms').val();
			var total_minutes = 0;
			var total_hours = 0;
			
			if(bedrooms != '' && bedrooms != '0')
			{
				total_minutes += parseInt(bedrooms, 10) * time_per_bedroom;
			}
			if(bathrooms != '' && bathrooms != '0')
			{
				total_minutes += parseInt(bathrooms, 10) * time_per_bathroom;
			}
			if($('.pjCbsExtrasCheckbox').length > 0)
			{
				$('.pjCbsExtrasCheckbox').each(function(){
					if($(this).is(':checked'))
					{
						total_minutes += parseInt($(this).attr('data-time'), 10);
					}
				});
			}
			if (total_minutes > 0)
			{
				total_hours = parseInt(total_minutes / 60, 10);
				var mod_minutes = (total_minutes % 60);
				if(mod_minutes > 0)
				{
					total_hours++;
				}
			}
			return total_hours;
		}
		function calculatePrice()
		{
			var subtotal = 0;
			var tax = 0;
			var total = 0;
			var deposit = 0;
			var price_per_hour = parseFloat($('#price_per_hour').val());
			var cleaning_materials_price = parseFloat($('#cleaning_materials_price').val());
			var hours = calculateHours();
			
			subtotal += price_per_hour * hours;
			if($('.pjCbsCleaningMaterials').length > 0)
			{
				if($('input[name="cleaning_materials"]:checked').val() == 'F')
				{
					subtotal += cleaning_materials_price;
				}
			}
			tax = (subtotal * parseFloat($('#tax').attr('data-tax'))) / 100;
			total = subtotal + tax;
			deposit = (total * parseFloat($('#deposit').attr('data-deposit'))) / 100;
			
			if(subtotal > 0)
		    {
				$('#subtotal').val(subtotal.toFixed(2));
				$('#tax').val(tax.toFixed(2));
	    		$('#total').val(total.toFixed(2));
	    		$('#deposit').val(deposit.toFixed(2));
		    }else{
		    	$('#subtotal').val('');
	    		$('#tax').val('');
	    		$('#total').val('');
	    		$('#deposit').val('');
		    }
		}
	});
})(jQuery_1_8_2);