var jQuery = jQuery || $.noConflict();
(function ($, undefined) {
	$(function () {
		"use strict";
		var validator,
			$frmCreate = $("#frmCreate"),
			$frmUpdate = $("#frmUpdate"),
			select2 = ($.fn.select2 !== undefined),
			validate = ($.fn.validate !== undefined),
			datepicker = ($.fn.datepicker !== undefined),
			datagrid = ($.fn.datagrid !== undefined),
			datetimeOptions = null;
			
		if (select2 && $(".select-country").length) {
            $(".select-country").select2({
                allowClear: true
            });
        };
        
        if($('.i-checks').length > 0)
		{
			$('.i-checks').iCheck({
	            checkboxClass: 'icheckbox_square-green',
	            radioClass: 'iradio_square-green'
	        }).on('ifChanged', function(event) {
	        	if ($frmCreate.length > 0 || $frmUpdate.length > 0)  {
	        		calcPrice.call(null);
	        	}
	        });
		}
        
        if($('.i-checks-file').length > 0)
		{
			$('.i-checks-file').iCheck({
	            checkboxClass: 'icheckbox_square-green',
	            radioClass: 'iradio_square-green'
	        }).on('ifChanged', function(event) {
	        	$('#cpSubmitButton').html(myLabel.btn_export);
				$('.cpFeedContainer').hide();
				$('.cpPassowrdContainer').hide();
	        });
		}
        
        if($('.i-checks-feed').length > 0)
		{
			$('.i-checks-feed').iCheck({
	            checkboxClass: 'icheckbox_square-green',
	            radioClass: 'iradio_square-green'
	        }).on('ifChanged', function(event) {
	        	$('.cpPassowrdContainer').show();
				$('#cpSubmitButton').html(myLabel.btn_get_url);
	        });
		}
        
        if($(".touchspin3").length > 0)
		{
			$(".touchspin3").TouchSpin({
				verticalbuttons: true,
	            buttondown_class: 'btn btn-white',
	            buttonup_class: 'btn btn-white',
	            max: 4294967295
	        });
		}
        
        if ($('.datepick').length > 0) {
        	if ($('#datePickerOptions').length) {
            	$.fn.datepicker.dates['en'] = {
            		days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
        		    daysMin: $('#datePickerOptions').data('days').split("_"),
        		    daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
        		    months: $('#datePickerOptions').data('months').split("_"),
        		    monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
        		    format: $('#datePickerOptions').data('format'),
                	weekStart: parseInt($('#datePickerOptions').data('wstart'), 10),
                	stepMinute: 5,
        		};
            };
        	$('.datepick').datepicker({autoclose: true}).on('changeDate', function (selected) {
        		if($(this).attr('name') == 'date_from')
        		{
        			if($('input[name="date_to"]').length > 0)
        			{
        				var $minDate = new Date(selected.date.valueOf());
        				$('input[name="date_to"]').datepicker('setStartDate', $minDate);
        				var $to = $('input[name="date_to"]'),
        					$date_to_value = $to.datepicker("getUTCDate");
        				if($date_to_value < selected.date)
    					{
        					$to.val($('input[name="date_from"]').val());
    					}
        			}
        		}
        		
        		if($(this).attr('name') == 'date_to')
        		{
        			if($('input[name="date_from"]').length > 0)
        			{
        				var $maxDate = new Date(selected.date.valueOf());
        				$('input[name="date_from"]').datepicker('setEndDate', $maxDate);
        				var $from = $('input[name="date_from"]'),
        					$date_from_value = $from.datepicker("getUTCDate");
        				if($date_from_value > selected.date)
    					{
        					$from.val($('input[name="date_to"]').val());
    					}
        			}
        		}
            });
        }
        
        if ($('#dateTimePickerOptions').length) {
        	var currentDate = new Date(),
        		$optionsEle = $('#dateTimePickerOptions');
        	
	        moment.updateLocale('en', {
				week: { dow: parseInt($optionsEle.data('wstart'), 10) },
				months : $optionsEle.data('months').split("_"),
		        weekdaysMin : $optionsEle.data('days').split("_")
			});
	        datetimeOptions = {
					format: $optionsEle.data('format'),
					locale: moment.locale('en'),
					allowInputToggle: true,
					ignoreReadonly: true,
					useCurrent: false
				};
	        $('.datetimepick').datetimepicker(datetimeOptions);
	        
	        var $dt_from =$('#from'),
				$dt_to =$('#to');
			$dt_from.datetimepicker(datetimeOptions).on('dp.change', function (e) {
				var $frm = $(this).closest("form"),
					$from = e.date.valueOf();
				if ($dt_to.val() != '') {
					var $to = $dt_to.data("DateTimePicker").date().valueOf();
					if ($to < $from) {
						$dt_to.val($dt_from.val());
					}
				}
				$dt_to.data("DateTimePicker").minDate(e.date);
				var $from = $frm.find('input[name="from"]').val(),
        			$to = $frm.find('input[name="to"]').val();
				if ($from != '' && $to != '') {
	        		validateTime($frm, $(this));
	        		$.ajax({
	        	        type: "POST",
	        	        url: "index.php?controller=pjAdminBookings&action=pjActionGetSpaces",
	        	        data: $frm.serialize(),
	        	        async:true,
	        	        success: function (data) {
	        	        	$('#cpSpaceContainer').html(data.ob_spaces);
							$('#tblExtrasClone').html(data.ob_extras);
							resetCalc.call(null);
	        	        }
	        	    });
	        	}
			});
			$dt_to.datetimepicker(datetimeOptions).on('dp.change', function (e) {
				var $frm = $(this).closest("form"),
					$from = $frm.find('input[name="from"]').val(),
	        		$to = $frm.find('input[name="to"]').val();
				$dt_from.data("DateTimePicker").maxDate(e.date);
				if ($from != '' && $to != '') {
	        		validateTime($frm, $(this));
	        		$.ajax({
	        	        type: "POST",
	        	        url: "index.php?controller=pjAdminBookings&action=pjActionGetSpaces",
	        	        data: $frm.serialize(),
	        	        async:true,
	        	        success: function (data) {
	        	        	$('#cpSpaceContainer').html(data.ob_spaces);
							$('#tblExtrasClone').html(data.ob_extras);
							resetCalc.call(null);
	        	        }
	        	    });
	        	}
			});

	        function validateTime($frm, $obj)
			{
				$.ajax({
					type: 'POST',
					async: true, 
					url: "index.php?controller=pjAdminBookings&action=pjActionCheckTime",
					data: $frm.serialize(),
					success: function(data){
						if(data.status == 'ERR')
						{
							if ($obj.attr('name') == 'from') {
								$frm.find("input[name='from']").attr('data-wt', 'closed').valid();
							} else {
								$frm.find("input[name='to']").attr('data-wt', 'closed').valid();
							}
						}else{
							$frm.find("input[name='from']").attr('data-wt', 'open').valid();
							$frm.find("input[name='to']").attr('data-wt', 'open').valid();
						}
						$('#cpRentalDays').val(data.rental_days);
					}
				});
			}
        }
        
        if ($frmCreate.length > 0 || $frmUpdate.length > 0) 
		{
        	$.validator.addMethod('fromTime',
			    function (value, element) {
					if($(element).attr('data-wt') == 'open')
					{
						return true;
					}else{
						return false;
					}
			    }
			);
			$.validator.addMethod('toTime',
			    function (value, element) {
					if($(element).attr('data-wt') == 'open')
					{
						return true;
					}else{
						return false;
					}
			    }
			);
    			
	        if ($frmCreate.length > 0 && validate) {
				$frmCreate.validate({
					rules: {
						"from":{
							fromTime: true
						},
						"to":{
							toTime: true
						},
						"uuid": {
							remote: "index.php?controller=pjAdminBookings&action=pjActionCheckUniqueId"
						}
					},
					messages: {
						"from":{
							fromTime: myLabel.invalid_from_dt
						},
						"to":{
							toTime: myLabel.invalid_to_dt
						},
						"uuid":{
							remote: myLabel.existing_uuid
						}
					},
					onkeyup: false,
					ignore: "",
					invalidHandler: function (event, validator) {
					    if (validator.numberOfInvalids()) {
					    	var $_id = $(validator.errorList[0].element, this).closest("div[id^='tab-']").attr("id");
					    	$('.nav-'+$_id).trigger("click");
					    };
					},
					submitHandler: function (form) {
						if($(form).find(":submit").get(0))
						{
							var l = Ladda.create( $(form).find(":submit").get(0) );
							l.start();
						}		
						if($(form).find(":submit").get(1))
						{
							var l = Ladda.create( $(form).find(":submit").get(1) );
							l.start();
						}	
						return true;
					}
				});
				
				if($('#from').val() != '' && $('#to').val() != '')
				{
					$.ajax({
						type: 'POST',
						async: true, 
						url: "index.php?controller=pjAdminBookings&action=pjActionCheckTime",
						data: $frmCreate.serialize(),
						success: function(data){
							if(data.status == 'OK')
							{
								$frmCreate.find("input[name='from']").attr('data-wt', 'open').valid();
								$frmCreate.find("input[name='to']").attr('data-wt', 'open').valid();
							}
							$('#cpRentalDays').val(data.rental_days);
						}
					});
					$.ajax({
	        	        type: "POST",
	        	        url: "index.php?controller=pjAdminBookings&action=pjActionGetSpaces",
	        	        data: $frmCreate.serialize(),
	        	        async:true,
	        	        success: function (data) {
	        	        	$('#cpSpaceContainer').html(data.ob_spaces);
							$('#tblExtrasClone').html(data.ob_extras);
							resetCalc.call(null);
	        	        }
	        	    });
				}
			}

	        if ($frmUpdate.length > 0 && validate) {
				$frmUpdate.validate({
					rules: {
						"from":{
							fromTime: true
						},
						"to":{
							toTime: true
						},
						"uuid": {
							remote: "index.php?controller=pjAdminBookings&action=pjActionCheckUniqueId&id=" + $frmUpdate.find("input[name='id']").val()
						}
					},
					messages: {
						"from":{
							fromTime: myLabel.invalid_from_dt
						},
						"to":{
							toTime: myLabel.invalid_to_dt
						},
						"uuid":{
							remote: myLabel.existing_uuid
						}
					},
					highlight: function(element) {
						if($(element).closest('.table').length > 0)
						{
							$(element).closest('td').addClass('has-error');
						}else{
							$(element).closest('.form-group').addClass('has-error');
						}
					},
					unhighlight: function(element) {
						if($(element).closest('.table').length > 0)
						{
							$(element).closest('td').removeClass('has-error');
						}else{
							$(element).closest('.form-group').removeClass('has-error');
						}
					},
					onkeyup: false,
					ignore: "",
					invalidHandler: function (event, validator) {
					    if (validator.numberOfInvalids()) {
					    	var $_id = $(validator.errorList[0].element, this).closest("div[id^='tab-']").attr("id");
					    	$('.nav-'+$_id).trigger("click");
					    };
					},
					submitHandler: function (form) {
						if($(form).find(":submit").get(0))
						{
							var l = Ladda.create( $(form).find(":submit").get(0) );
							l.start();
						}		
						if($(form).find(":submit").get(1))
						{
							var l = Ladda.create( $(form).find(":submit").get(1) );
							l.start();
						}
						return true;
					}
				});
			}
		}
		
		function formatName(val, obj) {
			return ['<div>' + val + '</div>', '<a href="index.php?controller=pjAdminBookings&action=pjActionUpdate&id=', obj.id, '">', obj.c_email, '</a>'].join("");
		}
		function formatStatus(val, obj) {
			if(val == 'confirmed')
			{
				return '<div class="btn bg-confirmed btn-xs no-margin"><i class="fa fa-check"></i> ' + myLabel.confirmed + '</div>';
			}else if(val == 'cancelled'){
				return '<div class="btn bg-cancelled btn-xs no-margin"><i class="fa fa-times"></i> ' + myLabel.cancelled + '</div>';
			}else if(val == 'pending'){
				return '<div class="btn bg-pending btn-xs no-margin"><i class="fa fa-exclamation-triangle"></i> ' + myLabel.pending + '</div>';
			}
		}
		if ($("#grid").length > 0 && datagrid) {
			var cache = {},
				search = window.location.search,
				_status = search.match(/&status=(\w+)/),
				_from = search.match(/&from=([\d\-\.\/]+)/),
				_to = search.match(/&to=([\d\-\.\/]+)/);
			if (_status) {
				cache.status = _status[1];
			}
			if (_from) {
				cache.from = _from[1];
			}
			if (_to) {
				cache.to = _to[1];
			}
			
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminBookings&action=pjActionUpdate&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminBookings&action=pjActionDeleteBooking&id={:id}"},
						 ],
				columns: [
		          		  {text: myLabel.date_time, type: "text", sortable: true, editable: false},
		          		  {text: myLabel.space, type: "text", sortable: true, editable: false},
				          {text: myLabel.name, type: "text", sortable: true, editable: false, renderer: formatName},
				          {text: myLabel.status, type: "text", sortable: true, editable: false, renderer: formatStatus}],
				dataUrl: "index.php?controller=pjAdminBookings&action=pjActionGetBooking" + pjGrid.queryString,
				dataType: "json",
				fields: ['from', 'space', 'c_name', 'status'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminBookings&action=pjActionDeleteBookingBulk", render: true, confirmation: myLabel.delete_confirmation}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminBookings&action=pjActionSaveBooking&id={:id}",
				select: {
					field: "id",
					name: "record[]",
					cellClass: 'cell-width-2'
				},
				cache: cache
			});
		}	
		
		$(document).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(),
				status: $this.find("select[name='status']").val()
			});
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminBookings&action=pjActionGetBooking" + pjGrid.queryString, "created", "DESC", content.page, content.rowCount);
			return false;
		}).on("change", ".pj-filter-status", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$(".frm-filter").trigger("submit");
			return false;
		}).on("reset", ".frm-filter-advanced", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$(".btn-advance-search").trigger("click");
			var $frm = $('.frm-filter-advanced');
			$frm.find("input[name='uuid']").val('');
			$frm.find("input[name='c_name']").val('');
			$frm.find("input[name='c_email']").val('');
			$frm.find("select[name='space_id']").val('');
			$frm.find("select[name='status']").val('');
			$frm.find("input[name='date_from']").val('');
			$frm.find("input[name='date_to']").val('');
			
			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;
			}
			cache.q = "";
			$.extend(cache, obj);
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminBookings&action=pjActionGetBooking" + pjGrid.queryString, "created", "DESC", content.page, content.rowCount);
			return false;
		}).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=pjAdminBookings&action=pjActionGetBooking" + pjGrid.queryString, "created", "DESC", content.page, content.rowCount);
			return false;
		}).on("change", "#payment_method", function (e) {
			switch ($("option:selected", this).val()) {
				case 'creditcard':
					$(".boxCC").show();
					break;
				default:
					$(".boxCC").hide();
			}
		}).on("click", ".cpAddExtra", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $tbody = $("#tblExtras tbody"),
				index = Math.ceil(Math.random() * 999999);
			
			var clone_text = $("#tblExtrasClone").find("tbody").html();
			clone_text = clone_text.replace(/\{INDEX\}/g, 'cp_' + index);
			$tbody.append(clone_text);
			return false;
		}).on("click", ".cpRemoveExtra", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $tr = $(this).closest("tr");
			$tr.css("backgroundColor", "#FFB4B4").fadeOut("slow", function () {
				$tr.remove();
				calcPrice.call(null);
			});	
			return false;
		}).on("change", ".cpExtraSelector", function (e) {
			var $tr = $(this).parent().parent(),
				$td_price = $tr.find("td").eq(1),
				$td_qty = $tr.find("td").eq(2),
				index = $(this).attr('data-index');
			if($(this).val() != '')
			{
				var type = $('option:selected', this).attr('data-type'),
					cnt = $('option:selected', this).attr('data-cnt'),
					is_single = $('option:selected', this).attr('data-is_single'),
					price_format = $('option:selected', this).attr('data-price_format'),
					td_qty_html = '',
					i = 0;
				
				$td_qty.html("");
				switch(is_single)
				{
					case "1":
						td_qty_html = '<input type="checkbox" name="qty['+index+']" id="extra_qty_'+index+'" data-index="'+index+'" class="cpExtraPrice" checked="checked"/>';
						$td_qty.append(td_qty_html);
						$('#extra_qty_' + index).iCheck({
				            checkboxClass: 'icheckbox_square-green',
				            radioClass: 'iradio_square-green'
				        }).on('ifChanged', function(event) {
				        	calcPrice.call(null);
				        });
						break;
					case "0":
						if(type == 'limited')
						{
							td_qty_html = '<select name="qty['+index+']" data-index="'+index+'" class="form-control cpExtraPrice">';
							td_qty_html += '<option value="">--</option>';
							for(i = 0; i <= parseInt(cnt, 10); i++)
							{
								td_qty_html += '<option value="'+i+'">'+i+'</option>';
							}
							td_qty_html += '</select>';
							$td_qty.append(td_qty_html);
						}else{
							td_qty_html = '<input type="text" name="qty['+index+']" id="extra_qty_'+index+'" data-index="'+index+'" class="form-control cpExtraPrice"/>';
							$td_qty.append(td_qty_html);
							$('#extra_qty_' + index).TouchSpin({
								verticalbuttons: true,
					            buttondown_class: 'btn btn-white',
					            buttonup_class: 'btn btn-white',
					            max: 4294967295
					        });
						}
						break;
				}
				$td_price.html(price_format);
			}else{
				$td_price.html("");
				$td_qty.html("");
			}
			calcPrice.call(null);
			return false;
		}).on("change", "#space_id", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $this = $(this),
				$option = $("option:selected", this);
			if($option.val() == '')
			{
				resetCalc.call(null);
			}else{
				calcPrice.call(null);
			}
		}).on("change", ".cpExtraPrice", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			calcPrice.call(null);
		}).on("change", "#export_period", function (e) {
			var period = $(this).val();
			if(period == 'last')
			{
				$('#last_label').show();
				$('#next_label').hide();
			}else{
				$('#last_label').hide();
				$('#next_label').show();
			}
		}).on("focus", "#reservations_feed", function (e) {
			$(this).select();
		}).on("click", ".cpApplyCode", function (e) {
			if($('#discount_code').val() !=  '')
			{
				var $frm = $(this).closest("form");
				$.post("index.php?controller=pjAdminBookings&action=pjActionApplyCode", $frm.serialize()).done(function(data) {
					if(data.code == 200)
					{
						$('#discount_code').attr('data-type', data.arr.type);
						$('#discount_code').attr('data-discount', data.arr.discount);
						$('.cpBtnCode').hide();
						$('.cpRemoveCode').show();
						$('.discountCodeContainer').removeClass('has-error');
						$('.discountCodeContainer').find('.help-block').html('');
					}else{
						$('#discount_code').attr('data-type', '');
						$('#discount_code').attr('data-discount', '');
						$('.discountCodeContainer').addClass('has-error');
						$('.discountCodeContainer').find('.help-block').html(myLabel.invalid_discount_code);
					}
					calcPrice.call(null);
				});
			}
		}).on("click", ".cpRemoveCode", function (e) {
			$('#discount_code').val("");
			$('#discount_code').attr('data-type', '');
			$('#discount_code').attr('data-discount', '');
			$('.cpBtnCode').hide();
			$('.cpApplyCode').show();
			calcPrice.call(null);
		}).on("click", "#btnEmail", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var booking_id = $(this).attr('data-id');
			var document_id = 0;
			var $emailContentWrapper = $('#emailContentWrapper');
			
			$('#btnSendEmailConfirm').attr('data-booking_id', booking_id);
			
			$emailContentWrapper.html("");
			$.get("index.php?controller=pjAdminBookings&action=pjActionConfirmation", {
				"booking_id": booking_id
			}).done(function (data) {
				$emailContentWrapper.html(data);
				if(data.indexOf("pjResendAlert") == -1)
				{
					myTinyMceInit.call(null, 'textarea#mceEditor', 'mceEditor');
					validator = $emailContentWrapper.find("form").validate({});
					$('#btnSendEmailConfirm').show();
				}else{
					$('#btnSendEmailConfirm').hide();
				}	
				$('#reminderEmailModal').modal('show');
			});
			return false;
		}).on("click", "#btnSendEmailConfirm", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $this = $(this);
			var $emailContentWrapper = $('#emailContentWrapper');
			if (validator.form()) {
				$('#mceEditor').html( tinymce.get('mceEditor').getContent() );
				$(this).attr("disabled", true);
				var l = Ladda.create(this);
			 	l.start();
				$.post("index.php?controller=pjAdminBookings&action=pjActionConfirmation", $emailContentWrapper.find("form").serialize()).done(function (data) {
					if (data.status == "OK") {
						$('#reminderEmailModal').modal('hide');
					} else {
						$('#reminderEmailModal').modal('hide');
					}
					$this.attr("disabled", false);
					l.stop();
				});
			}
			return false;
		});
		
		function calcPrice()
		{
			var $space_id = $('#space_id'),
				$frm = $space_id.closest('form'),
				rental_price = parseFloat($("option:selected", $space_id).attr('data-price')),
				rental_days = parseInt($("option:selected", $space_id).attr('data-days'), 10),
				total_extra_price = 0,
				discount = 0,
				subtotal = 0,
				tax = 0,
				total = 0,
				deposit = 0;
			if($space_id.val() != '')
			{
				$frm.find('.cpExtraPrice').each(function(){
					var cnt = 0,
						extra_price = 0,
						days = rental_days,
						index = $(this).attr('data-index'),
						$extra_id = $(this).closest('tr').find('.cpExtraSelector'),
						$option = $("option:selected", $extra_id),
						per = $option.attr('data-per'),
						unit_price = parseFloat($option.attr('data-price'));
					if($(this).is(':checkbox'))
					{
						if($(this).is(':checked'))
						{
							cnt = 1;
							if(per == 'booking')
							{
								days = 1;
							}
						}
					}else{
						if($(this).val() != '')
						{
							cnt = parseInt($(this).val(), 10);
							if(cnt > 0)
							{
								if(per == 'booking')
								{
									days = 1;
								}
							}
						}
					}
					extra_price = unit_price * days * cnt;
					$extra_id.next().val(extra_price);
					total_extra_price += extra_price;
				});
				subtotal = (rental_price + total_extra_price);
				
				var type = $('#discount_code').attr('data-type');
				if(type != '')
				{
					discount = parseFloat($('#discount_code').attr('data-discount'));
					if(type == 'percent')
					{
						discount = (subtotal * discount) / 100;
					}
				}
				subtotal = subtotal - discount;
				tax = (subtotal * myLabel.tax_percent) / 100;
				total = subtotal + tax;
				deposit = (total * myLabel.deposit_percent) / 100;
				
				$('#rental_price').val(rental_price.toFixed(2));
				$('#extra_price').val(total_extra_price.toFixed(2));
				$('#discount').val(discount.toFixed(2));
				$('#sub_total').val(subtotal.toFixed(2));
				$('#tax').val(tax.toFixed(2));
				$('#total').val(total.toFixed(2));
				$('#deposit').val(deposit.toFixed(2));
			}else{
				resetCalc.call(null, [1]);
			}
		}
		
		function resetCalc(clear)
		{
			if(clear == null)
			{
				$("#tblExtras tbody").html("");
			}
			$('#rental_price').val("");
			$('#extra_price').val("");
			$('#discount_code').val("");
			$('#discount').val("");
			$('#sub_total').val("");
			$('#tax').val("");
			$('#total').val("");
			$('#deposit').val("");
			$('.cpBtnCode').hide();
			$('.cpApplyCode').show();
		}
		
		function myTinyMceInit(pSelector, pValue) {
			tinymce.init({
				relative_urls : false,
				remove_script_host : false,
				convert_urls : true,
			    selector: pSelector,
			    theme: "silver",
			    height: 500,
			    plugins: [
			        'link image imagetools table'
			      ],
			    contextmenu: "link image imagetools table",
			    image_advtab: true,
			    setup: function (editor) {
			    	editor.on('change', function (e) {
			    		editor.editorManager.triggerSave();
			    	});
			    }
			});
			if (tinymce.editors.length) {							
				tinymce.execCommand('mceAddEditor', true, pValue);
			}
		}
		$("#reminderEmailModal").on("hidden.bs.modal", function () {
        	if (tinymce.editors.length > 0) 
			{
		        tinymce.execCommand('mceRemoveEditor',true, "mceEditor");
		    }
        });
		
		$(document).on('focusin', function(e) {
			if ($(e.target).closest(".mce-window").length) {
				e.stopImmediatePropagation();
			}
		});

	});
})(jQuery);