
//
// Table
// ( Loads data from ajax and JSON)
//
var Table = Class
		.create( {
			initialize : function(TableID, options) {
				this.id = TableID;
				this.container = $(TableID + 'Container');
				this.data = null;
				this.firstLoad = true;

				this.currentCommand = null;
				this.options = Object.extend( {
					url : false, // url JSON data
					formUrl : "",
					multiselect : false,
					showID :false,
					find : false,
					findText : "",
					tabs : false,
					onloadForm : false,
					nested : false,
					execute : false,
					executecmd : false
				}, options || {});
				this.container.innerHTML = "";

				if (History.get('elementid') && this.options.nested != true) {
					this.container.innerHTML = "";
					this.FormLoad(History.get('elementid'));
				} else {
					if (History.get('page') && this.options.nested != true)
						this.setPage(History.get('page'));
					else
						this.LoadData('getdata');
				}
				// methods
				this.findChange = this.findAction.bindAsEventListener(this);

				// get methods

			},
			
			Execute : function() {
				//if (this.firstLoad) {
					this.options.execute();
				//}
			},
			
			FormLoad : function(itemId) {
				if (this.options.formUrl!="") {
					// if periodical search is runing stop it
					if (this.findUpdater)
						this.findUpdater.stop();
					new Ajax.Updater(this.container, this.options.formUrl, {
						method : 'get',
						encoding : 'UTF-8',
						parameters : {
							q : 'form',
							form : this.id,
							id : itemId
						},
						onSuccess : function(request) {
							History.set('elementid', itemId);
						},
						onComplete : function() {
							// execute onload form function
						if (this.options.onloadForm != false)
							this.options.onloadForm();
						
					}.bind(this)
					});
				}
			},

			TableWrite : function() {

				this.CreateTable();

				// Table Controls
				if (this.firstLoad == true)
					this.CreateControls();

				if (this.data.Data != null) {
					// Create Table Header
					this.CreateHeaders();

					// Create Rows
					this.data.Data.each(function(item, index) {
						this.AddRow(item, index)
					}.bind(this));

					// Page info
					this.PrintPageInfo();
				}

				// show Tabs
				this.showTabs();

				// show Filters
				this.showFilters();

				// Create table Events
				this.createObservers();
				
				if (this.options.execute) {
					this.Execute();
				}
				
				this.firstLoad = false;
			},

			//
			// Load JSON data from url
			//
			LoadData : function(command) {

				new Ajax.Request(this.options.url + '&cmd=' + command, {
					encoding : 'UTF-8',
					onLoading : function() {
					}.bind(this),
					onSuccess : function(transport) {
						this.data = transport.responseJSON;
						this.TableWrite();
						History.set('page', this.data.Info.page);
						
					}.bind(this),
					onFailure : function() {
						alert('invalid data');
					}
				});
			},

			//
			// Add new row to table
			//
			AddRow : function(rowObj, index) {
				var rowObj = rowObj;
				var rowData = Object.values(rowObj);
				var rowid;

				// pair row (for color)
				if ((index % 2) == 0)
					var ispair = 'pair';
				else
					var ispair = 'unpair';

				var tr = new Element('tr', {
					'class' : ispair
				});

				var firstTD = true;
				rowData.each(function(item) {
					if (firstTD == true) {
						if (this.options.multiselect == true) {
							tr.id = 'rowdb_' + item;
							tr.insert(new Element('td', {
								'id' : 'slctrow_' + item,
								'class' : 'edit'
							}).update('<input type="checkbox" value=true>'));
						}
						// if showID is true (show id cell)
						if(this.options.showID == true)
							tr.insert(new Element('td').update(item));
					} else
						tr.insert(new Element('td').update(item));
					firstTD = false;
				}.bind(this));

				$(this.id + 'AjaxTable').down('tbody').insert(tr);
			},

			//
			// Create Table Structure into container
			//
			CreateTable : function() {
				if (this.firstLoad == true) {
					// insert controls row
					this.container
							.insert( {
								top : '<div id="' + this.id + '_controls" class="AjaxTableControls"></div>'
							});
					// insert tabs row
					this.container
							.insert( {
								top : '<div id="' + this.id + '_tabs" class="AjaxTableTabs"></div>'
							});
					// insert fix commands
					this.container
							.insert( {
								top : '<div id="' + this.id + '_fixcommands" class="AjaxTableFixCmds"></div>'
							});

				} else {
					$(this.id + '_tb').remove();
					// this.container.update();
				}

				var Tabl = new Element('div', {
					'id' : this.id + '_tb'
				});

				Tabl
						.insert( {
							top : '<table  id="' + this.id + 'AjaxTable" class="AjaxTable" align="center"><thead></thead><tbody></tbody></table>'
						});
				Tabl
						.insert( {
							bottom : '<div id="' + this.id + '_pager" class="AjaxTablePager"></div>'
						});

				this.container.insert(Tabl);
			},

			//
			// Create Table Headers
			//
			CreateHeaders : function() {
				var hdrs = Object.values(this.data.headers);

				var tr = new Element('tr', {});

				var firstLoad = true;
				hdrs.each(function(item, index) {
					if (firstLoad == true){
						tr.insert(new Element('td', {
							'id' : item.id + ''
						}).update(''));
						// if showID is true (show id cell)
						if(this.options.showID == true)
							tr.insert(new Element('td', {
								'id' : item.id + ''
							}).update(item.name + this.OrderPicture(item.order)));
					}
					else
						tr.insert(new Element('td', {
							'id' : item.id + ''
						}).update(item.name + this.OrderPicture(item.order)));
					firstLoad = false;
				}.bind(this));

				$(this.id + 'AjaxTable').down('thead').insert(tr)
			},

			//
			// Create Table Controls
			//
			CreateControls : function(firstLoad) {
				// find control
				if (this.options.find == true)
					$(this.id + '_controls')
							.insert(
									{
										top : '<input id="' + this.id + 'Find" class="searchReady" value=""></input>'
									});

				// command controls span
				$(this.id + '_controls').insert( {
					bottom : '<span id="' + this.id + 'Commands"></span>'
				});
			},

			//
			// Print page info
			// (number of pages and aditional information)
			//
			PrintPageInfo : function() {
				var nextBtn = ' <span id="' + this.id + 'NextPage" class="AjaxTableBTN" ><div id="next">&nbsp;&nbsp;&nbsp;</div></span>';
				var prevBtn = '<span id="' + this.id + 'PrevPage" class="AjaxTableBTN" ><div id="prev">&nbsp;&nbsp;&nbsp;</div></span> ';
				if(this.options.nested != true){	
					$(this.id + '_pager').insert(
						{		
							top : '<div class="totregs">'+this.data.Info.totalregs + ' Registros</div> &emsp;&emsp;&emsp;' 
							+ prevBtn + 'Págs' + this.data.Info.page + ' / ' + this.data.Info.pages +  nextBtn 
						});
			
				}
				else{
					$(this.id + '_pager').insert(
						{		
							top : '<div class="totregs">'+this.data.Info.totalregs + ' Registros</div> &emsp;&emsp;&emsp;' 
							+ prevBtn + 'Págs ' + this.data.Info.page + ' / ' + this.data.Info.pages +  nextBtn
						});
				}
			},

			//
			// Delete all table
			// show header cell order picture (up or down)
			//
			OrderPicture : function(ord) {

				if (ord > 0)
					return '<span class="OrdUp">&nbsp;&nbsp;&nbsp;&nbsp; </span>';
				else if (ord < 0)
					return '<span class="OrdDown">&nbsp;&nbsp;&nbsp;&nbsp; </span>';
			},

			setSelectedRow : function(row) {
				if (row.hasClassName('selected')) {
					// mark as unselected
					row.removeClassName('selected');
				} else {
					// mark as selected
					row.addClassName('selected');
				}
			},

			showTabs : function() {

				if (this.options.tabs != false) {
					var tabs = '<ul>';
					var tabCommands;
					var currentSel = this.data.filters.status;

					this.options.tabs.each(function(item) {
						// if is selected tab
							if (currentSel == item.id)
								var clss = "selected";
							else
								var clss = ""
							tabs = tabs + '<li class="' + clss + '" id="tab_'
									+ item.id + '">' + item.name + '</li>';
						}.bind(this));

					tabs = tabs + '</ul>';

					// print Tabs
					$(this.id + '_tabs').innerHTML = "<div id='new_" + this.id
							+ "' class='new'>Nuevo</div>";
					$(this.id + '_tabs').insert(tabs);

					// fix table commands
					$(this.id + '_fixcommands').innerHTML = "";
					this.options.tabs.each(function(e){
							if (e.id == currentSel)
								if(e.fixactions) {
									e.fixactions.each(function(e){
										$(this.id + '_fixcommands').insert(
												{
													top : '<a href="'+e.url+'"><img title="'+e.title+'" class="fixcommandBTN" src="Templates/images/'+e.icon+'" border=0/></a>'
												});
									}.bind(this));
								}
					}.bind(this));


					// asign Tab events
					this.options.tabs.each(function(item) {
						$('tab_' + item.id).observe('click',
								this.tabClick.bindAsEventListener(this));
					}.bind(this));

					//
					// Show command tabs
					//
					// look for the tab commands
					this.options.tabs.each(function(item) {
						if (item.id == currentSel)
							tabCommands = item.commands;

					}.bind(this));

					// Print commands
					$(this.id + 'Commands').innerHTML = " ";

					tabCommands.each(function(item) {
						$(this.id + 'Commands').insert(
								'<a id="command_' + item.id + '" >' + item.name
										+ '</a> ');
						// asign command events
						if (this.options.executecmd && item.id === this.options.executecmd){
							//establece como comando para a execucion de javascript o indicado en options.executecmd
						}
						else {
							$('command_' + item.id)
									.observe(
											'click',
											this.commandClick
													.bindAsEventListener(this));
							}
						}.bind(this));

					this.currentCommand = tabCommands;
				}
			},

			showFilters : function() {

				if (this.options.find == true) {
					if (this.data.filters.find == false) {
						if (this.firstLoad) {
							if (this.options.findText == "")
								$(this.id + 'Find').value = "Buscar...";
							else {
								$(this.id + 'Find').value = this.options.findText;
							}
						}
					} else
						$(this.id + 'Find').value = this.data.filters.find;
				}

			},

			getSelectedRows : function() {
				var rowsList = "";
				var comma = "";

				var row = $(this.id + 'AjaxTable').down('tbody').down('tr');

				while (row) {
					if (row.hasClassName('selected')) {
						rowsList = rowsList + comma + row.id.substring(6, 20);
						comma = ",";
					}
					row = row.next();

				}

				return rowsList;

			},

			//
			//
			// EVENTS
			//
			//

			createObservers : function() {

				var tabl = this.id;

				// Row Click
				$$('#' + tabl + 'AjaxTable tbody tr td').invoke('observe',
						'click', this.trClick.bindAsEventListener(this));

				// Header Click
				$$('#' + tabl + 'AjaxTable thead tr').invoke('observe',
						'click', this.headClick.bindAsEventListener(this));

				// Table Pager
				$$('#' + tabl + 'NextPage').invoke('observe', 'click',
						this.nextPage.bindAsEventListener(this));
				$$('#' + tabl + 'PrevPage').invoke('observe', 'click',
						this.prevPage.bindAsEventListener(this));

				// New element
				$$('#new_' + this.id).invoke('observe', 'click',
						this.FormLoad.bind(this));

				// Find actions
				if (this.options.find == true) // if find element exist
				{
					// find click
					$$('#' + this.id + 'Find').invoke('observe', 'click',
							this.findClick.bindAsEventListener(this));

					this.previousFindValue = $(this.id + 'Find').value;

					if (!this.findUpdater)
						this.findUpdater = new PeriodicalExecuter(
								this.findChange, 0.3);

				}

			},
			trClick : function(e) {
				var elm = Event.findElement(e, 'td')

				if (elm.identify().substring(0, 7) == 'slctrow') {
					this.setSelectedRow(Event.findElement(e, 'tr'));
				} else
					this.FormLoad(elm.up().id.substring(6, 20));

			},

			headClick : function(e) {
				var trHead = Event.findElement(e, 'td')
				this.LoadData('orderby&headerid=' + trHead.id);
			},

			setPage : function(page) {
				this.LoadData('pageset&page=' + page);
			},

			nextPage : function() {
				this.LoadData('pagenext');
			},

			prevPage : function() {
				this.LoadData('pageprev');
			},

			// Find methods
			findClick : function() {
				$(this.id + 'Find').value = "";
			},
			
			ntildeEncode : function(str) {
				return str.replace('ñ', '%C3%B1');
			},
			
			findAction : function() {
				if (!$(this.id + 'Find'))
					return 0;

				var Stamp = new Date();

				var actualTime = Stamp.getHours().toString()+Stamp.getSeconds().toString();

				// console.log(this.findLastChange + ' check ' + actualTime);

				if (this.findLastChange < (actualTime - 1)
						&& this.timerSwitch == 'on') {
					var termino = $(this.id + 'Find').value;
					if(termino.search(/ñ/i) != -1) {
						termino = this.ntildeEncode(termino);
					}
					//console.debug('termino=' + termino);
					this.LoadData('find&term=' + termino);
					// / Aparence
					$(this.id + 'Find').removeClassName('searching');
					$(this.id + 'Find').addClassName('searchReady');

					this.findLastChange = actualTime;
					this.timerSwitch = 'off';
				}

				if ($(this.id + 'Find').value != this.previousFindValue) {
					this.findLastChange = actualTime;
					this.timerSwitch = 'on'
					// / Aparence
					$(this.id + 'Find').removeClassName('searchReady');
					$(this.id + 'Find').addClassName('searching');
				}

				this.previousFindValue = $(this.id + 'Find').value

			},

			tabClick : function(e) {
				var tab = Event.findElement(e, 'li');

				this.LoadData('tabSet&tab=' + tab.id.substring(4, 20));
			},

			commandClick : function(e) {
				var cmd = Event.findElement(e, 'a');
				var command;
				;
				this.currentCommand.each(function(item) {
					if (cmd.id.substring(8, 20) == item.id)
						this.LoadData(item.command + '&items='
								+ this.getSelectedRows());
				}.bind(this));

			}
		});
