var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		"use strict";
		var validator,
			$frmCreateReservation = $('#frmCreateReservation'),
			$frmUpdateReservation = $('#frmUpdateReservation'),
			dialog = ($.fn.dialog !== undefined),
			datepicker = ($.fn.datepicker !== undefined),
			datagrid = ($.fn.datagrid !== undefined),
			validate = ($.fn.validate !== 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: 0
		});
		if (chosen) {
			$("#c_country").chosen();
		}
		if ($frmCreateReservation.length > 0 || $frmUpdateReservation.length > 0) 
		{
			$frmCreateReservation.validate({
				rules: {
					"validate_date": {
						remote: {
							url: "index.php?controller=pjAdminReservations&action=pjActionCheckDaysoff",
							data:{
								date: function(){
									return $frmCreateReservation.find('input[name="date"]').val();
								}
							}
						}
					},
					"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);
				    	}
				    };
				}
			});
			$frmUpdateReservation.validate({
				rules: {
					"validate_date": {
						remote: {
							url: "index.php?controller=pjAdminReservations&action=pjActionCheckDaysoff",
							data:{
								date: function(){
									return $frmUpdateReservation.find('input[name="date"]').val();
								}
							}
						}
					}
				},
				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);
				    	}
				    };
				}
			});
			
			$('#fdOrderList').find(".pj-field-count").spinner({
				min: 1,
				stop: function(e, ui){
					if($('#fdOrderList').find("tbody.main-body > tr").length > 0)
					{
						calPrice();
						calFinalPrice();
					}
				}
			});
			if($('#fdOrderList').find("tbody.main-body > tr").length > 0)
			{
				calPrice();
				$('#fdOrderList').show();
			}
		}
		function formatBooth (str, obj) {
			return str + ' x ' + obj.cnt;
		}
		if ($("#grid").length > 0 && datagrid) {
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminReservations&action=pjActionUpdate&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminReservations&action=pjActionDeleteReservation&id={:id}"}
						 ],
				columns: [
				          {text: myLabel.booth, type: "text", sortable: false, width:150, renderer: formatBooth},
				          {text: myLabel.date, type: "text", sortable: true, width:100},
				          {text: myLabel.name, type: "text", sortable: true, editable: false, width:150},
				          {text: myLabel.total, type: "text", sortable: true, editable: false, width:80},
				          {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=pjAdminReservations&action=pjActionGetReservation" + pjGrid.queryString,
				dataType: "json",
				fields: ['type', 'date', 'c_name', 'total', 'status'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminReservations&action=pjActionDeleteReservationBulk", render: true, confirmation: myLabel.delete_confirmation},
					   {text: myLabel.exported, url: "index.php?controller=pjAdminReservations&action=pjActionExportReservation", ajax: false}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminReservations&action=pjActionSaveReservation&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
		}
				
		$(document).on("focusin", ".datepicker", function (e) {
			var $this = $(this);
			
			$(this).datepicker( {
				firstDay: $this.attr("rel"),
				dateFormat: $this.attr("rev"),
				onSelect: function(dateText) {
				    var $frm = null;
				    if ($frmCreateReservation.length > 0) 
					{
				    	$frm = $frmCreateReservation;
					}
				    if ($frmUpdateReservation.length > 0) 
					{
				    	$frm = $frmUpdateReservation;
					}
				    $frm.find('input[name="validate_date"]').val(Math.ceil(Math.random() * 999999)).valid();
				    $.post("index.php?controller=pjAdminReservations&action=pjActionGetBooths", $frm.serialize()).done(function (data) {
						$('#boxBoothType').html(data);
						$('#textCapacity').html('');
						$('#textPrice').html('');
						$('#cnt')
						    .find('option')
						    .remove()
						    .end()
						    .append('<option value="">'+myLabel.choose+'</option>')
						    .val('');
						calFinalPrice();
					});
				}
			});
		}).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: "",
				resource_id: "",
				user_id: "",
				dt_from: "",
				dt_to: ""
			});
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminReservations&action=pjActionGetReservation", "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=pjAdminReservations&action=pjActionGetReservation", "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(),
				type: $this.find("select[name='type']").val()
			});
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminReservations&action=pjActionGetReservation", "created", "DESC", content.page, content.rowCount);
			return false;
		}).on("click", "#btnAddProduct", function (e) {
			var index = Math.ceil(Math.random() * 999999),
				$clone = $("#boxProductClone").find("tbody").html();
			$clone = $clone.replace(/\{INDEX\}/g, 'new_' + index);
			$('#fdOrderList').find("tbody.main-body").append($clone);
			$('#fdOrderList').find(".pj-field-count").spinner({
				min: 1,
				stop: function(e, ui){
					if($('#fdOrderList').find("tbody.main-body > tr").length > 0)
					{
						calPrice();
						calFinalPrice();
					}
				}
			});
			$('#fdOrderList').show();
		}).on("click", ".pj-remove-product", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$(this).closest(".fdLine").remove();
			if($('#fdOrderList').find("tbody.main-body > tr").length == 0)
			{
				$('#fdOrderList').hide();
			}else{
				calPrice();
				calFinalPrice();
			}
			return false;
		}).on("change", ".fdProduct", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $this = $(this),
				index = $this.attr("data-index");
			$('.fdExtraBusiness_'+index).hide();
			$('#fdExtraTable_' + index).find("tbody").html("");
			if($this.val() != '')
			{
				$('.business-' + index).show();
			}else{
				$('.business-' + index).hide();
			}
			$('.fdExtraButton_' + index).show();
			return false;
		}).on("click", ".pj-add-extra", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $this = $(this);
			var index = $this.attr('data-index');
			var	category_id = $('#fdProduct_' + index).val();
			
			if(category_id != '')
			{
				$.get("index.php?controller=pjAdminReservations&action=pjActionGetExtras", {
					category_id: category_id,
					index: $this.attr("data-index")
				}).done(function (data) {
					$(data).appendTo($this.siblings(".pj-extra-table").find("tbody"));
					$this.siblings(".pj-extra-table").find(".pj-field-count").spinner({
						min: 1,
						stop: function(e, ui){
							if($('#fdOrderList').find("tbody.main-body > tr").length > 0)
							{
								calPrice();
								calFinalPrice();
							}
						}
					});
				});
			}
			return false;
		}).on("click", ".pj-remove-extra", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$(this).parent().parent().remove();
			calPrice();
			calFinalPrice();
			return false;
		}).on("change", ".fdSize", function (e) {
			calPrice();
			calFinalPrice();
		}).on("change", ".fdExtra", function (e) {
			calPrice();		
			calFinalPrice();
		}).on("change", ".pj-field-count", function (e) {
			calPrice();
			calFinalPrice();
		}).on("change", "#payment_method", function (e) {
			switch ($("option:selected", this).val()) {
				case 'creditcard':
					$(".boxCC").show();
					break;
				default:
					$(".boxCC").hide();
			}
		}).on("change", "#booth_id", function (e) {
			
			$('#cnt')
			    .find('option')
			    .remove()
			    .end()
			    .append('<option value="">'+myLabel.choose+'</option>')
			    .val('');
			if($(this).val() != "")
			{
				var cnt = parseInt($('option:selected', this).attr('data-cnt'), 10);
				var capacity = parseInt($('option:selected', this).attr('data-capacity'), 10);
				var price = $('option:selected', this).attr('data-price_format');
				var option_str = '';
				
				for(var i = 1; i <= cnt; i++) 
				{
					option_str += '<option value="'+i+'">'+i+'</option>';
				}
				$('#cnt').append(option_str);
				$('#textCapacity').html(capacity);
				$('#textPrice').html(price);
			}else{
				$('#textCapacity').html('');
				$('#textPrice').html('');
			}
			calFinalPrice();
		}).on("change", "#cnt", function (e) {
			calFinalPrice();
		});
		
		function calPrice()
		{			
			$('#fdOrderList').find("tbody.main-body > tr.fdLine").each(function() {
				var total = 0,
					total_format = '',
					index = $(this).attr('data-index'),
					price = 0;
				
				$('.fdExtra_' + index).each(function() {
					var extra_index = $(this).attr('data-index'),
						extra = $(this).val(),
						extra_qty = parseInt($('#fdExtraQty_' + extra_index).val(), 10);
					
					if(extra != '' && extra_qty > 0)
					{
						var extra_price = parseFloat($('option:selected', this).attr('data-price'), 10);
						if(extra_price > 0)
						{
							total += extra_price * extra_qty;
						}
					}
				});
				total_format = formatCurrency(total, myLabel.currency, '');
				$('#fdTotalPrice_' + index).html(total_format);
			});
			
		}
		function calFinalPrice()
		{
			var sub_total = 0,
				tax = 0,
				total = 0,
				deposit = 0;
			if($('#cnt').val() != "")
			{
				$('#fdOrderList').find("tbody.main-body > tr.fdLine").each(function() {
					var index = $(this).attr('data-index');
					
					$('.fdExtra_' + index).each(function() {
						var extra_index = $(this).attr('data-index'),
							extra = $(this).val(),
							extra_qty = parseInt($('#fdExtraQty_' + extra_index).val(), 10);
						
						if(extra != '' && extra_qty > 0)
						{
							var extra_price = parseFloat($('option:selected', this).attr('data-price'));
							if(extra_price > 0)
							{
								sub_total += extra_price * extra_qty;
							}
						}
					});
				});
				var cnt = parseInt($('#cnt').val(), 10);
				var price = parseFloat($('option:selected', document.getElementById('booth_id')).attr('data-price'));
				sub_total += price * cnt;
			}
			if(sub_total > 0)
			{
				var tax_percentage = parseFloat($('#tax').attr('data-tax'));
				var deposit_percentage = parseFloat($('#deposit').attr('data-deposit'));
				tax = (sub_total * tax_percentage) / 100;
				total = sub_total + tax;
				deposit = (total * deposit_percentage) / 100;
				$('#subtotal').val(sub_total.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('');
			}
		}
		function formatCurrency(price, currency, separator)
		{
			var format = '---';
			switch (currency)
			{
				case 'USD':
					format = "$" + separator + price.toFixed(2);
					break;
				case 'GBP':
					format = "&pound;" + separator  + price.toFixed(2);
					break;
				case 'EUR':
					format = "&euro;" + separator  + price.toFixed(2);
					break;
				case 'JPY':
					format = "&yen;" + separator  + price.toFixed(2);
					break;
				case 'AUD':
				case 'CAD':
				case 'NZD':
				case 'CHF':
				case 'HKD':
				case 'SGD':
				case 'SEK':
				case 'DKK':
				case 'PLN':
					format = price.toFixed(2) + separator  + currency;
					break;
				case 'NOK':
				case 'HUF':
				case 'CZK':
				case 'ILS':
				case 'MXN':
					format = currency + separator  + price.toFixed(2);
					break;
				default:
					format = price.toFixed(2) + separator  + currency;
					break;
			}
			return format;
		}
	});
})(jQuery_1_8_2);