// JavaScript Document

var selectedQuestionid = 0;
var selectedGenderids = new Array();
var validator;
var demoMap;
var point;
var markerD;

$(function() {	
	
	$('#functionListen').click(function() {
		$('#content').css("background-image","url(images/ground_listen.png)");
		$('#mainAccordion').fadeIn(500); //in case mainAccordion is currently not displayed
		$('.accSpeakh').fadeOut(500);
		//$('.accSpeak').fadeOut(500, function(){
			//console.log("block!");
			$('.accListenh').fadeIn(500, function(){
				$('#mainAccordion').accordion( 'activate' , '#paneQuestion' );															
			});
		//});
		$('#infoMySelections').html("Start by choosing question and demographic filters in the panel to the right. <p>Then click 'Prepare Audio' in the 'Listen to your custom audio' section below, wait for the 'Play' button to activate and then click it.</p>");
		$('#myDemographics').fadeIn(500);
		$('#recordText').fadeOut(500);
		$('#reRecordButton').fadeOut(500);	
		$('#selectedNumberRecordings').removeClass("hidden").fadeIn(500);	
		$('#record').fadeOut(500, function(){
			$('#play').fadeIn(500);
		});
		
	});
	
	$('#functionSpeak').click(function() {
		$('#content').css("background-image","url(images/ground_speak.png)");
		$('#mainAccordion').fadeIn(500); //in case mainAccordion is currently not displayed
		$('#mainAccordion').accordion( 'activate' , '#paneQuestion' );
		$('.accListenh').fadeOut(500);
		$('.accListen').fadeOut(500, function(){
			$('.accSpeakh').fadeIn(500);
			
		});
		$('#myDemographics').fadeOut(500, function(){
			//$('#myQuestions').fadeIn(500);
		});
		
		$('#play').fadeOut(500, function(){
			$('#record').fadeIn(500);
		});
		//$('#numRec').fadeOut(500);
		//$('#selectedNumberRecordings').fadeOut(500);
		$('#infoMySelections').html("Start by choosing a question to speak about. <p>Click a question in the panel to the right and then follow the steps in the 'Make a recording' section below.</p>");
	});
	
	//MAP LOAD
	$('#mapIcon').click(function() {
		//$('#mapOverlay').jqmShow();
		//$('#mySelections').fadeOut(500, function(){
			//console.log("block!");
			//BlockUI code to block #mapLoad with message 'Loading Map!'
			$('#mapOverlay').block({ 
				message: '<span class="loadingGif"></span><div id="loadingMap">Loading Map!</div>', 
				css: { border: '1px solid #a00', position:'relative', margin:'15% auto', height:'70px' }, 
				centerX: true, 
				centerY: true
			});
			
			$('#mapLoad').load('map/ovmapplet.php', function() {
				//console.log("unblock!");
				//code to unblock #mapLoad element-called after load() is done	
				$('#mapOverlay').unblock();
			});
			//$('#mapLoad').fadeIn(500);
		//});
	});
	
	//$('#wimpy').block();
						   
	//legal consent to use recording
	$('#recnext3').click(function() {
			$('#playRecord').block({ 
				message: '<p><strong>Legal Mumbo Jumbo</strong></p><div class="" >By clicking "I Agree" below, you understand that any recording you make on this site will be used as part of the Ocean Voices art/conservation project.  You assign all rights to the recordings to Halsey Burgund and Wallace J. Nichols and allow them to use your comments to fulfill the goals of the project.  Thank you very much!</div><p><p><input type="button" id="btnAgree" value="I Agree" /> </p>', 
				css: { border: '1px solid #a00', height:'200px', width:'300px', fontSize:'9pt'}
			});
			$('#btnAgree').click(function() { 
            	$('#playRecord').unblock(); 
            	//return false; 
    		});
			//$('#btnAgree').click($.unblock);
	});
	
	//legal consent I AGREE button
	
	
	//function hovering
	$('#functionSpeak').hover(function() {
		//$('#recIcon').css("background-image","url(images/rec_icon_light.png)");
		$('#functionSpeak').css("background-image","url(images/speak_highlight.png)");
	}, function() {
		//$('#recIcon').css("background-image","url(images/rec_icon_dark.png)");
		$('#functionSpeak').css("background-image","url(images/speak.png)");
	}
	);
	
	$('#functionListen').hover(function() {
		//$('#playIcon').css("background-image","url(images/play_icon_light.png)");
		$('#functionListen').css("background-image","url(images/listen_highlight.png)");
	}, function() {
		//$('#playIcon').css("background-image","url(images/play_icon_dark.png)");
		$('#functionListen').css("background-image","url(images/listen.png)");
	}
	);
	$('#mapIcon').hover(function() {
		$('#mapIcon').css("background-image","url(images/ov_globe2_hover.png)");
	}, function() {
		$('#mapIcon').css("background-image","url(images/ov_globe2.png)");
	}
	);
	$('#prepAudio').hover(function() {
		$('#prepAudio').css("background-image","url(images/prepare_audio_highlight.png)");
	}, function() {
		$('#prepAudio').css("background-image","url(images/prepare_audio.png)");
	}
	);
	
	//autocomplete code
	/*$("#geoSearch").autocomplete('geo_suggest3.php', {
		width: 300,
		minChars: 4,
		max: 100,
		formatItem: function(data, i, n, value) {	
			return value.split(",")[0] + ", " + value.split(",")[1] + ", " + value.split(",")[2];
		},
		formatResult: function(data, value) {	
			return value.split(",")[0] + "," + value.split(",")[1] + "," + value.split(",")[2];
		}
	});
	
	
	$('#geoSearch').result(function(event, data, formatted) {
		var locationid = formatted.split(",")[3];
		autocompleteCallback(locationid);
	});*/
	
	//when submit button is clicked after filling out demographics
	$('#closeRecDialog').click(function() {
		validateDemoForm();
		var vld = $("#demographicForm").valid()
		//console.log(vld);
		if(vld) {
			$('#recDemoDialog').jqmHide(); 
			$('#recordText').html("<p>Congratulations!  You have successfully submitted your recording.  If you're on a roll, go ahead and make another recording in response to a different question.</p> <p>Your recording is now available to all on the map of recordings (click the globe above) and has been incorporated into the audio collages.  Click the LISTEN tab and hear yourself mixed in with other participants in an ever-changing audio collage.</p>").fadeIn(500);
			$('#mainAccordion').fadeOut(500, function(){
				$('#reRecordButton').removeClass("hidden").fadeIn(500);
			});
			addRecordingToDb();
			$('#record4').fadeOut(500, function(){
				$('#infoRecord').html("You need to pick a question (above right) before you can make a recording!");
				$('#recnext3').fadeOut(500);
				$('#record3').fadeIn(500);
			});
			//sendEmail();
		}
		
	});
	/*
	$('#recNext').click(function() {
		$(this).fadeOut(500);
		$('#flSetupMic').fadeOut(500, function(){
			$('#flRecord').removeClass("hidden").fadeIn(500);
		});
	});*/
	
	
	//make another recording button
	$('#reRecordButton').click(function() {
		resetRecord();
	});
	
	//prepare and open demographics overlay form
	$('#recContinue').click(function() {
		setupDemoMap();
		$("#geoSearch").autocomplete('geo_suggest3.php', {
			width: 300,
			minChars: 4,
			max: 100,
			formatItem: function(data, i, n, value) {	
				return value.split(",")[0] + ", " + value.split(",")[1] + ", " + value.split(",")[2];
			},
			formatResult: function(data, value) {	
				return value.split(",")[0] + "," + value.split(",")[1] + "," + value.split(",")[2];
			}
		});
		
		$('#geoSearch').result(function(event, data, formatted) {
			var locationid = formatted.split(",")[3];
			autocompleteCallback(locationid);
		});
		window.scroll(0,0);
		//jsonSuggestInitialize();
		stopRecording();
		//$('#recDemoDialog').jqmShow();
		//console.log("open demo form");
	});

	
	
	//reset all selections button
	$('#resetSelections').click(function() {
		resetSelections();
	});

	$("#mainAccordion").accordion({
		autoHeight: false,
		clearStyle: true,
		active: 0
		//collapsible: true 			
	});
	
	//initialize accordion by hiding the LISTEN panes
	$('.accListenh').fadeOut(500);
	$('.accListen').fadeOut(500);
	
	//submit recording form validation code
	validateDemoForm();
	//$('#locationid').val(0);
	//console.log($('#locationid').val());
	
	//initialize screen components
	initializeGui();	
	
	
	//custom validator method for combo boxes
	jQuery.validator.addMethod("notEqualTo", function(value, element, param) { 
	  return this.optional(element) || value != param; 
	}, "Please specify the correct domain for your documents");
	
	jQuery.validator.addMethod("lettersonly", function(value, element) {
			return this.optional(element) || /^[a-z]+$/i.test(value);
	}, "Please make a selection");

	
	//reset demographics form
	$('#resetDemographics').click(function() {
		$('.dmap').fadeOut(500).addClass("hidden");
		validator.resetForm();
		//jsonSuggestInitialize();
	});
	
	//cancel demographics form
	$('#cancelDemographics').click(function() {
		$('#recDemoDialog').jqmHide();
	});
	
	//close map overlay form
	$('#closeMap').click(function() {
		$('#mapOverlay').jqmHide();
	});
	
	
	//initialize jsonsuggest when field focused
	$("#geoSearch").focus(function () {
		//autocomplete code
		/*$("#geoSearch").autocomplete('geo_suggest3.php', {
			width: 300,
			minChars: 4,
			max: 100,
			formatItem: function(data, i, n, value) {	
				return value.split(",")[0] + ", " + value.split(",")[1] + ", " + value.split(",")[2];
			},
			formatResult: function(data, value) {	
				return value.split(",")[0] + "," + value.split(",")[1] + "," + value.split(",")[2];
			}
		});
	
	
		$('#geoSearch').result(function(event, data, formatted) {
			var locationid = formatted.split(",")[3];
			autocompleteCallback(locationid);
		});*/
    });
	
	//tooltips
	$(".tooltip").tooltip({
		position: ['top', 'center'],
		opacity: 0.95
	});
	
	//$('#showcase').slide();
	$("#showcase").easySlider({
		auto: false,
		continuous: true,
		numeric: true
	});
	
	$('#recnext1').click(function() {
		$('#record1').fadeOut(500, function(){
			$('#record2').removeClass("hidden").fadeIn(500);
		});
	});
	$('#recnext2').click(function() {
		$('#record2').fadeOut(500, function(){
			$('#record3').removeClass("hidden").fadeIn(500);
		});
	});
	$('#recnext3').click(function() {
		$('#record3').fadeOut(500, function(){
			$('#record4').removeClass("hidden").fadeIn(500);
		});
	});
	$('#recprev2').click(function() {
		$('#record2').fadeOut(500, function(){
			$('#record1').removeClass("hidden").fadeIn(500);
		});
	});
	$('#recprev3').click(function() {
		$('#record3').fadeOut(500, function(){
			$('#record2').removeClass("hidden").fadeIn(500);
		});
	});
	$('#recprev4').click(function() {
		$('#record4').fadeOut(500, function(){
			$('#record3').removeClass("hidden").fadeIn(500);
		});
	});
	
	$('#paneDemo').click(function() {
		//$('#wimpy').fadeOut(500);
		$('#numRec').fadeOut(500);
	});
	$('#paneQuestion').click(function() {
		//$('#wimpy').fadeOut(500);
		$('#numRec').fadeOut(500);
	});
	
	//ajax call to retrieve custom stream url
	$('#prepAudio').click(function() {
		var categoryid = $('#myCategoriesList li').attr("value");
		var subcategoryid = $('#mySubCategoriesList li').attr("value");
		var questionid = new Number;
		var ageid = new String; //new Array(); //'347'; //new Array(5,6,7);
		var genderid = new Array(); //'12';
		var usertypeid = new Array(); //new Array(7,10,23);
		//console.log("function called");
		
		//$('#wimpy').fadeOut(200, function() {			   
			$('#wimpy').css("opacity","1.0");
		//});
		
		if ( $('#myQuestionsList li').length ) {
			questionid = $('#myQuestionsList li').attr("value");
		}
		
		if($('#myAgesList li').attr("value") == 0) {
		$('#allAgesList li').each(function (i) {
			ageid += '&ageid[' + i + ']=';
			ageid += this.value;
			//console.log("ages=" + ages);
		});
		}
		else {
			$('#myAgesList li').each(function (i) {
				//ages += '&ages=';
				//ages += '&ageid[' + i + ']=';
				ageid += this.value;
				ageid += ',';
				//console.log("ages=" + ages);
			});
		}
		if($('#myGendersList li').attr("value") == 0) {
			$('#allGendersList li').each(function (i) {
				genderid += '&genderid[' + i + ']=';
				genderid += this.value;
				//console.log("genders=" + genders);
			});
		}
		else {
			$('#myGendersList li').each(function (i) {
				//genders += '&genders[' + i + ']=';
				genderid += this.value;
				genderid += ',';
				//console.log("genders=" + genders);
			});
		}
		if($('#myTypesList li').attr("value") == 0) {
			$('#allTypesList li').each(function (i) {
				usertypeid += '&usertypeid[' + i + ']=';
				usertypeid += this.value;
				//console.log("usertypes=" + usertypes);
			});
		}
		else {
			$('#myTypesList li').each(function (i) {
				//usertypes += '&usertypes[' + i + ']=';
				usertypeid += this.value;
				usertypeid += ',';
				//console.log("usertypes=" + usertypes);
			});
		}
		
		//first ajax call to return number of recordings in query
		/*$.ajax({
			url: 'number_of_recordings.php',
			type: 'POST',
			data: 	'categoryid=' + categoryid +
					'&subcategoryid=' + subcategoryid +
					'&questionid=' + questionid +
					 genderid +
					 ageid +
					 usertypeid,
			
			success: function(result) {
				//console.log(result);
				if(result==1){
					str=" recording matches";
				}
				else {str=" recordings match";}
				$('#numRec').text(result + str + " your selections").fadeIn(500);
			}
		});
		*/
		//second ajax call to instantiate stream and create wimpy button to play stream
		$.ajax({
			url: 'request_stream.php',
			type: 'POST',
			data: 	'categoryid=' + categoryid +
					'&subcategoryid=' + subcategoryid +
					'&questionid=' + questionid +
					'&ageid=' + ageid +
					'&genderid=' + genderid +
					'&usertypeid=' + usertypeid,
			
			success: function(result) {
				//console.log("you are playing stream url: " + result);
				$('#iceStreamName').text(result);
				var wimpString = "<script language='JavaScript' type='text/JavaScript'> writeWimpyButton('" + result + "', '120', '120', '&icecast=20');</script>";
				//console.log(wimpString);
				$('#wimpy').html(wimpString).fadeIn(500);
				$('#prepAudio').fadeOut(200, function(){
					$('#audioReady').fadeIn(200);
				});
			}
		});
		return false;
		
		
		
	});
	
	
	//ui functions - hovering
  	$("li").hover(
      function () {
        $(this).addClass("ui-state-highlight");
      }, 
      function () {
        $(this).removeClass("ui-state-highlight");
      }
    );
	
	//jgModal overlays
	$('#recDemoDialog').jqm({modal: true, overlay: 70, trigger: '#recContinue'});
    $('#mapOverlay').jqm({modal: true, overlay: 70, trigger: '#mapIcon'});
    //$('#mapFilter').jqm({modal: true, trigger: '#openMapFilter', overlay: 70});
	
	//connectToFlash("rw_record_b.swf");

	//these functions move individual selection divs
	$('#call').click(function() {
		var s = $(this).attr('id');					
		moveCategory(s);
	});
	$('#c1').click(function() {
		var s = $(this).attr('id');					
		moveCategory(s);
	});
	$('#c2').click(function() {
		var s = $(this).attr('id');					
		moveCategory(s);
	});
	$('#c3').click(function() {
		var s = $(this).attr('id');					
		moveCategory(s);
	});
	$('#c4').click(function() {
		var s = $(this).attr('id');					
		moveCategory(s);
	});
	$('#c5').click(function() {
		var s = $(this).attr('id');					
		moveCategory(s);
	});
	
	$('#scall').click(function() {
		var s = $(this).attr('id');					
		moveSubCategory(s);
	});
	$('#sc1').click(function() {
		var s = $(this).attr('id');					
		moveSubCategory(s);
	});
	$('#sc2').click(function() {
		var s = $(this).attr('id');					
		moveSubCategory(s);
	});
	$('#sc3').click(function() {
		var s = $(this).attr('id');					
		moveSubCategory(s);
	});
	$('#sc4').click(function() {
		var s = $(this).attr('id');					
		moveSubCategory(s);
	});
	$('#sc5').click(function() {
		var s = $(this).attr('id');					
		moveSubCategory(s);
	});
	
	$('#ageall').click(function() {
		var s = $(this).attr('id');					
		moveAgeAll(s);
	});
	$('#age1').click(function() {
		var s = $(this).attr('id');					
		moveAge(s);
	});
	$('#age2').click(function() {
		var s = $(this).attr('id');					
		moveAge(s);
	});
	$('#age3').click(function() {
		var s = $(this).attr('id');					
		moveAge(s);
	});
	$('#age4').click(function() {
		var s = $(this).attr('id');					
		moveAge(s);
	});
	$('#age5').click(function() {
		var s = $(this).attr('id');					
		moveAge(s);
	});
	$('#age6').click(function() {
		var s = $(this).attr('id');					
		moveAge(s);
	});
	$('#age7').click(function() {
		var s = $(this).attr('id');					
		moveAge(s);
	});
	
	$('#gall').click(function() {
		var s = $(this).attr('id');					
		moveGenderAll(s);
	});
	$('#g1').click(function() {
		var s = $(this).attr('id');					
		moveGender(s);
	});
	$('#g2').click(function() {
		var s = $(this).attr('id');					
		moveGender(s);
	});
	$('#g3').click(function() {
		var s = $(this).attr('id');					
		moveGender(s);
	});
	
	$('#tall').click(function() {
		var s = $(this).attr('id');					
		moveTypeAll(s);
	});
	$('#t1').click(function() {
		var s = $(this).attr('id');					
		moveType(s);
	});
	$('#t2').click(function() {
		var s = $(this).attr('id');					
		moveType(s);
	});
	$('#t3').click(function() {
		var s = $(this).attr('id');					
		moveType(s);
	});
	$('#t4').click(function() {
		var s = $(this).attr('id');					
		moveType(s);
	});
	$('#t5').click(function() {
		var s = $(this).attr('id');					
		moveType(s);
	});
	$('#t6').click(function() {
		var s = $(this).attr('id');					
		moveType(s);
	});
	$('#t7').click(function() {
		var s = $(this).attr('id');					
		moveType(s);
	});
	$('#t8').click(function() {
		var s = $(this).attr('id');					
		moveType(s);
	});
	$('#t9').click(function() {
		var s = $(this).attr('id');					
		moveType(s);
	});
	$('#t10').click(function() {
		var s = $(this).attr('id');					
		moveType(s);
	});
	$('#t11').click(function() {
		var s = $(this).attr('id');					
		moveType(s);
	});
	$('#t12').click(function() {
		var s = $(this).attr('id');					
		moveType(s);
	});
	$('#t13').click(function() {
		var s = $(this).attr('id');					
		moveType(s);
	});
	
	$('#q1').click(function() {
		var s = $(this).attr('id');					
		moveQuestion(s);
	});
	$('#q2').click(function() {
		var s = $(this).attr('id');					
		moveQuestion(s);
	});
	$('#q3').click(function() {
		var s = $(this).attr('id');					
		moveQuestion(s);
	});
	$('#q4').click(function() {
		var s = $(this).attr('id');					
		moveQuestion(s);
	});
	$('#q5').click(function() {
		var s = $(this).attr('id');					
		moveQuestion(s);
	});
	$('#q6').click(function() {
		var s = $(this).attr('id');					
		moveQuestion(s);
	});
	$('#q7').click(function() {
		var s = $(this).attr('id');					
		moveQuestion(s);
	});
	$('#q8').click(function() {
		var s = $(this).attr('id');					
		moveQuestion(s);
	});

});


//js for draggable selection lists
$(function() {
		$("#myCategoriesList, #allCategoriesList").sortable({
			connectWith: '.connectedSortable'
		}).disableSelection();
});


//plugin functions

/*$().ready(function() {
  $('#recDemoDialog').jqm({modal: true, overlay: 70});
  $('#recDemoDialog').jqmAddTrigger($('#recContinue'));
  $('#mapOverlay').jqm({modal: true, overlay: 70});
  $('#mapOverlay').jqmAddTrigger('#mapIcon'); 

  //$('#mapFilter').jqm({modal: true, trigger: '#openMapFilter', overlay: 70});
  //$('#cboCountry').val(0);
});*/

//geoSuggest code - called on dialog open in order to initialize properly
/*function jsonSuggestInitialize() {
	//console.log("jsonsuggest initialized");
	$('#recDemoDialog').show(500);
	$('input#geoSearch').jsonSuggest(function(text, wildCard, caseSensitive, notCharacter) {
		$('#loadingGeo').removeClass("hidden").fadeIn(500);
		//console.log("jsonsuggest active!");
		loc = $.ajax({
			type: 'GET',
			url: 'geo_suggest.php',
			data: 'textentry=' + text,
			dataType: 'json',
			async: false,
			success: function(result) {
				console.log("jsonsuggest success!");
				$('#loadingGeo').fadeOut(500);
			}
		});
		return eval(loc.responseText); 
		}, { ajaxResults:true, minCharacters:4, maxHeight:200, onSelect:jsonSuggestCallback }
	); 
}*/

/*function testing() {
	console.log("testing function");
	$('#myQuestions').hide(500);
	writeWimpyButton('http://scfire-mtc-aa02.stream.aol.com:80/stream/1006', '60', '60', '&icecast=20');
}*/
	
//jsonSuggest callback function
function autocompleteCallback(locationid) {	
		var geonameid = locationid;
		//console.log(geonameid);
		var table = 'geosuggest';
		$('#locationid').val(geonameid);
		//console.log($('#locationid').val());
		
		$.ajax({
			url: 'db_geoname_latlon.php',
			type: 'POST',
			data:	'geonameid=' + geonameid +
					'&table=' + table,
			
			success: function(result) {
				$('.dmap').removeClass("hidden");
				demoMap.checkResize();
				demoMap.clearOverlays();
				
				point = GLatLng.fromUrlValue(result);
				demoMap.setCenter(point,10, G_NORMAL_MAP);
				markerD = new GMarker(point, {draggable: true}); 
				demoMap.addOverlay(markerD);
				markerD.enableDragging();
				$("#myLatitude").text(markerD.getPoint().lat().toFixed(6));
				$("#myLongitude").text(markerD.getPoint().lng().toFixed(6));
				GEvent.addListener(markerD, "drag", function(){
					//$("#myLocation").text(markerD.getPoint().toUrlValue());
					$("#myLatitude").text(markerD.getPoint().lat().toFixed(6));
					$("#myLongitude").text(markerD.getPoint().lng().toFixed(6));
				});	
				$('#loadingGeo').fadeOut(500);
			}
		});
		return false;
}



//custom functions

//move functions
function moveCategory(selection) {
	selection = "#" + selection;
	var selectedCategoryid = $(selection).attr('value');
	//console.log(selectedCategoryid);
	$('#infoMySelections').fadeOut(500);
	//console.log(selection);
	if($(selection).parent().attr('id') == 'allCategoriesList') {
		//fade out all currently selected categories and append them back to allCategories list
		$('#myCategoriesList').children().fadeOut(500, function(){
			$('#myCategoriesList').children().appendTo('#allCategoriesList').fadeIn(500);
			$(selection).removeClass("ui-state-highlight").addClass("ui-state-default");
		});
		//fadeout all subcategories associated with previously selected category
		$('#mySubCategoriesList').children().remove();
		//filter(function () {
//        	return $(this).attr("categoryid") == selectedCategoryid;
//			console.log("trying to remove subcategories");
//        })
//        .addClass("hidden");
		
		//fadeout selected category from allCategories and fadein to myCategories
		$(selection).fadeOut(500, function(){
			$(selection).appendTo('#myCategoriesList').fadeIn(500);
			$(selection).removeClass("ui-state-highlight").addClass("ui-state-default");
			numberSelectedRecordings();
		});
		//unhide all subcategories associated with the selected category
		$('#allSubCategoriesList').children().addClass("hidden");
		$('#infoSubCategory').fadeOut(500);
		$('#allSubCategoriesList').children().filter(function () {
        	return $(this).attr("categoryid") == selectedCategoryid;
        })
        .removeClass('hidden');
		//hide all questions since all subcategories are removed and questions are associated with subcategories
		$('#allQuestionsList').children().addClass("hidden");
		//remove selected questions
		$('#myQuestionsList').children().remove();
	}
	else if($(selection).parent().attr('id') == 'myCategoriesList') {
		$(selection).fadeOut(500, function(){
			$(selection).appendTo('#allCategoriesList').fadeIn(500);
			$(selection).removeClass("ui-state-highlight").addClass("ui-state-default");
			numberSelectedRecordings();
		});
		//hide all subcategories associated with the de-selected category
		//$('#allSubCategoriesList').children().filter(function () {
//        	return $(this).attr("categoryid") == selectedCategoryid;
//        })
//        .addClass('hidden');
		//remove selected subcategories associated with deselected category and put them back into allSubCategories list as hidden
		$('#mySubCategoriesList').children().filter(function () {
        	return $(this).attr("categoryid") == selectedCategoryid;
        })
        .appendTo('#allSubCategoriesList').addClass('hidden');
		//hide all subcategories in allSub list
		$('#allSubCategoriesList').children().addClass("hidden");
		$('#infoSubCategory').fadeIn(500); //show sc warning
		//hide all questions associated with the deselected category
		$('#allQuestionsList').children().filter(function () {
    	   	return $(this).attr("categoryid") == selectedCategoryid;
    	})
    	.addClass('hidden');
		//remove selected questions
		$('#myQuestionsList').children().remove();
	};
}

function moveSubCategory(selection) {
	selection = "#" + selection;
	var selectedSubCategoryid = $(selection).attr('value');
	$('#infoMySelections').fadeOut(500);
	//console.log(selection);
	if($(selection).parent().attr('id') == 'allSubCategoriesList') {
		$(selection).fadeOut(500, function(){
			$(selection).appendTo('#mySubCategoriesList').fadeIn(500);
			$(selection).removeClass("ui-state-highlight").addClass("ui-state-default");
			numberSelectedRecordings();
		});
		//this code unhides all questions associated with the selected subcategory
		$('#infoQuestions').fadeOut(500);
		$('#allQuestionsList').children().filter(function () {
    	   	return $(this).attr("subcategoryid") == selectedSubCategoryid;
    	})
    	.removeClass('hidden');
	}
	else if($(selection).parent().attr('id') == 'mySubCategoriesList') {
		$(selection).fadeOut(500, function(){
			$(selection).appendTo('#allSubCategoriesList').fadeIn(500);
			$(selection).removeClass("ui-state-highlight").addClass("ui-state-default");
			numberSelectedRecordings();
		});
		//hide all questions associated with the deselected subcategory
		$('#allQuestionsList').children().filter(function () {
    	   	return $(this).attr("subcategoryid") == selectedSubCategoryid;
    	})
    	.addClass('hidden');
		//remove selected questions associated with deselected subcategory
		//$('#myQuestionsList').children().remove();
		$('#myQuestionsList').children().filter(function () {
    	   	return $(this).attr("subcategoryid") == selectedSubCategoryid;
    	})
    	.remove();
	};
}

function moveAge(selection) {
	selection = "#" + selection;
	$('#infoMySelections').fadeOut(500);
	//console.log(selection);
	if($(selection).parent().attr('id') == 'allAgesList') {
			$(selection).fadeOut(500, function(){
				$(selection).appendTo('#myAgesList').fadeIn(500);
				$(selection).removeClass("ui-state-highlight").addClass("ui-state-default");
				numberSelectedRecordings();
			});
	}
	else if($(selection).parent().attr('id') == 'myAgesList') {
			$(selection).fadeOut(500, function(){
				$(selection).appendTo('#allAgesList').fadeIn(500);
				$(selection).removeClass("ui-state-highlight").addClass("ui-state-default");
				numberSelectedRecordings();
			});
	};
	//move All back to allList if in myList already
	if($('#ageall').parent().attr('id') == 'myAgesList') {
			$('#ageall').fadeOut(500, function(){
				$('#ageall').prependTo('#allAgesList').fadeIn(500);
				$('#ageall').removeClass("ui-state-highlight").addClass("ui-state-default");
				numberSelectedRecordings();
			});
	}
	//activate 'Prepare Audio' button
	$('#audioReady').fadeOut(200, function(){
		$('#prepAudio').fadeIn(200);
	});
}
function moveAgeAll(selection) {
	selection = "#" + selection;
	$('#infoMySelections').fadeOut(500);
	//console.log(selection);
	//if in allList, move to myList and remove all children in myList
	if($(selection).parent().attr('id') == 'allAgesList') {
			$('#myAgesList').children().fadeOut(500, function(){
				$('#myAgesList').children().appendTo('#allAgesList').fadeIn(500);
				$(selection).removeClass("ui-state-highlight").addClass("ui-state-default");
			});
			$(selection).fadeOut(500, function(){
				$(selection).appendTo('#myAgesList').fadeIn(500);
				$(selection).removeClass("ui-state-highlight").addClass("ui-state-default");
				numberSelectedRecordings();
			});
	}
	//if in myList, move back to allList
	else if($(selection).parent().attr('id') == 'myAgesList') {
			$(selection).fadeOut(500, function(){
				$(selection).prependTo('#allAgesList').fadeIn(500);
				$(selection).removeClass("ui-state-highlight").addClass("ui-state-default");
				numberSelectedRecordings();
			});
	};
	//activate 'Prepare Audio' button
	$('#audioReady').fadeOut(200, function(){
		$('#prepAudio').fadeIn(200);
	});
}

function moveGender(selection) {
	selection = "#" + selection;
	$('#infoMySelections').fadeOut(500);
	//console.log(selection);
	if($(selection).parent().attr('id') == 'allGendersList') {
			$(selection).fadeOut(500, function(){
				$(selection).appendTo('#myGendersList').fadeIn(500);
				$(selection).removeClass("ui-state-highlight").addClass("ui-state-default");
				numberSelectedRecordings();
			});
	}
	else if($(selection).parent().attr('id') == 'myGendersList') {
			$(selection).fadeOut(500, function(){
				$(selection).appendTo('#allGendersList').fadeIn(500);
				$(selection).removeClass("ui-state-highlight").addClass("ui-state-default");
				numberSelectedRecordings();
			});
	};
	//move All back to allList if in myList already
	if($('#gall').parent().attr('id') == 'myGendersList') {
			$('#gall').fadeOut(500, function(){
				$('#gall').prependTo('#allGendersList').fadeIn(500);
				$('#gall').removeClass("ui-state-highlight").addClass("ui-state-default");
				numberSelectedRecordings();
			});
	}
	//activate 'Prepare Audio' button
	$('#audioReady').fadeOut(200, function(){
		$('#prepAudio').fadeIn(200);
	});
}

function moveGenderAll(selection) {
	selection = "#" + selection;
	$('#infoMySelections').fadeOut(500);
	//console.log(selection);
	//if in allList, move to myList and remove all children in myList
	if($(selection).parent().attr('id') == 'allGendersList') {
			$('#myGendersList').children().fadeOut(500, function(){
				$('#myGendersList').children().appendTo('#allGendersList').fadeIn(500);
				$(selection).removeClass("ui-state-highlight").addClass("ui-state-default");
			});
			$(selection).fadeOut(500, function(){
				$(selection).appendTo('#myGendersList').fadeIn(500);
				$(selection).removeClass("ui-state-highlight").addClass("ui-state-default");
				numberSelectedRecordings();
			});
		}
	//if in myList, move back to allList
	else if($(selection).parent().attr('id') == 'myGendersList') {
			$(selection).fadeOut(500, function(){
				$(selection).prependTo('#allGendersList').fadeIn(500);
				$(selection).removeClass("ui-state-highlight").addClass("ui-state-default");
				numberSelectedRecordings();
			});
		};
	//activate 'Prepare Audio' button
	$('#audioReady').fadeOut(200, function(){
		$('#prepAudio').fadeIn(200);
	});
}

function moveType(selection) {
	selection = "#" + selection;
	$('#infoMySelections').fadeOut(500);
	//console.log(selection);
	if($(selection).parent().attr('id') == 'allTypesList') {
			$(selection).fadeOut(500, function(){
				$(selection).appendTo('#myTypesList').fadeIn(500);
				$(selection).removeClass("ui-state-highlight").addClass("ui-state-default");
				numberSelectedRecordings();
			});
		}
	else if($(selection).parent().attr('id') == 'myTypesList') {
			$(selection).fadeOut(500, function(){
				$(selection).appendTo('#allTypesList').fadeIn(500);
				$(selection).removeClass("ui-state-highlight").addClass("ui-state-default");
				numberSelectedRecordings();
			});
		};
	//move All back to allList if in myList already
	if($('#tall').parent().attr('id') == 'myTypesList') {
			$('#tall').fadeOut(500, function(){
				$('#tall').prependTo('#allTypesList').fadeIn(500);
				$('#tall').removeClass("ui-state-highlight").addClass("ui-state-default");
				numberSelectedRecordings();
			});
		}
	//activate 'Prepare Audio' button
	$('#audioReady').fadeOut(200, function(){
		$('#prepAudio').fadeIn(200);
	});
}

function moveTypeAll(selection) {
	selection = "#" + selection;
	$('#infoMySelections').fadeOut(500);
	//console.log(selection);
	//if in allList, move to myList and remove all children in myList
	if($(selection).parent().attr('id') == 'allTypesList') {
			$('#myTypesList').children().fadeOut(500, function(){
				$('#myTypesList').children().appendTo('#allTypesList').fadeIn(500);
				$(selection).removeClass("ui-state-highlight").addClass("ui-state-default");
			});
			$(selection).fadeOut(500, function(){
				$(selection).appendTo('#myTypesList').fadeIn(500);
				$(selection).removeClass("ui-state-highlight").addClass("ui-state-default");
				numberSelectedRecordings();
			});
		}
	//if in myList, move back to allList
	else if($(selection).parent().attr('id') == 'myTypesList') {
			$(selection).fadeOut(500, function(){
				$(selection).prependTo('#allTypesList').fadeIn(500);
				$(selection).removeClass("ui-state-highlight").addClass("ui-state-default");
				numberSelectedRecordings();
			});
		};
	//activate 'Prepare Audio' button
	$('#audioReady').fadeOut(200, function(){
		$('#prepAudio').fadeIn(200);
	});
}

function moveQuestion(selection) {
	selection = "#" + selection;
	
	$('#infoMySelections').fadeOut(500);
	//console.log(selection);
	if($(selection).parent().attr('id') == 'allQuestionsList') {
			$('#myQuestionsList').children().fadeOut(500, function(){
				$('#myQuestionsList').children().appendTo('#allQuestionsList').fadeIn(500);
				$(selection).removeClass("ui-state-highlight").addClass("ui-state-default");
			});
			$(selection).fadeOut(500, function(){
				$(selection).appendTo('#myQuestionsList').fadeIn(500);
				$(selection).removeClass("ui-state-highlight").addClass("ui-state-default");
				numberSelectedRecordings();
			});
			selectedQuestionid = $(selection).attr('value');
			
			$('#flRecord').removeClass("hidden");
			$('#recnext3').removeClass("hidden").fadeIn(500);
			$('#infoRecord').html("You are now ready to make a recording.  In order to obtain the best possible sound quality, please ensure that ambient noise is kept to a minimum by isolating yourself and turning off noise-making machines such as fans, cats etc.</ br> Have fun and be yourself!");
			//console.log(selectedQuestionid);
		}
	else if($(selection).parent().attr('id') == 'myQuestionsList') {
			$(selection).fadeOut(500, function(){
				$(selection).appendTo('#allQuestionsList').fadeIn(500);
				$(selection).removeClass("ui-state-highlight").addClass("ui-state-default");
				numberSelectedRecordings();
			});
			selectedQuestionid = 0;
			$('#flRecord').addClass("hidden");
			$('#recnext3').fadeOut(500);
			$('#infoRecord').html("You need to pick a question (above right) before you can make a recording!");
			//console.log(selectedQuestionid);
		};
		//activate 'Prepare Audio' button
		$('#audioReady').fadeOut(200, function(){
			$('#prepAudio').fadeIn(200);
		});
}

function resetRecord() {
	$('#reRecordButton').fadeOut(500);
	$('#recordText').fadeOut(500);
	$('#mainAccordion').fadeIn(500, function(){
		$('#mainAccordion').accordion( 'activate' , 0 );									 
	});
	$('#myQuestionsList').children().fadeOut(500, function(){
		$('#myQuestionsList').children().appendTo('#allQuestionsList').fadeIn(500).removeClass("ui-state-highlight").addClass("ui-state-default");
	});
	$('#record4').fadeOut(500, function(){
		$('#infoRecord').html("You need to pick a question (above right) before you can make a recording!");
		$('#recnext3').fadeOut(500);
		$('#record3').fadeIn(500);
	});
}

function resetSelections() {
	$('#myCategoriesList').children().fadeOut(500, function(){
		$('#myCategoriesList').children().appendTo('#allCategoriesList').fadeIn(500).removeClass("ui-state-highlight").addClass("ui-state-default");
	});
	$('#mySubCategoriesList').children().fadeOut(500, function(){
		$('#mySubCategoriesList').children().appendTo('#allSubCategoriesList').fadeIn(500).removeClass("ui-state-highlight").addClass("ui-state-default");
		$('#allSubCategoriesList').children().addClass("hidden");
	});
	$('#myAgesList').children().filter(function () {
   	   	return $(this).attr("id") == "ageall";
   	})
    .prependTo('#allAgesList').fadeIn(500).removeClass("ui-state-highlight").addClass("ui-state-default");
	$('#myAgesList').children().fadeOut(500, function(){
		$('#myAgesList').children().appendTo('#allAgesList').fadeIn(500).removeClass("ui-state-highlight").addClass("ui-state-default");
	});
	$('#myGendersList').children().filter(function () {
   	   	return $(this).attr("id") == "gall";
   	})
    .prependTo('#allGendersList').fadeIn(500).removeClass("ui-state-highlight").addClass("ui-state-default");
	$('#myGendersList').children().fadeOut(500, function(){
		$('#myGendersList').children().appendTo('#allGendersList').fadeIn(500).removeClass("ui-state-highlight").addClass("ui-state-default");
	});
	$('#myTypesList').children().filter(function () {
   	   	return $(this).attr("id") == "tall";
   	})
    .prependTo('#allTypesList').fadeIn(500).removeClass("ui-state-highlight").addClass("ui-state-default");
	$('#myTypesList').children().fadeOut(500, function(){
		$('#myTypesList').children().appendTo('#allTypesList').fadeIn(500).removeClass("ui-state-highlight").addClass("ui-state-default");
	});
	$('#myQuestionsList').children().fadeOut(500, function(){
		$('#myQuestionsList').children().appendTo('#allQuestionsList').fadeIn(500).removeClass("ui-state-highlight").addClass("ui-state-default");
	});
	$('#allQuestionsList').children().addClass("hidden");
	$('#mainAccordion').accordion( 'activate' , false );
	$('#infoMySelections').fadeIn(1000);
}

//flash interaction - used to grab filename string from swf for entry into database - code taken from Flash help

function thisMovie(movieName) {
    var isIE = navigator.appName.indexOf("Microsoft") != -1;
    return (isIE) ? window[movieName] : document[movieName];
}

//calls function in flash
function stopRecording(str) {
    thisMovie("rw_record_b").asFunc(str);
}

//triggered when Record button in flash is clicked
function jsFunc(str) {
	str = str + ".flv"
	$('#filenameFromFlash').text(str);
	$('#recContinue').removeClass("hidden").show(500);
}




//function that does validation while form is being filled out as well as on submit
function validateDemoForm() {
	//console.log("validating?");
	var geonameid = $('#locationid').val();
	//console.log(geonameid);
	validator = $("#demographicForm").validate({
	  rules: { 
            firstname: {required: true, minlength: 2},
            lastname: {required: true, minlength: 2}, 
            email: { 
                required: true, 
                email: true
            },
			cboGender: {
				required: true,
				min: 1
			},
			cboAge: {
				required: true,
				min: 1
			},
			cboType: {
				required: true,
				min: 1
			},
			q: {
				required: true,
				minlength: 12
			},
			locationid: {
				required: false
			}
        }, 
        messages: { 
            firstname: {
				required: "Please enter your first name!", 
				minlength: jQuery.format("Please enter at least {0} characters")
			},
            lastname: {
				required: "Please enter your last name!", 
				minlength: jQuery.format("Please enter at least {0} characters")
			}, 
            email: { 
                required: "Please enter a valid email address"
            },
			cboGender: {
				min: "Please select a gender"
			},
			cboAge: {
				min: "Please select an age range"
			},
			cboType: {
				min: "Please select the most appropriate category"
			},
			q: {
				required: "Please enter your location and select from popup list",
				minlength: "Please enter your location and select from popup list"	
			},
			locationid: {
				required: "Please assign a location"
			}
        }
	});
}

//initialize screen - what's showing and what isn't
function initializeGui() {
	//console.log("initialize");
	$('#content').css("background-color","#003366");
	//$('.accListen').fadeOut(500, function(){
		//$('h3.accSpeak').fadeIn(500, function(){
			//$('#mainAccordion').accordion( 'activate' , 5 );								  
		//});
	//	$('#mainAccordion').accordion( 'activate' , false );
		
	//});
	$('#myDemographics').fadeOut(500);
	$('#myQuestions').fadeIn(500);

	$('#infoQuestions').addClass("hidden");
}



function setupDemoMap() {
	////map
	demoMap = new GMap2(document.getElementById("myMap"));
	demoMap.setCenter(new GLatLng(15.512161, -0.14110), 2, G_NORMAL_MAP);
	//demoMap.addControl(new GMapTypeControl(1));
	demoMap.addControl(new GSmallZoomControl());
	
	demoMap.enableContinuousZoom();
	demoMap.enableDoubleClickZoom();	
	
}

function numberSelectedRecordings() {
	var categoryid = $('#myCategoriesList li').attr("value");
	var subcategoryid = $('#mySubCategoriesList li').attr("value");
	var questionid = new Number;
	var ages = new String; //new Array(); //'347'; //new Array(5,6,7);
	var genders = new Array(); //'12';
	var usertypes = new Array(); //new Array(7,10,23);
	
	if ( $('#myQuestionsList li').length ) {
		questionid = $('#myQuestionsList li').attr("value");
	}
	
	if($('#myAgesList li').attr("value") == 0) {
		$('#allAgesList li').each(function (i) {
			ages += '&ages[' + i + ']=';
			ages += this.value;
			//console.log("ages=" + ages);
		});
	}
	else {
		$('#myAgesList li').each(function (i) {
			//ages += '&ages=';
			//ages += '&ageid[' + i + ']=';
			ages += this.value;
			ages += ',';
			//console.log("ages=" + ages);
		});
	}
	if($('#myGendersList li').attr("value") == 0) {
		$('#allGendersList li').each(function (i) {
			genders += '&genders[' + i + ']=';
			genders += this.value;
			//console.log("genders=" + genders);
		});
	}
	else {
		$('#myGendersList li').each(function (i) {
			//genders += '&genders[' + i + ']=';
			genders += this.value;
			genders += ',';
			//console.log("genders=" + genders);
		});
	}
	if($('#myTypesList li').attr("value") == 0) {
		$('#allTypesList li').each(function (i) {
			usertypes += '&usertypes[' + i + ']=';
			usertypes += this.value;
			//console.log("usertypes=" + usertypes);
		});
	}
	else {
		$('#myTypesList li').each(function (i) {
			//usertypes += '&usertypes[' + i + ']=';
			usertypes += this.value;
			usertypes += ',';
			//console.log("usertypes=" + usertypes);
		});
	}
	
	//first ajax call to return number of recordings in query
	$.ajax({
		url: 'number_of_recordings.php',
		type: 'POST',
		data: 	'categoryid=' + categoryid +
				'&subcategoryid=' + subcategoryid +
				'&questionid=' + questionid +
				'&ageid=' + ages +
				'&genderid=' + genders +
				'&usertypeid=' + usertypes,
		
		success: function(result) {
			//console.log(result);
			if(result==1){
				str=" recording matches";
			}
			else {str=" recordings match";}
			$('#numRec').text(result + str + " your selections").fadeIn(500);
			$('#selectedNumberRecordings').text(result + str + " your selections").fadeIn(500);
		}
	});
}