/********************************************
 INITIALIZATION   
********************************************/

// INITIALIZE GOOGLE API
google.load("maps", "2.125");
google.setOnLoadCallback(initialize);

// ADDITIONAL CONFIGURATION VARIABLES
config.tag_name = "response"; // name of element in xml data
config.max_info_width = 300; // max width for information window
config.add_delay = 100; // delay for adding markers
config.switch_interval_length = 8000; // milliseconds before switching to a different marker

// GLOBAL VARIABLES
var map = null;
var qs = new Querystring();

// SET ENVIRONMENT OPTIONS         
// turn testing on if in the development domain
if(config.testing == null) { config.testing = window.location.hostname == "ts.publicradio.org"; }

// sets the xml file. if a category is set, then it will pull the
// correct template and add the category to the querystring
if(config.filter_category != null && config.filter_category != "") {
	var xml_file = "category.php?format=xml&cat=" + config.filter_category +"&";
} else if(config.new_xml_path == true) {
	var xml_file = "category.php?format=xml&";
} else {
	var xml_file = "responsesXML.php?";
}

// set xml path for production
var production_xml_path = "http://being.publicradio.org/www_publicradio/applications/formbuilder/projects/your_story/"+xml_file+"name="+config.query_name;

// set xml path for development
if(config.test_xml != null) {
	var development_xml_path = config.test_xml;
} else {
	var development_xml_path = "http://ts.publicradio.org/iw-mount/default/main/being/WORKAREA/"+config.workarea+"/www_publicradio/applications/formbuilder/projects/your_story/"+xml_file+"name="+config.query_name
}


// INITIALIZE VARIABLES

// the id of the selected response
var selected_response_id = qs.get("response");
var selected_response = null;

// arrays for featured items, normal items (responses), and images
var featured = new Array();
var responses = new Array();
var images = new Array();

var loading = null;

// these hold markers for featured markers and normal (response) markers
var featured_markers = null;
var response_markers = null;


/********************************************
 FUNCTIONS   
********************************************/

// Get things started
function initialize() { 
	
	// create new google maps instance 
  map = new GMap2(document.getElementById(config.map_canvas_id));

	// configure google maps instance
  map.setMapType(G_PHYSICAL_MAP);
  map.disableContinuousZoom();
  map.disableScrollWheelZoom(); 
  map.addControl(new GSmallMapControl());
  map.setCenter(new GLatLng(config.init_x, config.init_y), config.init_zoom);
  
  if(config.testing) {
  	GDownloadUrl(development_xml_path, window.parseXmlData);
  } else {
  	GDownloadUrl(production_xml_path, window.parseXmlData);
  }
  
  // stop interval switching when map is clicked
  GEvent.addListener(map, 'click', function(){
  	window.clearInterval(window.switchWindowInterval);
  });
}

function parseXmlData(data, responseCode) {
  // console.log("parseXmlData");
  
  redicon = new GIcon();
	redicon.image = "http://www.apmstations.org/images/mm_20_red.png";
  // redicon.shadow = "http://www.apmstations.org/images/mm_20_shadow.png";
	redicon.iconSize = new GSize(12, 20);
  // redicon.shadowSize = new GSize(22, 20);
	redicon.iconAnchor = new GPoint(6, 20);
	redicon.infoWindowAnchor = new GPoint(5, 1);
	
  var xml = GXml.parse(data);
  
  var response_elements = xml.documentElement.getElementsByTagName("response");
  if(response_elements.length > 0) {
	  var i=0;
	  // if there is a selected response to show (rather than random featured)
	  if(selected_response_id) {
	    // console.log("load selected response: "+selected_response_id);
	    while(i<response_elements.length) {
	      var response = new ResponseObject(response_elements[i], redicon, config.query_name, config.testing);
	      if (response.id == selected_response_id) {
	        window.featured.push(response);
	        window.selected_response = response;
	      }
	      else { window.responses.push(response); }
	      
	      if(response.flickr_img != null && response.flickr_img != "") {
	      	window.images.push(response);
	      }
	      
	      i++;
	    }
	    
	  // else no selected response, go to default behavior (show random featured)
	  } else {
	    // console.log("default load behavior (random featured)");
	    while(i<response_elements.length) {
	    	// only add element if it has lat/lon data
	    	// if(isElementLatLonSet(response_elements[i])) {
		      var response = new ResponseObject(response_elements[i], redicon, config.query_name, config.testing);
		      // add to featured collection
			    if (response.featured) { window.featured.push(response); }
			    // add to regular collection
			    else { window.responses.push(response); }
			  // }

	      if(response.flickr_img != null && response.flickr_img != "") {
	      	window.images.push(response);
	      }

	      i++;
	    }
	  }
	  
	  addFeaturedMarkers();
	} else {
	 	$(config.loading_div_id).hide();
		$('no_responses').show();
	}
}

// checks to see if response element has latitude/longitude data
function isElementLatLonSet(e) {
	var lat = e.getElementsByTagName("latitude")[0];
	lat = lat.innerText || lat.textContent || "";
	var lon = e.getElementsByTagName("longitude")[0];
	lon = lon.innerText || lon.textContent || "";
	if (lat==""||lon=="") {
		return false
	}
	return true;
}

function updateLoadingMessage(response) {
  // console.log("Loading "+response.full_name);
  // $(config.loading_div_id).select(".loading_info")[0].update('Loading '+response.full_name);
  // if(response.flickr) {
  //   $(config.loading_div_id).select("img")[0].writeAttribute($H({src: response.getImageUrl('thumbnail')}));
  // }
}

function addFeaturedMarkers() {
  // console.log("addFeaturedMarkers");
  featured_markers = new SOFMarkerManager( window.map, window.featured, { addProgressively: false });
  
  var created_handler = window.updateLoadingMessage.bind(window);
  GEvent.addListener(featured_markers, 'markerCreated', created_handler);
  
  var completed_handler = window.addFeaturedMarkersComplete.bind(window);
  GEvent.addListener(featured_markers, 'markersAdded', completed_handler);
  
  featured_markers.createMarkers();
}

// This function is triggered once featured markers have been added
function addFeaturedMarkersComplete() {
  // console.log("addFeaturedMarkersComplete");

  $('#'+config.loading_div_id).hide();
  
  // if there is a selected response, zoom in on the location
  if(window.selected_response) {
    // console.log("zoom in for selected response");
    var handler = window.triggerAddRegularMarkersDelay.bind(window);
    GEvent.addListener(window.map, 'zoomend', handler);
    window.map.setCenter(new GLatLng(selected_response.latitude, selected_response.longitude), config.init_zoom+2);
  } else { // otherwise, just add the rest of the markers
  	triggerAddRegularMarkersDelay();
  	if(window.featured_markers.responses.length > 1) {
  		var handler = window.switchFeatured.bind(window);
  		window.switchWindowInterval = window.setInterval(handler, config.switch_interval_length);
		}
	}
  	
}

function switchFeatured() {
	// console.log("Switch featured");
	window.featured_markers.openRandomMarker();
}

function triggerAddRegularMarkersDelay() {
  // console.log("triggerAddMarkersDelay");
  GEvent.clearListeners(window.map, 'zoomend'); 	
  setTimeout(addRegularMarkersDelay, 1000);
}

function addRegularMarkersDelay() {
	// console.log("addRegularMarkersDelay");
  window.featured_markers.openRandomMarker();
  response_markers = new SOFMarkerManager( window.map, window.responses, { addProgressively: true, addDelay: config.add_delay });
  var handler = window.allMarkersAdded.bind(window);
  GEvent.addListener(response_markers, 'markersAdded', handler);
  response_markers.createMarkers();
}

function allMarkersAdded() {
  // console.log("All markers added.");
}

