var domain = "";

function displaySurvey(){
	var surveyXML = domain + "WciSurveyProxy.aspx?surveyid=";
	$$('.wciPollSurvey').each(function(poll){
		$('survey').setStyle('display','block');
		var id = poll.getProperty('id').replace(/\D/g,'');
		var participationId = (Cookie.get("ParticipationId") > 0)? "&ParticipantId="+Cookie.get("ParticipationId") : "";
		new Ajax(surveyXML + id + participationId + "&cache=" + $time(), {
			method: 'get',
			onComplete: function(text,xml){
				var survey = new wciPollSurvey({
					data: xml, // XML structure;
					div: $('surveyContent'), // container for poll;
					surveyParser: surveyXML + id,
					surveySubmit: domain + "WciSurveyProxy.aspx"
				});
			}
		}).request();
	});
	$E('a#closeBtn').addEvent('click',function(e){
		var participationId = (Cookie.get("ParticipationId") > 0)? "&ParticipantId="+Cookie.get("ParticipationId") : "";
		var surveyXML = domain + "WciSurveyProxy.aspx";
		var id = $E('#survey div.surveyContainer').getProperty('id').replace(/\D/g,'');
  	        var query="WciSurvey_SurveyId="+ id + participationId + "&WciSurvey_Status=CLOSED";
		new Ajax(surveyXML, {
			data: query,
			method: 'post',
			onComplete: function(text,xml){}
		}).request();
		$('survey').setStyle('display','none');
		// unpause flash module;
		if($('oeIndexModule')){
			document.getElementById('oeIndexModule').playPausedVideo();
		};
		new Event(e).stop();
	});
};
function declineSurvey(){
	var participationId = (Cookie.get("ParticipationId") > 0)? "&ParticipantId="+Cookie.get("ParticipationId") : "";
	var surveyXML = domain + "WciSurveyProxy.aspx";
	var id = $E('#survey div.surveyContainer').getProperty('id').replace(/\D/g,'');
	var query="WciSurvey_SurveyId="+ id + participationId + "&WciSurvey_Status=DECLINE";
	new Ajax(surveyXML , {
		data: query,
		method: 'post',
		onComplete: function(text,xml){}
	}).request();
};

var wciPollSurvey = new Class({
    initialize: function(options){
		this.options = options;
		// Show Total Count only if totals are over a certain threshold - default: 500;
		this.totalCountThreshold = this.options.totalCountThreshold || 500;
		// Get the first node in the XML file;
		this.survey = this.options.data.getElementsByTagName('Survey')[0];
		// Convert the XML into an Object{} - see formatData() for example structure;
		this.formData = this.formatData(this.survey);
		// Displaying only Poll (single questions);
		this.poll = this.formData.groups[0].questions;
		// Check Date Range to see if Poll is ready to go live;
		if($time() >= this.formData.dateStart && $time() <= this.formData.dateEnd){
			this.checkVotingStatus();
		} else {
			//this.options.div.remove();
		}
	},
	
	// ====== If Cookie is set, only show the results ====================
	checkVotingStatus: function(){
		//var hasVoted = Cookie.get("WciSurvey_SurveyId"+this.formData.surveyId);
		//if(hasVoted){
		//	this.displayResults();
		//} else {
			this.buildPoll();
		//}
	},
	
	// ====== Format the XML structure into an Object ====================
	formatData: function(survey){
		var data = {
			/* Date Range: Only Show Poll within Date Range */
			dateStart: new Date(survey.getAttribute("DateStart").replace(/-/g,"/").replace("T", " ")).getTime(),
			dateEnd: new Date(survey.getAttribute("DateEnd").replace(/-/g,"/").replace("T", " ")).getTime(),
			participationId: survey.getAttribute("ParticipantId"),
			// userConcept: [Open (no vote restrictions), Cookie (set voting limits)]
			userConcept: survey.getAttribute('UserConcept'),
			// Duration: Set in Minutes; Mootools' cookies set in Days.
			// Anything less than one day, set as percentage; modified in saveResults()
			cookieDuration: survey.getAttribute('CookieDuration'),
			surveyId: survey.getAttribute('SurveyId'),
			surveyType: 'Poll', // Poll or Survey
			groups: []
			/* 
			===== Example: Complete Structure =====
			groups: [{
				id: '#',
				questions:[{
					id: '#',
					type: 'type',
					total: '# total',
					text: 'this is the questions',
					answers: [{
						id: '#',
						type: 'radio',
						text: 'answer',
						stats: {
							percentage: '50%',
							count: '#'
						}
					}]
				}]
			}]
			*/
		};
		// Declare main "group" container object
		var oGroup;
		// Sort through the groups and parse the question(s) and options;
		var groups = survey.getElementsByTagName('Group');
		// If there is more than one group, assume that it is a survey;
		if(groups.length > 1) data.surveyType = "Survey";
		// Loop through "groups" - groups represent pages for survey pagination;
		for(w=0,wl=groups.length;w<wl;w++){
			var group = groups[w];
			// Each group can have multiple questions "per page";
			oGroup = {
				id: group.getAttribute('GroupId'),
				questions: []
			}
			var questionsGroup = group.getElementsByTagName('Questions');
			for(var x=0,xl=questionsGroup.length;x<xl;x++){
				// Per questions, find the question text and the possible answers;
				var questions = questionsGroup[x].getElementsByTagName('Question');
				for(var y=0,yl=questions.length;y<yl;y++){
					var question = questions[y];
					// ===== The Question =====
					var oQuestions = {
						id: question.getAttribute('QuestionId'),
						type: question.getAttribute('QuestionType'),
						total: question.getAttribute('Total'),
						text: question.getElementsByTagName('Text')[0].firstChild.nodeValue,
						answers: []
					}
					// ===== The Answers =====
					var answerGroup = question.getElementsByTagName('Answer');
					for(var z=0,zl=answerGroup.length;z<zl;z++){
						var answer = answerGroup[z];
						var strStats = answer.getElementsByTagName('Stat')[0];
						var oAnswer = {
							id: answer.getAttribute('AnswerId'),
							type: answer.getAttribute('AnswerType'),
							text: (answer.getElementsByTagName('Text')[0].hasChildNodes())? answer.getElementsByTagName('Text')[0].firstChild.nodeValue : '',
							stats: {
								percentage: strStats.getAttribute('Percentage'),
								count: strStats.getAttribute('Count')
							},
							name: ((answer.getAttribute('AnswerType') == 'Textbox') ? 'WciSurvey_Text' : "WciSurvey_QuestionId")  + oQuestions.id,
						}
						oQuestions.answers.push(oAnswer);
					};
					oGroup.questions.push(oQuestions);
				};
			};
		};
		data.groups.include(oGroup);
		return data;
	},
	
	// ====== Create the Poll options and Submit button ====================
	buildPoll: function(){
		var list = new Element('ul');
		var comments = new Element('div', {'class':'input'});
		this.poll.each(function(question,int){
			if(question.answers.length === 1){
				comments.appendText(question.text);
				comments.adopt(
					new Element('textarea',{
						'name': question.answers[0].name,
						'id': 'wciPoll_'+this.formData.groups[0].id+"-"+question.answers[0].id
					})
				)
			} else {
				var li = new Element('li').appendText(question.text);
				list.adopt(li);
				var answers = new Element('ul');
				var answer = "";
				question.answers.each(function(option,n){
					answer = new Element('label')
					.adopt(
						new Element('input',{
							'type': option.type,
							'class': option.type,
							'name': option.name,
							'id': 'wciPoll_'+this.formData.groups[0].id+"-"+option.id+int,
							'value': option.id
						})
					).appendText(" "+option.text);
					answers.adopt(answer)
				}.bind(this));
				li.adopt(answers);
			};
		}.bind(this));
		// Create submit button and click event to submit form;
		var submitBtn = new Element('a',{
			'id':'btnSurveySubmit',
			'events':{
				'click': function(){
					// Before we submit, check to make sure an option has been selected.
					if(($(this.options.div).getElements('input').getSelected()).length){
						var participationId = "&ParticipantId="+this.formData.participationId;
						var query = 'WciSurvey_SurveyId='+this.formData.surveyId + participationId + "&"+$('survey').toQueryString();
						new Ajax(this.options.surveySubmit, {
							data: query,
							method: 'post',
							onSuccess: function(text, xml){
								this.saveResults();
							}.bind(this),
							onFailure: function(instance){
								this.failedResults();
							}.bind(this)
						}).request();
					}
				}.bind(this)
			}
		});
		comments.adopt(submitBtn);
		this.options.div.adopt(list,comments);
	},
	
	// ====== The Option has been submitted, now set the cookie (if applicable) ====================
	saveResults: function(){
		if(this.formData.userConcept == "Cookie"){
			var oneDay = 60*60*24;
			var duration = (this.formData.cookieDuration < oneDay)? this.formData.cookieDuration/(60*24) : this.formData.cookieDuration;
			Cookie.set("WciSurvey_SurveyId"+this.formData.surveyId, "true", {duration: duration});
		}
		Cookie.set("ParticipationId", this.formData.participationId, {duration: (60*60*24)*365});
		$('survey').setStyle('display','none');
		// unpause flash module;
		if($('oeIndexModule')){
			document.getElementById('oeIndexModule').playPausedVideo();
		};
		//this.retrieveResults();
	},
	
	// ====== Pull the most recent totals for the results ====================
	retrieveResults: function(){
		new Ajax(this.options.surveyParser + "&cache=" + $time(), {
			method: 'get',
			onComplete: function(text,xml){
				// Update the main variables with the most recent ones
				this.survey = xml.getElementsByTagName('Survey')[0];
				this.formData = this.formatData(this.survey);
				this.poll = this.formData.groups[0].questions[0];
				//
				//this.displayResults();
			}.bind(this)
		}).request();
	},
	
	// ====== Size the results based on Percentages ====================
	displayResults: function(){
		this.container.empty();
		this.poll.answers.each(function(option,n){
			var result = new Element('div', {
				'class':'results',
				'id':'results_'+this.formData.groups[0].id+'-'+option.id,
				'styles': { 'width':(option.stats.percentage*100).toInt()+'%'}
			}).adopt(
				new Element('span').setText((option.stats.percentage*100).toInt()+'%')
			)
			this.container.adopt(result).appendText(option.text);
			//result.effect('width', {duration: 2500, transition:Fx.Transitions.Circ.easeInOut}).start(0,result.getCoordinates().width)
		}.bind(this));
		// Show Total Count only if totals are over a certain threshold;
		if(this.poll.total >= this.totalCountThreshold){
			this.container.adopt(new Element('div',{'class':'resultsTotal'}).appendText("(Total Votes: "+this.poll.total+")"));
		}
	},
	
	// ====== If Cookie is set, only show the results ====================
	failedResults: function(){
		alert('We were unable to save your survey. Please try again.');
	}
});
Array.extend({
	getSelected: function(){
		return new Elements(this.filter(function(option){
			return option.checked;
		}));
	}
});