//******************************************************************************
// MooDataTable 0.1: A data table for MooTools 1.2
// License: MIT License 
// Copyright (c) 2008 Jean-Nicolas Jolivet [http://www.silverscripting.com]

var MooDataTableAjax = new Class({
	Implements: [Events, Options],
	options: {
		url: 'post.php',
		method: 'get',
		perPage: 20,
		identificator: 't',
		nrCols: 4, 
		Asearch: null,
		AsearchSelect: null,
		AiniSearch: null,
		noResults: 'Nu sunt rezultate!',
		iniOrderField: '',
		headerCaptions: [],
		headerIds: [],
		width: 400
	},
	
	initialize: function(el, options) {
		this.setOptions(options);
		this.el = $type(el) === 'string' ? $(el) : el;
		this.pages = 0;
		this.createElements();
	},
	
	createElements: function() {
		// build the table structure...
		var structureHtml = "<table cellspacing='0'><thead><tr></tr></thead><tfoot><tr><td colspan=\"" + this.options.nrCols + "\"><span class=\"moo-foot-left\"></span><span class=\"moo-foot-right\"></span></td></tr></tfoot><tbody></tbody></table>";
		
		// Assign the HTML and CSS class to our element
		this.el.set('html', structureHtml);
		this.el.addClass('moo-table');
		//this.el.setStyle('width', this.options.width + "px");
		// Grab the important elements
		this.table = this.el.getChildren("table")[0];
		this.tableBody = this.table.getChildren("tbody")[0];
		this.tableHead = this.table.getChildren("thead")[0];
    this.footer = this.table.getElements('tfoot > tr > td')[0];
    this.footergtp = this.footer.getElements('span.gotopage')[0];
		this.footerLeft = this.table.getElements('tfoot > tr > td > span.moo-foot-left')[0];
		this.footerRight = this.table.getElements('tfoot > tr > td > span.moo-foot-right')[0];
		
		// initiate and create the headers
		this.headersEl = [];
		this.createHeaders();
		
	},
	createHeaders: function() {
		var headerCaptions = this.options.headerCaptions;
		var headerIds = this.options.headerIds;
		var headerTr = this.tableHead.getChildren("tr")[0];
		
		// Create the column headers
		first = 1;
		headerCaptions.each(function(header, index){
			var headerTd = new Element('th', {id: headerIds[index]});
			headerTd.set('html', headerCaptions[index]);
			
			// add the click event for column re-ordering
			if (first==0) {
				//	prima coloana nu se ordoneaza ca este Nr.crt
				headerTd.addEvent("click", function(arg1){
					this.reorder(arg1.get('id'));
				}.bind(this, headerTd));
			}
			first = 0;
			this.headersEl.push(headerTd);
			headerTd.inject(headerTr);
			
			
		}, this);
		
		// Set the initial page and sort column...
		this.page = 1;
		this.sort = '';
		// set the sort order to DESC, it will be inverted to ASC by default on first call...
		this.sortOrder = "DESC";
		
		if (this.options.iniOrderField) {
			//	highlight ini order
			this.reorder(this.options.iniOrderField);	
		} else {
			this.reorder(headerIds[0]);
		}		
	},
	
	reorder: function(id) {
		var orderClass = "";
		if(this.sort == id) {
			// same column clicked... just reverse the order...
			this.sortOrder = this.sortOrder == "DESC" ? "ASC" : "DESC";
		}
		else {
			// new column clicked, set to ASC by default
			this.sortOrder = "ASC";
		}
		
		orderClass = this.sortOrder == "ASC" ? "moo-active-asc" : "moo-active-desc";
		this.activeColumnEl = this.tableHead.getChildren("tr")[0].getChildren("th#" + id)[0];
		this.headersEl.each(function(el){
			el.removeClass('moo-active-column');
			el.removeClass('moo-active-asc');
			el.removeClass('moo-active-desc');
		});
		this.activeColumnEl.addClass("moo-active-column");
		this.activeColumnEl.addClass(orderClass);
		this.sort = id;
		// send the new request
		this.requestData(this.page);
	},
	
	requestData: function(page) {
		// initiate the ajax request...
		this.footerLeft.set('html', 'Incarcare date...');
		pageURL = this.options.identificator + "_perPage=" + this.options.perPage;
		if (this.options.iniOrderField) {
			pageURL = pageURL + '&' + this.options.identificator + '_sort=' + this.options.iniOrderField;
			this.options.iniOrderField = '';
		} else {
			pageURL = pageURL + '&' + this.options.identificator + '_sort=' + this.sort;
		}
		if (this.options.iniOrderDirection) {
			pageURL = pageURL + '&' + this.options.identificator + '_sortOrder=' + this.options.iniOrderDirection;
			this.options.iniOrderDirection = '';
		} else {
			pageURL = pageURL + '&' + this.options.identificator + '_sortOrder=' + this.sortOrder ;
		}		
		
		goToPage = "&" + this.options.identificator + "_page=" + page;

		if (this.options.AiniSearch) {
			//	ini search
			for(count=0; count<this.options.AiniSearch.length; count++) {
				$('as_' + this.options.identificator + '_' + this.options.AiniSearch[count][0]).value = this.options.AiniSearch[count][1];
				pageURL = pageURL + 
							goToPage + 
							"&" + this.options.identificator + "_q_" + this.options.AiniSearch[count][0] + "=" + this.options.AiniSearch[count][1];
			}
			// unset ini search
			this.options.AiniSearch = null;
		} else {
			//	custom search
			if (this.options.Asearch.length > 0) {
				for(count=0; count<this.options.Asearch.length; count++) {
					if ($('as_' + this.options.identificator + '_' + this.options.Asearch[count]).value) {
						if (this.firstSearch==1) page = 1;
						this.firstSearch = 0;
						pageURL = pageURL + 
							goToPage + 
							"&" + this.options.identificator + "_q_" + this.options.Asearch[count] + "=" + $('as_' + this.options.identificator + '_' + this.options.Asearch[count]).value;
					} else {
						pageURL = pageURL + goToPage;	
					}
					goToPage = '';
				}
			}
		}
		if (this.options.AsearchSelect.length > 0) {
			for(count=0; count<this.options.AsearchSelect.length; count++) {
				if ($('as_' + this.options.identificator + '_' + this.options.AsearchSelect[count]).value) {
					if (this.firstSearch==1) page = 1;
					this.firstSearch = 0;
					pageURL = pageURL + 
						goToPage + 
						"&" + this.options.identificator + "_q_" + this.options.AsearchSelect[count] + "=" + $('as_' + this.options.identificator + '_' + this.options.AsearchSelect[count]).value;
				} else {
					pageURL = pageURL + goToPage;	
				}
				goToPage = '';
			}
		}

		//if (this.isSearch) {
			//pageURL = pageURL + goToPage;	
		//}
		pageURL = pageURL + goToPage;
		
		pageURL = pageURL + '&' + this.options.identificator + '_bust=' + new Date().getTime();
		
		var jsonRequest = new Request.JSON({
			url: this.options.url, 
			method: this.options.method,
			onSuccess: function(resp){
				if(resp == null) {
					this.footerLeft.set('html', "Rezultatul este invalid...");
				} else {
					if (resp.total > 0) {
						if (this.recreate == 1) {
							this.createElements();
							this.recreate = 0;
						}
						this.parseData(resp.total, resp.page, resp.rows);
					} else {
						this.el.set('html', '<div class="attn"><p>' + this.options.noResults + '</p></div>');
						this.recreate = 1;
					}
					document.getElementById('mesaj_'+ this.options.identificator).innerHTML = resp.sql;
				}
			}.bind(this),
			onFailure: function() {
				this.footerLeft.set('html', "Informatiile nu au fost gasite...");
			}.bind(this)
		}).send(pageURL);
		this.page = page;
		
	},
	
	parseData: function(total, page, rows) {

		// empty the table first...
		this.tableBody.empty();
		rows.each(function(row, index) {
			var index = index + 1;
			// Create a new row...
			var tr = new Element('tr');
			// Check if it's an even row...
			var cssClass = index % 2 == 0 ? 'moo-table-even' : 'moo-table-odd';
			tr.addClass(cssClass);
			
			row.each(function(cell) {
				indexCell = 1;
				tempCell = '';
				tempClass = '';
				cell.each(function(pair, indexCell) {
					if (indexCell==1) {
						tempCell = pair;
					} else {
						tempClass = pair;
					}
					indexCell ++;
				}, this);
				
				var td = new Element('td');
				td.set('html', tempCell);
				if (tempClass) td.addClass(tempClass);
				td.inject(tr);
			}, this);
			
			tr.inject(this.tableBody);
			if(index == this.options.perPage) {
				tr.addClass('moo-table-last');
			}
		}, this);
		// set the total pages if not set...
		this.pages = Math.ceil(total / this.options.perPage);
		var recMax = this.options.perPage * page;
		recMax = recMax > total ? total : recMax;
		var recMin = (this.options.perPage * page) - (this.options.perPage - 1); 
		// Set the footer data
		//this.footerLeft.set('html', "Pagina " + page + " din " + this.pages + " [ " + recMin + " - " + recMax + " din " + total + " ]");
		this.footerLeft.set('html', "Pagina " + page + " din " + this.pages);
		this.paginate();
		//new clickChange($('formMaterialeContent'), $$('#tabelMateriale a'));
		//new clickChange($('formReteteContent'), $$('#tabelRetete a'));
	},
	
	paginate: function() {
		// clear the old pagination...
		//alert(this.page + " " + this.pages);
		this.footerRight.empty();
		$$('span.gotopage').dispose();
		
		if(this.pages == 1) {
			return;
		}else {
			if(this.page > 1) {
				// previous link
				var prevLink = new Element('a', {
					'html': "Inapoi",
					'href': "#",
					'events': {
						'click': function() {
							this.pageClicked("prev");
							return false;
						}.bind(this)
					}
				});
				prevLink.inject(this.footerRight);
			}
			// First page
			if(this.page == 1) {
				// We are on the first page so, non-clickable...
				var page1Span = new Element('span', {
					'html': "1",
					'class': 'moo-active-page'
				});
				page1Span.inject(this.footerRight);
			} else {
				// Not on first page so... clickable...
				var page1Link = new Element('a', {
					'html': '1',
					'href': "#",
					'events': {
						'click': function() {
							this.pageClicked("first");
							return false;
						}.bind(this)
					}
				});
				page1Link.inject(this.footerRight);
			}
			

			if(this.page > 2) {
				var leftSpacer = new Element('span', {'html': '...'});
				leftSpacer.inject(this.footerRight);
				if(this.page == this.pages && this.pages > 3) {
					var minusTwo = new Element('a', {
						'html': this.page - 2 + "",
						'href': "#",
						'events': {
							'click': function() {
								this.pageClicked(this.page - 2);
								return false;
							}.bind(this)
						}
					});
					minusTwo.inject(this.footerRight);
				}
				var minusOne = new Element('a', {
					'html': this.page - 1 + "",
					'href': "#",
					'events': {
						'click': function() {
							this.pageClicked(this.page - 1);
							return false;
						}.bind(this)
					}
				});
				minusOne.inject(this.footerRight);
			}
			if(this.page != 1 && this.page != this.pages) {
				var current = new Element('span', {
						'html': this.page + "",
						'class': 'moo-active-page'
					});
					current.inject(this.footerRight);
			}
			if(this.page < this.pages - 1) {
				
				var plusOne = new Element('a', {
					'html': this.page + 1 + "",
					'href': "#",
					'events': {
						'click': function() {
							this.pageClicked(this.page + 1);
							return false;
						}.bind(this)
					}
				});
				plusOne.inject(this.footerRight);
				
				if(this.page == 1 && this.pages > 3) {
					var plusTwo = new Element('a', {
						'html': this.page + 2 + "",
						'href': "#",
						'events': {
							'click': function() {
								this.pageClicked(this.page + 2);
								return false;
							}.bind(this)
						}
					});
					plusTwo.inject(this.footerRight);
				}
				// spacer
				var rightSpacer = new Element('span', {'html': '...'});
				rightSpacer.inject(this.footerRight);
			}
			if(this.page == this.pages) {
				var lastPageSpan = new Element('span', {
					'html': this.pages + "",
					'class': 'moo-active-page'
				});
				lastPageSpan.inject(this.footerRight);
			} else {
				var lastPageLink = new Element('a', {
					'html': this.pages + "",
					'href': "#",
					'events': {
						'click': function() {
							this.pageClicked("last");
							return false;
						}.bind(this)
					}
				});
				lastPageLink.inject(this.footerRight);
			}
			
			if(this.page < this.pages) {
				var nextLink = new Element('a', {
					'html': "Inainte",
					'href': "#",
					'events': {
						'click': function() {
							this.pageClicked("next");
							return false;
						}.bind(this)
					}
				});
				nextLink.inject(this.footerRight);
			}
     
      if((this.pages > 3) && !( $$('span.gotopage').length>0 ) ) {
     // if((this.pages > 3)  && !(this.footergtp) ) {
        var gotopage = new Element('span', {
          'class':'gotopage',
          'html': 'Go to: <input type="text" name="gotopage" id="gotopage" />'
        });
        gotopage.inject(this.footerRight,'after');
        this.gotopage();
      }
    /*
      if( (this.pages <= 3) && ($$('.gotopage').length>0)){
        //$$('.gotopage').dispose();
        $$('.gotopage').setStyle('display','none');
      }*/
    
		}
	},
gotopage:function(){
      var data =  this; 
     $$("#gotopage").addEvent('blur', function(){
        data.pageClicked(parseInt($("gotopage").value));
  }.bind(this));
  }, 
pageClicked: function(page) {
		if($type(page) === "string") {
			if(page === "next" && this.page < this.pages) {
				this.requestData(this.page + 1);
			}else if(page === "prev" && this.page > 1) {
					this.requestData(this.page - 1);
			}else if(page === "first" && this.page != 1) {
					this.requestData(1);
			}else if(page === "last" && this.page != this.pages) {
					this.requestData(this.pages);
			}
		}else {
			if(page > 0 && page <= this.pages) {
				this.requestData(page);
			}
		}
	},
	
	// only "public" method, (with the constructor huh)...
	// used if, for example, you delete a record and you
	// want to refresh the current active page...
	reloadActivePage: function(){
		this.requestData(1);
		this.paginate();
	},
	reloadWithMessage: function(message){
		this.requestData(1);
		this.paginate();
		message=message.replace(/\'/g,'\\\'');
		setTimeout("document.getElementById('mesaj_" + this.options.identificator + "').innerHTML = '" + message + "';", "1000");
	},
	searchPage: function(){
		this.firstSearch = 1;
		this.requestData(1);
		this.paginate();
	}
});
