var PollObject = Class.create({
	initialize: function(el){
		this.preloader = eHA.polls.preloader.clone(true);
		this.properties = eHA.elementToObjectLiteral(el);
		this.el = $(el);
		this.form = $(el).down("form");
		this.cookieName = "poll-"+this.properties.assetid;
		
		if(typeof Cookie.getData(this.cookieName)==="undefined"){
			this.form.observe("submit",function(evt){
				evt.stop();
				this.submit(true,function(){
					this.compute();
				}.bind(this));
			}.bind(this));
			this.el.down("a.view").observe("click",function(evt){
				evt.stop();
				this.submit(false,function(){
					this.compute();
				}.bind(this));
			}.bind(this));
		}else{
			// cookie saved, show results immediately
			this.submit(false,function(){
				this.compute();
			}.bind(this));
		}
		//
		
	},
	submit: function(checkVote,callback){
		var URL = "/cs/Satellite";
 		var parameters = {
 	 			childpagename: eHA.Site+"/eHA_Module_C/"+eHA.Site+"/Poll/json",
 	 			site: eHA.Site,
 	 			c: "eHA_Module_C",
 	 			cid: this.properties.assetid,
 	 			pagename: eHA.Site+"_default_Wrapper"
 	 		};
 		
 		if(checkVote){
 			parameters.packedargs = this.form.serialize();
 			Cookie.setData(this.cookieName, this.form.serialize(true).vote);
 			eHA.log.create(Object.toJSON(parameters),3);
 		}
 		
		this.ajaxRequest = new Ajax.Request(URL,
		{
			method:'get',
			parameters: parameters,
			onCreate: function(){
				//this.form.replace(this.preloader);
				eHA.log.create("pollModule "+this.properties.assetid+": AJAX request for JSON created", 3);
			}.bind(this),
			onSuccess: function(transport){
				eHA.log.create("pollModule "+this.properties.assetid+": AJAX request for JSON succeeded", 3);
			}.bind(this),
			/*
			 * expected response data:
			 * 
			 * {
			 *	"response" : "junk from XML post...",
			 *  "results":
			 * [
					{
						"label"		:"1 cup",
						"value"		:6
					},
					{
						"label"		:"2 cups",
						"value"		:3
					},
					...
				]
			 * }
			 */
			onComplete: function(transport){
				// add transport.responseText to this.properties
				eHA.log.create("pollModule "+this.properties.assetid+": AJAX request for JSON completed", 3);
				if(transport.responseText){
					eHA.log.create("pollModule "+this.properties.assetid+": attempting to evaluate JSON and add to newsModuleObject", 3);
					try{
						var fullResponse = transport.responseText.evalJSON(true);
						this.results = fullResponse.results;
						this.properties.complete = true;
					}catch(err){
						eHA.log.create("pollModule "+this.properties.assetid+":"+err.name+" - "+err.message, 1);
					}
				}else{
					eHA.log.create("pollModule "+this.properties.assetid+": problem with transport.responseText onComplete", 1);
				}
				if(typeof callback!=="undefined" && callback){
					callback();
				}
			}.bind(this),
			onFailure: function(){
				eHA.log.create("pollModule "+this.properties.assetid+": AJAX request for JSON resulted in failure", 1);
			}.bind(this)
		});
	},
	compute: function(callback){
		try{
			this.totalVotes = 0;
			this.mostVotes = 0;
			this.leastVotes = Infinity;
			// first loop to amass total
			for(var i=0;i<this.results.length;i++){
				this.totalVotes = parseInt(this.totalVotes,10) + parseInt(this.results[i].value,10);
				if(this.results[i].value>this.mostVotes){
					this.mostVotes = this.results[i].value;
				}
				if(this.results[i].value<this.leastVotes){
					this.leastVotes = this.results[i].value;
				}
			}
			// second loop to compute percentages
			for(var i=0;i<this.results.length;i++){
				this.results[i].percentage = Math.round(parseInt(this.results[i].value,10) / 
						parseInt(this.totalVotes,10)*100);
			}
			this.writeResults();
		}catch(err){
			eHA.log.create("pollModule "+this.properties.assetid+": "+err.toString(),1);
		}
	},
	writeResults: function(){
		try{
			var resultsHTML = "<ul>";
			for(var i=0;i<this.results.length;i++){
				var thisClass = "";
				if(this.results[i].value===this.mostVotes){
					thisClass = "most";
				}
				if(this.results[i].value===this.leastVotes){
					thisClass = "least";
				}
				if(i%2==1){
					thisClass += " alt";
				}
				resultsHTML += "<li class='result"+i+" "+thisClass+"'><h5>"+this.results[i].label+"</h5>"
				+"<div><div style='width:0%;'><span>"+this.results[i].percentage+"%</span></div></div></li>";
			}
			resultsHTML += "</ul>";
			this.resultsDiv = new Element("div",{className:"results"}).update(resultsHTML);
			this.form.replace(this.resultsDiv);
			this.growResults();
		}catch(err){
			eHA.log.create("pollModule "+this.properties.assetid+": "+err.toString(),1);
		}
	},
	growResults: function(){
		try{
			var parallelArray = new Array();
			for(var i=0;i<this.results.length;i++){
				parallelArray.push(new Effect.Morph(this.resultsDiv.down(".result"+i+">div>div"),
						{style:"width:"+this.results[i].percentage+"%;",sync:true}));
			}
			new Effect.Parallel(parallelArray,{duration:eHA.polls.duration});
		}catch(err){
			eHA.log.create("pollModule "+this.properties.assetid+": error in growResults: "+err.toString(),1);
		}
	}

});


eHA.polls = {
	init: function(){
		this.preloader = new Element("img",{src:eHA.resourcepath+"images/wide-preloader.gif",
				alt:"please wait",className:"preloader"});
		this.pollObjects = {};
		$$(".poll").each(function(el){
			var assetid = eHA.elementToObjectLiteral(el).assetid;
			this.pollObjects[assetid] = new PollObject(el);
		}.bind(this));
	},
	duration: 1.5
};

