/*--------------------------------------------------------------------------------
					Adding Positivity Javascript
					Author: Matt Donovan
					Contact: mattddonovan[at]gmail[dot]com
					URL: http://dawnrecorder.org
---------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------
						Question Handling Functionality
---------------------------------------------------------------------------------*/

// signalFeedback(String e): pops up feedback window with given feedback string
function signalFeedback(e){
	$('dialogText').innerHTML = '<h4 id="fbContent">'+e+'</h4>'; 
	$('FeedbackPopup').className = 'dialogVisible';
	$('FeedbackPopup').style.display = 'block';
	$('FeedbackPopup').style.opacity = 0;
	Effect.Appear('FeedbackPopup', {duration:0.5});
}

// confirmDialog(): dismisses the feedback dialog
function confirmDialog(){
	Effect.Fade('FeedbackPopup', {duration:0.5, afterFinish:function(){
		$('FeedbackPopup').className = 'dialogHidden';
	}});
}

// checkSuggestion(): form validation for question suggestion submissions */
function checkSuggestion(){
	var home_country = $('home_country').value;
	var location = $('location').value;
	var category = $('selectedCategory').value;
	var question_content = $('question_content').value;
	var output = '';
	if(home_country==0){
		output = 'Please select your<br>Home Country';
		signalFeedback(output);
	}
	else{
		if(location==0){
			output = 'Please select your<br>Current Location';
			signalFeedback(output);
		}else{
			if(category==0){
				output = 'Please select a Category<br>For your question';
				signalFeedback(output);
			}else{
				if(question_content==''){
					output = 'Please enter a<br>valid question';
					signalFeedback(output);
				}else{
					return true;
				}
			}
		}
	}
}

// checkResponse(): form validation for response submissions */
function checkResponse(){
	var home_country = $('home_country').value;
	var location = $('location').value;
	var response_content = $('response_content').value;
	var output = '';
	if(home_country==0){
		output = 'Please select your<br>Home Country';
		signalFeedback(output);
	}
	else{
		if(location==0){
			output = 'Please select your<br>Current Location';
			signalFeedback(output);
		}else{
			if(response_content==''){
				output = 'Please enter a<br>valid response';
				signalFeedback(output);
			}else{
				return true;
			}
		}
	}
}
			

// submitQuestion(): submits a question to the database */
function submitQuestion(){
	if(checkSuggestion()){
		var url = 'php/submitQuestion.php';
		var pars = $('questionSubmission').serialize();
		var target = '';
		var myAjax = new Ajax.Updater(target, url, {method:'post', parameters:pars, onComplete:function(){
			signalFeedback('Question Submitted.<br>Thank you for your contribution.');
			$('question_content').value = '';
			}
		});
	}
	createCookie('user_home_country_cookie', $('home_country').value, 30);
	createCookie('user_home_country_long_cookie', $('home_country_combo').value, 30);
	createCookie('user_current_location_cookie', $('location').value, 30);
	createCookie('user_current_location_long_cookie', $('location_combo').value, 30);
}

// submitResponse(): submits a response to a question to the database
function submitResponse(){
	if(checkResponse()){
		var url = 'php/submitResponse.php';
		var pars = $('questionResponse').serialize()+'&date_submitted='+formatDate(todaysDate);
		var target = '';
		var myAjax = new Ajax.Updater(target, url, {method:'post', parameters:pars, onComplete: function(){
			signalFeedback('Response Submitted.<br>Thank you for your contribution.');
			$('response_content').value = '';
			}	
		});
	}
	createCookie('user_home_country_cookie', $('home_country').value, 30);
	createCookie('user_home_country_long_cookie', $('home_country_combo').value, 30);
	createCookie('user_current_location_cookie', $('location').value, 30);
	createCookie('user_current_location_long_cookie', $('location_combo').value, 30);
}

/*--------------------------------------------------------------------------------
						Display Functionality
---------------------------------------------------------------------------------*/

// checkTime(): checks for integers less than 10 and appends a 0 to ensure a (2) character string
function checkTime(i){
	if (i < 10){
  		i = "0" + i;
	}
	return i;
}

// updateDateDisplay(): updates the displayed date
function updateDateDisplay(){
	var monthName=new Array("January","February","March","April","May","June","July","August","September","October","November","December");
	var output = '<h5>'+monthName[currentDate.getMonth()]+' '+currentDate.getDate()+', '+currentDate.getFullYear()+'</h5>';
	var target = $('dateDisplay');
	target.innerHTML=output;
}

// updateQuestionDisplay(): updates the displayed question
function updateQuestionDisplay(){
	Effect.Fade('questionDisplayContent', {duration:0.5, afterFinish: function(){	
		var url = 'php/getQuestion.php';
		var pars = 'date='+formatDate(currentDate);
		var target = 'questionDisplayContent';
		var ajaxRequest = new Ajax.Updater(target, url, {
				method:'post', 
				parameters:pars, 
				onComplete: function(){
						Effect.Appear('questionDisplayContent', {duration:.75});
      			}
      	})}});
}
     	
// updateQuestionDisplay(): updates the displayed question
function updateRandomQuestion(){
	if($('response_content').value != ""){
		signalFeedback('Please submit or <br>clear your response<br>before responding to<br> another question.')
	}else{
		Effect.Fade('categoryDisplayContent', {duration:0.5});
		Effect.Fade('questionDisplayContent', {duration:0.5, afterFinish: function(){	
			var url = 'php/getRandomQuestion.php';
			var pars = 'date='+formatDate(currentDate);
			var target = 'questionDisplayContent';
			var ajaxRequest = new Ajax.Updater(target, url, {
				method:'post', 
				parameters:pars, 
				onComplete: function(){
					Effect.Appear('questionDisplayContent', {duration:0.75});
					var cat = $('category_name').value;
					var out = '<img src=\"img/'+cat+'.png\"/><span class=\"catName\">'+cat+'</span>';
					$('categoryDisplayContent').innerHTML = out;
					Effect.Appear('categoryDisplayContent', {duration:0.5});
			}});
		}});
	}
}


// updateCategoryDisplay(): updates the displayed category
function updateCategoryDisplay(){
	Effect.Fade('categoryDisplayContent', {duration:0.5, afterFinish: function(){
		var url = 'php/getCategory.php';
		var pars = 'date='+formatDate(currentDate);
		var target = 'categoryDisplayContent';
		var ajaxRequest = new Ajax.Updater(target, url, {
			method:'post', 
			parameters:pars,
			onComplete: function(){
				Effect.Appear('categoryDisplayContent', {duration:0.5});
			}});
	}});
}

// updateCategorySelection(): Updates the displayed category while submitting a question
function updateCategorySelection(){
	Effect.Fade('categoryDisplayContent', {duration:0.5, afterFinish: function(){
		var out='';
		if(($('selectedCategory').value==0)){
			var out = '<img src="img/Sensing the Environment.png"><span class="catName">Select a Category</span>';
			$('categoryDisplayContent').innerHTML = out;
		}else{
			var cat = $('selectedCategory').value;
			var out = '<img src=\"img/'+cat+'.png\"/><span class=\"catName\">'+cat+'</span>';
			$('categoryDisplayContent').innerHTML = out;
		}
		Effect.Appear('categoryDisplayContent', {duration:0.5});
	}});
}


// updateResponderDisplay(): updates the visual elements of the widget
function updateResponderDisplay(){
	updateDateDisplay();
	updateQuestionDisplay();
	updateCategoryDisplay();
}

// updateSuggesterDisplay(): updates the visual elements of the widget
function updateSuggesterDisplay(){
	updateDateDisplay();
}

/*--------------------------------------------------------------------------------
						Calendar Functionality
---------------------------------------------------------------------------------*/

// previousDay(): steps back to the previous day
function previousDay(){
	currentDate.setDate(currentDate.getDate()-1);
	updateResponderDisplay();
}

// nextDay(): advances to the next day
function nextDay(){
	if((currentDate.getMonth()==todaysDate.getMonth())&&(currentDate.getDate()==todaysDate.getDate())){
		updateResponderDisplay();
	}else{
		currentDate.setDate(currentDate.getDate()+1);
		updateResponderDisplay();
	}
}

// formatDate(): creates a database-friendly string from a date object
function formatDate(d){
	var mm = checkTime(d.getMonth()+1);
	var dd = checkTime(d.getDate());
	var yyyy = d.getFullYear();
	var output = mm+''+dd+''+yyyy;
	return output;
}

// runStartup(): initializes the widget
function runStartup(){
	loadResponder();
}


/*--------------------------------------------------------------------------------
						Navigation Functionality
---------------------------------------------------------------------------------*/

// createLoadImage(): creates the loading image when populating new contet
function createLoadImage(){
	var target = $('WidgetContainer');
	var loading = "<span style=\"position:absolute; top:"+(target.style.height/2)+"; left:"+(target.style.width/2)+";\"><img src=\"../img/ajax_loader.gif\"></span>";
	target.innerHTML = loading;
}

// loadResponse(): loads the question answer form
function loadResponder(){
	resetWidgetNav();
	$('addAResponse').className = 'selected';
	document.displayState = "Responder";	
	Effect.Fade('WidgetContent', {duration:0.5, afterFinish: function(){
	var url = 'response_form.html';
	var target = 'WidgetContent';
	var ajaxRequest = new Ajax.Updater(target, url, {
		onComplete:function(){			
			updateResponderDisplay();
			$('home_country').style.visibility = 'hidden';
			new Autocompleter.SelectBox('home_country');
			$('location').style.visibility = 'hidden';
			new Autocompleter.SelectBox('location');
			Effect.Appear('WidgetContent', {duration:0.5});
			
			var userHomeCountryCode = readCookie('user_home_country_cookie');
			var userHomeCountryText = readCookie('user_home_country_long_cookie');
			var userCurrentLocationCode = readCookie('user_current_location_cookie');
			var userCurrentLocationText = readCookie('user_current_location_long_cookie');

			
			if(userHomeCountryCode){
				$('home_country').value = userHomeCountryCode;
			}
			if(userHomeCountryText){
				$('home_country_combo').value = userHomeCountryText;
			}
			if(userCurrentLocationCode){
				$('location').value = userCurrentLocationCode;
			}
			if(userCurrentLocationText){
				$('location_combo').value = userCurrentLocationText;
			}
		}});
	}});
}
			

// loadSuggester(): loads the question suggestion form
function loadSuggester(){
	resetWidgetNav();
	$('suggestAQuestion').className = 'selected';
	document.displayState = "Suggester";
	Effect.Fade('WidgetContent', {duration:0.5, afterFinish: function(){
	var url = 'suggestion_form.html';
	var target = 'WidgetContent';
	var ajaxRequest = new Ajax.Updater(target, url, {
		onComplete:function(){
			updateSuggesterDisplay();
			$('home_country').style.visibility = 'hidden';
			new Autocompleter.SelectBox('home_country');
			$('location').style.visibility = 'hidden';
			new Autocompleter.SelectBox('location');
			$('selectedCategory').style.visibility = 'hidden';
			new Autocompleter.SelectBox('selectedCategory');
			$('selectedCategory_combo').value = 'Question Category          ';
			Effect.Appear('WidgetContent', {duration:0.5});
			
			$('selectedCategory').value = 0;
			updateCategorySelection();
			
			var userHomeCountryCode = readCookie('user_home_country_cookie');
			var userHomeCountryText = readCookie('user_home_country_long_cookie');
			var userCurrentLocationCode = readCookie('user_current_location_cookie');
			var userCurrentLocationText = readCookie('user_current_location_long_cookie');
			if(userHomeCountryCode){
				$('home_country').value = userHomeCountryCode;
			}
			if(userHomeCountryText){
				$('home_country_combo').value = userHomeCountryText;
			}
			if(userCurrentLocationCode){
				$('location').value = userCurrentLocationCode;
			}
			if(userCurrentLocationText){
				$('location_combo').value = userCurrentLocationText;
			}
		}});
	}});
}


// resetPageNav(): resets the page navigation elements to defaults
function resetPageNav(){
	$('contributePositivity').className = 'contributePositivity';
	$('viewAllPositivity').className = 'viewAllPositivity';
	$('contactUs').className = 'contactUs';
}

// resetWidgetNav(): resets the widget navigation elements to defaults
function resetWidgetNav(){
	$('addAResponse').className = '';
	$('suggestAQuestion').className = '';
	//$('uploadAnImage').className = '';
}

// loadViewer(): loads the View All Positivity content
function loadViewer(){
	resetPageNav();
	$('viewAllPositivity').className = 'selected';
	Effect.Fade('CopyText', {duration:0.5, afterFinish: function(){
		$('CopyText').innerHTML = '<p>Please check back for interactive visualizations of your many responses</p>';
		Effect.Appear('CopyText', {duration:0.5});
	}});
}

// loadContact(): loads the Contact Us content
function loadContact(){
	resetPageNav();
	$('contactUs').className = 'selected';
	Effect.Fade('CopyText', {duration:0.5, afterFinish: function(){
		$('CopyText').innerHTML = '<p>adding positivity +<br>is a design research project<br>originated by Ann McDonald<br>and Sareena Sernsukskul<br>Please send any comments or questions to<br><a href="mailto:info@addingpositivity.org">info@addingpositivity.org</a></p>';
		Effect.Appear('CopyText', {duration:0.5});
	}});
}

// loadContribute(): loads the Contribute Positivity content
function loadContribute(){
	resetPageNav();
	$('contributePositivity').className = 'selected';
	Effect.Fade('CopyText', {duration:0.5, afterFinish: function(){
		$('CopyText').innerHTML = '<p style="margin-bottom:30px;">adding positivity +<br/>encourages consideration of<br/>similarities and differences in<br/>worldview and encourages an<br/>increased awareness of the<br/>impact of our interactions with<br/>our environments and with<br/>others.</p><h1>please add responses</h1><p class="interactionLinks" style="margin-bottom:15px;">add your responses online or<br/>download the widget to your<br/>desktop to see a new question<br/>to respond to every day.</p><a class="downloadOSX" href="files/Adding-Positivity-Widget-(OSX).zip"></a><a class="downloadVista" href="#"></a><p>our hope is that the information<br/>gathered and shared here will<br/>reciprocate through action and<br/>additional ideas.<br/></p>';
		Effect.Appear('CopyText', {duration:0.5});
	}});
}

/*--------------------------------------------------------------------------------
						Effects Related Functionality
---------------------------------------------------------------------------------*/

// toggleWidget(): toggles the state of the widget (expanded or contracted)
function toggleWidget(){
	if(document.collapsed==true){
		expandWidget();
	}else{
		contractWidget();
	}
}

// fadeOut(Element e): fades out an element
function fadeOut(e){
	var target = $(e.id);
	new Effect.Fade(target, {duration:0.2});
}

// fadeIn(Element e): fades in an element
function fadeIn(e){
	var target = $(e.id);
	new Effect.Appear(target, {duration:0.2});
}

// contractWidget(): contracts the widget 
function contractWidget(){
	controlScaleRatio = (96/491)*100;
	widgetScaleRatio = (90/485)*100;
	new Effect.Fade('WidgetControls', {duration:0.3});
	new Effect.Fade('WidgetContent', {
		duration:0.2, 
		afterFinish:function(){
			new Effect.Scale('ControlWrapper', controlScaleRatio, {duration:0.3, scaleContent:false});
			new Effect.Scale('WidgetContainer', widgetScaleRatio, {duration:0.3, scaleContent:false, afterFinish:function(){
				document.collapsed=true;
			}});
	}});
}

// expandWidget(): expands the widget 
function expandWidget(){
	controlScaleRatio = 491/96*100;
	widgetScaleRatio = 485/90*100;
	new Effect.Scale('ControlWrapper', controlScaleRatio, {duration:0.3, scaleContent:false});
	new Effect.Scale('WidgetContainer', widgetScaleRatio, {
		duration:0.3,
		scaleContent:false,
		afterFinish:function(){
			document.getElementById('WidgetContent').style.opacity=0;
			document.getElementById('WidgetContent').style.visibility='visible';
			new Effect.Appear('WidgetControls', {duration:0.5});
			new Effect.Appear('WidgetContent', {duration:0.5});
			document.collapsed=false;
	}});
}

/*--------------------------------------------------------------------------------
						Cookie Functionality
---------------------------------------------------------------------------------*/

// createCookie(String name, String value, Int days): creates a cookie
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

// readCookie(String name): reads the contents of a stored cookie
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

// eraseCookie(String name): erases a given cookie
function eraseCookie(name) {
	createCookie(name,"",-1);
}
