var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		"use strict";
		var validator,
			$frmCreateOrder = $('#frmCreateOrder'),
			$frmUpdateOrder = $('#frmUpdateOrder'),
			$dialogConfirmation = $("#dialogConfirmation"),
			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);
		}
		if($frmCreateOrder.length > 0 || $frmUpdateOrder.length > 0)
		{
			$frmCreateOrder.find(".field-int").spinner({
				min: 1
			});
			$frmUpdateOrder.find(".field-int").spinner({
				min: 1,
				stop: function(e, ui){
					var $tr = $(this).closest('tr')
					var index = $tr.attr('data-index');
					var type = $tr.attr('data-type');
					if(type == 'product')
					{
						calProductRowPrice(index);
					}else{
						calPackageRowPrice(index);
					}
				}
			});
		}
		if (chosen) {
			$("#c_country").chosen();
			if($frmUpdateOrder.length > 0)
			{
				$('#pjCsProductList').find('.pjCsProductSelector').chosen();
				$('#pjCsPackageList').find('.pjCsPackageSelector').chosen();
			}
		}
		function checkProduct()
		{
			var valid = true;
			if($('#pjCsProductList').find('.pjCsProductSelector').length > 0)
			{
				$('#pjCsProductList').find('.pjCsProductSelector').each(function(){
					if($(this).val() == '')
					{
						valid = false;
					}
				});
			}
			if(valid == false)
			{
				$('.pjCsProductError').show();
				$tabs.tabs(tOpt).tabs("option", "active", 0);
			}else{
				$('.pjCsProductError').hide();
			}
			return valid;
		}
		function checkPackage()
		{
			var valid = true;
			if($('#pjCsPackageList').find('.pjCsPackageSelector').length > 0)
			{
				$('#pjCsPackageList').find('.pjCsPackageSelector').each(function(){
					if($(this).val() == '')
					{
						valid = false;
					}
				});
			}
			if(valid == false)
			{
				$('.pjCsPackageError').show();
				$tabs.tabs(tOpt).tabs("option", "active", 0);
			}else{
				$('.pjCsPackageError').hide();
			}
			return valid;
		}
		if ($frmCreateOrder.length > 0 || $frmUpdateOrder.length > 0) 
		{
			$frmCreateOrder.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);
				    	}
				    };
				},
				submitHandler: function(form){
					if(checkProduct() == true && checkPackage() == true)
					{
						form.submit();
					}
					return false;
				}
			});
			$frmUpdateOrder.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);
				    	}
				    };
				},
				submitHandler: function(form){
					if(checkProduct() == true && checkPackage() == true)
					{
						form.submit();
					}
					return false;
				}
			});
			
			$('#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=pjAdminOrders&action=pjActionUpdate&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminOrders&action=pjActionDeleteOrder&id={:id}"}
						 ],
				columns: [
				          {text: myLabel.delivery_dt, type: "text", sortable: false, width:200},
				          {text: myLabel.name, type: "text", sortable: true, editable: false, width:200},
				          {text: myLabel.total, type: "text", sortable: true, editable: false, width:90},
				          {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=pjAdminOrders&action=pjActionGetOrder" + pjGrid.queryString,
				dataType: "json",
				fields: ['delivery_dt', 'c_name', 'total', 'status'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminOrders&action=pjActionDeleteOrderBulk", render: true, confirmation: myLabel.delete_confirmation},
					   {text: myLabel.exported, url: "index.php?controller=pjAdminOrders&action=pjActionExportOrder", ajax: false}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminOrders&action=pjActionSaveOrder&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 ($frmCreateOrder.length > 0) 
					{
				    	$frm = $frmCreateOrder;
					}
				    if ($frmUpdateOrder.length > 0) 
					{
				    	$frm = $frmUpdateOrder;
					}
				    $frm.find('input[name="validate_date"]').val(Math.ceil(Math.random() * 999999)).valid();
				    $.post("index.php?controller=pjAdminOrders&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=pjAdminOrders&action=pjActionGetOrder", "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=pjAdminOrders&action=pjActionGetOrder", "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=pjAdminOrders&action=pjActionGetOrder", "created", "DESC", content.page, content.rowCount);
			return false;
		}).on("focusin", ".datetimepick", function (e) {
			var $this = $(this);
			
			$(this).datetimepicker({
				firstDay: $this.attr("rel"),
				dateFormat: $this.attr("rev"),
				timeFormat: $this.attr("lang"),
				stepMinute: 5,
				minDate: 0,
				
			});
			
		}).on("click", "#btnAddProduct", function (e) {
			var index = Math.ceil(Math.random() * 999999),
				$clone = $("#boxProductClone").find("tbody").html();
			
			$clone = $clone.replace(/\{INDEX\}/g, 'new_' + index);
			$('#pjCsProductList').find("tbody.main-body").append($clone);
			$('#pjCsProductList').find(".field-int").spinner({
				min: 1,
				stop: function(e, ui){
					var $tr = $(this).closest('tr')
					var index = $tr.attr('data-index');
					var type = $tr.attr('data-type');
					calProductRowPrice(index);
				}
			});
			$('#pjCsProductList').find('.pjCsProductSelector').chosen();
		}).on("click", ".pj-remove-product", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$(this).closest("tr").remove();
			calFinalPrice();
			return false;
		}).on("change", ".pjCsProductSelector", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var value = $(this).val(),
				index = $(this).attr('data-index'),
				option = $('option:selected', this).attr('data-size');
			if(value != '')
			{
				if(option == 'T')
				{
					$('.pj-loader').show();
					$.ajax({
						type: "GET",
						dataType: "html",
						url: "index.php?controller=pjAdminOrders&action=pjActionGetSizes&product_id=" + value + "&index=" + index,
						success: function (data) {
							$('#pjCsSizePrice_' + index).html(data);
							$('.pj-loader').hide();
							calProductRowPrice(index);
						}
					});
				}else{
					var price_format = $('option:selected', this).attr('data-price_format');
					$('#pjCsSizePrice_' + index).html(price_format);
					calProductRowPrice(index);
				}
			}
			checkProduct();
			return false;
		}).on("click", "#btnAddPackage", function (e) {
			var index = Math.ceil(Math.random() * 999999),
				$clone = $("#boxPackageClone").find("tbody").html();
			
			$clone = $clone.replace(/\{INDEX\}/g, 'new_' + index);
			$('#pjCsPackageList').find("tbody.main-body").append($clone);
			$('#pjCsPackageList').find(".field-int").spinner({
				min: 1,
				stop: function(e, ui){
					var $tr = $(this).closest('tr')
					var index = $tr.attr('data-index');
					var type = $tr.attr('data-type');
					calPackageRowPrice(index);
				}
			});
			$('#pjCsPackageList').find('.pjCsPackageSelector').chosen();
		}).on("change", ".pjCsPackageSelector", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var value = $(this).val(),
				index = $(this).attr('data-index');
			if(value != '')
			{
				var price_format = $('option:selected', this).attr('data-price_format');
				$('#pjCsSizePrice_' + index).html(price_format);
			}
			checkPackage();
			calPackageRowPrice(index);
			return false;
		}).on("change", ".pjCsSizeSelector", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var index = $(this).attr('data-index');
			calProductRowPrice(index);
			return false;
		}).on("change", "#payment_method", function (e) {
			switch ($("option:selected", this).val()) {
				case 'creditcard':
					$(".boxCC").show();
					break;
				default:
					$(".boxCC").hide();
			}
		}).on("click", ".pjMrbSendConfirm", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$dialogConfirmation.data('id', $(this).attr('data-id')).dialog('open');
		});
		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=pjAdminOrders&action=pjActionConfirmation", {
						"order_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[csApp.locale.button.send] = function () {
						if (validator.form()) {
							$.post("index.php?controller=pjAdminOrders&action=pjActionConfirmation", $dialogConfirmation.find("form").serialize()).done(function (data) {
								$dialogConfirmation.dialog("close");
							})
						}
					};
					buttons[csApp.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 calProductRowPrice(index)
		{
			var $productSelector = $('#product_id_' + index);
			var qty = parseInt($('#qty_' + index).val(), 10);
			var value = $productSelector.val(),
				option = $('option:selected', '#product_id_' + index).attr('data-size');
			
			if(value != '')
			{
				var price = 0;
				if(option == 'T')
				{
					price = $('option:selected', '#size_id_' + index).attr('data-price');
				}else{
					price = $('option:selected', '#product_id_' + index).attr('data-price');
				}
			
				var product_price = qty * parseFloat(price);
				$('#product_unit_price_' + index).val(price);
				$('#product_price_' + index).val(product_price);
				
				var product_price_format = formatCurrency(product_price, myLabel.currency, '');
				
				$('#pjCsProductPrice_' + index).html(product_price_format);
			}else{
				$('#product_unit_price_' + index).val('');
				$('#product_price_' + index).val('');
				$('#pjCsProductPrice_' + index).html('');
			}
			calFinalPrice();
		}
		function calPackageRowPrice(index)
		{
			var $packageSelector = $('#package_id_' + index);
			var qty = parseInt($('#qty_' + index).val(), 10);
			var value = $packageSelector.val();
			
			if(value != '')
			{
				var price = $('option:selected', '#package_id_' + index).attr('data-price');
			
				var package_price = qty * parseFloat(price);
				$('#package_unit_price_' + index).val(price);
				$('#package_price_' + index).val(package_price);
				var package_price_format = formatCurrency(package_price, myLabel.currency, '');
				$('#pjCsPackagePrice_' + index).html(package_price_format);
			}else{
				$('#package_unit_price_' + index).val('');
				$('#package_price_' + index).val('');
				$('#pjCsPackagePrice_' + index).html('');
			}
			calFinalPrice();
		}
		function calFinalPrice()
		{			
			var sub_total = 0,
				tax = 0,
				total = 0,
				deposit = 0;
			
			$('.pjCsHiddenPrice').each(function(){
				if($(this).val() != '')
				{
					var price = parseFloat($(this).val(), 10);
					sub_total += price;
				}
			});
			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);