/*********************************************************************************************
File: 		VoteInfo.js
Author:		Kris Felscher (kris@re-imaginations.com)
Date:		04/24/2007
Project:	talklikebobdylan.com
Description:
		This script will create a vote system that allows users to rank items according to
	their favorite submission.
	
Version History:
VERSION		DATE		AUTHOR			DESCRIPTION
1.0			04/24/2007	KPF				Initial Version

TODO:
	- Add category options
	- REMOVE STATIC PATHS (yes this is silly but I'm in a time crunch)
		->VoteInfo.prototype.BuildVoteGUI()
	
	- Build Thank you box
	- Add Voting Cookie
	- Build Error Handler CSS
*********************************************************************************************/

/*********************************************************************************************
Include Scripts
*********************************************************************************************/
//include_once('inc/js/VoteItem.js');
//include_once('inc/js/Ajax.js');
/* End Includes *****************************************************************************/

/* Methods **********************************************************************************/
//Constructor
function VoteInfo() {
	this._items = new Array();
	return this;
}

/* Prototype Properties *********************************************************************/
VoteInfo.prototype._items;
VoteInfo.prototype._voteDataURL;
VoteInfo.prototype._voteSubmitURL;
VoteInfo.prototype._parentContainer;

/* Prototype Methods ************************************************************************/
/* Build ******************************************
	Buids the voting GUI. First we check to see
	if we have submission data, if so we build the
	GUI. If not, we grab the information from
	the DB, then build the GUI.
**************************************************/
VoteInfo.prototype.Build = function() {
	if(this._voteDataURL && this._voteSubmitURL) {
		if (this._items.length) {
			if (!this.BuildVoteGUI()) {
				this.BuildErrorBox('VoteInfo->Build: Unable to display items.');	
			}
		} else { 
			//pull submissions from the database
			if (!this.GetItems()) {
				this.BuildErrorBox('VoteInfo->Build: Unable to retreive data.');
			}
		}
	} else {
		this.BuildErrorBox("VoteInfo->Build: URL's not specified");
	}
}

/* GetItems****************************************
	Pulls info from the database using Ajax.
**************************************************/
VoteInfo.prototype.GetItems = function() {
	//use _this to maintain scope when passing functions to the Ajax class
	_this = this;
	var ajax = new Ajax();
		if (ajax) {
			ajax._requestURL = this._voteDataURL;
			ajax._processor = function(data) {_this.ParseVoteData(data)};
			ajax._errorHandler = function(err) {_this.BuildErrorBox(err)};
			ajax._requestMethod = "GET";
			ajax._overrideMimeType = true;
			//make the Ajax request, if it fails, throw an error
			if (ajax.Connect()) {
				return true;
			} else {
				this.BuildErrorBox("VoteInfo->GetItems: Unable to connect to url");
				return false;
			}
		} else {
			this.BuildErrorBox("VoteInfo->GetItems: Unable to create Ajax Component");
			return false;
	}
}

/* RankItemUp ************************************
	Swaps items in the _items array
**************************************************/
VoteInfo.prototype.RankItemUp = function(item_index) {
	var itemHolder = this._items[item_index];
	this._items[item_index] = this._items[item_index-1];
	this._items[item_index-1] = itemHolder;
	this.Build();
}

VoteInfo.prototype.RankItemDown = function(item_index) {
	var itemHolder = this._items[item_index];
	this._items[item_index] = this._items[item_index+1];
	this._items[item_index+1] = itemHolder;
	this.Build();
}

VoteInfo.prototype.MoveItemToTop = function(item_index) {
	var itemHolder = this._items[item_index]
	//remove the item from the array
	this._items.splice(item_index,1);
	//add the item back to the array, we reverse the
	//array to make it easier
	this._items.reverse();
	this._items.push(itemHolder);
	//resort the array
	this._items.reverse();
	this.Build();
}

VoteInfo.prototype.SubmitVote = function() {}

/* BuildContainer *********************************
	Buids a containing DIV and adds it to the
	page using DOM.
**************************************************/
VoteInfo.prototype.BuildContainer = function() {
	var container = document.createElement('div');
		container.setAttribute('id','vote_container');
		container.setAttribute('class','container');
	try {
		if (this._parentContainer) {
			document.getElementById(this._parentContainer).appendChild(container);
		} else {
			document.body.appendChild(container);
		}
		return true;
	} catch (e) {
		//throw errors here as the ErrorHandler calls
		//this function to create a container.
		alert('VoteInfo->BuildContainer: Unable to attach objects to page');
		return false;
	}
}

/* BuildVoteGUI ***********************************
	Builds the voting Interface
**************************************************/
VoteInfo.prototype.BuildVoteGUI = function() {
	var innerHTML;
	//insert items into the container, this can
	//only be done if the container has been created.
	//If the BuildContainer method can't create one
	//we have to die here.
	if (document.getElementById('vote_container')) {
		//if the container exists, clear it out
		this.ClearVoteGUI;
	} else {
		this.BuildContainer();
	}

	//begin the basic innerHTML definition
	innerHTML = "<table class=\"container\">";
	for (var i = 0; i < this._items.length; i++) {
		innerHTML +=  "<tr class=\"" + ((i%2==0)?"submission":"submission_alt") + "\" id=\"submission_" + i + "\" onmouseover=\"this.className='submission_over'\" onmouseout=\"this.className='" + ((i%2==0)?"submission":"submission_alt") + "'\" onclick=\"vote.OpenDiv(" + i + ")\">"
        			+ 	"<td class=\"vote item\"><img src=\"/media/images/vote_images/item_" + i + ".gif\" /></td>" 
            		+ 	"<td class=\"vote info\"><span class=\"title\">" + this._items[i]._title +"</span><br /><span class=\"small\"><b>Submitted by: </b>" + this._items[i]._submitter + "</span></td>" 
            		+ 	"<td class=\"vote move\">"; 
        	if (i != 0) {
				innerHTML += " <a href=\"javascript:vote.RankItemUp(" + i + ")\" onmouseover=\"vote.SwapItemImage(" + i + ",'up','over')\" onmouseout=\"vote.SwapItemImage(" + i + ",'up','out')\"><img id=\"item_" + i + "_up\" src=\"/media/images/vote_images/arrow_up.gif\" border=\"0\" title=\"Move Up\"/></a>" 
			}
			if (i < this._items.length-1) {
				innerHTML += " <a href=\"javascript:vote.RankItemDown(" + i + ")\" onmouseover=\"vote.SwapItemImage(" + i + ",'down','over')\" onmouseout=\"vote.SwapItemImage(" + i + ",'down','out')\"><img id=\"item_" + i + "_down\" src=\"/media/images/vote_images/arrow_down.gif\"  border=\"0\" title=\"Move Down\"/></a>" 
			}
			if (i != 0) {
			    innerHTML += " <a href=\"javascript:vote.MoveItemToTop(" + i + ")\" onmouseover=\"vote.SwapItemImage(" + i + ",'top','over')\" onmouseout=\"vote.SwapItemImage(" + i + ",'top','out')\"><img id=\"item_" + i + "_top\" src=\"/media/images/vote_images/arrow_top.gif\"  border=\"0\"  title=\"Move To Top\"/></a></td>" 
			}
		innerHTML += 	"</td>"  
            		+ 	"<td class=\"vote rank\"><span class=\"big\">" + this._items[i]._points + "</span><br /><span class=\"small\">points</span></td>"
        			+ "</tr>"
					+ "<tr class=\"submission_info\" id=\"submission_" + i + "_data\">"
        			+ 	"<td colspan=\"4\">"
            		+ 		"<div class=\"video\">" + this._items[i]._embedData + "</div>"
                	+ 		"<div class=\"video_info\">"
                	+ 			"<p><span class=\"small strong\">Submitted by:</span><span class=\"small\">" + this._items[i]._submitter + "</span></p>"
                	+ 			"<p><span class=\"small strong\">Submitter's Website:</span><span class=\"small\"><a href=\"" + this._items[i]._submitter_url + "\" target=\"_blank\">" + this._items[i]._submitter_url + "</a><span></p>"
                    + 			"<hr />"
                    + 			"<p><span class=\"small strong\">Info</span></p>"
					+ 			"<p class=\"longtext\">" + this._items[i]._description + "</p>"
                	+ 		"</div>"
            		+ 	"</td>"
        			+ "</tr>";
	}
	innerHTML += "</table><div class=\"container_footer\"><a href=\"javascript:vote.Vote()\" class=\"vote_button\"><img src=\"/media/images/vote_images/send_button.gif\" border=\"0\"/></a></div>";
	document.getElementById('vote_container').innerHTML = innerHTML;
	return true;
}


VoteInfo.prototype.ClearVoteGUI = function() {document.getElementById('vote_container').innerHTML = "";}
VoteInfo.prototype.FillVoteItem = function(item_index) {}

/* ParseVoteData **********************************
	Parses the data returned from the Ajax connection
**************************************************/
VoteInfo.prototype.ParseVoteData = function(data) {
	//istantiate the ._items property
	this._items = new Array();
	//create a new VoteItem object for each submission
	for (var i = 0; i < data.getElementsByTagName('submission').length; i++) {
		this._items[i] = new VoteItem();
		this._items[i]._id = data.getElementsByTagName('id')[i].childNodes[0].nodeValue;
		this._items[i]._title = data.getElementsByTagName('title')[i].childNodes[0].nodeValue;
		this._items[i]._submitter = data.getElementsByTagName('submitter')[i].childNodes[0].nodeValue;
		this._items[i]._submitter_url = data.getElementsByTagName('submitter_url')[i].childNodes[0].nodeValue;
		this._items[i]._submitter_email = data.getElementsByTagName('submitter_email')[i].childNodes[0].nodeValue;
		this._items[i]._description = data.getElementsByTagName('description')[i].childNodes[0].nodeValue;
		this._items[i]._embedData = data.getElementsByTagName('link_data')[i].childNodes[0].nodeValue;
		this._items[i]._points = data.getElementsByTagName('current_score')[i].childNodes[0].nodeValue;
	} 
	//build the GUI
	this.Build();
}

/* BuidErrorBox ***********************************
	Handles errors gracefully
**************************************************/
VoteInfo.prototype.BuildErrorBox = function(err_text){
	//build the vote container and add the message
	//inside
	this.BuildContainer();
	//create the error box
	var err = document.createElement('div');
		err.setAttribute('class','voteError');
		err.setAttribute('id','vote_err');
	//create the error message
	var errText = document.createTextNode(err_text);
	//add the error box to the container
	document.getElementById('vote_container').appendChild(err);
	//add the error message to the error box
	document.getElementById('vote_err').appendChild(errText);
}

/* SubmitVote  ***********************************
	Submits votes to the database
**************************************************/
VoteInfo.prototype.Vote = function() {
	var voteString = "";
	var ajax = new Ajax();
	var _this = this;
	
	// build the vote string
	for (var i = 0; i < this._items.length; i++) {
		voteString += "r" + i + "=" + this._items[i]._id + "&";	
	}

	//use _this to maintain scope when passing functions to the Ajax class
		if (ajax) {
			ajax._requestURL = this._voteSubmitURL + ((this._voteSubmitURL.indexOf('?') >= 0)?"&":"?") +  voteString;
			ajax._processor = function(data) {_this.CheckVoteData(data)};
			ajax._errorHandler = function(err) {_this.BuildErrorBox(err)};
			ajax._requestMethod = "GET";
			ajax._overrideMimeType = true;
			//make the Ajax request, if it fails, throw an error
			if (ajax.Connect()) {
			} else {
				this.BuildErrorBox("VoteInfo->GetItems: Unable to connect to url");
			}
		} else {
			this.BuildErrorBox("VoteInfo->GetItems: Unable to create Ajax Component");
	}

}

/* CheckVoteData **********************************
	called when th evote has been submitted
**************************************************/
VoteInfo.prototype.CheckVoteData = function(data) {
	if (document.getElementById('vote_container')) {
		//if the container exists, clear it out
		document.getElementById('vote_container').innerHTML = "";
	} else {
		this.BuildContainer();
	}

	document.getElementById('vote_container').innerHTML = "Thank you for voting, you may vote again tomorrow.";
	
}



/*********************************************************************************************
Page Functions
	These functions perform actions on the page, they're included here in order
	to keep all of the scripts together
*********************************************************************************************/
VoteInfo.prototype.OpenDiv = function(div) {
	var this_div = document.getElementById('submission_' + div + '_data');
	if (this_div.className == 'submission_info') {
		this.CloseDivs();
	}
	this_div.className = (this_div.className=='submission_info')?'submission_info_open':'submission_info';
}
		
VoteInfo.prototype.CloseDivs = function() {
	for (var i = 0; i < this._items.length; i++) {
		document.getElementById('submission_' + i + '_data').className = "submission_info";
	}
}
		
VoteInfo.prototype.SwapItemImage = function(item_id, move, evnt) {
	document.getElementById('item_' + item_id + '_' + move).src = '/media/images/vote_images/arrow_' + move + (evnt=='over'?'_over':'') + '.gif';
}