/*
Vote Casting
Usage:		new Vote(mgid, collectionId, variableName, RefernceToTheVoteElementInHtml);
Example:	new Vote('mgid:tw:user:flux.com:B1680000000068B10001000068B1', '87', 'somerandomname', this);
** it needs the reference to the Vote element in html for DOM/style manipulation.
*/
var Vote = function (mgid, cid, varName,  voteObj)
{
	this.dataServiceUrl	= '/sitewide/dataservices/contest/cast_vote.jhtml';
	this.captchaImgUrl	= '/sitewide/dataservices/contest/captcha_image.jhtml';
	this.mgid			= mgid;
	this.cid			= cid;
	this.varName		= varName;							//this is variable name of the object which constructed a new instance of the Vote class. Hacky -- but necessary.
	this.voteObj		= voteObj;							//vote button	
	this.parentObj		= voteObj.parentNode;				//parent obj of vote button
	this.parentObjHtml	= voteObj.parentNode.innerHTML;
	this.messageObj		= document.getElementById("message"+varName);	//message div object for displaying voting message	
	this.captcha		= null;
	this.voteVerification	= new VoteVerification();
	
	this.init();
	
}

Vote.prototype.init= function() 
{	
	this.captcha = null;	//reset it for good measures.
	this.processMessageBox("showCaptcha");
}


Vote.prototype.castVote = function() //cast the vote!
{
	var xmlData = this.createXmlData();
	var voteObjPtr = this;	//a pointer to the original Vote object. Ajax needs this or else it will lose reference to Vote obj.	
	
	//verifyVote
	if(this.exceedVotes() != true)
	{
		var ajaxReq = new Ajax.Request(
			this.dataServiceUrl,
			{
				method:'post',				
				contentType: 'text/xml',
				encoding:'', //must be no char encoding. gdc screws up with encoding
				postBody:xmlData,
				onSuccess: function(transport){
					var response = transport.responseText || "no response text";
					if(response.indexOf('response code=\"OK\"')>=0)
					{					
						voteObjPtr.processVoteSuccess();
					}else
					{						
						voteObjPtr.processVoteFailure();
					}
				},

				onCreate: function(){
					voteObjPtr.processVoteInProgress();
				},

				onFailure: function(){
					voteObjPtr.processVoteFailure();
				}

			}
		);
	}
	else
	{
		this.processMessageBox("showVoteMaxed");
		setTimeout(this.varName+".processMessageBox('showDefault');",2000);
	}
}

Vote.prototype.exceedVotes	= function()
{
	var	result			= false;
	result				= this.voteVerification.exceedTotalVotes(this.cid);
	
	return result;
}


Vote.prototype.processVoteSuccess = function(){		
	this.voteVerification.processNewVoteEntry(this.cid);	
	this.processMessageBox("showSuccess");
	setTimeout(this.varName+".processMessageBox('showDefault');",2000);
}

Vote.prototype.processVoteFailure = function(){	
	this.processMessageBox("showFailure");
	setTimeout(this.varName+".processMessageBox('showDefault');",2000);
}

Vote.prototype.processVoteInProgress = function(){	
	this.processMessageBox("showInProgress");
}

Vote.prototype.createXmlData = function()
{
	var xmlData = ""+
				"<"+
				"answers collectionID=\""+this.cid+"\">"+						
				"<"+
				"answer tag=\"contestEntryId\""+
				">"+this.mgid+"<"+
				"/answer"+
				">"+

				"<"+
				"answer tag=\"successURL\" /"+">"+

				"<"+
				"answer tag=\"ipAddress\""+
				">"+"0.0.0.0"+"<"+
				"/answer"+
				">"+

				"<"+
				"answer tag=\"numberOfVotes\""+
				">"+"1"+"<"+
				"/answer"+
				">"+

				"<"+
				"answer tag=\"captcha\""+
				">"+this.captcha+"<"+
				"/answer"+
				">"+
				"<"+
				"/answers"+
				">";
	return xmlData;
}



Vote.prototype.processVoteButton = function(operationType){
	var voteObjPtr	= this;		
	
	var buttonHtml = {
		DEFAULT:		"<a class=\"voteButtonDefault\" onclick=\"window."+voteObjPtr.varName+" = new Vote('"+voteObjPtr.mgid+"', '"+voteObjPtr.cid+"', '"+voteObjPtr.varName+"', this);\" href=\"javascript:void(0);\">VOTA <img width=\"19\" height=\"18\" style=\"vertical-align: top;\" src=\"/sitewide/img/buttons/voteButton.gif\"/></a>",
		INPROGRESS:		"<a class=\"voteButtonInProgress\" href=\"javascript:void(0);\">VOTANDO</a>",
		CAPTCHA:		"<a class=\"voteButtonSubmitCaptcha\" onclick=\"window."+voteObjPtr.varName+".processMessageBox('submitCaptchaAndCast');\" href=\"javascript:void(0);\">ENVIAR</a>",
		DISABLED:		"<a class=\"voteButtonDisabled\" href=\"javascript:void(0);\">VOTA <img width=\"19\" height=\"18\" style=\"vertical-align: top;\" src=\"/sitewide/img/buttons/voteButton.gif\"/></a>"
	}
	
	var operations = {
			changeVoteButton: function(state)
			{
				voteObjPtr.parentObj.innerHTML = state;
			}
	}

	switch(operationType)
	{
		case "showDefault":			operations.changeVoteButton(buttonHtml.DEFAULT);	break;		
		case "showSuccess":			operations.changeVoteButton(buttonHtml.DISABLED);	break;
		case "showFailure":			operations.changeVoteButton(buttonHtml.DISABLED);	break;
		case "showInProgress":		operations.changeVoteButton(buttonHtml.INPROGRESS);	break;
		case "showCaptcha":			operations.changeVoteButton(buttonHtml.CAPTCHA);	break;		
		case "resetButton":			operations.changeVoteButton(buttonHtml.DEFAULT);	break;		
	}	

}




Vote.prototype.processMessageBox = function(operationType){
	var voteObjPtr	= this;		
	
	var messages	= {
		FAILURE:		"Hubo un error con tu voto. Por favor espera un instante y vota de nuevo.",
		SUCCESS:		"¡Gracias por votar!",
		INPROGRESS:		"Voto en progreso....",
		CAPTCHA:		"<div class=\"left\" style=\"width:86px; height:36px;\"><img height=\"36\" width=\"86\" src=\"/sitewide/img/spacer.gif\" border=\"1\" id=\"captcha"+voteObjPtr.varName+"\" /></div><div class=\"right\"><a href=\"/faq/\" class=\"whatIsThis\" title=\"¿Qué es esto?\">?</a></div><div class=\"clear\"></div>"+
						"Escribe el código<br/><input type=\"text\" value=\"\" id=\"captchaInput"+voteObjPtr.varName+"\" onkeydown=\"UTILS.keyListener(event, this)\" />"+
						"",
		BLANK:			""
	}
	
	
	var operations = {	
		hideMessageBox:	function(){
			var className = voteObjPtr.messageObj.className;
			if(className.indexOf('Hide')<0){
				voteObjPtr.messageObj.className = className+"Hide";
			}
			this.displayMessage(messages.BLANK);
		},
		
		showMessageBox:	function(){
			var className = voteObjPtr.messageObj.className;			
			if(className.indexOf('Hide')>-1){				
				voteObjPtr.messageObj.className = className.substring(0, className.indexOf('Hide'));
			}
		},		
		
		hideBadge:	function(){
			try{
				var badgeContainer = voteObjPtr.messageObj.parentNode;
				var foundIt = false;

				while(foundIt==false)
				{	
					if(badgeContainer.tagName != undefined){
						if(badgeContainer.className.indexOf("badgeContainer")>-1){
							badgeContainer.className= "badgeContainerHide";
							foundIt = true;
						}
					}				
					badgeContainer = badgeContainer.nextSibling;	//finding the badgeContainer
				}
			}
			catch(e)
			{}
		},		
		
		showBadge:	function(){
			try{
				var badgeContainer = voteObjPtr.messageObj.parentNode;
				var foundIt = false;

				while(foundIt==false)
				{	
					if(badgeContainer.tagName != undefined){
						if(badgeContainer.className.indexOf("badgeContainer")>-1){
							badgeContainer.className= "badgeContainer";
							foundIt = true;
						}
					}				
					badgeContainer = badgeContainer.nextSibling;	//finding the badgeContainer
				}
			}
			catch(e)
			{}
		},

		displayMessage:	function(theMessage){			
			voteObjPtr.messageObj.innerHTML = theMessage;
		},
		
		
		collectCaptcha:	function()
		{
			voteObjPtr.captcha = document.getElementById('captchaInput'+voteObjPtr.varName).value;		
		},

		generateCaptchaImage:	function(state)
		{
			var captchaObj	= document.getElementById("captcha"+voteObjPtr.varName);
			var captchaSrc	= voteObjPtr.captchaImgUrl;
			var blankSrc	= "/sitewide/img/spacer.gif";			
			var	timeObj		= new Date();
			var tempImage	= new Image (86,36); 
			var loadingImage= new Image (86,36); 			
			loadingImage.src= "/sitewide/img/icons/loadTiny.gif";
			
			if(captchaObj){
				switch (state)
				{
					case "blank": //not that neccesary since the previous captcha node gets taken out of the html dom out right.
						captchaObj.src	= blankSrc;
						
						break;

					case "new":						
						captchaObj.src  = loadingImage.src;
						timeObj			= timeObj.getTime();						
						captchaSrc		= captchaSrc + "?" +timeObj + Math.floor(Math.random()*100000);						
						tempImage.src	= captchaSrc;
						
						//weird hack for ie6 -- captcha generation is not fast enough and js craps out.
						eval("setTimeout(\"document.getElementById(\'captcha"+voteObjPtr.varName+"\').src = \'"+tempImage.src+"\';\", 350)");
						
						
						break;
				}
			}
			
		
		},
		
		hidePreviousMessageBox: function()
		{			
			var prevVoteObj = GLOBAL_VARS['Vote_CurrentObject'];			
			
			if(prevVoteObj)
			{		
				if(voteObjPtr.varName != prevVoteObj.varName)
				{
					prevVoteObj.processMessageBox("clearCaptcha");
					prevVoteObj.processMessageBox("showDefault");
				}
			}
		},
		
		saveCurrentMessageBoxToGlobalVar: function()
		{			
			GLOBAL_VARS['Vote_CurrentObject'] = voteObjPtr;			
		}
	}
	
	
	
	var main =
	{	

		showInProgress: function(){			
			operations.displayMessage(messages.INPROGRESS);			
			voteObjPtr.processVoteButton(operationType);
		},
		
		
		showSuccess: 	function(){
			operations.displayMessage(messages.SUCCESS);
			voteObjPtr.processVoteButton(operationType);
		},

		showFailure: 	function(){			
			operations.displayMessage(messages.FAILURE);
			voteObjPtr.processVoteButton(operationType);
			
			
		},
		
		showCaptcha: 	function(){		
			operations.hideBadge();			
			operations.hidePreviousMessageBox();
			operations.saveCurrentMessageBoxToGlobalVar();			
			operations.showMessageBox();				
			operations.displayMessage(messages.CAPTCHA);			
			operations.generateCaptchaImage("new");					
			document.getElementById("captchaInput"+voteObjPtr.varName).focus();	//set focus on input field
			voteObjPtr.processVoteButton(operationType);
		},
		
		showDefault:	function(){			
			operations.hideMessageBox();
			operations.showBadge();
			voteObjPtr.processVoteButton(operationType);
			
		},
		
		submitCaptchaAndCast:	function(){			
			operations.collectCaptcha();
			voteObjPtr.castVote();
		},
		
		resetCaptcha: function (){
			operations.generateCaptchaImage("blank"); 
		}
		
		
	}
	
	switch(operationType)
	{
		case "showDefault":				main.showDefault();	break;
		case "showSuccess":				main.showSuccess();	break;		
		case "showFailure":				main.showFailure();	break;		
		case "showInProgress":			main.showInProgress();break;				
		case "showCaptcha":				main.showCaptcha();	break;
		case "submitCaptchaAndCast":	main.submitCaptchaAndCast();	break;
		case "clearCaptcha":			main.resetCaptcha(); break;
	}
	
	
}






