var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		var $frmCreateProduct = $("#frmCreateProduct"),
			$frmUpdateProduct = $("#frmUpdateProduct"),
			$dialogRemove = $('#dialogRemove'),
			dialog = ($.fn.dialog !== undefined),
			validate = ($.fn.validate !== undefined),
			datagrid = ($.fn.datagrid !== undefined);

		if ($frmCreateProduct.length > 0 && validate) {
			$frmCreateProduct.on('submit', function(e){
				for (i = 1; i <= 3; i++) {
					if($('#offer_type').is(":checked"))
					{
						$('input[name="price_suggest_'+i+'"]').addClass('required');
						$('select[name="price_suggest_'+i+'_action"]').addClass('required');
						$('select[name="price_range_'+i+'_action"]').removeClass('required err');
					}else{
						$('input[name="price_suggest_'+i+'"]').removeClass('required err');
						$('select[name="price_suggest_'+i+'_action"]').removeClass('required err');
						$('select[name="price_range_'+i+'_action"]').addClass('required');
					}
					if($('#offer_type').is(":checked") && $('select[name="price_suggest_'+i+'_action"]').val() == 'promo' )
					{
						$('input[name="price_suggest_'+i+'_promo"]').addClass('required');
					}else{
						$('input[name="price_suggest_'+i+'_promo"]').removeClass('required err');
					}
					if($('#offer_type').is(":checked") && $('select[name="price_suggest_'+i+'_action"]').val() == 'email' )
					{
						$('input[name="price_suggest_'+i+'_email"]').addClass('required');
					}else{
						$('input[name="price_suggest_'+i+'_email"]').removeClass('required err');
					}
					if($('#offer_type').is(":checked") && $('select[name="price_suggest_'+i+'_action"]').val() == 'thank' )
					{
						$('input[name="price_suggest_'+i+'_message"]').addClass('required');
					}else{
						$('input[name="price_suggest_'+i+'message"]').removeClass('required err');
					}
					
					if($('#suggest_type').is(":checked") && $('select[name="price_range_'+i+'_action"]').val() == 'promo' )
					{
						$('input[name="price_range_'+i+'_promo"]').addClass('required');
					}else{
						$('input[name="price_range_'+i+'_promo"]').removeClass('required err');
					}
					if($('#suggest_type').is(":checked") && $('select[name="price_range_'+i+'_action"]').val() == 'email' )
					{
						$('input[name="price_range_'+i+'_email"]').addClass('required');
					}else{
						$('input[name="price_range_'+i+'_email"]').removeClass('required err');
					}
					if($('#suggest_type').is(":checked") && $('select[name="price_range_'+i+'_action"]').val() == 'thank' )
					{
						$('input[name="price_range_'+i+'_message"]').addClass('required');
					}else{
						$('input[name="price_range_'+i+'_messsage"]').removeClass('required err');
					}
				}
		    });
			$frmCreateProduct.validate({
				errorPlacement: function (error, element) {
					if(element.parent().hasClass('pj-form-field-custom'))
					{
						error.insertAfter(element.parent().parent());
					}else{
						error.insertAfter(element.parent());
					}
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: "",
				invalidHandler: function (event, validator) {
					var localeId = $(validator.errorList[0].element, this).attr('lang');
					if(localeId != undefined)
					{
						$(".pj-multilang-wrap").each(function( index ) {
							if($(this).attr('data-index') == localeId)
							{
								$(this).css('display','block');
							}else{
								$(this).css('display','none');
							}
						});
						$(".pj-form-langbar-item").each(function( index ) {
							if($(this).attr('data-index') == localeId)
							{
								$(this).addClass('pj-form-langbar-item-active');
							}else{
								$(this).removeClass('pj-form-langbar-item-active');
							}
						});
					}
				}
			});
		}
		if ($frmUpdateProduct.length > 0 && validate) {
			$frmUpdateProduct.on('submit', function(e){
				for (i = 1; i <= 3; i++) {
					if($('#offer_type').is(":checked"))
					{
						$('input[name="price_suggest_'+i+'"]').addClass('required');
						$('select[name="price_suggest_'+i+'_action"]').addClass('required');
						$('select[name="price_range_'+i+'_action"]').removeClass('required err');
					}else{
						$('input[name="price_suggest_'+i+'"]').removeClass('required err');
						$('select[name="price_suggest_'+i+'_action"]').removeClass('required err');
						$('select[name="price_range_'+i+'_action"]').addClass('required');
					}
					if($('#offer_type').is(":checked") && $('select[name="price_suggest_'+i+'_action"]').val() == 'promo' )
					{
						$('input[name="price_suggest_'+i+'_promo"]').addClass('required');
					}else{
						$('input[name="price_suggest_'+i+'_promo"]').removeClass('required err');
					}
					if($('#offer_type').is(":checked") && $('select[name="price_suggest_'+i+'_action"]').val() == 'email' )
					{
						$('input[name="price_suggest_'+i+'_email"]').addClass('required');
					}else{
						$('input[name="price_suggest_'+i+'_email"]').removeClass('required err');
					}
					if($('#offer_type').is(":checked") && $('select[name="price_suggest_'+i+'_action"]').val() == 'thank' )
					{
						$('input[name="price_suggest_'+i+'_message"]').addClass('required');
					}else{
						$('input[name="price_suggest_'+i+'message"]').removeClass('required err');
					}
					
					if($('#suggest_type').is(":checked") && $('select[name="price_range_'+i+'_action"]').val() == 'promo' )
					{
						$('input[name="price_range_'+i+'_promo"]').addClass('required');
					}else{
						$('input[name="price_range_'+i+'_promo"]').removeClass('required err');
					}
					if($('#suggest_type').is(":checked") && $('select[name="price_range_'+i+'_action"]').val() == 'email' )
					{
						$('input[name="price_range_'+i+'_email"]').addClass('required');
					}else{
						$('input[name="price_range_'+i+'_email"]').removeClass('required err');
					}
					if($('#suggest_type').is(":checked") && $('select[name="price_range_'+i+'_action"]').val() == 'thank' )
					{
						$('input[name="price_range_'+i+'_message"]').addClass('required');
					}else{
						$('input[name="price_range_'+i+'_messsage"]').removeClass('required err');
					}
				}
		    });
			$frmUpdateProduct.validate({
				errorPlacement: function (error, element) {
					if(element.parent().hasClass('pj-form-field-custom'))
					{
						error.insertAfter(element.parent().parent());
					}else{
						error.insertAfter(element.parent());
					}
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: "",
				invalidHandler: function (event, validator) {
					var localeId = $(validator.errorList[0].element, this).attr('lang');
					if(localeId != undefined)
					{
						$(".pj-multilang-wrap").each(function( index ) {
							if($(this).attr('data-index') == localeId)
							{
								$(this).css('display','block');
							}else{
								$(this).css('display','none');
							}
						});
						$(".pj-form-langbar-item").each(function( index ) {
							if($(this).attr('data-index') == localeId)
							{
								$(this).addClass('pj-form-langbar-item-active');
							}else{
								$(this).removeClass('pj-form-langbar-item-active');
							}
						});
					}
				}
			});
			
			if($dialogRemove.length > 0 && dialog)
			{
				$dialogRemove.dialog({
					autoOpen: false,
					resizable: false,
					draggable: false,
					modal: true,
					height: 160,
					width: 350,
					buttons: (function () {
						var buttons = {};
						buttons[spApp.locale.button.remove] = function () {
							
							var product_id = $dialogRemove.data('id');
							$.ajax({
								type: "GET",
								dataType: "json",
								url: "index.php?controller=pjAdminProducts&action=pjActionRemoverOffers&id=" + product_id,
								success: function (res) {
									if(res.code == 200)
									{
										$dialogRemove.dialog("close");
										
										window.location.href = 'index.php?controller=pjAdminProducts&action=pjActionUpdate&id=' + product_id;
									}
								}
							});
						};
						buttons[spApp.locale.button.cancel] = function () {
							$dialogRemove.dialog("close");
						};
						
						return buttons;
					})()
				});
			}
		}
		
		function formatOffers(str, obj){
			if(str == '0')
			{
				return 0;
			}else{
				return '<a href="index.php?controller=pjAdminOffers&action=pjActionIndex&product_id='+obj.id+'">'+str+'</a>';
			}
		}
		if ($("#grid").length > 0 && datagrid) {
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminProducts&action=pjActionUpdate&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminProducts&action=pjActionDeleteProduct&id={:id}"},
				          {type: "view", url: "preview.php?product_id={:id}&theme=" + myLabel.theme, target: '_blank'},
				          {type: "install", url: "index.php?controller=pjAdminOptions&action=pjActionInstall&id={:id}"}
				          ],
				columns: [{text: myLabel.name, type: "text", sortable: true, editable: true, width: 190},
				          {text: myLabel.price, type: "text", sortable: true, editable: false, width: 80},
				          {text: myLabel.offers, type: "text", sortable: true, editable: false, width: 80, align: "center", renderer: formatOffers},
				          {text: myLabel.average, type: "text", sortable: true, editable: false, width: 80},
				          {text: myLabel.status, type: "select", sortable: true, editable: true, width: 100, options: [
				                                                                                     {label: myLabel.active, value: "T"}, 
				                                                                                     {label: myLabel.inactive, value: "F"}
				                                                                                     ], applyClass: "pj-status"}],
				dataUrl: "index.php?controller=pjAdminProducts&action=pjActionGetProduct",
				dataProduct: "json",
				fields: ['name', 'price', 'cnt_offers', 'avg', 'status'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminProducts&action=pjActionDeleteProductBulk", render: true, confirmation: myLabel.delete_confirmation}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminProducts&action=pjActionSaveProduct&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
		}
		
		$(document).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=pjAdminProducts&action=pjActionGetProduct", "name", "ASC", 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=pjAdminProducts&action=pjActionGetProduct", "name", "ASC", 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=pjAdminProducts&action=pjActionGetProduct", "name", "ASC", content.page, content.rowCount);
			return false;
		}).on("change", "input:radio", function (e) {
			if($(this).val() == 'offer')
			{
				$('#pjSpOfferBox').show();
				$('#pjSpSuggestBox').hide();
			}else{
				$('#pjSpOfferBox').hide();
				$('#pjSpSuggestBox').show();
			}
		}).on("change", ".pjSpSuggestAction", function (e) {
			var value = $(this).val(),
				index = $(this).attr('data-index');
			$('.price_suggest_' + index).hide();
			$('#price_suggest_'+index+'_'+value+'_box').show();
		}).on("change", ".pjSpRangeAction", function (e) {
			var value = $(this).val(),
				index = $(this).attr('data-index');
			$('.price_range_' + index).hide();
			$('#price_range_'+index+'_'+value+'_box').show();
		}).on("keyup", "#price", function (e) {
			updateTitles();
		}).on("click", ".pjSpRemoveDuplicates", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$dialogRemove.data('id', $(this).attr('data-id')).dialog('open');
		});
		
		function updateTitles()
		{
			var $label_one = $('#pjSpLabelOne').attr('data-title'),
				$label_two = $('#pjSpLabelTwo').attr('data-title'),
				$label_three = $('#pjSpLabelThree').attr('data-title'),
				$price = $('#price');

			var currency = $price.attr('data-currency'),
				price = $price.val();
			if(price != '')
			{
				if(!isNaN(price))
				{
					var price = parseFloat(price),
						range_1 = 0,
						range_2 = 0,
						range_3 = 0,
						range_4 = 0,
						range_5 = 0,
						range_6 = 0;
					range_1 = ((price * 0) / 100).toFixed(2);
					range_2 = ((price * 33.33) / 100).toFixed(2);
					range_3 = (parseFloat(range_2) + 0.01).toFixed(2);
					range_4 = ((price * 66.66) / 100).toFixed(2);
					range_5 = (parseFloat(range_4) + 0.01).toFixed(2);
					range_6 = ((price * 100) / 100).toFixed(2);
					
					range_1 = formatCurrency(range_1, currency);
					range_2 = formatCurrency(range_2, currency);
					range_3 = formatCurrency(range_3, currency);
					range_4 = formatCurrency(range_4, currency);
					range_5 = formatCurrency(range_5, currency);
					range_6 = formatCurrency(range_6, currency);
					
					$label_one = $label_one.replace("{R1}", range_1);
					$label_one = $label_one.replace("{R2}", range_2);
					
					$label_two = $label_two.replace("{R3}", range_3);
					$label_two = $label_two.replace("{R4}", range_4);
					
					$label_three = $label_three.replace("{R5}", range_5);
					$label_three = $label_three.replace("{R6}", range_6);
					
					$('#pjSpLabelOne').html($label_one);
					$('#pjSpLabelTwo').html($label_two);
					$('#pjSpLabelThree').html($label_three);
				}
			}
		}
		
		function formatCurrency(price, currency)
		{
			var format = '';
			switch (currency)
			{
				case 'USD':
					format = "$" + price;
					break;
				case 'GBP':
					format = "&pound;" + price;
					break;
				case 'EUR':
					format = "&euro;" + price;
					break;
				case 'JPY':
					format = "&yen;" + price;
					break;
				case 'AUD':
				case 'CAD':
				case 'NZD':
				case 'CHF':
				case 'HKD':
				case 'SGD':
				case 'SEK':
				case 'DKK':
				case 'PLN':
					format = price + currency;
					break;
				case 'NOK':
				case 'HUF':
				case 'CZK':
				case 'ILS':
				case 'MXN':
					format = currency + price;
					break;
				default:
					format = price + currency;
					break;
			}
			return format;
		}
	});
})(jQuery_1_8_2);