/*
$(document).ready(function() {

	// DF: Added, as a 'uniqueness' to replace email
	top.surveykey = 's'+Math.round(Math.random()*10000000000);
	
	if($.cookie('survey')=='isviewed') {
		return false;
	}

	$.cookie('survey', 'isviewed');

	setTimeout(showSurvey, 500);
});
*/

function showSurvey() {	
	(function($) {		//function that preloads images
		  var cache = [];
		  $.preLoadImages = function() {
		    var args_len = arguments.length;
		    for (var i = args_len; i--;) {
		      var cacheImage = document.createElement('img');
		      cacheImage.src = arguments[i];
		      cache.push(cacheImage);
		    }
		  }
		})(jQuery)
	jQuery.preLoadImages("images/button-nothanks.png", "images/button-finish.png", "images/button-close.png", "images/content-top.png", "images/content-middle.png", "images/content-bottom.png", "images/logo-survey.png");
	
	var survey;
	
	survey = '<div id="greyout" style="position:absolute;top:0;left:0:"></div>';
	survey += '<div id="survey-container">';
		survey += '<div id="top"></div>';
		survey += '<div id="middle">';
			survey += '<div id="inner">';
				survey += '<img src="http://iopclive.3ev.info/images/logo-survey.png" /><div id="surveyTitle">IOPC Funds Micro-Survey</div>';
				survey += '<p>We are continually improving our Document Server to make it as useful as possible and we would very much appreciate if you could take a few moments to answer these questions:</p>';

				survey += '<form name="surveyform" id="surveyform" action="dataHandling.php" method="POST">';
					survey += '<div class="questions">1. Which one of the following best describes your business sector?<span id="valid1" class="valid"></span></div>';
					survey += '<input type="hidden" id="q1a" value="Which one of the following best describes your business sector?" />';
					survey += '<div class="answer">';
						survey += '<label for="r1a"><input type="radio" name="radio1" id="r1a" class="radio1" value="Government" /> Government</label><br />';
						survey += '<label for="r1b"><input type="radio" name="radio1" id="r1b" class="radio1" value="Intergovernmental Organisation" /> Intergovernmental Organisation</label><br />';
						survey += '<label for="r1c"><input type="radio" name="radio1" id="r1c" class="radio1" value="Non-Governmental Organisation" /> Non-Governmental Organisation</label><br />';
						survey += '<label for="r1d"><input type="radio" name="radio1" id="r1d" class="radio1" value="Academic Researcher" /> Academic Researcher</label><br />';
						survey += '<label for="r1e"><input type="radio" name="radio1" id="r1e" class="radio1" value="Student" /> Student</label><br />';
						survey += '<label for="r1f"><input type="radio" name="radio1" id="r1f" class="radio1" value="Other" /> Other:</label>';
						survey += '<div id="showOtherSector">';
							survey += 'Business sector?';
							survey += '<input type="hidden" id="q2a" value="(Other) Business sector" /><br />';
							survey += '<input type="text" id="q2b" size="35"></input>';
						survey += '</div>';
					survey += '</div>';
					
					survey += '<div class="questions">2. Did you find the information you needed today?<span id="valid2" class="valid"></span></div>';
					survey += '<input type="hidden" id="q3a" value="Did you find the information you needed today?" />';
					survey += '<div class="answer">';
						survey += '<label for="r2a"><input type="radio" name="radio2" id="r2a" class="radio2" value="Yes" /> Yes</label><br />';
						survey += '<label for="r2b"><input type="radio" name="radio2" id="r2b" class="radio2" value="No" /> No</label>';
							survey += '<div id="userInfoNotFound">';
								survey += 'Please comment:<br />';
								survey += '<input type="hidden" id="q4a" value="(User couldn\'t find info they were looking for) User comment:" />';
								survey += '<textarea id="q4b" cols="45" rows="4"></textarea>';
							survey += '</div>';
					survey += '</div>';

					survey += '<div class="questions">3. Any further comments/suggestions:</div>';
					survey += '<input type="hidden" id="q5a" value="Any further comments/suggestions" />';
					survey += '<div class="answer"><textarea id="q5b" cols="46" rows="5"></textarea></div>';
				
					survey += '<div id="buttons">';
						survey += '<a href="#" class="nothanks left closeSurvey">No Thanks</a>';
						survey += '<input type="hidden" name="submitted"></input>';
						survey += '<input id="submit" type="image" class="finish right" src="images/button-finish.png" alt="Submit Button" />';
					survey += '</div>';
				survey += '</form>';
		survey += '</div></div>';
		survey += '<div id="bottom"></div>';
	survey += '</div>';

	$("body").prepend(survey);
	
	$(".closeSurvey").click(function(){ closeSurvey(); });						//IE6 fixes - IE6 didn't like directly calling the functions from the HTML tags
	$(".radio1").click(function(){ showOtherSector(); $('#valid1').hide();});	//so instead doing it from jquery
	$("#submit").click(function(){ finishing(); return false;});
	
	$(".radio2").click(function(){ $('#valid2').hide();});		//(duplicate of line below which we dont want to comment out unless below is included)
	//$(".radio2").click(function(){ showInfoNotFound(); $('#valid2').hide();});	//uncomment if u want the 'didnt find info I want' to pop up to user
	
	$("#survey-container").fadeIn();
	$("#greyout").css({
		opacity: 0.7,
		'width':$(document).width(),
		'height':$(document).height(),
		'background-color':'#000',
		'z-index':999
	});
};

function closeSurvey() {
	$("#survey-container").fadeOut('slow');
	$("#greyout").fadeOut('fast');
}

/** Shows the other text field for the sector question if it is not already showing.
 *  If its already showing it'll be hidden.
 */
function showOtherSector() {
	var radio1 = $('input[name="radio1"]:checked', '#surveyform').val();
	
	if(radio1 == "Other") {
		$('#showOtherSector').show('slow');
	} else {
		$('#showOtherSector').hide('slow');
	}
}

/** Shows the 'please comment' textarea for the 'did you find useful information' question
 *  If its already showing it'll be hidden.
 */
function showInfoNotFound() {
	var radio1 = $('input[name="radio2"]:checked', '#surveyform').val();
	
	if(radio1 == "No") {
		$('#userInfoNotFound').show('slow');
	} else {
		$('#userInfoNotFound').hide('slow');
	}
}

/** Checks that use has input something for questions (if not reminds user)
 *  If all ok then posts variables to php file that updates database
 */
function finishing() {
	var q1b = $('input[name="radio1"]:checked', '#surveyform').val();
	var q3b = $('input[name="radio2"]:checked', '#surveyform').val();
	
	if(q1b === undefined || q3b === undefined) {
		if(q1b === undefined)
			$('#valid1').show();
		if(q3b === undefined)
			$('#valid2').show();
	} else {
		//if user selects Other for Q1 the input for the other text field is fetched, else empty string
		var q2b = (q1b != "Other") ? "" : $("#q2b").val();
		
		//if user adds a comment for Q2 then the question that goes into the database depends on their yes/no answer for Q2
		var q4a = (q3b == "Yes") ? "(User was able to find what they were looking for) User comment:" : $("#q4a").val();
				

/*
		//this array needs to represent the number of questions & answers in the inner div
		$.post("http://iopclive.3ev.info/dataHandling.php", { "questions" : [
					[ $('#q1a').val() , q1b ],
					[ $('#q2a').val() , q2b ],
					[ $('#q3a').val() , q3b ],
					[ q4a , $('#q4b').val() ],
					[ $('#q5a').val() , $('#q5b').val() ]
			], email : $('#email').val()
		});
*/


		function sendAnswer(email, question, answer) {
			try {
			$.getJSON('http://iopclive.3ev.info/jsonsubmit.php?callback=?', {
			    'e' : top.surveykey,
			    'q' : question,
			    'a' : answer
			},
			function() {
				console.log('q='+question);
			});
			} catch(e) {
				alert(e.message);
			}
		}

		sendAnswer(
			$('#email').val(),
			'sector',
			q1b + ' ' + q2b);

		sendAnswer(
			$('#email').val(),
			'find',
			q3b);

		sendAnswer(
			$('#email').val(),
			'findcomment',
			$('#q4b').val());

		sendAnswer(
			$('#email').val(),
			'other',
			$('#q5b').val());
		




		var newInner = '<img src="http://iopclive.3ev.info/images/logo-survey.png" /><div id="surveyTitle">IOPC Funds Micro-Survey</div>';
		newInner += '<div class="question">Thank you.</div>';
		newInner += '<div id="buttons"><a href="#" id="test" onClick="closeSurvey();" class="right close closeSurvey">Close</a></div>';
		
		$("#survey-container").fadeOut('slow', function() {
			$("#inner").html(newInner);
			$("#survey-container").fadeIn('slow');
		});
	}
}




// DF: Moved to end

$(document).ready(function() {
	var viewedValue = 'isviewed4'; // Change this for updates in case IEx is annoying

	try {
          // DF: Added, as a 'uniqueness' to replace email
          top.surveykey = 's'+Math.round(Math.random()*10000000000);

          if($.cookie('survey')==viewedValue) {
                 return false;
          }

          $.cookie('survey', viewedValue);

          //setTimeout(showSurvey, 5000);
          
          $('a.mainlinkeng, a.pdflink, a.mainlinkspa, a.pdflink, a.mainlinkfra').click(function(){
            showSurvey();
          });

	} catch(e) {
  	  alert(e.message);
	}
});


