﻿ACCP.Controls.Listing = Class.create();
Object.extend(ACCP.Controls.Listing.prototype,
{
	initialize : function(elemId, minimizeEmailAddress, columns, rows, totalRowsOfData, url, identifier, iconify, actions, emailize, nonSortables, noRecordsMessage)
	{
		this.minimizeEmailAddress = minimizeEmailAddress;
		this.emailize = emailize;
		this.actions  = actions;
		this.iconify	= iconify;
		this.columns	= columns;
		this.rows			= rows;
		this.elem			= $(elemId);
		this.id				= elemId;
		this.pageNum	= 1;
		this.sortBy		= "";
		this.cells    = new Array();
		this.highlightClass		= "listing-selected-column-td";
		this.unhighlightClass = "";
		this.sortDirection = "asc";
		this.leftArrow = false;
		this.leftArrowText = "< Back";
		this.leftArrowClass = "listing-arrow-left";
		this.leftArrowHoverClass = "listing-arrow-left-hover";
		this.leftArrowDisabledClass = "listing-arrow-disabled";
		this.rightArrow = false;
		this.rightArrowClass = "listing-arrow-right";
		this.rightArrowHoverClass = "listing-arrow-right-hover";
		this.leftArrowDisabledClass = "listing-arrow-right-disabled";
		this.rightArrowText = "Next >";
		this.topBar = false;
		this.topBarClass = "listing-top-bar";
		this.totalRowsOfData = totalRowsOfData;
		this.numbersIndicator = false;		
		this.numbersIndicatorClass = "listing-numbers";
		this.listingClass = "listing";
		this.rowOddHoverClass = "listing-row-odd-hover";
		this.rowEvenHoverClass = "listing-row-even-hover";
		this.url = url;
		this.identifier = identifier;
		this.ajaxLoader = false;
		this.ajaxShader = false;
		this.mainTable = false;
		this.nonSortables = nonSortables;			
		this.noRecordsMessage = noRecordsMessage;
		this.noRecordsDiv = false;
		this.noRecordsExist = false;
		this.headers = new Array();
	},
	sort : function(col, sortDirection)
	{
		if (col != "")
		{
			this.pageNum = 1;
			if (ACCP.General.Exists(sortDirection))
			{
				this.sortDirection = sortDirection;
			}
			else
			{
				if (col == this.sortBy)
				{
					this.sortDirection = ((this.sortDirection == "asc") ? "desc" : "asc");
				}
				else
				{
					this.sortDirection = "desc";
				}		
			}
			
			for (var j in this.columns)
			{
				if (!ACCP.General.Exists(this.nonSortables[j]))
				{
					this.headers[j].className = "listing-data-table-header";
				}				
			}
			
			this.headers[col].className = "listing-data-table-header listing-data-table-header-" + this.sortDirection;
			
			this.sortBy = col;
		}
		this.getNewData();		
	},
	getNewData : function()
	{
		this.disableButtons();
		this.ajaxLoader = document.createElement("div");
		this.ajaxLoader.className = "listing-ajax-loader";
		this.ajaxLoader.style.height = this.mainTable.offsetHeight + "px";
		this.ajaxLoader.style.width = this.mainTable.offsetWidth + "px";
		var position = ACCP.General.GetPosition(this.mainTable);
		this.ajaxLoader.style.left = position.x + "px";
		this.ajaxLoader.style.top = position.y + "px";
		this.ajaxShader = this.ajaxLoader.cloneNode(false);
		this.ajaxShader.className = "listing-ajax-shader";
		document.body.appendChild(this.ajaxLoader);
		document.body.appendChild(this.ajaxShader);
		
		Listing.GetNewData(this.id, this.rows, this.pageNum, this.sortBy, this.sortDirection, this.fillGrid.bind(this));
	},
	clearTable : function()
	{
		for (var i = 1; i < this.cells.length; i++)
		{
			for (var j in this.columns)
			{
				this.cells[i][j].innerHTML = "&nbsp;";
				this.cells[i][j].className = this.unhighlightClass;
				this.cells[i][j].identifier = false;
				this.cells[i][j].onclick = null;
				this.cells[i][j].href = null;
				
				if (ACCP.General.Exists(this.nonSortables[j]))
				{
					this.cells[i][j].className = "listing-cell-no-sort";
				}
			}
		}
	},
	fillGrid : function(response)
	{
		if (this.ajaxLoader)
		{
			this.ajaxShader.parentNode.removeChild(this.ajaxShader);
			this.ajaxLoader.parentNode.removeChild(this.ajaxLoader);
		}
		this.clearTable();

		// If there are fewer rows returned than we have space for, then we'll hide the empty ones.
		if (this.rows > response.value["Rows"].length)
		{
			for (var i = response.value["Rows"].length; i < this.rows; i++)
			{
				for (var j in this.columns)
				{
					this.cells[i+1][j].parentNode.style.display = "none";
					break; // Run it just once.
					//this.cells[i+1][j].style.display = "none";
				}			
			}
		}
		else
		{
			for (var i = 0; i < this.rows; i++)
			{
				for (var j in this.columns)
				{
					this.cells[i+1][j].parentNode.style.display = "";
					break; // Run it just once.
					//this.cells[i+1][j].style.display = "";
				}			
			}
		}

		// If no records were returned...
		if (response.value["Rows"].length == 0 && !this.noRecordsDiv)
		{
			counter = 0;
			for (var j in this.columns)
			{
				counter++;
			}
			
			var td = document.createElement("td");
			this.noRecordsDiv = td;
			td.colSpan = counter;
			td.innerHTML = this.noRecordsMessage;
			var tr = document.createElement("tr");
			tr.appendChild(td);
			this.mainTable.firstChild.appendChild(tr); // Have to add it to "tbody" instead of "table"
			this.noRecordsExist = true;
			this.disableButtons();
		}

		for (var i = 0; i < this.rows && i < response.value["Rows"].length; i++)
		{			
			for (var j in this.columns)
			{
				this.cells[i+1][j].identifier = response.value["Rows"][i][this.identifier];
				// Make sure that the data is not null.
				if (ACCP.General.Exists(response.value["Rows"][i][j]))
				{
					// If this field should be an icon representing a file
					if (this.iconify[j])
					{												
						if (isNaN(parseInt(this.iconify[j])) == false)
						{
							this.cells[i+1][j].innerHTML = ""; // Clear out anything that used to be there.
							var iconDiv = document.createElement("div");
							iconDiv.className = ACCP.Template.Iconify(response.value["Rows"][i][j]);
							this.cells[i+1][j].appendChild(iconDiv);
						}
						else
						{						
							this.cells[i+1][j].innerHTML = response.value["Rows"][i][j];
							this.cells[i+1][j].style.width = "20px";
						}						
					}
					else
					{
						// If this cell has an email field that we want to link to...
						if (this.emailize[j])
						{
							if (response.value["Rows"][i][j] != "")
							{
								if (this.minimizeEmailAddress)
								{
									this.cells[i+1][j].innerHTML = "<a href='mailto:"+ response.value["Rows"][i][j].replace("''", "'") + "'>E-mail</a>";
								}
								else
								{
									this.cells[i+1][j].innerHTML = "<a href='mailto:"+ response.value["Rows"][i][j].replace("''", "'") + "'>" + response.value["Rows"][i][j].replace("''", "'") + "</a>";
								}
							}
							else
							{
								this.cells[i+1][j].innerHTML = "&nbsp;";
							}
						}
						else
						{
							if (typeof response.value["Rows"][i][j] == "string")
							{
								if (response.value["Rows"][i][j] == "")
								{
									this.cells[i+1][j].innerHTML = "&nbsp;";
								}
								else
								{
									this.cells[i+1][j].innerHTML = response.value["Rows"][i][j].replace("''", "'");
								}
							}
							else if (typeof response.value["Rows"][i][j] == "object")
							{
								var date = response.value["Rows"][i][j];
								
								// Source: http://home.clara.net/shotover/datetest.htm
								
								var dy = date.getFullYear() 	// Get full year (as opposed to last two digits only)
								var dm = date.getMonth() + 1 	// Get month and correct it (getMonth() returns 0 to 11)
								if ( dy < 1970 ) dy = dy + 100; 	// We still have to fix the millennium bug
								var ys = new String(dy) 	// Convert year, month and date to strings
								var ms = new String(dm) 	 
								if ( ms.length == 1 ) ms = "0" + ms; 	// Add leading zeros to month and date if required
								ys = ms + "/" + ys;
								
								this.cells[i+1][j].innerHTML = ys;
							}
						}
					}					
				}				
				if (ACCP.General.Exists(this.actions[j]))
				{				
					var debug = ((window.location.toString().indexOf('debug') > -1) ? "&debug=1" : "");
			
					var url = this.actions[j][0].replace("[[row_id]]", this.cells[i+1][j].identifier)
					url += ((this.actions[j][0].indexOf("?") > -1) ? "&col_name="+j : "?col_name="+j);
					url += debug;
					
					var isPopup = this.actions[j][1];

					if (this.cells[i+1][j].innerHTML != "&nbsp;" && this.cells[i+1][j].innerHTML != "")
					{
						var rowLink = document.createElement("a");
						rowLink.href = url;
						if (isPopup)
						{
							rowLink.target = "_blank";
						}
						rowLink.innerHTML = this.cells[i+1][j].innerHTML;
						this.cells[i+1][j].innerHTML = "";
						this.cells[i+1][j].appendChild(rowLink);
					}
					else
					{
						this.cells[i+1][j].style.innerHTML = "&nbsp;";
						this.cells[i+1][j].style.textDecoration = "none";
					}
				}
			}
		}
		if (this.sortBy != "")
		{
			// Hightlight the necessary column, if applicable
			for (var i = 1; i <= this.rows; i++)
			{
				this.cells[i][this.sortBy].className = this.highlightClass;
			}
		}
		
		this.setNumbers();
		if ((this.pageNum) * this.rows < this.totalRowsOfData)
		{
			this.rightArrow.className = "listing-arrow-right";
		}
		else
		{
			this.rightArrow.className = "listing-arrow-right-disabled";
		}
		
		if (this.pageNum == 1)
		{
			this.leftArrow.className = "listing-arrow-left-disabled";
		}
		else
		{
			this.leftArrow.className = "listing-arrow-left";
		}
		
		
		if (!this.noRecordsExist)
		{
			this.enableButtons();
		}
		else
		{
			this.numbersIndicator.innerHTML = "Results 0 to 0 of 0";
		}
							
		ACCP.Template.ResizeDivs();
	},
	movePrevious : function()
	{
		if (this.pageNum > 1)
		{
			this.pageNum--;
			this.getNewData();			
		}		
	},
	moveNext : function()
	{
		if ((this.pageNum) * this.rows < this.totalRowsOfData)
		{
			this.pageNum++;
			this.getNewData();
		}
	},
	setNumbers : function()
	{
		this.numbersIndicator.innerHTML = "Results " + ((this.pageNum - 1) * this.rows + 1) + " to " + ((((this.pageNum) * this.rows) <= this.totalRowsOfData) ? ((this.pageNum) * this.rows) : this.totalRowsOfData) + " of " + this.totalRowsOfData;
	},
	disableButtons : function()
	{
		this.leftArrow.onclick = function() { };
		this.rightArrow.onclick = function() { };

		for (var j in this.columns)
		{
			this.headers[j].onclick = function() { };
			this.headers[j].style.cursor = "normal";
		}
	},
	enableButtons : function()
	{
		this.leftArrow.onclick = function(){ this.listing.movePrevious(); };
		this.rightArrow.onclick = function(){ this.listing.moveNext(); };
		
		for (var j in this.columns)
		{
			if (!ACCP.General.Exists(this.nonSortables[j]))
			{
				this.headers[j].onclick		= function() { this.listing.sort(this.colName) };
				this.headers[j].style.cursor = "pointer";
			}
		}
	},
	render : function()
	{
		this.elem.className = this.listingClass;		
	
		// Render the misc stuff
		this.numbersIndicator = document.createElement("span");
		this.numbersIndicator.className = this.numbersIndicatorClass;		
		this.setNumbers();
		
		this.leftArrow = document.createElement("a");
		this.leftArrow.className	= this.leftArrowClass;
		this.leftArrow.innerHTML	= this.leftArrowText;
		this.leftArrow.href = "javascript:void(0)";
		this.leftArrow.listing		= this;
		this.leftArrow.onclick = function(){ this.listing.movePrevious(); };
		this.leftArrow.onmouseover = function() { if (this.listing.pageNum > 1) this.className = this.listing.leftArrowHoverClass; };
		this.leftArrow.onmouseout  = function() { if (this.listing.pageNum > 1) this.className = this.listing.leftArrowClass; };
		
		this.rightArrow = document.createElement("a");
		this.rightArrow.className	= this.rightArrowClass;
		this.rightArrow.innerHTML	= this.rightArrowText;
		this.rightArrow.listing		= this;
		this.rightArrow.href = "javascript:void(0)";
		this.rightArrow.onclick = function() { this.listing.moveNext(); };
		this.rightArrow.onmouseover = function() { if ((this.pageNum) * this.rows < this.totalRowsOfData) this.className = this.listing.rightArrowHoverClass; };
		this.rightArrow.onmouseout  = function() { if ((this.pageNum) * this.rows < this.totalRowsOfData) this.className = this.listing.rightArrowClass; };
		
		this.topBar = document.createElement("div");
		this.topBar.className = this.topBarClass;		
		
		if (this.pageNum == 1 && this.rows + 1 >= this.totalRowsOfData)
		{
		
		}
		else
		{		
			this.topBar.appendChild(this.rightArrow);
			this.topBar.appendChild(this.leftArrow);		
		}		
		
		this.topBar.appendChild(this.numbersIndicator);		
	
		// Render the actual "data" region of the listing
		var table = document.createElement("table");
		this.mainTable = table;
		this.elem.appendChild(table);
		
		this.elem.appendChild(this.topBar);
		
		table.cellPadding = 0;
		table.cellSpacing = 0;
		
		var tbody = document.createElement("tbody");
		table.appendChild(tbody);
		
		for (var i = 0; i <= this.rows; i++)
		{
			var tableRow = document.createElement("tr");
			if (i > 0)
			{
				tableRow.className = ((i % 2 == 1) ? "listing-row-odd" : "listing-row-even");
			}
			
			tableRow.listing = this;
			
			if (i > 0)
			{
				tableRow.defaultClassName = tableRow.className;
				if (i % 2 == 1)
				{
					tableRow.onmouseover = function() { if (this.firstChild.identifier) { this.className = this.listing.rowOddHoverClass; } };
				}
				else
				{
					tableRow.onmouseover = function() { if (this.firstChild.identifier) { this.className = this.listing.rowEvenHoverClass; } };
				}
				tableRow.onmouseout = function() { if (this.firstChild.identifier) { this.className = this.defaultClassName; } };
			}
			
			tbody.appendChild(tableRow);
			
			for (var j in this.columns)
			{
				tableCell = document.createElement("td");
				tableRow.appendChild(tableCell);
				if (i == 0) // Then it is a header cell
				{					
					if (ACCP.General.Exists(this.nonSortables[j]))
					{
						tableCell.className = "listing-data-table-header-no-sort";	
						tableCell.innerHTML = "&nbsp;";
					}	
					else
					{
						tableCell.className = "listing-data-table-header";	
						tableCell.innerHTML = this.columns[j][0];
					}
					
					tableCell.listing		= this;
					tableCell.colName   = j;

					if (!ACCP.General.Exists(this.nonSortables[j]))
					{
						tableCell.onclick		= function(j) { this.listing.sort(this.colName) };
						tableCell.style.cursor = "pointer";
					}
					this.headers[j] = tableCell;
				}
				else
				{
					if (ACCP.General.Exists(this.nonSortables[j]))
					{
						tableCell.className = "listing-cell-no-sort";
					}					
				
					tableCell.innerHTML = "&nbsp;";					
					tableCell.listing = this;
					if (ACCP.General.Exists(this.cells[i]) == false)
					{
						this.cells[i] = new Array();
					}
					this.cells[i][j] = tableCell;
					if (this.url != "")
					{
						tableCell.onclick = function() 
																{
																	if (this.identifier)
																	{
																		if (this.listing.url.indexOf("?") > -1)
																		{
																			window.location = this.listing.url + ((this.identifier != null)?"&item_id="+this.identifier : "") 	
																		}	
																		else
																		{
																			window.location = this.listing.url + ((this.identifier != null)?"?item_id="+this.identifier : "") 	
																		}
																	}
																};
					}
				}
			}			
		}
	}
}, false);