var gSuggestionList;
function openSuggestionNoteDialog(){
	$("#suggestform_searchresults").hide();
	$("#suggestform").dialog("open");
	$("#suggestform_contactinfo").show();
}

function openSuggestionAddDialog(){
	$("#suggestform_searchresults").show();
	$("#suggestform").dialog("open");
	$("#suggestform_contactinfo").show();
}

function searchFailure(){
	$("#suggestionsearchform").dialog("close");
}

function doTransitionToEdit(){
	var newLocation = "http://" + document.location.hostname +"/trips/edit.php?map_id=" + mapExtId;
	window.location = newLocation;
}

function setupPageTransition(){
	$("#editMapButton").click(doTransitionToEdit);
}

function clearAddSuggestionFields(){
	$("#suggestionTitleField").val("");
	$("#suggestionTitleDisplay").html("");
	$("#suggestionAddressField").val("");
	$("#suggestionAddressDisplay").html("");
	$("#suggestionStateEtcField").val("");
	$("#suggestionStateEtcDisplay").html("");	
}

function clearSuggestionNote( leaveSuggestorInfo ){
	if(leaveSuggestorInfo != true){
		$("#suggestform #suggestformFields #suggest_name ").val("");
		$("#suggestform #suggestformFields #suggest_website").val("");
		$("#suggestform #suggestformFields #suggest_twitter").val("");
		$("#suggestform #suggestformFields #suggest_email").val("");
	}
	$("#suggestform #suggestformFields #suggest_note").val("");
	
}

function clearSuggestion( leaveSuggestorInfo ){
	var mainForm = "#suggestionsearchform";
	var contactForm = "#suggestorContactInfo";
	
	var contactLocator = mainForm + " " + contactForm + " " ;

	if(leaveSuggestorInfo != true){
		$(contactLocator + "#suggest_name").val("");
		$(contactLocator + "#suggest_website").val("");
		$(contactLocator + "#suggest_twitter").val("");
		$(contactLocator + "#suggest_email").val("");
	}
	$(contactLocator + "#suggest_note").val("");
	fillInSuggestorNameFromCookies();
	
}

function hideSuggestionSearchResults(){
	$("#resultsScroller").hide();
}
function showSuggestionSearchResults(){
	$("#suggestform_searchresults").show();
	$("#resultsScroller").show();
}
function showSuggestionSubmission(){
	$("#suggestorContactInfo").show();
}
function hideSuggestionSubmission(){
	$("#suggestorContactInfo").hide();
}

function cancelSuggestionSubmission(){
	hideSuggestionSubmission();
	showSuggestionSearchResults();
}

function submitSuggestionSubmission(){
	postSubmission();
	hideSuggestionSubmission();
	showSuggestionSearchResults();
}

function submitSuggestionNote(){
	postSubmissionNote();
}

function showSuggestionFields( title, address, city, state, country, phonenumber, latitude, longitude){
	var stateEtcDisplay = city + ", " + state + ", " + country;
	$("#suggestionTitleField").val(title);
	$("#suggestionTitleDisplay").html(title);
	$("#suggestionAddressField").val(address);
	$("#suggestionAddressDisplay").html(address);
	$("#suggestionCityField").val(city);
	$("#suggestionStateField").val(state);
	$("#suggestionCountryField").val(country);
	$("#suggestionPhoneField").val(phonenumber);
	$("#suggestionLatitudeField").val(latitude);
	$("#suggestionLongitudeField").val(longitude);
	$("#suggestionStateEtcDisplay").html(stateEtcDisplay);	
	
	
}

function setupSuggestionFormButtons(){
	//$("#submit_suggestionnote_button").click( submitSuggestionSubmission );
	$("#cancel_suggestionnote_button").click( cancelSuggestionSubmission );
}

function setupDialogs(){
    $("#placeinfobox").dialog({
		bgiframe: true,
		autoOpen: false,
		height: 300,
		width: 420,
		modal: false,
		title: "Place Info",
		dialogClass:'placeinfobox',
		zindex:9,
		resizable:false			
	});
	
	$("#suggestform").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 250,
			width: 420,
			modal: true,
			title: "<img src='/images/addanote25.png'> leave a note",
			dialogClass:'suggestionform',
			zindex:9,
			resizable:false				
		});
	$("#suggestionsearchform").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 250,
			width: 420,
			modal: true,
			title: "<img src='/images/wmapicons25/suggestedpoint.png'> suggestion",
			dialogClass:'searchresults',
			zindex:9,
			resizable:false				
		});
	
}

function prepareForSearchResultReady(){
// open dialog
  $("#suggestionsearchform").dialog("open");
  showSuggestionSearchResults();
  $("#suggestorContactInfo").hide();
// do other things
}

function setupSidebar(){
	$(".leftsidebar").accordion();
	
}
function openSuggestionBar(){
	$("#suggestbar").show();
	$("#suggestbutton").hide();
}
function setupSuggestionActions(){
	$("#suggestbutton").click(openSuggestionBar);
	$("#suggestaddnote").click(openSuggestionNoteDialog);
}

function setInfoBoxTitle( titleContents ){
	$("#placeinfobox").dialog( "option", "title", titleContents );
}

function fillInInfoBox( id, title, streetAddress, city, state, country, phoneNumber, lat, lng, description, typeName ){
	var html = "<div class='placeName'>"+ unescape(title) +"</div>";
	if(( streetAddress != 'undefined' ) &&  (streetAddress) && (streetAddress != "null") && (streetAddress != "") && (streetAddress != "No Street Address") && (streetAddress != city) && (streetAddress != state) ){
	  	html += "<div class='placeAddress1'>"+ streetAddress +"</div>";
	}
	if( (city != 'undefined') && (city) && (city != "null") && (city != "") && (city != "No City") && (city != name)){
	  	html += "<div class='placeCity'>"+ city +"</div>";
	}
	if( (state != 'undefined') && (state) && (state != "null") && (state != "") && (state != "No State")){
	  	html += "<div class='placeState'>"+ state +"</div>";
	}
	if( (country != 'undefined') && (country) && (country != "null") && (country != "") && (country != "No Country") && (country != state)){
	  	html += "<div class='placeCountry'>"+ country +"</div>";
	}
	html += "<div style='clear:both;'></div>";
	if( (phoneNumber) && (phoneNumber != "null") && (phoneNumber != "") && (typeof(phoneNumber) != 'undefined')){
	  	html += "<div class='placePhoneNumber'>"+ phoneNumber +"</div>";
	}
	if( (description) && (description != "null") && (description != "") && (typeof(description) != 'undefined')){
		html += "<br /><div class='placeDescription'>"+description +"</div>";
	}
	html += "<div class='navElement'><a href='#' onclick='clickPrevGlobalPoint();'><img src='/images/leftarrow.png' /></a><a href='#' onclick='clickNextGlobalPoint();'><img src='/images/rightarrow.png' /></a></div>";
	
	$("#placeinfobox").html(html);
  

}

function fillInSuggestionInfoBox( id, title, streetAddress, city, state, country, phoneNumber, lat, lng, description, typeName, suggestorName, suggestorWebsite, suggestorTwitter ){
	var html = "<div class='placeName'>"+ unescape(title) +"</div>";
	if( (streetAddress) && (streetAddress != "null") && (streetAddress != "") && (streetAddress != "No Street Address") && (streetAddress != city) && (streetAddress != state) ){
	  	html += "<div class='placeAddress1'>"+ streetAddress +"</div>";
	}
	if( (city) && (city != "null") && (city != "") && (city != "No City") && (city != name)){
	  	html += "<div class='placeCity'>"+ city +"</div>";
	}
	if( (state) && (state != "null") && (state != "") && (state != "No State")){
	  	html += "<div class='placeState'>"+ state +"</div>";
	}
	if( (country) && (country != "null") && (country != "") && (country != "No Country") && (country != state)){
	  	html += "<div class='placeCountry'>"+ country +"</div>";
	}
	html += "<div style='clear:both;'></div>";
	if( (phoneNumber) && (phoneNumber != "null") && (phoneNumber != "") && (typeof(phoneNumber) != 'undefined')){
	  	html += "<div class='placePhoneNumber'>"+ phoneNumber +"</div>";
	}
	if( (description) && (description != "null") && (description != "") && (typeof(description) != 'undefined')){
		html += "<br /><div class='placeDescription'>"+description +"</div>";
	}
	if(suggestorName != ""){
		html += "<br /><div class='suggestorDetails'>";
		html += "<div class='suggestedBy'>submitted by </div>";
		if(suggestorWebsite != ""){
		  html += "<div class='suggestorName'><a href='"+ suggestorWebsite + "'>" + suggestorName +"</a></div>";
		}
		else{
			html += "<div class='suggestorName'>" + suggestorName +"</div>";
		}
		if( suggestorTwitter != ""){
			var twitterLink = "<a href='http://www.twitter.com/"+suggestorTwitter+"'>@" + suggestorTwitter + "</a>";
			html+= "<div class='suggestorTwitter'>Chat with "+ twitterLink +" on twitter.</div>";
		}
		html += "</div>";
	}
	$("#placeinfobox").html(html);
  

}


function retrieveSuggestionList(){
	$.post("/suggestions/getList.php", {mapId: mapId},
	  function(data){
	    if(data != ""){
	      giveFeedback("Suggestions loaded.");
	      gSuggestionList = data;
	      showSuggestionPoints();
	    }
	  }, "json");
	
}

function showSuggestionPoints(){

	for( iMarker = 0; iMarker < gSuggestionList.length; iMarker++){
		if( (gSuggestionList[iMarker].latitude == "") 
			|| (gSuggestionList[iMarker].longitude == "") 
			|| (gSuggestionList[iMarker].name == "") ){
			//skip it, do something else
		}
		else{
			var typeName = "suggestion";
			var marker = makeNewMarker( gMap, gSuggestionList[iMarker].latitude, gSuggestionList[iMarker].longitude, gPointTypeList[typeName].iconPath, gSuggestionList[iMarker].name);
			marker.set("marker_num", iMarker);
			gSuggestionInfoList[iMarker] =  gSuggestionList[iMarker];
			google.maps.event.addListener(marker, 'click', function() {
			  var markerData = gSuggestionInfoList[this.get("marker_num")];
			  var typeName = 'suggestion';
			  var newInfoBoxTitle = "<span><img src='"+ gPointTypeList[typeName].iconPath +"' /> " + typeName +  "</span>";
			  setInfoBoxTitle(newInfoBoxTitle);
			   fillInSuggestionInfoBox(markerData.point_id,
			   					markerData.name, markerData.street_address,
			   					markerData.city, markerData.state, markerData.country, 
			   					markerData.phoneNumber, markerData.latitude, markerData.longitude, 
			   					markerData.description, markerData.type, markerData.suggestor_name, markerData.suggestor_website, markerData.suggestor_twitter);
			   $("#placeinfobox").dialog('open');
			 });
			
			var category = "suggestion";
			
			if(!gMarkerList[category]){
			  gMarkerList[category] = new Array();
			}
			if(!gMarkerList[typeName]){
			  gMarkerList[typeName] = new Array();
			}
			
			gMarkerList[category].push(marker);
			gMarkerList[typeName].push(marker);
			
		}
	  }
}

function postSubmissionNote(){

	var paramArray = [];
	paramArray['mapId'] = mapId;
	paramArray['suggestorName'] = $("#suggestform #suggestformFields #suggest_name ").val();
	paramArray['suggestorWebsite'] = $("#suggestform #suggestformFields #suggest_website").val();
	paramArray['suggestorTwitter'] = $("#suggestform #suggestformFields #suggest_twitter").val();
	paramArray['suggestorEmail'] = $("#suggestform #suggestformFields #suggest_email").val();
	paramArray['description'] = $("#suggestform #suggestformFields #suggest_note").val();

	$.post("/suggestions/addSuggestion.php", { title: "", 
	street_address: "",
	city: "",
	state: "",
	country: "",
	phone_number: "",
	latitude: "",
	longitude: "",
	description: paramArray['description'],
	suggestorName: paramArray['suggestorName'],
	suggestorWebsite: paramArray['suggestorWebsite'],
	suggestorTwitter: paramArray['suggestorTwitter'],
	suggestorEmail: paramArray['suggestorEmail'],
	mapId: paramArray['mapId']},
	  function(data){
	    if(data == "SUCCESS"){
	      $("#suggestform").dialog('close');
	      giveFeedback("Suggestion saved. Thanks!");
	      //clear note, but leave suggestor information, for easy 
	      // multiple suggestions
	      clearSuggestionNote(true);
	    }
	    else{
	      alert("There was a problem, please try again." + data);
	    }
	  });
}

function handleSuggestorCookies( name, website, twitter, email ){
	var nameCookieValue = $.cookie("twmSuggestorName");
	var websiteCookieValue = $.cookie("twmSuggestorWebsite");
	var twitterCookieValue = $.cookie("twmSuggestorTwitter");
	var emailCookieValue = $.cookie("twmSuggestorEmail");
	
	if( nameCookieValue != name ){
		$.cookie("twmSuggestorName", name, { expires: 7 });
	}
	if( websiteCookieValue != website ){
		$.cookie("twmSuggestorWebsite", website, { expires: 7 });
	}
	if( twitterCookieValue != twitter ){
		$.cookie("twmSuggestorTwitter", twitter, { expires: 7 });
	}
	if( emailCookieValue != email ){
		$.cookie("twmSuggestorEmail", email, { expires: 7 });
	}
	//alert($.cookie("twmSuggestorName"));
}

function fillInSuggestorNameFromCookies(){
	var nameCookieValue = $.cookie("twmSuggestorName");
	var websiteCookieValue = $.cookie("twmSuggestorWebsite");
	var twitterCookieValue = $.cookie("twmSuggestorTwitter");
	var emailCookieValue = $.cookie("twmSuggestorEmail");
	if(nameCookieValue == null){
		nameCookieValue = "";
	}
	if(websiteCookieValue == null){
		websiteCookieValue = "";
	}
	if(twitterCookieValue == null){
		twitterCookieValue = "";
	}
	if(emailCookieValue == null){
		emailCookieValue = "";
	}
	$("#suggestor_name").val(nameCookieValue);
	$("#suggestor_website").val(websiteCookieValue);
	$("#suggestor_twitter").val(twitterCookieValue);
	$("#suggestor_email").val(emailCookieValue);
}

function postSubmission(){
	var paramArray = [];
	var mainForm = "#suggestionsearchform";
	var pointForm = "#suggestionpointinfo";
	var contactForm = "#suggestorContactInfo";
	
	var pointLocator = mainForm + " " + contactForm + " " + pointForm + " ";
	var contactLocator = mainForm + " " + contactForm + " " ;
	
	paramArray['mapId'] = mapId;
	paramArray['title'] = $(pointLocator + "#suggestionTitleField").val();
	paramArray['street_address'] = $(pointLocator + "#suggestionAddressField").val();
	paramArray['city'] = $(pointLocator + "#suggestionCityField").val();
	paramArray['state'] = $(pointLocator + "#suggestionStateField").val();
	paramArray['country'] = $(pointLocator + "#suggestionCountryField").val();
	paramArray['phone_number'] = $(pointLocator + "#suggestionPhoneField").val();
	paramArray['latitude'] = $(pointLocator + "#suggestionLatitudeField").val();
	paramArray['longitude'] = $(pointLocator + "#suggestionLongitudeField").val();
	
	
	
	paramArray['suggestorName'] = $("#suggestor_name").val();
	paramArray['suggestorWebsite'] = $("#suggestor_website").val();
	paramArray['suggestorTwitter'] = $("#suggestor_twitter").val();
	paramArray['suggestorEmail'] = $("#suggestor_email").val();
	
	
	paramArray['description'] = $(contactLocator + "#suggest_note").val();
	if( paramArray['suggestorName'] == null  ){
		alert("Please fill in your name.");
		return;
	}
	
	handleSuggestorCookies(paramArray['suggestorName'], paramArray['suggestorWebsite'], paramArray['suggestorTwitter'], paramArray['suggestorEmail']);

	$.post("/suggestions/addSuggestion.php", { title: paramArray['title'], 
	street_address: paramArray['street_address'],
	city: paramArray['city'],
	state: paramArray['state'],
	country: paramArray['country'],
	phone_number: paramArray['phone_number'],
	latitude: paramArray['latitude'],
	longitude: paramArray['longitude'],
	description: paramArray['description'],
	suggestorName: paramArray['suggestorName'],
	suggestorWebsite: paramArray['suggestorWebsite'],
	suggestorTwitter: paramArray['suggestorTwitter'],
	suggestorEmail: paramArray['suggestorEmail'],
	mapId: paramArray['mapId']},
	  function(data){
	    if(data == "SUCCESS"){
	      $("#suggestsearchform").dialog('close');
	      
	      giveFeedback("Suggestion saved. Thanks!");
	      //clear note, but leave suggestor information, for easy 
	      // multiple suggestions
	      clearSuggestion(true);
	      retrieveSuggestionList();
	    }
	    else{
	      alert("There was a problem, please try again." + data);
	    }
	  });
	
}

function loadTwitter( mapId ){

   $.post("/twitter/getSavedTweets.php", { map_id: mapId },
   function(data){
          $.each(data, function(i,item){
            $("#twitter_canvas").append("<div class='tweet_entry'><div class='tweet_image'><img src='" + item.photo_url + "' title='"+ item.twitter_name +"'/></div><div class='tweet_text'>" + item.tweet + "</div><div class='tweet_reply'> <a href='http://twitter.com/?status=@"+item.twitter_name+"%20&in_reply_to_status_id="+ item.tweet_id +"&in_reply_to="+item.twitter_name+"'>@</a> <a href='http://twitter.com/?status=RT @"+escape(item.twitter_name+item.tweet) + "'>rt</a> </div><div class='tweet_time'>"+ item.timestamp +"</div><div style='clear:both;' /></div>"); 
          });
   }, "json");
}


function giveFeedback(feedback){
	$("#feedback").show();
	$("#feedback").text(feedback);
	$("#feedback").fadeOut(4000);
}
