var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		"use strict";
		var $frmCreateProduct = $("#frmCreateProduct"),
			$frmUpdateProduct = $("#frmUpdateProduct"),
			$dialogDeleteImage = $("#dialogDeleteImage"),
			$dialogDeleteModelImage = $("#dialogDeleteModelImage"),
			$dialogDelete = $("#dialogDeleteModel"),
			dialog = ($.fn.dialog !== undefined),
			multiselect = ($.fn.multiselect !== undefined),
			validate = ($.fn.validate !== undefined),
			datagrid = ($.fn.datagrid !== undefined),
			remove_arr = new Array();
		
		if (multiselect) {
			$("#category_id").multiselect({
				noneSelectedText: myLabel.select_categories
			});
		}
		
		if($(".pj-feature-grid").length > 0)
		{
			var head_height = $('.content-head-row').height();
			$('.content-head-row').height(head_height + 20);
			$('.title-head-row').height(head_height + 20);
			
			$('.title-row').each(function(index) {
			    var id = $(this).attr('lang');
			    var content_height = $('#content_row_' + id).height(),
			    	title_height =  $(this).height(),
			    	set_height = content_height;
			    if(set_height < title_height)
			    {
			    	set_height = title_height;
			    }
			    $(this).height(set_height);
			    $('#content_row_' + id).height(set_height);
			});
			$(".wrapper1").scroll(function(){
		        $(".wrapper2")
		            .scrollLeft($(".wrapper1").scrollLeft());
		    });
		    $(".wrapper2").scroll(function(){
		        $(".wrapper1")
		            .scrollLeft($(".wrapper2").scrollLeft());
		    });
		    
		    $(".wrapper2").height($("#compare_table").height() + 24);
		}
		
		function setModels()
		{
			var index_arr = new Array(),
				number_of_models = $('#pc_model_list').find(".pc-model-row").length;
				
			$('#pc_model_list').find(".pc-model-row").each(function (index, row) {
				index_arr.push($(row).attr('data-index'));
			});
			$('#index_arr').val(index_arr.join("|"));
		}
		
		if ($frmCreateProduct.length > 0 && validate) {
			$frmCreateProduct.validate({
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ""
			});
			$frmCreateProduct.submit(function(e){
				if($frmCreateProduct.valid())
				{
					setModels();
				}
			});
		}
		if ($frmUpdateProduct.length > 0 && validate) {
			$frmUpdateProduct.validate({
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ""
			});
			$frmUpdateProduct.submit(function(e){
				if($frmUpdateProduct.valid())
				{
					setModels();
				}
			});
		}
		if ($dialogDeleteImage.length > 0 && dialog) 
		{
			$dialogDeleteImage.dialog({
				modal: true,
				autoOpen: false,
				resizable: false,
				draggable: false,
				width: 400,
				buttons: (function () {
					var buttons = {};
					buttons[pcApp.locale.button.yes] = function () {
						$.ajax({
							type: "GET",
							dataType: "json",
							url: $dialogDeleteImage.data('href'),
							success: function (res) {
								if(res.code == 200){
									$('#image_container').remove();
									$dialogDeleteImage.dialog('close');
								}
							}
						});
					};
					buttons[pcApp.locale.button.no] = function () {
						$dialogDeleteImage.dialog("close");
					};
					
					return buttons;
				})()
			});
		}
		function formatImage(val, obj) {
			var src = val ? val : 'app/web/img/backend/150x100.png';
			return ['<a href="index.php?controller=pjAdminProducts&action=pjActionUpdate&id=', obj.id ,'"><img src="', src, '" style="width: 80px" /></a>'].join("");
		}
		if ($("#grid").length > 0 && datagrid) {
			
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminProducts&action=pjActionUpdate&id={:id}"},
				          {type: "preview", url: "preview.php?product_id={:id}", target: "_blank"},
				          {type: "features", url: "index.php?controller=pjAdminProducts&action=pjActionFeature&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminProducts&action=pjActionDeleteProduct&id={:id}"}
				          ],
				columns: [{text: myLabel.image, type: "text", sortable: false, editable: false, width: 80, renderer: formatImage},
				          {text: myLabel.name, type: "text", sortable: true, editable: true, width: 190, editableWidth: 170},
				          {text: myLabel.models, type: "text", sortable: true, editable: false, width: 70, align: "center",},
				          {text: myLabel.categories, type: "text", sortable: true, editable: false, width: 90, align: "center",},
				          {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",
				dataType: "json",
				fields: ['thumb_path', 'name', 'models', 'categories', '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("click", '.pj-add-model', function(e){
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var clone_text = $('#pc_model_clone').html(),
				index = Math.ceil(Math.random() * 999999),
				number_of_models = $('#pc_model_list').find(".pc-model-row").length,
				order = parseInt(number_of_models, 10) + 1;
			clone_text = clone_text.replace(/\{INDEX\}/g, 'pc_' + index);
			clone_text = clone_text.replace(/\{ORDER\}/g, order);
			$('#pc_model_list').append(clone_text);
		}).on("click", '.pj-remove-model', function(e){
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $this = $(this);
			if($this.hasClass('pj-confirm'))
			{
				if ($dialogDelete.length > 0 && dialog) 
				{
					$dialogDelete.dialog({
						modal: true,
						autoOpen: false,
						resizable: false,
						draggable: false,
						width: 400,
						buttons: (function () {
							var buttons = {};
							buttons[pcApp.locale.button.yes] = function () {
								removeModel($this);
								$dialogDelete.dialog("close");
							};
							buttons[pcApp.locale.button.no] = function () {
								$dialogDelete.dialog("close");
							};
							
							return buttons;
						})()
					});
				}
				$dialogDelete.dialog("open");
			}else{
				removeModel($this);
			}
		}).on("click", ".pj-delete-image", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$dialogDeleteImage.data('href', $(this).data('href')).dialog("open");
		}).on("click", ".pj-delete-model-image", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$dialogDeleteModelImage.data('link', $(this)).data('href', $(this).data('href')).dialog("open");
		});
		
		function removeModel($link)
		{
			var $model = $link.parent().parent(),
				id = $model.attr('data-index');
			
			if(id.indexOf("pc") == -1)
			{
				remove_arr.push(id);
			}
			$('#remove_arr').val(remove_arr.join("|"));
			$model.remove();
			
			$('#pc_model_list').find(".pc-model-row").each(function (order, row) {
				var index = $(row).attr('data-index'),
					title = "#" + (order + 1);
				$('.pc-title-' + index).html(title);
			});
		}
		
		if ($dialogDeleteModelImage.length > 0 && dialog) 
		{
			$dialogDeleteModelImage.dialog({
				modal: true,
				autoOpen: false,
				resizable: false,
				draggable: false,
				width: 400,
				buttons: (function () {
					var buttons = {};
					buttons[pcApp.locale.button.yes] = function () {
						$.ajax({
							type: "GET",
							dataType: "json",
							url: $dialogDeleteModelImage.data('href'),
							success: function (res) {
								if(res.code == 200){
									var $link = $dialogDeleteModelImage.data('link');
									$link.parent().parent().remove();
									$dialogDeleteModelImage.dialog('close');
								}
							}
						});
					};
					buttons[pcApp.locale.button.no] = function () {
						$dialogDeleteModelImage.dialog("close");
					};
					
					return buttons;
				})()
			});
		}
	});
})(jQuery_1_8_2);