/*
		$(".preview").getPaginatedContent({
			enableSearchFrm: true,				//enable search form
			searchFrm: ".frm_search",			//search form selector
			ajaxData: "/rest/",					//ajax data url
			dataNumber: 8,						//number of content per page
			paginationClass: ".pagination"		//pagination class
		});
*/
(function($){
	
	$.fn.extend({ 
		getpaginatedcontent: function(options) { 
		
            var defaults = {
					enableSearchFrm: true,				//enable search form
					searchFrm: ".frm_search",			//search form selector
					ajaxData: "/rest/",					//ajax data url
					ajaxFilter: "",						//ajax filter
					dataNumber: 0,						//number of content per page
					paginationClass: ".pagination",		//pagination class
					noDataMessage: "Nessun risultato.",	
					errorMessage: "Si &egrave; verificato un errore.",
					datePattern: "dd-MM-yyyy",
					callback: ""
            };
			var options = $.extend(defaults, options); 
            
			//GLOBAL VARS
			var viewing_page = 0;
			var total_contents = 0;
	
            return this.each(function(){
				var searchfilter="";
                var obj = $(this);
				
				//-- ie6 fix --
				$(obj).find("a").each(function(i){
					var hrefval = $(this).attr("href");
					if(hrefval.indexOf("#linkuri")!=-1){
						temp = new Array();
						temp = $(this).attr("href").split("#");
						$(this).attr("href", "http://"+temp[1]+"/");
					}
				});
				//-- end ie6 fix --
				
				obj.hide();
				searchEngine(true);
				
				function ajaxcall(val){
					if(typeof(val)!=undefined){
						viewing_page = val;
					}
					var offset = viewing_page*options.dataNumber;
					obj.parent().find(".generatedContent").remove();
					var filter = "limit="+options.dataNumber+"&offset="+offset+"&filter="+searchfilter+" "+options.ajaxFilter;
					$.ajax({
						type: "GET",
						url: options.ajaxData,
						data: filter,
						dataType: "json",
						error: function(){
							obj.hide();
							obj.parent().find("p.noresult").remove();
							$("<p>"+options.errorMessage+"</p>").insertBefore(obj);
							$(options.paginationClass).hide();
							return false;
						},
						success: function(data){
							viewing_page++;
							if(data.totalCount!=0){
								$(".noresult").remove();
								total_contents = data.totalCount;
								$.each(data.contentList, function(i, item){
									processData(item);
								});
								paginate();
							}else{
								obj.hide();
								obj.parent().find("p.noresult").remove();
								$("<p class=\"noresult\">"+options.noDataMessage+"</p>").insertBefore(obj);
								$(options.paginationClass).hide();
							}
						}
					});
				}
				
				function searchEngine(isFirst){
					if(options.enableSearchFrm){
						$.ajax({
							type: "GET",
							url: options.ajaxData,
							data: "filter="+options.ajaxFilter+"&orderBy=date desc",
							dataType: "json",
							error: function(){
								$(options.searchFrm).hide();
								return false;
							},
							success: function(data){
								if(data.totalCount!=0){
									var actualyear = "";
									$.each(data.contentList, function(i, item){
										var itemdate = printableDate(item.date, "yyyy");
										if(itemdate!=actualyear){
											actualyear=itemdate;
											$(options.searchFrm+" #year").append("<option value=\""+itemdate+"\">"+itemdate+"</option>");
										}
									});
								}else{
									$(options.searchFrm).hide();
								}
							},
							complete: function(){
								$(options.searchFrm+" .btn").unbind("click");
								$(options.searchFrm+" .btn").bind("click", function(){
									var text = $(options.searchFrm+" input").val();
									var month = $(options.searchFrm+" #month").val();
									var year = $(options.searchFrm+" #year").val();
									searchfilter = "";
									if(text!=""){
										searchfilter = "(title contains '"+text+"' or abstract contains '"+text+"' or richtext contains '"+text+"')";
									}
									if(text!="" && (year!="" || month!="")){
										searchfilter = searchfilter+" and";
									}
									if(year!="" && month!=""){
										searchfilter = searchfilter+" date>="+year+"-"+month+"-01T00:00:00Z and date<="+year+"-"+month+"-31T23:59:59Z";
									}else if(month!=""){
										searchfilter = searchfilter+" date>=1900-"+month+"-01T00:00:00Z and date<=3000-"+month+"-31T23:59:59Z";
									}else if(year!=""){
										searchfilter = searchfilter+" date>="+year+"-01-01T00:00:00Z and date<="+year+"-12-31T23:59:59Z";
									}else if(text==""){
										searchfilter = "";
									}
									
									if(searchfilter!="" && options.ajaxFilter!=""){
										searchfilter = searchfilter + " and";
									}
									searchEngine(false);
								});
								ajaxcall(0);
								if(isFirst) {
									eval(options.callback);
								}
							}
						});
						
					}else{
						ajaxcall(0);
					}
				}
				
				function processData(item){
					var tplobj = obj.clone();
					
					var replacehtml = tplobj.html();
					if(typeof(item["timeo:link"].link)!="undefined" && item["timeo:link"].link!="" && item["timeo:link"].link.href!=""){
						var downloadEXT = item["timeo:link"].link.href["kca:src"];
						downloadEXT = downloadEXT.substring(downloadEXT.lastIndexOf(".")+1, downloadEXT.length);
						replacehtml = replacehtml.replace(/#linkext/g, downloadEXT);
						
						
						replacehtml = replacehtml.replace(/http\:\/\/linkuri\//g, item["timeo:link"].link.href["kca:src"]);
						//size
						var size = parseInt(parseInt(item["timeo:link"].link.href["kca:contentLength"],10)/1024);
						replacehtml = replacehtml.replace(/#linksize/g, size+"kB");
					}
					if(typeof(item.preview)!="undefined"){
						//alert( item.preview["kca:src"]);
						replacehtml = replacehtml.replace(/http\:\/\/imgpath\//g, item.preview["kca:src"]);
 					}
					
 
					if(typeof(item.date)!="undefined"){
						replacehtml = replacehtml.replace(/#date/g, printableDate(item.date, options.datePattern));
					}
					if(typeof(item.title)!="undefined"){
						replacehtml = replacehtml.replace(/#title/g, item.title);
					}
					if(typeof(item.abstract)!="undefined"){
						replacehtml = replacehtml.replace(/#abstract/g, removeP(item.abstract));
					}
					
					replacehtml = replacehtml.replace(/#id/g, item["kca:id"]);
					tplobj.html(replacehtml);
					if(typeof(item.preview)=="undefined") {
						/*tplobj.find("img[src$='imgpath']").parent().next().removeClass("small");
						tplobj.find("img[src$='imgpath']").parent().next().addClass("large");*/
						tplobj.find("img[src$='imgpath']").parent().remove();
					}
					
					if(typeof(item["timeo:link"].link)=="undefined") {
						tplobj.find("[href$='linkuri']").remove();
					}
					tplobj.addClass("generatedContent");
					tplobj.insertBefore(obj);
					tplobj.show();
				}
				
				function printableDate(data, pattern){
					var year = data.substring(0,4);
					var month = data.substring(5,7);
					var day = data.substring(8,10);
					
					var datePattern = pattern.replace(/dd/g, day);
					datePattern = datePattern.replace(/MM/g, month);
					datePattern = datePattern.replace(/yyyy/g, year);
					
					return datePattern;
				}
				
				function paginate(){
					var startContent = ((viewing_page*options.dataNumber)-options.dataNumber)+1;
					var endContent = viewing_page*options.dataNumber;
					$(options.paginationClass+" .page").html(startContent+"-"+endContent);
					$(options.paginationClass+" .total").html(total_contents);
					
					if((startContent+options.dataNumber)>=total_contents){
						$(options.paginationClass+" .next").unbind("click");
						$(options.paginationClass+" .next").hide();
					}else{
						$(options.paginationClass+" .next").show();
						$(options.paginationClass+" .next").unbind("click");
						$(options.paginationClass+" .next").bind("click", function(){
							ajaxcall((viewing_page));
							return false;
						});
					}
					if((startContent-options.dataNumber)<1){
						$(options.paginationClass+" .prev").unbind("click");
						$(options.paginationClass+" .prev").hide();
					}else{
						$(options.paginationClass+" .prev").show();
						$(options.paginationClass+" .prev").unbind("click");
						$(options.paginationClass+" .prev").bind("click", function(){
							ajaxcall((viewing_page-2));
							return false;
						});
					}
					
				}
				
				function removeP(data){
					data = data.replace(/<p>/g,"");
					/*if(enableTruncate){
						data = smartTruncate(data, sizeTruncate);
					}*/
					return data;
				}
				
				//if(!options.enableSearchFrm){
					//ajaxcall(viewing_page);
				//}
			}); 
        } 
    }); 
})(jQuery);
