var jQuery_1_8_2 = $.noConflict();
(function ($, undefined) {
	$(function () {
		var $frmCreateJob = $("#frmCreateJob"),
			$frmUpdateJob = $("#frmUpdateJob"),
			$frmExportJobs = $("#frmExportJobs"),
			$frmAdvancedSearch = $('.frm-filter-advanced');
			datepicker = ($.fn.datepicker !== undefined),
			validate = ($.fn.validate !== undefined),
			tipsy = ($.fn.tipsy !== undefined),
			chosen = ($.fn.chosen !== undefined),
			datagrid = ($.fn.datagrid !== 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 ($frmAdvancedSearch.length > 0) {
			if (chosen) {
				$("#category_id").chosen();
				$("#country_id").chosen();
				$("#employer_id").chosen();
			}
		}
		if ($frmExportJobs.length > 0 && validate) {
			$frmExportJobs.validate({
				rules: {
					"password": {
						required: function(){
							if($('#feed').is(':checked'))
							{
								return true;
							}else{
								return false;
							}
						}
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ".ignore"
			});
		}
		if ($frmCreateJob.length > 0 && validate) {
			$frmCreateJob.validate({
				rules: {
					"job_refid": {
						required: true,
						remote: "index.php?controller=pjAdminJobs&action=pjActionCheckRefId"
					}
				},
				messages: {
					"job_refid":{
						required: myLabel.field_required,
						remote: myLabel.same_refid
					},
					"status":{
						required: myLabel.field_required
					},
					"type_id":{
						required: myLabel.field_required
					},
					"category_id":{
						required: myLabel.field_required
					},
					"is_featured":{
						required: myLabel.field_required
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ''
			});
			if (chosen) {
				$("#category_id").chosen();
			}
		}
		if ($frmUpdateJob.length > 0 && validate) {
			
			$frmUpdateJob.validate({
				rules: {
					"job_refid": {
						required: true,
						remote: "index.php?controller=pjAdminJobs&action=pjActionCheckRefId&id=" + $frmUpdateJob.find("input[name='id']").val()
					},
				},
				messages: {
					"job_refid":{
						required: myLabel.field_required,
						remote: myLabel.same_refid
					},
					"status":{
						required: myLabel.field_required
					},
					"type_id":{
						required: myLabel.field_required
					},
					"category_id":{
						required: myLabel.field_required
					},
					"is_featured":{
						required: myLabel.field_required
					},
					"expired":{
						required: myLabel.field_required
					},
					"i18n[1][job_title]":{
						required: myLabel.field_required
					},
					"i18n[2][job_title]":{
						required: myLabel.field_required
					},
					"i18n[3][job_title]":{
						required: myLabel.field_required
					}
				},
				errorPlacement: function (error, element) {
					console.log(element.attr('name'));
					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);
				    	}
				    }
				    $(".pj-multilang-wrap").each(function( index ) {
						if($(this).attr('data-index') == myLabel.localeId)
						{
							$(this).css('display','block');
						}else{
							$(this).css('display','none');
						}
					});
					$(".pj-form-langbar-item").each(function( index ) {
						if($(this).attr('data-index') == myLabel.localeId)
						{
							$(this).addClass('pj-form-langbar-item-active');
						}else{
							$(this).removeClass('pj-form-langbar-item-active');
						}
					});
				}
			});
			
			if (chosen) {
				$("#category_id").chosen();
				$("#country_id").chosen();
				if($("#employer_id").length > 0)
				{
					$("#employer_id").chosen();
				}
			}
			
			tinymce.init({
				relative_urls : false,
				remove_script_host : false,
			    selector: "textarea.mceEditor",
			    theme: "modern",
			    browser_spellcheck : true,
			    contextmenu: false,
			    width: 550,
			    height: 350,
			    plugins: [
			         "advlist autolink link image lists charmap print preview hr anchor pagebreak",
			         "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
			         "save table contextmenu directionality emoticons template paste textcolor"
			   ],
			   toolbar: "insertfile undo redo | styleselect fontselect fontsizeselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | l      ink image | print preview media fullpage | forecolor backcolor emoticons"
			});
			
			$("#employer_id").on('change', function(e){
				var employer_id = $(this).val();
				if(employer_id == '')
				{
					$('.pjJLEditEmployer').css('display', 'none');
				}else{
					$('.pjJLEditEmployer').attr('href', 'index.php?controller=pjAdminEmployers&action=pjActionUpdate&id=' + employer_id).css('display', 'inline-block');
				}
			})
		}
		
		if ($("#grid").length > 0 && datagrid) {
			
			function formatDefault (str, obj) {
				if (obj.role_id == 3) {
					return '<a href="#" class="pj-status-icon pj-status-' + (str == 'F' ? '0' : '1') + '" style="cursor: ' +  (str == 'F' ? 'pointer' : 'default') + '"></a>';
				} else {
					return '<a href="#" class="pj-status-icon pj-status-1" style="cursor: default"></a>';
				}
			}
			function showApplications(str, obj){
				if(str == '0' || str == null)
				{
					return 0;
				}else{
					return '<a href="index.php?controller=pjAdminApplications&action=pjActionIndex&job_id='+obj.id+'">'+str+'</a>';
				}
			}
			var gridOpts = {
				buttons: [{type: "edit", url: "index.php?controller=pjAdminJobs&action=pjActionUpdate&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminJobs&action=pjActionDeleteJob&id={:id}"}
				          ],
				columns: [{text: myLabel.refid, type: "text", sortable: true, editable: false, width: 100},
				          {text: myLabel.type, type: "text", sortable: true, editable: false, width: 90},
				          {text: myLabel.category, type: "text", sortable: true, editable: false, width: 130},
				          {text: myLabel.exp_date, type: "text", sortable: true, editable: false, width: 80},
				          {text: myLabel.applications, type: "text", sortable: true, editable: false, width: 90, align: "center", renderer: showApplications},
				          {text: myLabel.is_published, type: "select", sortable: true, editable: true, width: 86, options: [
				                                                                                     {label: myLabel.yes, value: "T"}, 
				                                                                                     {label: myLabel.no, value: "F"},
				                                                                                     {label: myLabel.exp_date, value: "E"}
				                                                                                     ], applyClass: "pj-status"}],
				dataUrl: "index.php?controller=pjAdminJobs&action=pjActionGetJob" + pjGrid.queryString,
				dataType: "json",
				fields: ['job_refid', 'type_title', 'category', 'expired', 'cnt_applications', 'status'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminJobs&action=pjActionDeleteJobBulk", render: true, confirmation: myLabel.delete_confirmation},
					   {text: myLabel.revert_status, url: "index.php?controller=pjAdminJobs&action=pjActionStatusJob", render: true},
					   {text: myLabel.exported, url: "index.php?controller=pjAdminJobs&action=pjActionExportJob", ajax: false}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminJobs&action=pjActionSaveJob&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			};
			
			if (pjGrid.isEmployer === true) {
				function formatExtend(val, obj) {
					if(obj.status == 'E')
					{
						return ['<a class="pj-button" href="index.php?controller=pjAdminJobs&action=pjActionPayment&id=', val, '">', myLabel.extend_exp_date, '</a>'].join("");
					}else{
						return "&nbsp;";
					}
				}
				
				gridOpts.columns = [{text: myLabel.refid, type: "text", sortable: true, editable: false, width: 100},
							          {text: myLabel.type, type: "text", sortable: true, editable: false, width: 80},
							          {text: myLabel.category, type: "text", sortable: true, editable: false, width: 100},
							          {text: myLabel.exp_date, type: "text", sortable: true, editable: false, width: 80},
							          {text: myLabel.applications, type: "text", sortable: true, editable: false, width: 90, renderer: showApplications, align: "center"},
							          {text: "", type: "text", sortable: false, editable: false, renderer: formatExtend, width: 102}
							        ];
				gridOpts.fields = ['job_refid', 'type_title', 'category', 'expired', 'cnt_applications', 'id'];
				gridOpts.paginator.actions = [
				     					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminJobs&action=pjActionDeleteJobBulk", render: true, confirmation: myLabel.delete_confirmation}				    					   
				    					];
					
			}
			
			var $grid = $("#grid").datagrid(gridOpts);
		}
		
		
		$(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: "",
				refid: "",
				employer_id: "",
				keyword: "",
				type_id: "",
				category_id: "",
				country_id: "",
				address_state: "",
				address_city: ""
			});
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminJobs&action=pjActionGetJob", "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=pjAdminJobs&action=pjActionGetJob", "created", "DESC", content.page, content.rowCount);
			return false;
		}).on("click", ".pj-status-1", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			return false;
		}).on("click", ".pj-status-0", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$.post("index.php?controller=pjAdminJobs&action=pjActionSetActive", {
				id: $(this).closest("tr").data("object")['id']
			}).done(function (data) {
				$grid.datagrid("load", "index.php?controller=pjAdminJobs&action=pjActionGetJob");
			});
			return false;
		}).on("click", ".pj-button-detailed, .pj-button-detailed-arrow", function (e) {
			e.stopPropagation();
			$(".pj-form-filter-advanced").toggle();
		}).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, {
				q: $(".frm-filter").find("input[name='q']").val()
			});
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminJobs&action=pjActionGetJob", "created", "DESC", content.page, content.rowCount);
			return false;
		}).on("reset", ".frm-filter-advanced", function (e) {
			$(".pj-button-detailed").trigger("click");
			if (chosen) {
				$("#employer_id").val('').trigger("liszt:updated");
				$("#category_id").val('').trigger("liszt:updated");
				$("#country_id").val('').trigger("liszt:updated");
			}
		}).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(),
				refid: "",
				employer_id: "",
				keyword: "",
				type_id: "",
				category_id: "",
				country_id: "",
				address_state: "",
				address_city: ""
			});
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminJobs&action=pjActionGetJob", "id", "ASC", content.page, content.rowCount);
			return false;
		}).on("focusin", ".datepick", function (e) {
			var $this = $(this);
			$this.datepicker({
				firstDay: $this.attr("rel"),
				dateFormat: $this.attr("rev"),
				onClose: function (selectedDate) {
					var name = $this.attr("name");
					if (name == "date_from[]") {
						$this.closest("tr").find(".datepick[name='date_to[]']").datepicker("option", "minDate", selectedDate);
					} else if (name == "date_to[]") {
						$this.closest("tr").find(".datepick[name='date_from[]']").datepicker("option", "maxDate", selectedDate);
					}
				}
			});
		}).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", ".listing-tip", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			return false;
		}).on("click", "#employer_show", function (e) {
			if($("#employer_id").length > 0)
			{
				if($(this).is(":checked"))
				{
					$("#employer_id").rules("add", "required");
				}else{
					$("#employer_id").rules("remove", "required");
				}
			}
		}).on("click", "#file", function (e) {
			$('#tsSubmitButton').val(myLabel.btn_export);
			$('.tsFeedContainer').hide();
			$('.tsPassowrdContainer').hide();
		}).on("click", "#feed", function (e) {
			$('.tsPassowrdContainer').show();
			$('#tsSubmitButton').val(myLabel.btn_get_url);
		}).on("focus", "#members_feed", function (e) {
			$(this).select();
		}).on("change", "#status", function (e) {
			if($('option:selected', this).val() == 'E')
			{
				$('.expiredWrapper').show();
				$('#expire').addClass('required');
			}else{
				$('.expiredWrapper').hide();
				$('#expire').removeClass('required');
			}
		});
		
		if (tipsy) {
			$(".listing-tip").tipsy({
				offset: 1,
				opacity: 1,
				html: true,
				gravity: "nw",
				className: "tipsy-listing"
			});
		}
		
		if ($("#export_grid").length > 0 && datagrid) 
		{
			var $grid = $("#export_grid").datagrid({
				buttons: [{type: "view", url: "index.php?controller=pjAdminJobs&action=pjActionExportFeed{:params}", 'target' : "_blank"},
				          {type: "delete", url: "index.php?controller=pjAdminJobs&action=pjActionDeletePassword&id={:id}"}
				          ],
				columns: [{text: myLabel.format, type: "text", sortable: false, editable: false, width: 300},
				          {text: myLabel.job_created, type: "text", sortable: false, editable: false, width: 310}
				          ],
				dataUrl: "index.php?controller=pjAdminJobs&action=pjActionGetPassword",
				dataType: "json",
				fields: ['format', 'period'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminJobs&action=pjActionDeletePasswordBulk", render: true, confirmation: myLabel.delete_confirm}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminJobs&action=pjActionSavePassword&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
		}
	});
})(jQuery_1_8_2);