// Instantiate a couple of important global variables
var goAllEntries = new Array();  // Array of all the XML 'entry' nodes
var glRows = new Array();        // Array of all ClipTableRow objects
var glShownRows = new Array();   // Array of all ClipTableRow objects we are showing on all pages
var goMainTable;                 // HTMLEntity: document.getElementById('mainTable')
var gsSortedBy;                  // String: ClipTableRow attribute name to sort by
var giPerPage;                   // Number of rows to display on the page
var vsDirection = "Up";          // Direction by which we are sorting



// Class definition for the page navigation table
function PaginationTable(xiCurPage) {

	// figure out how many pages we need to display the data
	function roundUp(xfRoundMe) { return (xfRoundMe - (xfRoundMe % 1) + 1) };
	var viPagesNeeded = roundUp((glShownRows.length - 1)/ giPerPage);


	// create the table (this.poTable) and set its attributes
	this.poTable = document.createElement("table");
	this.poTable.className = "pagination";
	this.poTable.cellspacing = "0";
	this.poTable.cellpadding = "0";


	// create the row and cell objects
	this.poRow = document.createElement("tr");
	this.poCells = new Array();
	for (var i = 0; i < viPagesNeeded + 2; i++) this.poCells[i] = document.createElement("td");

	// a cell with '<' as a 'previous page' button
	this.poCells[0].className = "outside";
	this.poCells[0].align = "right";
	if (xiCurPage == 1) {
		this.poCells[0].innerHTML = "&lt; ";
	} else {
		this.poCells[0].innerHTML = "<a href='javascript: toPage(" + (xiCurPage-1).toString() + ");'>&lt; </a>";
		
	}

	// the numbered cells
	var vlNums = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty"];
	for (var i = 1; i <= viPagesNeeded; i++) {
		this.poCells[i].id = vlNums[i+1];
		this.poCells[i].align = "center";
		
		vlNums[i+1].className = "topOn";
		
		
		if (i == xiCurPage) {
			
			// smb edit
			this.poCells[i].className = 'topOn';
			this.poCells[i].innerHTML = i.toString();
		} else {
			this.poCells[i].className = 'topOff';
			this.poCells[i].innerHTML = "<a href='javascript: toPage("+ i.toString() +")' onmouseover='changeClass(\""+ vlNums[i+1] +"\",\"topOn\");' onmouseout='changeClass(\""+ vlNums[i+1] +"\",\"topOff\");'>"+ i.toString() +"</a>";
		}
	}

	// a cell with '>' as a 'next page' button
	this.poCells[viPagesNeeded + 1].className = "outside";
	this.poCells[viPagesNeeded + 1].align = "left";
	if (xiCurPage == viPagesNeeded){
		this.poCells[viPagesNeeded + 1].innerHTML = "&gt; ";
	} else {
		this.poCells[viPagesNeeded + 1].innerHTML = "<a href='javascript: toPage(" + (xiCurPage+1).toString() + ");'> &gt;</a>";
	}


	// append the cells to the row
	for (var i = 0; i < this.poCells.length; i++) {
		this.poRow.appendChild(this.poCells[i]);
	}


	// append the row to the table
	this.poTBody = document.createElement("tbody");
	this.poTBody.appendChild(this.poRow);
	this.poTable.appendChild(this.poTBody);

}



// Class definition for a clip archive table row
function ClipTableRow(xoEntry) {

	// get all the needed information out of XML
	this.piClipId = parseInt(xoEntry.getAttribute("piClipId"));
	this.piTimeScale = parseInt(xoEntry.getAttribute("piTimeScale"), 10);
	this.piDate = parseInt(xoEntry.getAttribute("piDate"), 10);
	this.pfRating = parseFloat(xoEntry.getAttribute("pfRating"));
	this.psVisName = xoEntry.getAttribute("psVisName");
	this.psThumbnailFileName = xoEntry.getAttribute("psThumbnailFileName");
	this.psDownloadURL = xoEntry.getAttribute("psDownloadURL");
	this.psType = xoEntry.getAttribute("psType");
	this.psTopic = xoEntry.getAttribute("psTopic");
	this.psTimeScale = xoEntry.getAttribute("psTimeScale");
	this.psDate = xoEntry.getAttribute("psDate");
	this.piVotes = xoEntry.getAttribute("piVotes");
	
	//changes by MAT
	var psDescription = xoEntry.getElementsByTagName("description")[0].childNodes[0].nodeValue;
	
	if (this.piClipId == 71){
		//Single tests here (to avoid looping)
	}
	if (psDescription.length > 150) psDescription = psDescription.substring(0, 150) + "...";

	// create the TR HTMLEntity, call it this.voRow
	this.psHtml = new Array();
	this.psHtml[this.psHtml.length] = "<a href='javascript:mSetVarInFlash(\"nav_swf\",\"piVideoFromJS\",\""+this.piClipId+"\");mPopupVideo();'><img src='/thumbnails/"+this.psThumbnailFileName+"' alt='"+this.psVisName+"' title='"+this.psVisName+"' width='100' height='100' /></a>";
	this.psHtml[this.psHtml.length] = this.DownloadURL == null ? "<div width='300'><span class='archiveHead'>"+this.psVisName+"</span><br />"+psDescription+"</div>" : "<div width='300'><span class='archiveHead'>"+this.psVisName+"</span><br />"+psDescription+"<br /><span class='archiveSubhead'><a href='"+this.psDownloadURL+"'>Quicktime download - fullsize</a></span></div>";
	this.psHtml[this.psHtml.length] = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="66" height="23" id="rating'+this.piClipId+'" align="middle"><param name="allowScriptAccess" value="sameDomain" /><param name="movie" value="archive/rating.swf?pfRating='+this.pfRating+'&piClipId='+this.piClipId+'" /><param name="quality" value="high"/><param name="bgcolor" value="#E2F8F6" /><embed src="archive/rating.swf?pfRating='+this.pfRating+'&piClipId='+this.piClipId+'" quality="high" bgcolor="#E2F8F6" width="66" height="23" name="rating'+this.piClipId+'" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object><br /><span class="subhead">Votes: '+this.piVotes+'</span>';
	this.psHtml[this.psHtml.length] = this.psTimeScale;
	this.psHtml[this.psHtml.length] = this.psType;
	this.psHtml[this.psHtml.length] = this.psTopic;
	this.psHtml[this.psHtml.length] = this.psDate;
	this.voRow = document.createElement("tr");
	this.vlTDs = new Array();
	for (var i = 0; i < this.psHtml.length; i++){
		this.vlTDs[i] = document.createElement("td");
		switch(i){
			case 0: 
				this.vlTDs[i].className = "imageCell";
				break;
			case 1:
				this.vlTDs[i].className = "topOff";
				break;
			case 2:
			case 3:
			case 4:
			case 5:
			case 6:
				this.vlTDs[i].className = "topOff";
			case 7:
				this.vlTDs[i].align = "center";
		}
		this.vlTDs[i].innerHTML = this.psHtml[i];
		this.voRow.appendChild(this.vlTDs[i]);
	}
}


// callback function for archive XML retrieval - gets placed in ajaxManager.js => loadXML()
function handleArchiveXML() {
	if (BrowserDetect.browser == "Explorer") {
		var voMSXMLDoc = new ActiveXObject("MSXML2.DOMDocument");
		voMSXMLDoc.loadXML(goXHR.responseText);
		goAllEntries = voMSXMLDoc.getElementsByTagName("entry");
	} else {
		goAllEntries = goXHR.responseXML.getElementsByTagName("entry");
	}
	
	giPerPage = goAllEntries.length;
	
	glRows = [];
	glShownRows = [];
	
	goMainTable = document.getElementById("mainTable");
	for (var i = 0; i < goAllEntries.length; i++) {
		glRows.push(new ClipTableRow(goAllEntries[i]));
		glShownRows.push(new ClipTableRow(goAllEntries[i]));
	}
	reorderTableRows('psVisName', 1);
	
	voOuterDiv = document.getElementById("outer");
	voOuterDiv.style.visibility = "visible";
	voPreloader = document.getElementById("preloader");
	voPreloader.style.visibility = "hidden";
	
	var voKeywordField = document.getElementById("keywords");
	voKeywordField.onfocus = activateEnterCapture;
	voKeywordField.onblur = deactivateEnterCapture;
}



function activateEnterCapture(){
	var voKeywordField = document.getElementById("keywords");
	if (BrowserDetect.browser == "Explorer") {
		document.onkeydown = function(e){
			if (window.event.keyCode == 13){
				formSubmit();
			}
		};
	} else {
		document.onkeypress = function(e){
			if (e.which == 13){
				formSubmit();
			}
		};
	}
}

function deactivateEnterCapture(){
	if (BrowserDetect.browser == "Explorer") {
		document.onkeydown = function(){return;};
	} else {
		document.onkeypress = function(){return;};
	}
}



// Sort an array of objects by a common property
function sortObjectsBy(xsSortBy, xlSortMe) {
	function sortHelper(a,b) {
		if (typeof a[xsSortBy]=="number" && typeof b[xsSortBy]=="number") return a[xsSortBy] - b[xsSortBy];
		if (a[xsSortBy].toString().toLowerCase() == b[xsSortBy].toString().toLowerCase()) return 0;
		return a[xsSortBy].toString().toLowerCase() > b[xsSortBy].toString().toLowerCase() ? 1 : -1;
		}
	return xlSortMe.sort(sortHelper);
}



function reorderTableRows(xsSortBy, xiPage) {
	
	// 'hotkey' the body of the mainTable
	var voTbody = goMainTable.getElementsByTagName("tbody")[0];
	
	// resort or reverse the rows
	if (!arguments[2]) {
		sortObjectsBy(xsSortBy, glShownRows);
		vsDirection = "Up";
	} else {
		if(gsSortedBy != xsSortBy) {
			sortObjectsBy(xsSortBy, glShownRows);
			vsDirection = "Up";
		} else {
			glShownRows.reverse();
			var vsNewDirection = vsDirection == "Up" ? "Down" : "Up";
			vsDirection = vsNewDirection;
		}
	}
	gsSortedBy = xsSortBy;
	
	// remove all the generated rows of the table
	while (voTbody.childNodes.length > 1) {
		voTbody.removeChild(voTbody.childNodes[1]);
	}
	
	var viStart = ((xiPage - 1) * giPerPage);
	var viEnd = Math.min(xiPage * giPerPage, glShownRows.length);
	
	// place the rows back into the table
	var curRowObj;
	for (var i = viStart; i < viEnd; i++) {
		curRowObj = glShownRows[i];
		if (curRowObj.voRow) voTbody.appendChild(curRowObj.voRow);
		else break;
	}
	
	// remove the pagination table
	var paginationDiv = document.getElementById('pagination');
	paginationDiv.innerHTML = "";
	
	// replace the pagination table
	var newPagTable = new PaginationTable(xiPage);
	paginationDiv.appendChild(newPagTable.poTable);
	
	// hide all the sort indicator images
	var imgs = [];
	var allimgs = document.getElementsByTagName("img");
	for (var i = 0; i < allimgs.length; i++) {
		if (allimgs[i].className == "indicator") {
			imgs.push(allimgs[i]);
		}
	}
	for (var i = 0; i < imgs.length; i++) {
		imgs[i].style.display = "none";
	}
	
	// show the sort indicator image that we want
	var img = document.getElementById(xsSortBy+vsDirection);
	img.style.display="inline";
	
}



function toPage(xiPage) {
	// 'hotkey' the body of the mainTable
	var voTbody = goMainTable.getElementsByTagName("tbody")[0];
	
	// remove all the generated rows of the table
	while (voTbody.childNodes.length > 1) {
		voTbody.removeChild(voTbody.childNodes[1]);
	}
	
	var viStart = ((xiPage - 1) * giPerPage);
	var viEnd = Math.min(xiPage * giPerPage, glShownRows.length);
	
	// place the rows back into the table
	var curRowObj;
	for (var i = viStart; i < viEnd; i++) {
		curRowObj = glShownRows[i];
		if (curRowObj.voRow) voTbody.appendChild(curRowObj.voRow);
		else break;
	}
	
	// remove the pagination table
	var paginationDiv = document.getElementById('pagination');
	paginationDiv.innerHTML = "";
	
	// replace the pagination table
	var newPagTable = new PaginationTable(xiPage);
	paginationDiv.appendChild(newPagTable.poTable);
}


function ajaxSearch(xsKeywords) {
	// get rid of commas and periods with a regExp
	var xlKeywords = xsKeywords.split(" ");
	var voPunc = /[.,]+/g;
	var vlFixedKWs = new Array();
	for (var i = 0; i < xlKeywords.length; i++) {
		vlFixedKWs.push(xlKeywords[i].replace(voPunc, ""));
	}
	var vsSearchString = vlFixedKWs.join("%20");
	
	var vfCallback = function() {
		if (goXHR.readyState == 4 && goXHR.status == 200) {
			var vsIDs = goXHR.responseText;
			var vlIDs = vsIDs.split(" ");
			
			glShownRows = [];
			
			for (var j = 0; j < vlIDs.length; j++) {
				for (var i = 0; i < glRows.length; i++) {
					if (parseInt(vlIDs[j]) == glRows[i].piClipId) glShownRows.push(glRows[i]);
				}		
			}
			
			reorderTableRows(gsSortedBy, 1);
			
			var voResultDiv = document.getElementById("searchResult");
			if (xsKeywords == "" || xsKeywords == null) {
				voResultDiv.innerHTML = "";
			} else {
				if (vlIDs.length == 1 && vlIDs[0] == "") viResults = 0;
				else viResults = vlIDs.length;
				voResultDiv.innerHTML = "your search returned "+viResults+" results.<a style=\"margin-left: 5px;\" href=\"javascript: formSubmit(true);\"><font color=\"#54ccbb\">Show All</font></a>";
				
				
				
			}
		}
	}
	
	ajaxRequest("/php/search.php?q="+vsSearchString, null, vfCallback);
}


function formSubmit() {
	var voTextField = document.getElementById('keywords');
	var vsSearchVal = voTextField.value;
	if (arguments[0]) vsSearchVal = "";
	ajaxSearch(vsSearchVal);
}


