/*
 * GPort requires {name:<port of>,latlng:<GLatLng()>,zoom:<zoom>)
 */
function GPort(opts) { 
  this.zoom = 12;
  this.latlng = null;
  this.name = 'Unnamed';
  this.initialize(opts);
};


GPort.prototype.initialize = function(opts) { 
  for(var i in opts) { 
    this[i] = opts[i];
  }
};


GPort.prototype.toString = function() { 
  return this.name;
};



/*
 * GPortControl implements interface GControl()
 */
function GPortControl(printable,selectable) { 
  GListControl.call(this,printable,selectable);

  this.setOptionLength(15);
  this.setWidth('140px');
  this.setDefaultTitle('Port of...','Jump to a port');
  this.loaded = false;

  GEvent.addListener(this,"itemselected",function(idx) {
    if( typeof(this.items[idx]) != "undefined" &&
        typeof(this.items[idx]["latlng"]) != "undefined" &&
        typeof(this.items[idx]["zoom"]) != "undefined" ){
      this.map.setCenter(this.items[idx].latlng,this.items[idx].zoom);
    }
  }); 
}
// Extends GControl()
GPortControl.prototype = new GListControl();


GPortControl.prototype.sort = function() { 
  return this.items.sort(function(a,b) {return (a['name']>b['name'])?1:-1;});
};


GPortControl.prototype.load = function() { 
  var LC = this;
  var url = 'xml/ports.xml';
  LC.loaded = false;

  this.getTitleContainer().innerHTML = "Loading...";
  GDownloadUrl(url,function(data,code) { 
    if( code != 200 ) { 
      LC.loaded = true;
      GEvent.trigger(LC,"load",data,code);
      return false;
    }

    LC.reset();
    var dom = GXml.parse(data);
    var ports = dom.getElementsByTagName("port");
    for(var i=0,n=ports.length; i<n; i++) { 
      var coast = ports[i].getAttribute("coast");
      if( String(coast).toUpperCase() != "PACIFIC" ) { 
        continue;
      }
      var country = ports[i].getAttribute("country");
      if( String(country).toUpperCase() != "UNITED STATES" ) { 
        continue;
      }
      if( String(ports[i].getAttribute("latitude")).length < 1 ||
          String(ports[i].getAttribute("longitude")).length < 1 ){
        continue;
      }
      var lat = parseFloat(ports[i].getAttribute("latitude"));
      var lon = parseFloat(ports[i].getAttribute("longitude"));
      var name = ports[i].firstChild.nodeValue;
      LC.add(new GPort({'latlng':new GLatLng(lat,lon),'name':name}));
    }

    LC.sort();
    LC.redraw();
    LC.loaded = true;
    GEvent.trigger(LC,"load",data,code);
  });
};


GPortControl.prototype.isLoaded = function() { 
  return this.loaded;
};
