/******************************************
 Emerson
 ******************************************/
// Create new Emerson namespace
Emerson = function() {
  return this;
}

// Setup default settings
$.extend(Emerson, {
  map: null, markerManager: null, markers: [],
  infoWindowWidth: [350, 450]
});

// Create the GIcon objects for all the available
// asset types
Emerson.icons = {}
$.each("A AP APT APTV APV AT ATV AV P PT PTV PV T TV V".split(' '), function(index, name) {
  var icon            = new GIcon(G_DEFAULT_ICON);
      icon.image      = "./images/icons/" + name + ".gif";
      icon.shadow     = "./images/icons/shadow.png";
      icon.shadowSize = new GSize(72, 38);
      icon.iconSize   = new GSize(36, 38);
      icon.iconAnchor = new GPoint(0, 38);
      icon.imageMap   = [0,0, 36,0, 36,38, 0,38];
  Emerson.icons[name] = icon;
});

// Helper function to retrieve icon by type
Emerson.getIcon = function(type) {
  return this.icons[type];
}

// Adds a new asset marker to the 
// Emerson.markers collection
Emerson.addAssetMarker = function(options) {
  var asset = new Emerson.Asset(options);
  var marker = asset.createMarker();
  this.markers.push(marker);
}

// Adds an array of asset markers to the
// Emerson.markers collection
Emerson.addAssetMarkers = function(options_array) {
  for(var i = 0; i < options_array.length; i++) {
    this.addAssetMarker(options_array[i]);
  }
}

Emerson.clearMarkers = function() {
  this.markers = [];
}

// Clears markers from the marker manager
// and adds markers from Emerson.markers
// collection
Emerson.drawMarkers = function() {
  this.markerManager.clearMarkers();
  this.markerManager.addMarkers(this.markers, 1);
  this.markerManager.refresh();
  this.applyFilters();
}

// Updates the visible type filter, which
// hides asset markers that do not match the
// filter and shows asset markers that do match
Emerson.updateTypeFilter = function(filter) {
  $.each(this.markers, function(index, marker) {
    if (filter != '' && marker.asset.match(filter)) {
      marker.show();
    } else {
      marker.hide();
    }
  });
}

Emerson.applyFilters = function() {
  this.updateTypeFilter(Emerson.filters.toString());
}

/******************************************
 Emerson.Filter
 ******************************************/
Emerson.Filter = function() {
  this.A = true;
  this.P = true;
  this.T = true;
  this.V = true;
  return this;
}

// $.extend(Emerson.Filter.prototype, {
//   A: true, P: true, T: true, V: true
// });

Emerson.Filter.prototype = {
  toArray: function() {
    var result = [];
    for(key in this) {
      if (this[key] == true) {
        result.push(key);
      } // end if
    } // end for key
  
    return result;
  },
  
  toString: function() {
    return this.toArray().join('');    
  },
  
  set: function(type, value) {
    this[type] = value;
  }  
}

// Create instance of Emerson.Filter
Emerson.filters = new Emerson.Filter();


// Asset object constructor
// Valid options:
//   latitude, longitude
//   title, caption, type
Emerson.Asset = function(options) {
  this.options = $.extend({
    type: 'T',
    latitude: 0,
    longitude: 0
  }, options);
  
  return this;
}

Emerson.Asset.prototype = {
  // Creates a GMarker object with event bindings
  // to the asset
  createMarker: function() {
    // Setup the proper icon
    var options = { icon: Emerson.getIcon(this.options.type) }
    
    // Create the GMarker object
    var point  = new GLatLng(this.options.latitude, this.options.longitude);
    var marker = new GMarker(point, options);
        marker.asset = this;

    // Bind listener
    GEvent.addListener(marker, 'click', function() {
      marker.asset.show(marker);
    });
        
    return marker;
  },
  
  // Returns true if the asset has the 
  // given type (i.e. 'A', 'P', etc.)
  hasType: function(type) {
    return (this.options.type.indexOf(type) >= 0);
  },
  
  // Returns true if the asset matches
  // the given type filter (i.e. 'ATV', 'AP', etc.)
  match: function(filter) {
    var types = filter.split('').join('|');
    var re    = new RegExp(types);
    return (this.options.type.match(re) != null);
  },
  
  // GMarker "click" event binding function which
  // shows the available assets as a tabbed infowindow
  show: function(marker) {
    var tabs = [];
    var types = {A:'Audio',P:'Photo',T:'Text',V:'Video'};
    
    for(type in types) {
      var title = types[type];
      if (this.hasType(type)) {
        var data = this.options[type];
        var html = this.createHtmlForType(type, data);
        tabs.push(new GInfoWindowTab(title, html));
      }
    }
    
    // tabs.push(new GInfoWindowTab("Text", "Hello this is some sample text. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."));
    // tabs.push(new GInfoWindowTab("Video", '<div style="width:450px; height: 400px;"><object width="425" height="355"><param name="movie" value="http://www.youtube.com/v/2A-fuFeRekE&rel=1"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/2A-fuFeRekE&rel=1" type="application/x-shockwave-flash" wmode="transparent" width="425" height="355"></embed></object></div>'));
    marker.openInfoWindowTabsHtml(tabs, {maxWidth: Emerson.infoWindowWidth[1]});
  },
  
  createHtmlForType: function(type, alldata) {
    var html = '';
    
    // if (type == 'P') {
    //   data.title = data[0].title;
    //   data.author = data[0].author;
    // }
    
    html += '<div class="text">';

    for(var i = 0; i < alldata.length; i++) {
      data = alldata[i];

      html += '<table style="width:100%"><tr><td><h5>' + data.title + '</h5>' +
              '<h6>By ' + data.author + '</h6></td><td class="date"><nobr>' + data.date + '</nobr><br /><nobr>' + data.time + '</nobr></td></tr></table>';
      
      switch(type) {
        case 'A':
          html += 
          '<object type="application/x-shockwave-flash" data="./flash/player.swf" id="audioplayer'+data.id+'" height="24" width="290">' +
          '<param name="movie" value="./flash/player.swf">' +
          '<param name="FlashVars" value="playerID='+data.id+'&amp;soundFile='+data.url+'">' +
          '<param name="quality" value="high">' +
          '<param name="menu" value="false">' +
          '<param name="wmode" value="transparent">' +
          '</object><br />';
          break;
        case 'P':
          var js = 'onclick="return Emerson.lightbox(this);"';
          html += '<div><div class="photo"><a href="' + data.url + '"' + js + ' alt="'+data.url+'"><img src="' + data.thumbnail_url + '" rel="lightbox" class="photo" /><div class="enlarge">Click to enlarge</div></a></div></div>';
          break;
        case 'T':
          break;
        case 'V':
          var matches = data.url.match('v=\([-A-Za-z0-9_]+\)');
          if (matches.length > 0) {
            var video_id = matches[1];
        
            var w = 280;
            var h = 235;

            html += '<div class="video"><object width="' + w + '" height="' + h + '"><param name="movie" value="http://www.youtube.com/v/' + key + '&rel=1"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/' + video_id + '&rel=1" type="application/x-shockwave-flash" wmode="transparent" width="' + w + '" height="' + h + '"></embed></object></div>';
          }  
          break;
      }

      if (data.caption) html += data.caption;
      if (i < (alldata.length-1)) html += '<div class="spacer" style="clear:left;"></div>';
    }  
    
    html += '</div>';
    var w = Emerson.infoWindowWidth[0];
    
    // In the rare case of 4 tabs, increase the width
    // to accomodate (tabs need ~ 90 pixels of space)
    if (this.options.type.length == 4) w += 90;
    
    html  = '<div class="info-tab" style="width: ' + w + 'px">' + html + '</div>';
    return html;
  }
}

Emerson.lightbox = function(link) {
  $.fn.lightbox();
  $(link).lightbox.start(link);
  return false;
}