/**
	Surveys, javascript functions
	@author Oded Idan
	@package Surveys
	@uses jQuery
	2008-30-03
**/

var surveyPercentage = {
	
	data : null,
	jsonCallback : null,
	
	// Parses percentage data for a specific question
	parseData : function(questionId) {
		
		var dataArray = new Array();
		var totalAnswers = 0;
		for (i in this.data) {
			if (String(this.data[i]["question_id"]) != String(questionId))
				continue;
		
			totalAnswers += Number(this.data[i]["answers"]);
			dataArray[this.data[i]["answer_id"]] = this.data[i]["answers"];
		}
		
		// Now, make percentages out of the new data
		for (i in dataArray) {
			dataArray[i] = 100 * dataArray[i] / totalAnswers;
		}
		
		return dataArray;
	},
	
	/**
	 * Retrieve data via JSON request
	 */
	getData : function(surveyId) {
		jQ.ajax({
		  type: "GET",
		  url: "/srv/surveys/json_stats.php?s=" + surveyId,
		  dataType: "json",
		  success: function(data) { 
				surveyPercentage.data = data; 
				if (typeof surveyPercentage.jsonCallback === 'function')
				 surveyPercentage.jsonCallback(data);
			}
		});
	},
	
	/**
	 * Add one answer to data array - useful when answering a survey and THEN showing percentage
	 */
	addAnswer : function(questionId, answerId) {
		var found = false; // Flag, used for creating a new answer if it isn't found
		for (i in this.data) {
			if (this.data[i]["question_id"] == questionId && this.data[i]["answer_id"] == answerId) {
		  	this.data[i]["answers"] = Number(this.data[i]["answers"]) + 1;
				found = true;
		  }
		}
		
		if (!found)
			this.data.push({ "question_id" : questionId, "answer_id" : answerId, "answers" : 1 });
		
	},
	
	// Draw percentages attaches funky elements as percentage results to elements.
	// Keys in elements array must be equal to those in the percentage array.
	drawPercentages : function(elementsArray, percentageArray, addNumbers) {
		
		for (i=0; i<elementsArray.length; i++) {
			
			// Calculate element offset sizes:
			if (typeof elementsArray[i] === "undefined")
			 continue;
			
			var eWidth = elementsArray[i].offsetWidth;
			var eHeight = elementsArray[i].offsetHeight;
			
			if (isNaN(eWidth) || isNaN(eHeight))
			 continue;
			
			// Calculate final size:
			var finalWidth = Math.round((eWidth/100) * percentageArray[i]);
			
			if (!percentageArray[i])
				finalWidth = 0;
			
			// Create new element:
			var answerE = getElement("DIV");
			elementsArray[i].appendChild(answerE);
			answerE.className = "percentageBar";
			answerE.style.height = eHeight + 'px';
			answerE.setAttribute('perc', percentageArray[i]);
			answerE.setAttribute('totalwidth', eWidth);
			// Animate element:
			jQ(answerE).animate({
				"width" : finalWidth
			}, 
			{
				step : function(x){ 
					// Calculate what should be written in the display:
					var percDisplay = x / (Number(this.getAttribute('totalwidth')) / 100);
					// Reduce # of decimals to 0:
					percDisplay = Math.round(percDisplay);
					jQ(this).html(percDisplay + '%');
				},
				duration: 1500,
				easing: 'easeOutBounce'
			
			});
		}
		
	}
	
}

/**
* Surveys page
* 
* @uses jQuery
**/
	
// Assign a global survey ID and completion status via PHP. Sorry about that :(
var surveyId = '';
var surveyComplete = false;

//********************************************************************************************//
//********************************************************************************************//
/**
	Actions to be performed when page is fully loaded.
	This initializes the entire survey functionality.
**/
jQ(document).ready(function() {
		
		// Check whether we need the floater, and if we do, bind a click event to the survey:
		if (isFloaterNeeded())
			attachFloaterEvents();
		
		// If the survey hasn't been completed, activate it!
		else {
			activateSurvey();
			}
		
		// Otherwise, check if the survey has been completed
		if (surveyComplete == true) {
			if (typeof console !== "undefined")
				console.log("SRV1");
			unattachAnswerEvents();
			displaySurveyPercentage();
		}
			
		
});

//********************************************************************************************//
//********************************************************************************************//
/**
	Function: activateSurvey.
	Executes a few functions which have been separated for clarity, but needed to
	be executed together in order to activate full survey functionality.
**/
var activateSurvey = function() {
	retrieveJsonCollapsation(); // This retrieves JSON data and parses it
	unattachFloaterEvents(); // Removes any events that may relate to the floater
	attachAnswerEvents(); // Attaches the survey answers click events
}

//********************************************************************************************//
//********************************************************************************************//
/**
	Function: retrieveJsonCollapsation
	Sends an AJAX request which retrieves JSON data about which questions collapse and expand, then
	launches a callback function (addCollapsation) which handles its functionality. 
**/
var retrieveJsonCollapsation = function() {
jQ.ajax({
	  type: "GET",
	  url: "/srv/surveys/json_collapse.php?s=" + surveyId,
	  dataType: "json",
	  success: addCollapsation
	});
}

//********************************************************************************************//
//********************************************************************************************//
/**
		Function: addCollapsation
		Handle collapsation and expansion of dependent questions.
		Once an answer has been clicked, the question will be opened, and the other answers 
		would be assigned a function that closes it once you click on them. 
**/
	var addCollapsation = function(data) {
	    var answerId;
	    var questionId;
	    for (i in data) {
	    		answerId = i;
	        jQ(".answerRadio[value="+answerId+"]").click(function() {
	            jQ("#surveyQuestion_"+data[this.value]).slideDown(200);
	            jQ(this).siblings("input[type=radio]")
	            .attr("collapseAnswer",data[this.value])
	            .click(function() {
	            	// Try to figure out a slideup function here
	            	jQ("#surveyQuestion_"+jQ(this).attr("collapseAnswer")).slideUp(200);
	            });
	            
	        });
	    }
	}
	
//********************************************************************************************//
//********************************************************************************************//
/**
		Function: attachAnswerEvents
		Handle hovering and clicking the answer text, to trigger a click on a checkbox,
		Also, monitor the amount of answered questions to remove the HAFIRA button.
		-- Added percentage stuff
	**/
	var attachAnswerEvents = function() {
		jQ(".answerText")
			// Click:
			.click(function() { 
				// Trigger a click on the radio button:
				jQ(this).prev(".answerRadio").trigger("click");
				// Remove selected class for siblings
				jQ(this).siblings(".answerText").removeClass("answerText_selected");
				// Add class for selected element
				jQ(this).addClass("answerText_selected");
				
				// Monitor number of answered visible questions, submit survey if all are answered.
				if (jQ(".answerText_selected").length == jQ(".surveyQuestion:visible").length)
					submitSurvey();
					
				// Add percentage display:
				surveyPercentage.questionId = jQ(this).prev(".answerRadio").attr("question");
				surveyPercentage.answerId = jQ(this).prev(".answerRadio").attr("value");
				displaySurveyPercentage(surveyPercentage.questionId);
				
				// Remove any click event for this question's answers:
				jQ(this).parent(".surveyQuestion").children(".answerText").unbind("click");
				
				})
			// Hover:
			.hover(function() { jQ(this).addClass('answerText_hover'); }, function() { jQ(this).removeClass('answerText_hover') });
		} // ENDOF FUNCTION attachAnswerEvents //
		
		
//********************************************************************************************//
//********************************************************************************************//
/**
	Function: unattachAnswerEvents
	Unbinds click actions from answers. This basically disables the survey functionality.
**/
var unattachAnswerEvents = function() {
	jQ(".answerText").unbind("click");
}		
		
//********************************************************************************************//
//********************************************************************************************//
/**
	Function: displaySurveyPercentage.
	Displays the result percentages on the survey.
	Has a questionId parameter to allow it to display results for one question at a time.
	@see /scripts/surveys.js
**/
var displaySurveyPercentage = function(questionId) {
	
	surveyPercentage.jsonCallback = function() {
		if (typeof surveyPercentage.questionId !== "undefined")
			surveyPercentage.addAnswer(surveyPercentage.questionId, surveyPercentage.answerId);
		
		var currentQuestionId = 0;
		
		for (i in surveyPercentage.data) {	
			
			// Allow skipping irrelevant questions if questionId is set
			if (typeof questionId !== "undefined")
				if (surveyPercentage.data[i]["question_id"] != questionId)
					continue;
					
			// Avoid parsing/filling the same question many times
			if (surveyPercentage.data[i]["question_id"] == currentQuestionId)
				continue;
			
			var currentQuestionId = surveyPercentage.data[i]["question_id"];
			// Parse question data
			var questionData = surveyPercentage.parseData(currentQuestionId);
			
			// Attach percentage bar elements to a proper array:
				var elementsArray = new Array(); 
				jQ("#surveyQuestion_" + currentQuestionId).children(".answerPercentage").each(
					function() {
						var answerId = jQ(this).next(".answerRadio").attr("value");
						
						elementsArray[answerId] = this;
					}
				);
			surveyPercentage.drawPercentages(elementsArray, questionData);
		}
	}
	surveyPercentage.getData(surveyId);
	
}
		
//********************************************************************************************//
//********************************************************************************************//
/**
	Function: attachFloaterEvents
	Binds a click event to the survey questions, so that they would launch the floater 
**/
var attachFloaterEvents = function() {
	jQ(".surveyQuestion").bind("click",basicDataFloater);
}
		
//********************************************************************************************//
//********************************************************************************************//
/**
	Function: unattachFloaterEvents
	Removes the click event to the survey questions, so that it wouldn't launch a floater anymore.
	Launched after the floater has been closed
**/
var unattachFloaterEvents = function() {
	jQ(".surveyQuestion").unbind("click",basicDataFloater);
}
		
//********************************************************************************************//
//********************************************************************************************//
/**
	Function: isFloaterNeeded
	Returns TRUE if we're missing details and a basic data floater should be shown, or FALSE otherwise.
	Used to determine whether to bind floater events to the survey.
**/
var isFloaterNeeded = function() {
	if (neededFields.gender != '' && neededFields.age != '' && neededFields.location != '')
		return false;
	else
		return true;
}
		
//********************************************************************************************//
//********************************************************************************************//
/**
	Function: basicDataFloater.
	Display a new staticFloater needed for attaching age/gender/location data to any survey.
**/
var basicDataFloater = function() {
	
	// Abort popup if all required fields are already present:
	if (neededFields.gender != '' && neededFields.age != '' && neededFields.location != '')
		return;
	
	var basicDataBox = new StaticPopup;
	
	// Disable people from clicking ESC and closing this thing ;)
	basicDataBox.useHotkeys = false;
	
	basicDataBox.content.style.textAlign = "right";
	
	basicDataBox.setContent('', 440, 150);
	basicDataBox.content.appendChild(boxTitles(basicDataBox));
	if (neededFields.gender == '')
		basicDataBox.content.appendChild(genderBox(basicDataBox));
	if (neededFields.age == '')
		basicDataBox.content.appendChild(ageBox(basicDataBox));
	if (neededFields.location == '') {
		basicDataBox.content.appendChild(locationBox(basicDataBox));
		var locationCombox = new Combox('neededFields_location',"location",Forms.getYeshuvim(),false);
		locationCombox.onChange = function(val) {
			if (val != '' && val != null) {
				neededFields.submitField('location', val, basicDataBox);
				jQ("#neededFields_location_container").fadeOut(400);
			}
		}
	}
	
	basicDataBox.showCenter(StaticPopup.BUTTON_NONE);
	
}

//********************************************************************************************//
//********************************************************************************************//
/**
	A static object which stores the basic data and submits/closes popup when everything is set.
	Assigns needed basic data via PHP. Sorry about that :(
**/
var neededFields = {
	gender : '', 
	age : '', 
	location : '',
	
	submitField : function(fieldname, data, boxHandle) {
		if (fieldname == 'age' || fieldname == 'gender' || fieldname == 'location') {
			this[fieldname] = data;
		}
			
		if (this.age != '' && this.gender != '' && this.location != '') {
			if (this.age != "NA") // Avoid anonymous users sending useless AJAX
				jQ.ajax(
					{
						type: "POST",
						url: "/srv/settings/findme_ajax.php",
						data: "gender="+ neededFields.gender +"&age=" + neededFields.age + "&location=" + neededFields.location,
						success: function() { boxHandle.hide(); activateSurvey(); }
					}
				);
		}
	}
}


//********************************************************************************************//
// Here are a few functions which attach elements to the basic data static floater:
/**
	Box titles, to be included to the floater
**/
var boxTitles = function(basicDataBox) {
	var titleText = "רק רגע!";
	var secondaryTitleText = "אנחנו צריכים לדעת עליכם כמה פרטים לפני שאתם עונים על הסקר. הפרטים שאתם מכניסים נשארים חסויים, כמובן.";
	
	var container = getElement("DIV", { style : { textAlign : "center" } });
	var bigTitle = getElement("DIV", { innerHTML : titleText, style : { fontSize : "2em", color : "#aa0000" } });
	var smallTitle = getElement("DIV", { innerHTML : secondaryTitleText, style : { marginBottom : "10px" } });
	
	container.appendChild(bigTitle);
	container.appendChild(smallTitle);
	
	return container;
	
}

/**
	Gender box, to be included to the floater
**/
var genderBox = function(basicDataBox) {
	var container = getElement("TABLE");
	var body = getElement("TBODY");
	var row = getElement("TR");
	var iam_box = getElement("TD", { innerHTML : "אני: ", style : { width : "130px" } });
	var m_box = getElement("TD", { innerHTML : "בן", className : "genderSpan", style : { backgroundColor: '#49E9FF' } });
	var f_box = getElement("TD", { innerHTML : "בת", className : "genderSpan", style : { backgroundColor: '#FF8ED4' } });
	
	m_box.onclick = function() {
		neededFields.submitField('gender', 'm', basicDataBox);
		jQ(container).fadeOut(200);
	}
	f_box.onclick = function() {
		neededFields.submitField('gender', 'f', basicDataBox);
		jQ(container).fadeOut(400);
	}
	
	container.appendChild(body);
	body.appendChild(row);
	row.appendChild(iam_box);
	row.appendChild(m_box);
	row.appendChild(f_box);
	
	return container;
}

/**
	Age box - to be included to the floater
**/
var ageBox = function(basicDataBox) {
	var container = getElement("TABLE");
	var body = getElement("TBODY");
	var row = getElement("TR");
	var iam_box = getElement("TD", { innerHTML : "נולדתי בתאריך:", style : { width : "130px" } });
	var inputCell = getElement("TD", { style : { textAlign : "right" } });
	var inputEl = getElement("INPUT");
	
	container.appendChild(body);
	body.appendChild(row);
	row.appendChild(iam_box);
	row.appendChild(inputCell);
	inputCell.appendChild(inputEl);
	
	Date.firstDayOfWeek = 0;
	Date.monthNames = [ 'ינואר','פברואר','מרץ','אפריל','מאי','יוני','יולי','אוגוסט','ספטמבר','אוקטובר','נובמבר','דצמבר' ];
	Date.dayNames = [ 'א','ב','ג','ד','ה','ו','ש' ];
	
	jQ(inputEl).datePicker( 
		{
			clickInput : true,
			startDate:'01/01/1910',
			year:'1990'
		}
	)
	.bind(
		'dateSelected',
		function(e, d)
		{
			neededFields.submitField('age', d.getFullYear() + '-' + (d.getMonth()+1) + '-' + d.getDate(), basicDataBox);
				jQ(container).fadeOut(400);
		}
	);
	
	;
	
	return container;
}

/**
	Location box - to be included to the floater
**/
var locationBox = function(basicDataBox) {
var container = getElement("TABLE", { id : "neededFields_location_container" });
	var body = getElement("TBODY");
	var row = getElement("TR");
	var iam_box = getElement("TD", { innerHTML : "מקום מגורים:", style : { width : "130px" } });
	var selectCell = getElement("TD", { id : "neededFields_location", style : { textAlign : "right" } });
	
	container.appendChild(body);
	body.appendChild(row);
	row.appendChild(iam_box);
	row.appendChild(selectCell);
	
	return container;

}



//********************************************************************************************//
//********************************************************************************************//
/**
	Function: collectSubmissionData
	Collects all survey data to be submitted via a POST ajax.
**/
var collectSubmissionData = function() {
	var dataString = '';
	
	var inputs = jQ(".answerRadio").each(
		function() {
			if (this.checked) {
				if (dataString != '')
					dataString += '&';
				dataString += this.name + '=' + this.value;
			}
		}
	);
	
	return dataString;
	
}

//********************************************************************************************//
//********************************************************************************************//
/**
	Function: submitSurvey
	Try to submit, or launch an alert if survey hasn't been completed by an unregistered visitor
**/
var submitSurvey = function() {
	if (jQ("#surveyForm").attr("pendingcompletion") == "true") {
		if (jQ(".answerText_selected").length < jQ(".surveyQuestion:visible").length) {
			MessageBox.alert("גולשים לא רשומים חייבים לענות על כל השאלות בסקר");
			return false;
		}
	}
	
	// Collect data:
		var surveyData = collectSubmissionData();
	// Submit survey via AJAX POST, and disable survey functionality:
		jQ.ajax({
		  type: "POST",
		  url: "/srv/surveys/common.php?action=submitremote",
		  data: 'surveyId='+surveyId+'&'+surveyData,
		  success: function(msg) {
		  	unattachAnswerEvents();
		  }
		 });
}