/**
 * @author Mihai Varga
 */
(function($) {
$.widget("ui.gridview", {

	_init: function() {
			this.element
				.css({"clear":"both"})
				.wrap("<div></div>").parent().addClass("ui-widget ui-gridview");								

			this.gridtable={
				obj:this,
				header:"",
				pages:"",
				rows:"",
				loader:"",
				search:""
			};			
			
			var self=this,index;
			
			this.gridtable.header=$(this.element.children("thead").children("tr")[0]).children();
			this.options.no_cols=this.gridtable.header.length;
			this.gridtable.header
					.attr("sortdir","0")
					.css({
						"cursor": 'pointer'						
					})
					.addClass("ui-widget-header ui-gridview-header-col")
					.click(function()
					{	
						self.options.sortby=$(this).attr("sortby");
						$(this).next().each(function(){
							$(this).removeClass("ui-gridview-header-col-desc");
							$(this).removeClass("ui-gridview-header-col-asc");
						});
						$(this).prevAll().each(function(){
							$(this).removeClass("ui-gridview-header-col-desc");
							$(this).removeClass("ui-gridview-header-col-asc");
						});
						if ($(this).attr("sortdir") <= 0) {
							$(this).attr("sortdir", 1);
							self.options.sortdir=1;
							$(this).removeClass("ui-gridview-header-col-desc");
							$(this).addClass("ui-gridview-header-col-asc");
						}
						else {
							$(this).attr("sortdir", -1);
							self.options.sortdir=-1;
							$(this).removeClass("ui-gridview-header-col-asc");
							$(this).addClass("ui-gridview-header-col-desc");
						}	
						self._refresh();
					}
			);
			
			htmlitem = "<div class='ui-widget-content ui-gridview-pages'></div>";
			this.element.after(htmlitem);
			this.gridtable.pages = this.element.next();				
				
			this._show_pages();							
			
			this.element.before("<div class='ui-gridview-loader'><div class='ui-gridview-loader-text'>Loading...</div></div>");
			this.gridtable.loader=this.element.prev()[this.element.prev().size()-1];
			$(this.gridtable.loader).hide();
			
			this._show_search()
				._show_nopage_selector()			
				._refresh();
	},
	
	_displayLoader:function(){
		$(this.gridtable.loader)
			.width(this.element.parent(".ui-gridview").width())
			.height(this.element.parent(".ui-gridview").height())
			.css("line-height",this.element.parent(".ui-gridview").height()+"px");		
		this.element.parent(".ui-gridview").children().hide();
		$(this.gridtable.loader).show();
		
		return this;
	},
	
	_calcPages:function(){
		this.options.no_pages = Math.floor(this.options.no_results / this.options.no_rows);
				if (this.options.no_results % this.options.no_rows != 0) 
					this.options.no_pages++;
		return this;		
	},
	
	_hideLoader:function(){
		this.element.parent(".ui-gridview").children().show();
		$(this.gridtable.loader).hide();
		
		return this;
	},	

	_refresh:function()
	{
		this._displayLoader();
		var self=this,index;
		kwd=$('#gridview_kwd').val();
		
		if($('#gridview_kwd_word:checked').length)
			kwd="\""+kwd+"\"";
		$.ajax({
			url: this.options.url,
			data: "kwd="+kwd+"&sortBy=" + (this.options.sortby?this.options.sortby:"") + "&sortAscending=" + (this.options.sortdir > 0 ? "true" : "false")+"&numberOfRows="+this.options.no_rows+"&startIndex="+(this.options.current_page*this.options.no_rows),
			cache: true,
			success: function(response){
				self._display(response)
					._show_pages()
					._hideLoader();
			}
		});
		
		return this;
	},
	
	_display:function(content){
		var self=this,index;
		this.element.children("tbody").html("");
		for(i=0;i<this.options.no_rows;i++)
		{
			class="ui-gridview-row";
			if((i%2))					
				class+=" ui-gridview-row-alt";
			this.element.children("tbody").append("<tr class='"+class+"'></tr>");
			for(j=0;j<this.options.no_cols;j++)
			{
				this.element.children("tbody").children().eq(i).append("<td></td>");
			}			
		}
		
		this.element.children("tbody")
		this.gridtable.rows=this.element.children("tbody").children("tr");
		if(self.options.rowclick!='')
			this.gridtable.rows.each(function(i,el)
			{
											
					$(el).click(
						function(){
							self.options.rowclick(this);
							}
					);
			});
		list=content.split("|||");
		last=list[list.length-1];
		if(last!="")
		{
			last_a=last.split("###");
			if(last_a.length==1)
				this.options.no_results=$.trim(last);
		}
		
		for(i=0;i<list.length;i++)
		{
			if (this.gridtable.rows.size()>i) {
				if (list[i]) {
					row = list[i].split("###");					
					if (row.length== this.gridtable.header.size()) {						
						for (j = 0; j < this.gridtable.header.size(); j++) {		
							if($($(this.gridtable.rows[i]).children("td")[j]))					
								$($(this.gridtable.rows[i]).children("td")[j]).html(row[j]);							
						}						
					}
					else {												
						for (j = 0; j < this.gridtable.header.size(); j++) {
							if($($(this.gridtable.rows[i]).children("td")[j]))
								$(this.gridtable.rows[i]).hide();								
						}						
					}
				}
				else {					
					for (j = 0; j < this.gridtable.header.size(); j++) {
						if($($(this.gridtable.rows[i]).children("td")[j]))
							$(this.gridtable.rows[i]).hide();
					}
				}
			}			
		}
		if(list.length<this.gridtable.rows.size()){
			for(i=list.length;i<this.gridtable.rows.size();i++)
				for (j = 0; j < this.gridtable.header.size(); j++)
					if($($(this.gridtable.rows[i]).children("td")[j]))
						$(this.gridtable.rows[i]).hide();
		}
		
		return this;
	},
	
	_show_pages : function(){		
		
		
			this._calcPages();
			
			$(this.gridtable.pages)
				.html("")
				.css({"clear":"both"});
			if (this.options.no_pages > 1) {
				if (this.options.current_page > this.options.max_pages / 2 - 1) {
					$(this.gridtable.pages)
						.append("<a class='ui-state-default ui-corner-all ui-gridview-page' page='" + 0 + "'><<</a>")
						.append("<a class='ui-state-default ui-corner-all ui-gridview-page' page='" + (this.options.current_page - 1) + "'><</a>");
				}
				
				var start = Math.floor(this.options.current_page - this.options.max_pages / 2 + 1) >= 0 ? Math.floor(this.options.current_page - this.options.max_pages / 2 + 1) : 0;
				var end = Math.floor(this.options.current_page + this.options.max_pages / 2) <= this.options.no_pages ? Math.floor(this.options.current_page + this.options.max_pages / 2) : this.options.no_pages;
				end = end + (this.options.max_pages - (end - start));
				if (end > this.options.no_pages) {
					end = this.options.no_pages;
					start = start - (this.options.max_pages - (end - start));
				}
				if (start < 0) 
					start = 0;
				
				for (i = start; i < end; i++) {
					cls = "class='ui-state-default ui-corner-all ui-gridview-page'";
					if (i == this.options.current_page) 
						cls = "class='ui-state-active ui-corner-all ui-gridview-page-selected'";
					htmlitem = "<a " + cls + " page='" + i + "'>" + (i + 1) + "</a>";
					$(this.gridtable.pages).append(htmlitem);
				}
				
				if (end < this.options.no_pages) {
					$(this.gridtable.pages)
						.append("<a class='ui-state-default ui-corner-all ui-gridview-page' page='" + (this.options.current_page + 1) + "'>></a>")
						.append("<a class='ui-state-default ui-corner-all ui-gridview-page' page='" + (this.options.no_pages - 1) + "'>>></a>");
				}
				var self = this, index;
				$(this.gridtable.pages).children()
					.click(function(){
						self.options.current_page = parseInt($(this).attr("page"));
						self._refresh();
					})
					.mouseover(function(){
						$(this).toggleClass("ui-state-hover");
					})
					.mouseout(function(){
						$(this).toggleClass("ui-state-hover");
					});				
			}			
			to=((this.options.current_page * this.options.no_rows + this.options.no_rows < this.options.no_results) ? 
					this.options.current_page * parseInt(this.options.no_rows) + parseInt(this.options.no_rows) 
					: 
					this.options.no_results);
			if(to>this.options.no_results)to=this.options.no_results;
			$(this.gridtable.pages)
				.append("<div class='ui-gridview-result'>"+this.options.text_pages_result + (this.options.current_page * this.options.no_rows + 1) + " "+this.options.text_pages_to+" " + to + " "+this.options.text_pages_of+" " + this.options.no_results + "</div>")
				.css({"clear":"both"})
				.addClass("clearfix");
		
		return this;
	},
	
	_show_search:function(){
		this.element.before("<div class='ui-widget-content ui-gridview-top'></div>")
			.prev()
				.css({"display": "block"})
				.append("<div class='ui-gridview-search'>"+this.options.text_search+"</div>")
				.children()
					.append("<input type='text' class='ui-widget-content ui-gridview-search-input' name='gridview_kwd' id='gridview_kwd'/><label><input type='checkbox' name='gridview_kwd_word' id='gridview_kwd_word'/>"+this.options.text_search_portion+"</label>")
					.css({"float": "left"});
		
			
		var self=this,index;
		$("#gridview_kwd_word").parent().click(function(){
			if($("#gridview_kwd").val()!="")
				self._refresh();
		});
		$("#gridview_kwd")
			.css("margin",2)
			.keyup(			
			function(e){
				if (e.which == 13) {
					self.options.current_page=0;
					self._refresh();										
				}
			}			
		);
		
		return this;
	},
	_show_nopage_selector:function(){		
		this.element.prev()
			.append("<div class='ui-gridview-no_rows'>"+this.options.text_no_rows+"</div>")
			.children(".ui-gridview-no_rows")
				.append("<input type='text' class='ui-widget-content ui-gridview-norows-input' value='"+this.options.no_rows+"' name='gridview_norows' id='gridview_norows'/>")
				.css({"float": "right"});
		
		var self=this,index;
		$("#gridview_norows")
			.css("margin",2)
			.keyup(			
			function(e){
				if (e.which == 13) {
					self.options.current_page=0;
					self.options.no_rows=$("#gridview_norows").val();
					self._refresh();										
				}
			}			
		);
		return this;
	},
	
	refresh:function(){
		this._refresh();
	},
	
	destroy: function() {

		
		this.valueDiv.remove();

		$.widget.prototype.destroy.apply(this, arguments);

	}
});

$.extend($.ui.gridview, {
	version: "1.7",
	defaults: {
		url:'',
		no_rows:10,
		no_cols:10,
		no_results:1,
		current_page:1,
		max_pages:10,					
		rowclick:'',
		text_search:'Cauta:',
		text_search_portion:' ca si portiune de text?',
		text_no_rows:'Nr randuri/pagina:',
		text_pages_result:'Rezultate: ',
		text_pages_to:'pana la',
		text_pages_of:'din'
	}
});

})(jQuery);

