// google.load("maps", "2.x");
/*****************************************************************************
  class SOFMarkerManager
  
  Manages loading and adding large numbers of markers to the map.
*****************************************************************************/
// var SOFTitleOverlay = function(url) { this._url = url; }

// var SOFTitleOverlay = function() {}
// 
// SOFTitleOverlay.prototype = new GControl(true);
// 
// SOFTitleOverlay.prototype.initialize = function(map) {
// 		var container = document.createElement("div");
// 		// container.innerHTML = '<img style="cursor:pointer;" src="'+image_url+'" border="0">';
// 		container.innerHTML = '<img style="cursor:pointer;" src="http://speakingoffaith.org/programs/2008/abortion/images/map-title-overlay.png" border="0">';
// 		container.style.width = '400px';
// 		container.style.height = '26px';
// 		// url = _url;
// 		// GEvent.addDomListener(container, 'click', function(){ document.location = url; });
// 		map.getContainer.appendChild(container);
// 		return container;
// };
// 
// SOFTitleOverlay.prototype.getDefaultPosition = function() {
// 		return new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(70, 0));
// };

/*****************************************************************************
  class SOFMarkerManager
  
  Manages loading and adding large numbers of markers to the map.
*****************************************************************************/
var SOFMarkerManager = Class.create();
SOFMarkerManager.prototype = {
  initialize: function(map, responses, opts) {
  	// console.log("initialize SOFMarkerManager");
    // create an alternative reference for this obj, for when
    // this doesn't work
    var self = this;
    this.map = map;
    this.manager = new GMarkerManager(map);
    this.responses = responses;
    this.markers = new Array();
    // markers waiting to be added
    this.waiting_markers = new Array();
    this.last_open_rand = null;
    
    this.addProgressively = opts.addProgressively ? true : false;
    if(this.addProgressively) { this.addDelay = opts.addDelay || 0; }
  },
  
  createMarkers: function(addWhenComplete) {
    // console.log("SOFMarkerManager:createMarkers");
    for(i=0;i<this.responses.length;i++) {
      GEvent.trigger(this, 'markerCreated', this.responses[i]);
      if(this.addProgressively) {
        // add this marker to the waiting markers queue
        this.waiting_markers.push(this.responses[i].marker)
        // after a delay, add the first marker in the queue to the map
        var handler = this.addFirstWaitingMarker.bind(this);
        setTimeout(handler, this.addDelay*i);
      }
      this.markers.push(this.responses[i].marker);
    }
    if(addWhenComplete != false) { this.addMarkers(); }
  },
  
  addFirstWaitingMarker: function() {
    // console.log("SOFMarkerManager:addFirstWaitingMarker");
    if(this.waiting_markers.length > 0) {
      this.manager.addMarker(this.waiting_markers.shift(),0);
    }
  },
  
  addMarkers: function() {
    // console.log("SOFMarkerManager:addMarkers");
    if(!this.addProgressively && this.markers.length > 0) {
    	// console.log("markers:", this.markers);
      this.manager.addMarkers(this.markers,0,10);
      this.manager.refresh();
    } 
    GEvent.trigger(this, "markersAdded");
  },
  
  // opens a random marker within this set
  openRandomMarker: function() {
   // console.log("SOFMarkerManager:openRandomMarker");
		do {
			rand = Math.floor(Math.random()*this.responses.length);
		} while ( rand == this.last_open_rand);
		this.last_open_rand = rand;
   // console.log("marker: ",(this.markers[rand]));
   // GEvent.trigger(this.markers[rand], 'click');
   this.responses[rand].openMarkerWindow();
  }
};

/*****************************************************************************
  class ResponseObject
  
	Default model for a response.
  
*****************************************************************************/
var ResponseObject = Class.create();
ResponseObject.prototype = {
  initialize: function(e, icon, proj, test) {
    // console.log("initialize ResponseObject")
    this.AUTO_ATTRIBUTES = new Array();
    this.AUTO_ELEMENTS = [
      "id",
      ["name", "full_name"],
      "city",
      "state",
      "zip",
      "country",
      "born",
      "practices",
      "faith",
      "flickr_img",
      "audio_file",
      "quote",
      "latitude",
      "longitude"
    ]
    this.TESTING_PATH_PREFIX = "http://ts.publicradio.org/iw-mount/default/main/being/WORKAREA/adayton/www_publicradio/applications/formbuilder/projects/your_story/";
    this.PRODUCTION_PATH_PREFIX = "http://being.publicradio.org/www_publicradio/applications/formbuilder/projects/your_story/";
    
		this.testing = test;
    this.point = null;
    this.marker = null;
    this.featured = e.getAttribute("featured") == "1" ? true : false;
    this.autoObjectifyElement(e);
    this.gatherCategories(e);
    this.setMarker(e, icon);
    this.project_name = proj;
    if(this.testing) {
    	this.path_prefix = this.TESTING_PATH_PREFIX;
    } else {
    	this.path_prefix = this.PRODUCTION_PATH_PREFIX;
    }
    this.story_link = this.path_prefix+'story.php?name='+this.project_name+'&response='+this.id+"#story";
  },
  
  setMarker: function(e, icon) {
    // console.log("setMarker: "+this.full_name);
    if(this.latitude && this.longitude) {
      this.point = new GLatLng( this.latitude, this.longitude);
      var handler = this._markerOnClick.bind(this);
      this.marker = new GMarker(this.point, icon);
      GEvent.addListener(this.marker, 'click', handler);
    } else {
      // console.error("Latitude and longitude not set for response #"+this.id);
    }
  },
  
  // gather category elements into the categories array
  gatherCategories: function(e) {
    // console.log("gatherCategories");
    this.categories = new Array();
    category_elements = e.getElementsByTagName('category');
    for(i=0;i<category_elements.length;i++) {
      var el = category_elements[i];
      var el_name = el.innerText || el.textContent || el.firstChild.nodeValue;
      this.categories.push(el_name);
    }
  },
  
  // Uses the AUTO_ATTRIBUTES and AUTO_ELEMENTS arrays to
  // automagically set the object attributes
  autoObjectifyElement: function(e) {
    // console.log("autoObjectifyElement");
    // Automagically assigns all DOM attributes in the
    // AUTO_ATTRIBUTES array to be object attributes.
    //
    // Transformations are listed as a two-element array
    // (for instance, ['things', 'thingies'] would import
    // the DOM attribute 'things' as object attribute
    // 'thingies')
    //
    for(i=0; i<this.AUTO_ATTRIBUTES.length; i++) {
      var key = null;
      var attr_name = null;
      if(typeof this.AUTO_ATTRIBUTES[i] == "string") {
        key = attr_name = this.AUTO_ATTRIBUTES[i];
      } else {
        key = this.AUTO_ATTRIBUTES[i][0];
        attr_name = this.AUTO_ATTRIBUTES[i][1];
      }
      if(e.getAttribute(key)) { this[attr_name] = e.getAttribute(key); }
      else { this[attr_name] = null; }
    }
        
    // Automagically assigns all DOM elements in the
    // AUTO_ELEMENTS array to be object attributes
    //
    // Transformations are listed as a two-element array
    // (for instance, ['things', 'thingies'] would import
    // the DOM element 'things' as object attribute
    // 'thingies')
    //
    for(i=0;i<this.AUTO_ELEMENTS.length;i++) {
      var key = null;
      var attr_name = null;
      if(typeof this.AUTO_ELEMENTS[i] == "string") {
        key = attr_name = this.AUTO_ELEMENTS[i];
      } else {
        attr_name = this.AUTO_ELEMENTS[i].pop();
        key = this.AUTO_ELEMENTS[i].pop();
      }
      var el = e.getElementsByTagName(key)[0];
      if(el && el.hasChildNodes()) { 
        this[attr_name] = el.innerText || el.textContent || el.firstChild.nodeValue;
      }
      else {
        this[attr_name] = null;
      }
    }
  },
  
  getAddress: function() {
    address = "";
    if(this.city) { address = address + this.city + " ";}
    if(this.state) { address = address + this.state + " ";}
    if(this.country) { address = address + this.country + " ";}
    if(this.zip) { address = address + this.zip + " ";}
    return address;
  },
  
  getImageUrl: function(size) {
    var url;
    if(this.flickr_img) {
      var suf;
      // split_url = this.flickr_img.split(".");
      // var ext = split_url.pop();
      var ext = 'jpg';
      var url_base = this.flickr_img;
      switch(size) {
        case "square": suf = '_s'; break;
        case "thumbnail": suf = '_t'; break;
        case "small": suf = '_m'; break;
        case "medium": suf = ''; break;
        case "large": suf = '_b'; break;
        default: suf = ''; break;
      }
      url = url_base + suf + '.' + ext;
    } else {
      console.error("No image url set")
    }
    return url;
  },
  
  getInfoWindowHtml: function() {
    var html = "";
    
    // info window div open
    var opentag = '<div id="map_info_window"';
    if(this.flickr_img) { opentag += ' class="has_photo"'; }
    opentag += '>';
    
    html += opentag;
    
    if(this.flickr_img || this.audio ) { html += '<div class="left_column">'; }
    
    // add image (if available)
    if(this.flickr_img) {
      html += '<a href="'+this.story_link+'"><img width="75" height="75" src="'+this.getImageUrl('square')+'" alt="'+this.full_name+'" /></a>';
    }
    
    if(this.flickr_img || this.audio ) { html += '</div>'; }    
    
    // add name
    html += '<a class="name" href="'+this.story_link+'">'+this.full_name+'</a>';
    html += '<br />'
    
    // add geo information
    // this will need to be more advanced to deal with different countries, etc.
  	var geo = '<span class="geo">';
  	if(this.country != 'US' && this.country != 'USA' && this.country != 'United States') { // international
  		geo += this.city+', '+this.country;
  	} else { //US
  		geo += this.city+', '+this.state+' (USA)';
  	}
  	geo += '</span>';

    html += geo;
    html += '<br />';
    
    // add birth year, religious info
    var background = '<span class="background">'
   // if(this.born) { background += 'Born in '+this.born; }
   // if(this.born && this.faith) { background += '<br />'}
    // if(this.practices) { background += 'practices '+this.practices.toLowerCase()}
    if(this.faith) { background += this.faith; }
    background += '</span>'
    html += background;
    
    // add audio player (if available)
    // [disabled for now until some issues with the audio player are figured out]
    if (this.audio_file) {
      html += '<div class="audio_player">';
      html += this.audioPlayerHtml(this.formatAudioUrl(this.audio_file));
      html += '</div>'
    }
    
    // add pullqoute
    html += '<p class="quote">"'+this.quote+'"';    
    html += '</p>';
    
    // add link
    html += '<a href="'+this.story_link+'">Read more &hellip;</a>';
    
    // close info window div
    html += '<div class="clear"></div>'
    
    return html;
  },
  
  audioPlayerHtml: function(audio_url) {
    var player_url = "audio_button/musicplayer.swf"; // location of the swf
      var noflash_url = "noflash.gif"; // location of noflash image
      var swf_url = player_url+'?song_url='+audio_url; // embed url
      var html = "";  
      
      var width = 100;
      var height = 17;
    
    html += '<a href="'+this.story_link+'">&raquo; <strong>Hear '+this.full_name.split(" ")[0]+"\'s story</strong></a>"
      
    // console.log(audio_url);
    
    // object element open
    // html += '<object';
    //     html += ' type="application/x-shockwave-flash"';
    //     html += ' data="'+swf_url+'"';
    //     html += ' width="'+width+'"';
    //     html += ' height="'+height+'"';
    //     html += '>';
    
    // nested param element
    // html += '<param';
    //   html += ' name="movie"';
    //   html += ' value="'+swf_url+'"';
    //   html += ' />';
    
    // nested img element
    // html += '<img';
    // html += ' src="'+noflash_url+'"';
    // html += ' width="'+width+'"';
    // html += ' height="'+height+'"';
    // html += ' alt="Audio recording"';
    // html += ' />';
    
    // object element close
    // html += '</object>';
    
    return html;
  },
  
  formatAudioUrl: function(partial_url) {
    // use regular expression to avoid extra spaces & line breaks
    // also, capture the bitrate suffix seperately, as the download
    // versions are 128 rather than 64
    var regex = /(speakingoffaith\/[A-z0-9_]+\/\d{4}\/\d{2}\/\d{2}\/[A-z0-9_]*_\d{2,3})/;
    var prefix = "http://download.publicradio.org/podcast/";
    // var bitrate = "_64";
    var ext = ".mp3";
    
    // console.log("mp3 url: "+regex.exec(partial_url)[1]);
    var audio_url = prefix+regex.exec(partial_url)[1]+ext;
    
    return audio_url;
  },
  
  openMarkerWindow: function() {
    this.marker.openInfoWindowHtml(this.getInfoWindowHtml(),
    {
    	maxWidth: window.config.max_info_width,
    	onOpenFn: this._onOpenInfoWindow()
    });
  },
  
  _onOpenInfoWindow: function() {
  	// window.console.log("open info window");
  	// window.setTimeout(this._setInfoWindowClick, 2000);

  },
  
  // _setInfoWindowClick: function() {
  // 	$('map_info_window').observe('click', function() {
  // 	  		window.console.log("map info window click");
  // 	  });  	
  // },
  
  _markerOnClick: function() {
    // console.log("Click!", this.marker);
    window.clearInterval(window.switchWindowInterval);
    this.openMarkerWindow();
  }
};

