/*
jQuery.fn.jobs = function(options) {
	var settings = jQuery.extend({
		// put defaults here
	}, options);
	
	
	$("div.vacancy").hover(
		function(){ 
			$(this).addClass("over");
		}, 
		function() { 
			$(this).removeClass("over");
		} 
	)
	//.click(function () { 
	//	console.log($(this).attr("class"));
		//location.href =$(".vacancy.over .link > a").attr('href');
	//	return false;
	//});
	
	// if possible, return "this" to not break the chain
	return this;
};
*/

(function($) {
	$.fn.jobs = function(options) {
		options = $.extend({ page: 0, sort: 'nameASC', regionId: [], q:'', genreId:[], levelId:[], experienceId:[], typeId:[], employerId:[], importDate:[], city:'', minHours:'8', maxHours:'40', hot:0}, options || {});
		
		arrCompareItems = [];
		
		// Reload vancancies
		updatePage = function() {
			showLoader();
			
			var ajaxManager = $.manageAjax.create('cacheQueue', { 
				queue: true,  
				cacheResponse: false,
				abortOld: true
			}); 
		
			ajaxManager.add({
				type: "GET",
				url: "/includes/ajax/ajax.jobs.php",
				data: options,//"{'page':'" + options.page + "'}",
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				success: function(data) {
					showPaging();
					fillJobs(data);
					updateControls(data);
					hideLoader();
					//$.address.value('?regionId=4&genreId=5');
			
					strAddress = '?';	
					$.each(options, function(key, val) {
						strAddress += key +'='+val+'&';
					});
					//$.address.value(strAddress);
				},
				error: function(xhr, ajaxOptions) {
					updateControls();
					$("#jobs").html('Geen vacatures gevonden');	
					$("#job_count").html('Er zijn <span class="orange">0</span> vacatures gevonden');
					hideLoader();
				}
			});
		};
		
		// Process data to jobs layer
		fillJobs = function(data) {
			if(data.allure.count == '1') $("#job_count").html('Er is <span class="orange">'+data.allure.count+'</span> vacature gevonden');
			else  $("#job_count").html('Er zijn <span class="orange">'+data.allure.count+'</span> vacatures gevonden');
			$("#jobs").setTemplateElement("template");
			$("#jobs").processTemplate(data.allure);
			addJobsHover();
			addComparator();
			showPaging(data.allure.page, data.allure.pageTotal);
		}
		
		
		// Update controls
		updateControls = function(data) {
			$.each($("#left_column > .node > .node_content > ul"), function() {
				$(this).children("li").addClass("disabled").children("input").attr("disabled", "disabled");
				$(this).children("li").children("label").children("span").html('(0)');
			});
			if(data) {
				$.each(
					data.allure.enabledControls,
					function(i,cats) {
						$.each(cats.ids, function(i,id) {
							$("#left_column > .node > .node_content > ul").children("#container_" + cats.control + '_' +id[0]).removeClass("disabled");
							$("#left_column > .node > .node_content > ul").children("#container_" + cats.control + '_' +id[0]).children("input").removeAttr("disabled");
							$("#left_column > .node > .node_content > ul").children("#container_" + cats.control + '_' +id[0]).children("label").children("span").html('('+id[1]+')');
						});
					}
				);				
	
				$.each($("#left_column > .node > .node_content > ul > li"), function() {
					if($(this).children("input").attr("disabled") && $(this).children("input").attr("checked")) {
						$(this).children("input").removeAttr("checked");
						arr = eval('options.'+$(this).children("input").attr('name'));
						var removeItem = $(this).children("input").val();
						arr = jQuery.grep(arr, function(a) {
							return a != removeItem;
						});					
						eval('options.'+$(this).children("input").attr('name')+' = arr');
					}
				});
			}
		}

		showPaging = function(page, pageTotal) {
			
			//PAGING TOP
			if(page == 1) {
				if(pageTotal == 1) $("#paging").html('<a href="#" class="btn disabled">&laquo;</a> Pagina <strong>'+page+'</strong> van <strong>'+pageTotal+'</strong> <a href="#" class="btn disabled">&raquo;</a>');
				else  $("#paging").html('<a href="#" class="btn disabled">&laquo;</a> Pagina <strong>'+page+'</strong> van <strong>'+pageTotal+'</strong> <a href="#" class="btn up">&raquo;</a>');
			}
			else if(page == pageTotal) $("#paging").html('<a href="#" class="btn down">&laquo;</a> Pagina <strong>'+page+'</strong> van <strong>'+pageTotal+'</strong> <a href="#" class="btn disabled">&raquo;</a>');
			else $("#paging").html('<a href="#" class="btn down">&laquo;</a> Pagina <strong>'+page+'</strong> van <strong>'+pageTotal+'</strong> <a href="#" class="btn up">&raquo;</a>');

			$("#paging a.btn.disabled").click(
				function(){ 
					return false;
				}
			);
			$("#paging a.btn.up").click(
				function(){ 
					updatePaging(1);
					return false;
				}
			);
			$("#paging a.btn.down").click(
				function(){ 
					updatePaging(-1);
					return false;
				} 
			);
			
			//PAGING BOTTOM
			if(page > 1) $("#paging_bottom").html('<a href="#" class="btn down">&laquo; vorige</a>');
			else $("#paging_bottom").html('<a href="#" class="btn disabled">&laquo; vorige</a>');

			for(x=1;x<=pageTotal;x++){
				if(x == page) $("#paging_bottom").append('<a href="#" class="btn nr active">'+x+'</a>');
				else $("#paging_bottom").append('<a href="#" class="btn nr">'+x+'</a>');
			}
			if(page < pageTotal) $("#paging_bottom").append('<a href="#" class="btn up">volgende &raquo;</a>');
			else $("#paging_bottom").append('<a href="#" class="btn disabled">volgende &raquo;</a>');
			
			$("#paging_bottom a.btn.nr").click(
				function(){ 
					updatePaging($(this).html()-1, 1);
					return false;
				}
			);
			$("#paging_bottom a.btn.disabled").click(
				function(){ 
					return false;
				}
			);
			$("#paging_bottom a.btn.up").click(
				function(){ 
					updatePaging(1);
					return false;
				}
			);
			$("#paging_bottom a.btn.down").click(
				function(){ 
					updatePaging(-1);
					return false;
				} 
			);
		}
		updatePaging = function(n, paging_bottom) {
			if(paging_bottom) options.page = n;
			else options.page = options.page+n;
			updatePage();
		}
		
		//Show loading layer
		showLoader = function() {
			if ($(".loader").css("display") != "block") {
				if ($(".loader").parent().offset() != null) {
					bgxPos = $(".loader").width()/2 + $(".loader").parent().offset().left - 24;
				}else {
					bgxPos = $(".loader").width() / 2 - 24;
				}
				
				height = $(".loader").parent().height();
				$(".loader").show();
				if($(".loader").css("background-attachment")=="fixed") { //for browsers that don't support fixed background attachements (IE6)
					$(".loader").css("background-position", bgxPos+"px 50%");
				}
				$(".loader").css({
					"height": height+"px",
					"opacity": "0"
				}).animate({ opacity: 0.7 }, 500);
			}
			
		};

		//Hide loading layer
		hideLoader = function() {
			height = $(".loader").parent().height();
			$(".loader").css({
				"height": height+"px"
			}).animate({ opacity: 0 }, 500, function() {
				$(this).hide()
			});
		};

		//Remove q string from searchcriteria's
		removeQWord = function() {
			$("a.delete_q").click(
				function() {
					$(this).parent().remove();
					options.q = '';
					options.page = 0;
					arrCompareItems = [];
					updatePage();
					return false;
				}
			);
		}

		//Add hover states on jobs
		addJobsHover = function() {
			$("div.job").hover(
				function(){ 
					$(this).addClass("over");
				}, 
				function() { 
					$(this).removeClass("over");
				} 
			);
		}

		//Add hover states on jobs
		addComparator = function() {
			//arrCompareItems = [];
			$("div.compare input").click(
				function(){ 
					if(this.checked) {
						if(arrCompareItems.length == 3) return false;
						arrCompareItems.push(this.value);
						
						if(arrCompareItems.length == 1) {
							$(this).next().html('Selecteer meerdere producten<br />om te vergelijken');
						}
						else if(arrCompareItems.length > 1) {
							jQuery.each($("div.compare input"), function() {
								if(this.checked) $(this).next().html('Vergelijk de geselecteerde vacatures<br /><a href="/jobs_compare.php?n=1&jobs='+arrCompareItems.join(",")+'"><img src="/images/btn-compare.gif" /></a>');
							});
							
						}
					}
					else {
						removeItem = this.value;
						arrCompareItems = jQuery.grep(arrCompareItems, function(value) {
							return value != removeItem;
						});

						jQuery.each($("div.compare input"), function() {
							if(this.checked){
								if(arrCompareItems.length == 1) $(this).next().html('Selecteer meerdere producten<br />om te vergelijken');
								else $(this).next().html('Vergelijk de geselecteerde vacatures<br /><a href="/jobs_compare.php?n=1&jobs="'+arrCompareItems.join(",")+'"><img src="/images/btn-compare.gif" /></a>');
							}
							else $(this).next().html('Vergelijk');
						});
					}
				} 
			);
			//checking if there are already items checked to be compared.
			$.each(arrCompareItems, function(n, val) {
				objThis = $('#compare_'+val);
				objThis.attr('checked', true);

				if(arrCompareItems.length == 1) {
					$(objThis).next().html('Selecteer meerdere producten<br />om te vergelijken');
				}
				else if(arrCompareItems.length > 1) {
					jQuery.each($("div.compare input"), function() {
						if(this.checked) $(this).next().html('Vergelijk de geselecteerde vacatures<br /><a href="/jobs_compare.php?n=1&jobs='+arrCompareItems.join(",")+'"><img src="/images/btn-compare.gif" /></a>');
					});
					
				}
			});
		}

		removeEmptyItems = function() {
			$.each(options, function(key, val) {
				if(jQuery.isArray(val)) {
					//console.log(jQuery.isArray(val));
					//console.log('waarde: ' + val[0]);
					//if(val[0] == '') console.log('leeg');
					
					if(val[0] == '') {
						arr = jQuery.grep(val, function(a) {
							return a != '';
						});
						eval('options.'+key+' = arr');					
					}
					//console.log('waarde: ' + key);
					//console.log('waarde: ' + val[0]);
				}
			});
			
		}

	
		//Do onload
		$("input.post_option").click(
			function(){ 
				if(this.checked) {
					eval('options.'+this.name+'.push('+this.value+')');
					$(this).closest('ul').next('.deselector').show();
				}
				else {
					arr = eval('options.'+this.name);
					var removeItem = this.value;
					arr = jQuery.grep(arr, function(a) {
						return a != removeItem;
					});
					eval('options.'+this.name+' = arr');
					if(arr.length == 0) $(this).closest('ul').next('.deselector').hide();
				}
				options.page = 0;
				arrCompareItems = [];
				updatePage();
			} 
		);

		$("select#sorting").change(
			function(){ 
				options.sort = this.value;
				updatePage();
			} 
		);

		
		$("div.deselector a").click(
			function(){ 
				jQuery.each($(this).parent().prev().children(), function() {
					jQuery.each($(this).children('.post_option'), function() {
						if(this.checked) {
							this.checked = false;
							arr = eval('options.'+this.name);
							var removeItem = this.value;
							arr = jQuery.grep(arr, function(a) {
								return a != removeItem;
							});
							eval('options.'+this.name+' = arr');
						}
					});
				});
				$(this).closest('div').hide();
				options.page = 0;
				arrCompareItems = [];
				updatePage();
				return false;
			}
		);
		$("div.selector_all a.select").click(
			function(){ 
				jQuery.each($(this).parent().prev().children(), function() {
					jQuery.each($(this).children('.post_option'), function() {
						if(!this.checked && !this.disabled) {
							eval('options.'+this.name+'.push('+this.value+')');
							this.checked = true;
							//$(this).trigger('click');
						}
					});
				});
				options.page = 0;
				arrCompareItems = [];
				updatePage();
				return false;
			}
		);
		$("div.selector_all a.deselect").click(
			function(){ 
				jQuery.each($(this).parent().prev().children(), function() {
					jQuery.each($(this).children('.post_option'), function() {
						if(this.checked) {
							this.checked = false;
							arr = eval('options.'+this.name);
							var removeItem = this.value;
							arr = jQuery.grep(arr, function(a) {
								return a != removeItem;
							});
							eval('options.'+this.name+' = arr');
						}
					});
				});
				options.page = 0;
				arrCompareItems = [];
				updatePage();
				return false;
			}
		);

		$("#slider-range").slider({
			range: true,
			min: 4,
			max: 40,
			step: 4,
			values: [8, 40],
			slide: function(event, ui) {
				$("#amount").val(ui.values[0] + ' uur - ' + ui.values[1] + ' uur');
				options.minHours = ui.values[0];
				options.maxHours = ui.values[1];
				arrCompareItems = [];
				updatePage();
			}
		});
		$("#amount").val($("#slider-range").slider("values", 0) + ' uur - ' + $("#slider-range").slider("values", 1) + ' uur');
		
		//$.each($.address.parameterNames(), function(n, val) {
		//	if(val != '') eval('options.'+val+' = $.address.parameter(val)');
		//});
		
		removeQWord();
		removeEmptyItems();
		addComparator();
		addJobsHover();
		hideLoader();
		
		arrCompareItems = [];
		updatePage();
	};

})(jQuery);
