/** @preserve Maintained by the Office of Web & New Media, Missouri State University.
* Compacted version available at
* http://search.missouristate.edu/map/mobile/examples/ZoomPanControl_compiled.js
*
* Usage:
* map.controls[google.maps.ControlPosition.TOP_LEFT].push(new missouristate.web.ZoomPanControl(map));
*/
if(typeof isSecure == 'undefined'){
    var isSecure = false;
}
/**
* @param {string} tagName
* @param {Object.<string, string>} properties
* @returns {Node}
*/
function CreateElement(tagName, properties) {
    var elem = document.createElement(tagName);
    for (var prop in properties) {
        if (prop == "style")
            elem.style.cssText = properties[prop];
        else if (prop == "class")
            elem.className = properties[prop];
        else
            elem.setAttribute(prop, properties[prop]);
    }
    return elem;
}

/**
* @constructor
* @param {google.maps.Map} map
*/
function ZoomPanControl(map) {
    this.map = map;
    this.originalCenter = map.getCenter();

    var t = this;
    var zoomPanContainer = CreateElement("div", { 'style': "position: relative; padding: 5px;" });

    //Pan Controls
    var PanContainer = CreateElement("div", { 'style': "position: relative; left: 2px; top: 5px; width: 56px; height: 56px; padding: 5px; overflow: hidden;" });
    zoomPanContainer.appendChild(PanContainer);
    var div = CreateElement("div", { 'style': "width: 56px; height: 56px; overflow: hidden;" });
    div.appendChild(CreateElement("img", { 'alt': ' ', 'src': ((isSecure) ? 'https' : 'http') + '://media.cruisetravel.nl/images/mapcontrols3d5.png', 'style': "position: absolute; left: 0px; top: -1px; -moz-user-select: none; border: 0px none; padding: 0px; margin: 0px; width: 59px; height: 492px;" }));
    PanContainer.appendChild(div);

    div = CreateElement("div", { 'style': "position: absolute; left: 0px; top: 19px; width: 18.6667px; height: 18.6667px; cursor: pointer;", 'title': 'Pan left' });
    google.maps.event.addDomListener(div, "click", function() { t.pan(PanDirection.LEFT); });
    PanContainer.appendChild(div);
    div = CreateElement("div", { 'style': "position: absolute; left: 37px; top: 19px; width: 18.6667px; height: 18.6667px; cursor: pointer;", 'title': 'Pan right' });
    google.maps.event.addDomListener(div, "click", function() { t.pan(PanDirection.RIGHT); });
    PanContainer.appendChild(div);
    div = CreateElement("div", { 'style': "position: absolute; left: 19px; top: 0px; width: 18.6667px; height: 18.6667px; cursor: pointer;", 'title': 'Pan up' });
    google.maps.event.addDomListener(div, "click", function() { t.pan(PanDirection.UP); });
    PanContainer.appendChild(div);
    div = CreateElement("div", { 'style': "position: absolute; left: 19px; top: 37px; width: 18.6667px; height: 18.6667px; cursor: pointer;", 'title': 'Pan down' });
    google.maps.event.addDomListener(div, "click", function() { t.pan(PanDirection.DOWN); });
    PanContainer.appendChild(div);
    div = CreateElement("div", { 'style': "position: absolute; left: 19px; top: 19px; width: 18.6667px; height: 18.6667px; cursor: pointer;", 'title': 'Reset center' });
    google.maps.event.addDomListener(div, "click", function() { t.map.setCenter(t.originalCenter); });
    PanContainer.appendChild(div);

    //Zoom Controls
    var zoomContainer = CreateElement("div", { 'style': "position: relative; width: 58px; height: 48px; -moz-user-select: none; overflow: hidden;" });
    zoomPanContainer.appendChild(zoomContainer);
    div = CreateElement("div", { 'style': "position: absolute; left: 18px; top: 0px; width: 24px; height: 22px; overflow: hidden; background-image: url('"+((isSecure) ? 'https' : 'http') + "://media.cruisetravel.nl/images/mapcontrols3d5.png'); background-position: -17px -65px; background-repeat: no-repeat; cursor: pointer;", 'title': 'Zoom in' });
    google.maps.event.addDomListener(div, "click", function() { t.zoom(ZoomDirection.IN); });
    zoomContainer.appendChild(div);
    div = CreateElement("div", { 'style': "position: absolute; left: 18px; top: 21px; width: 24px; height: 22px; overflow: hidden; background-image: url('"+((isSecure) ? 'https' : 'http') + "://media.cruisetravel.nl/images/mapcontrols3d5.png'); background-position: -17px -360px; background-repeat: no-repeat; cursor: pointer;", 'title': 'Zoom out' });
    google.maps.event.addDomListener(div, "click", function() { t.zoom(ZoomDirection.OUT); });
    zoomContainer.appendChild(div);

    return zoomPanContainer;
}

/** @param {PanDirection} direction */
ZoomPanControl.prototype.pan = function(direction) {
    var panDistance = 50;
    if (direction == PanDirection.UP || direction == PanDirection.DOWN) {
        panDistance = Math.round(this.map.getDiv().offsetHeight / 2);
        this.map.panBy(0, direction == PanDirection.DOWN ? panDistance : -1 * panDistance);
    }
    else {
        panDistance = Math.round(this.map.getDiv().offsetWidth / 2);
        this.map.panBy(direction == PanDirection.RIGHT ? panDistance : -1 * panDistance, 0);
    }
}

/** @param {ZoomDirection} direction */
ZoomPanControl.prototype.zoom = function(direction) {
    var zoom = this.map.getZoom();
    if (direction == ZoomDirection.IN && zoom < 19)
        this.map.setZoom(zoom + 1);
    else if (direction == ZoomDirection.OUT && zoom > 1)
        this.map.setZoom(zoom - 1);
}

/** @enum */
var PanDirection = {
    LEFT: 0,
    RIGHT: 1,
    UP: 3,
    DOWN: 4
}

/** @enum */
var ZoomDirection = {
    IN: 0,
    OUT: 1
}

window["missouristate"] = window["missouristate"] || {};
window["missouristate"]["web"] = window["missouristate"]["web"] || {};
window["missouristate"]["web"]["ZoomPanControl"] = ZoomPanControl;
/* CLASS MAP_V3 (V3 API GOOGLE)
 * Needs JQUERY and http://maps.google.com/maps/api/js?sensor=false
 * /js/modules/googlemaps/ZoomPanControl.js
 */
function load_map(settingsObject,msg)
/************************************************************************************************
FUNCTION: load_map
*************************************************************************************************
ARGUMENT: settingsObject
RETURN: MapClass
LAST REVISED: 18102007
AUTHOR: Joost Galama
DESCRIPTION: Create Google Map v3 Class
*************************************************************************************************/
{
    var map = new Map(settingsObject,msg);
    return map;
}
function Map(settingsObject, msg)
{
    eval(msg);

//    VARS
    this.portMarkers    = new Array();
    this.areaCrumbs     = new Array();
    this.Settings       = jQuery.extend({
        center: new google.maps.LatLng(38.8225909761771, 3.1640625),
        target: "map",
        hide_overlay: true,
        scroll: false,
        weather: false,
        zoom: 3,
        icon: "numbers",
        track: false,
        controls: true,
        mapTypeControl: null
    },settingsObject);

    this.initMap();
//    FUNCTIONS

//    START
}
Map.prototype.ports_visible = function(bool)
{
    
    for(var i = 0 ; i < this.portMarkers.length ; i++)
    {
        if(bool)
        {
            this.portMarkers[i].setMap(null);
        }else {
            this.portMarkers[i].setMap(this.map);
        }
    }
}
Map.prototype.ports;
//Map.prototype.goBack = function()
//{
//    if(typeof newArea != "undefined")
//    {
//        newArea(this.areaCrumbs.pop());
//    }
//     if(this.areaCrumbs.length <= 1){
//             $('#backbutton').hide();
//     }else {
//             $('#backbutton').show();
//     }
//}
Map.prototype.getPortBounds = function()
{
    var lat_min = this.ports[0].lat();
    var lat_max = this.ports[0].lat();
    var lng_min = this.ports[0].lng();
    var lng_max = this.ports[0].lng();
    npoints = this.ports.length;
    for (cnt = 0; cnt < npoints; cnt++)
    {
            if (this.ports[cnt].lat() < lat_min) lat_min = this.ports[cnt].lat();
            if (this.ports[cnt].lat() > lat_max) lat_max = this.ports[cnt].lat();
            if (this.ports[cnt].lng() < lng_min) lng_min = this.ports[cnt].lng();
            if (this.ports[cnt].lng() > lng_max) lng_max = this.ports[cnt].lng();
    }
    var sw = new google.maps.LatLng(lat_min,lng_min);
    var ne = new google.maps.LatLng(lat_max,lng_max);

    if(sw.lng() - ne.lng() > 180 || sw.lng() - ne.lng() < -180)
    {
        var nordeast = ne;
        ne = sw;
        sw = nordeast;
    }
    var square = new google.maps.LatLngBounds(sw,ne);

    return square;
}
Map.prototype.gotoArea = function(areaID)
{

    var bounds;
    var NorthEast;
    var SouthWest;
    if(areaID != 0 && typeof this.worldLocations != "undefined")
    {
        for(var i = 0 ; i < this.worldLocations.length ; i++)
        {
            if(this.worldLocations[i].id == this.vaargebied)
            {
                NorthEast = this.worldLocations[i].pointNW;
                SouthWest = this.worldLocations[i].pointSE;
                bounds = new google.maps.LatLngBounds(NorthEast,SouthWest);
                break;
            }
        }
    }else if(typeof this.worldLocations != "undefined"){
        NorthEast = this.worldLocations[0].pointNW;
        SouthWest = this.worldLocations[0].pointSE;
        bounds = new google.maps.LatLngBounds(NorthEast,SouthWest);
    }

    if(this.Settings.pageType != "harbour")
    {
        this.map.fitBounds(bounds);
    }
}

Map.prototype.setPorts = function(msg){
    eval(msg);
}
Map.prototype.initMap = function()
{
    if(this.Settings.pageType == "harbour")
    {
        this.Settings.center = this.ports[0];
    }
    this.map = new google.maps.Map(document.getElementById(this.Settings.target), {
        zoom: this.Settings.zoom,
        mapTypeId: google.maps.MapTypeId.TERRAIN,
        scrollwheel:this.Settings.scroll,
        navigationControl:false,
        mapTypeControl:this.Settings.mapTypeControl,
        center: this.Settings.center
    });
    boundsDoFit = false;
    if(this.getBounds())
    {
        this.map.fitBounds(this.getBounds());
        boundsDoFit = true;
    }


    this.map.ContentWindow = new google.maps.InfoWindow({content:""});
    if(this.Settings.controls){
        this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(new missouristate.web.ZoomPanControl(this.map));
    }
    myMap = this;
    google.maps.event.addListener(this.map, 'zoom_changed', function() {
        onZoomChanged(myMap);
    });
    if(typeof routeXML != "undefined")
    {
        this.drawRoute(routeXML);
        boundsDoFit = true;
    }
    if(typeof this.ports != "undefined")
    {
         this.loadPorts(this.Settings.icon);
         if(!boundsDoFit && this.ports.length < 100 && this.ports.length > 1){
            this.map.fitBounds(this.getPortBounds());
            boundsDoFit = true;
         }
    }
    if(this.Settings.hide_overlay == false){
        this.loadOverlays();
    }
}
Map.prototype.loadOverlays = function()
{
    var myMap = this;
    if(typeof this.worldLocations != "undefined"){
    for(var i = 0; i < this.worldLocations.length; i++){
            if(this.worldLocations[i].zoomLevel != '' && this.worldLocations[i].image != '' && this.worldLocations[i].image != undefined && this.worldLocations[i].image != "undefined")
            {

                    var locationMarker = new CustomMarker(this.worldLocations[i].pointNW, this.map, this.worldLocations[i].image, null, {i: i, id:this.worldLocations[i].id}, this);
                    locationMarker.onClick = function(){
                        newArea(this.obj.id,true);
                    }
                    locationMarker.onMouseOver = function(){
                        $(this.div_).children().attr('src', myMap.worldLocations[this.obj.i].rollOver);
                    }
                    locationMarker.onMouseOut = function(){
                        $(this.div_).children().attr('src', myMap.worldLocations[this.obj.i].image);
                    }
                    locationMarker.setEventListener("click");
                    locationMarker.setEventListener("mouseover");
                    locationMarker.setEventListener("mouseout");
//                            {
//                                    this.setImage(this.worldLocations[this.i].rollOver);
//                             });

//                    locationMarker.i = i;
//                    locationMarker.zoomLevel = this.worldLocations[i].zoomLevel;
//                    locationMarkers.push(locationMarker);
//                    GEvent.addListener(locationMarker,"mouseover",function()
//                            {
//                                    this.setImagethis.worldLocations[this.i].rollOver);
//                             });
//                    GEvent.addListener(locationMarker,"mouseout",function()
//                            {
//                                    this.setImage(this.worldLocations[this.i].image);
//                             });
//                    GEvent.addListener(locationMarker,"click",function()
//                            {
//                                    newArea(this.worldLocations[this.i].id,'true');
//                            }
//                    );
//                    map.addOverlay(locationMarker);
                    this.locationMarkers.push(locationMarker);
            }
    }
    }
}
Map.prototype.locationMarkers = new Array();
Map.prototype.getBounds = function()
{
    var bounds;
    var NorthEast;
    var SouthWest;
    if(typeof this.vaargebied != "undefined" && typeof this.worldLocations != "undefined")
    {
        for(var i = 0 ; i < this.worldLocations.length ; i++)
        {
            if(this.worldLocations[i].id == this.vaargebied)
            {
                NorthEast = this.worldLocations[i].pointNW;
                SouthWest = this.worldLocations[i].pointSE;
                bounds = new google.maps.LatLngBounds(NorthEast,SouthWest);
                break;
            }
        }
        return bounds;
    }else {
        return false
    }
}
function onZoomChanged(map){
    currentZoomLevel = map.map.getZoom();
    
    if(currentZoomLevel > 14){
            map.map.setMapTypeId(google.maps.MapTypeId.SATELLITE);
    }else {
            map.map.setMapTypeId(google.maps.MapTypeId.TERRAIN);
    }
    if(map.locationMarkers.length > 0)
    {
        for(var numMarker = 0; numMarker < map.locationMarkers.length; numMarker++)
        {
            if(currentZoomLevel != 2){
                map.locationMarkers[numMarker].setMap(null);
            }else {
                map.locationMarkers[numMarker].setMap(map.map);
            }
        }
    }
 }

Map.prototype.hide_weather = function(){
    
}
Map.prototype.load_weather = function(){
    
} 
//SET PORT MARKERS


Map.prototype.drawRoute = function(kml){
    route = new google.maps.KmlLayer(((isSecure) ? 'https' : 'http') + '://www.cruisetravel.nl/kml/'+kml+'?rand='+(new Date()).getDate());
//    route = new google.maps.KmlLayer('http://gmaps-samples.googlecode.com/svn/trunk/ggeoxml/cta.kml');
//   route = new google.maps.KmlLayer('http://www.joostmedia.nl/kml/cta.kml');
    route.setValues({ clickable: false });
    route.setMap(this.map);
}
Map.prototype.activateWeatherMap = function(){
    if(this.WeatherMapIsActivate){
        return;
    }else {
        this.weatherIsVisible = false;
        this.WeatherMapIsActivate = true;
        $('.but_weather').click(function(event){
            event.preventDefault();
            this.weatherIsVisible = !this.weatherIsVisible;
            if(this.weatherIsVisible){
                $('.weer').show();
                $(this).css('background-position', '0px -16px');
            }else{
                $('.weer').hide();
                $(this).css('background-position', '0px 0px');
            }
        });
    }
}
Map.prototype.loadPorts = function(kind){
    this.points = new Array()
    if(this.portMarkers.length > 0){
        this.removePorts();
    }
    if(typeof this.ports != "undefined")
    {
        var number = 0;
        var marker;
        var harbour_array = new Array();
        var hasRoute = false;
        if(typeof this.harbours != "undefined" && this.harbours != "")
        {
            hasRoute = true;
            harbour_array = this.harbours.split(',');
        }else {
            harbour_array.push(1);
        }
        var portIDs = new Array();
        for(var i = 0 ; i < this.ports.length ; i++){
            for(var routeDay = 0; routeDay < harbour_array.length; routeDay++)
            {
                if(this.port_id[routeDay] == harbour_array[i] || !hasRoute)
		{

                    if(typeof days != "undefined"){
                        number = days[routeDay];
                    }else{
                        number = i+1;
                    }
                    if(portIDs.find(this.port_id[i])!= -1){
                        offset = 10;
                    }else {
                        offset = 0;
                        portIDs.push(this.port_id[i]);
                    }
                   if(this.Settings.weather != false && typeof this.port_weather[i] != "undefined")
                   {
                        this.activateWeatherMap();
                        obj = {id:this.port_id[i],weather:this.port_weather[i],offset:offset};
                   }else {
                        obj = {id:this.port_id[i],offset:offset};
                   }
                   
                   marker = new CustomMarker(this.ports[i], this.map, kind, number, obj, this);

                    var daynum = "";
                    if(typeof portInfoWindow != "undefined")
                    {
                        marker.onClick = function (){
                            show_info(this.number-1,'#mapkaartinfo','port');
                            if(info_slider!=""){
                                window.clearInterval(info_slider);
                                info_slider = "";
                            }
                        }
                    }else {
                        var port_ArrayId;
                        if(typeof days != "undefined") //days globalvar
                        {

        //                    for(var n = 0; n < days.length; n++)
        //                    {
        //                        if(days[n] == this.number){
        //                            port_ArrayId = n;
        //                        }
        //                    }
                            daynum = "/daynr/"+marker.number;
                        }else {
                            daynum = "";
                        }
                    }
                    marker.obj.infoContent = "<iframe src='/ajax/googlemaps/index/harbourinfo/harbour_id/" +marker.obj.id + "" +daynum+ "' frameborder='0' width='275' height='255' scrolling='no' />";

                   marker.setEventListener("click");
                   marker.setEventListener("mouseover");
                   marker.setEventListener("mouseout");

                   this.portMarkers.push(marker);
                }
            }
        }
    }
}
Map.prototype.showWeather = function(){
        $('.weer').show();
}
Map.prototype.hideWeather = function(){
        $('.weer').hide();
}
Map.prototype.removePorts = function(){
        for(var i = 0 ; i < this.portMarkers.length ; i++){
            this.portMarkers[i].remove();
            this.portMarkers[i].setMap(null);
        }
        this.portMarkers = new Array();
}
//CLASS CustomMarker
//
//Needs:
//   "Position"  - google.maps.LatLng()
//   "map"       - google.maps
//   "number"    - iconNumber:Number
//   "obj"       - markerObject (obj.name, obj.id) etc
function CustomMarker(latlng, map, kind_, number, obj_, ct_map) {
    this.obj = obj_;
    this.size = 0;
    this.kind = kind_;
    this.holder = ct_map;
    this.obj = jQuery.extend({
        offset: 0
    },obj_);
    url = ((isSecure) ? 'https' : 'http') + "://www.cruisetravel.nl/";
    roundCourse=false;
    switch(this.kind){
            case "start":
                    url +="start.png";
                    break;
            case "round":
                    url = "/images/harbours.php?number="+number+"";
                    this.size = 25;
                    roundCourse = true;
                    break;
            case "noNumbers":
                    url = "/images/googlemaps/0.png";
                    this.size = 8;
                    break;
            case "numbers":
                    url = "/images/harbours.php?number="+number+"";
                    this.size = 25;
                    offset = 0;
                    break;
            default:
                    url = kind_;
                    break;
    }

    this.number = number;
    this.latlng_ = latlng;
    this.src = url;
    this.setMap(map);
  }

  CustomMarker.prototype = new google.maps.OverlayView();
  CustomMarker.prototype.onClick;
  CustomMarker.prototype.draw = function() {
    var me = this;

    // Check if the div has been created.
    var div = this.div_;
    if (!div) {
      // Create a overlay text DIV
      div = this.div_ = document.createElement('DIV');
      // Create the DIV representing our CustomMarker
      div.style.border = "none";
      div.style.position = "absolute";
      div.style.paddingLeft = this.obj.offset+"px";
      div.style.paddingTop = this.obj.offset+"px";
      div.style.cursor = 'pointer';

      var mouseOverDiv = document.createElement('DIV');
      mouseOverDiv.style.border = "none";
      mouseOverDiv.style.position = "absolute";
      mouseOverDiv.setAttribute("class","harbourOver");
      mouseOverDiv.style.paddingLeft = this.obj.offset+"px";
      mouseOverDiv.style.paddingTop = this.obj.offset+"px";
      mouseOverDiv.style.cursor = 'pointer';
      mouseOverDiv.style.display = 'none';
      
      var mouseOver = document.createElement("img");
      mouseOver.src = ((isSecure) ? 'https' : 'http') + "://media3.cruisetravel.nl/images/label_klikhier.png";
      mouseOverDiv.appendChild(mouseOver);
      var img = document.createElement("img");
      img.src = this.src;
      if(this.size > 0)
      {
        img.width = this.size;
        img.height = this.size;
      }

    // Position the overlay

      div.appendChild(img);
      div.appendChild(mouseOverDiv);
    if(typeof this.obj.weather != "undefined" && this.obj.weather != "") {

        if(this.holder.checkDistance(this.latlng_)){
            var weer = document.createElement('div');
            weer.setAttribute("class","weer");
            var weerImage = document.createElement('img');
            weerImage.src = this.obj.weather;
            weer.style.display = 'none';
            weer.style.position = "absolute";
            weer.appendChild(weerImage);
            div.appendChild(weer);
        }
    }
    
      google.maps.event.addDomListener(img, "mouseover", function(event) {
        google.maps.event.trigger(me, "mouseover");
      });
      google.maps.event.addDomListener(div, "click", function(event) {
        google.maps.event.trigger(me, "click");
      });
      google.maps.event.addDomListener(img, "mouseout", function(event) {
        google.maps.event.trigger(me, "mouseout");
      });

      // Then add the overlay to the DOM
      var panes = this.getPanes();
      panes.overlayImage.appendChild(div);
    }
    var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);
    if (point) {
        if(this.size > 0){
            point.x -= this.size/2;
            point.y -= this.size/2;
        }
      div.style.left = point.x + 'px';
      div.style.top = point.y + 'px';
    }
  };
  Map.prototype.points = new Array();
  Map.prototype.checkDistance = function(point){
        for(var i = 0 ; i < this.points.length ; i++){
            AB = this.points[i].lat() - point.lat();
            if(AB < 0){
                AB *= -1;
            }
            BC = this.points[i].lng() - point.lng();
            if(BC < 0){
                BC *= -1;
            }
            distance = Math.sqrt(AB^2 + BC^2);
            if(distance < 1.9){
                return false;
            }
        }
        this.points.push(point);
        return true;
  }
  CustomMarker.prototype.onClick = function(){
        var markersMap = this.getMap();
        markersMap.ContentWindow.setContent(this.obj.infoContent);
        markersMap.ContentWindow.open(this.getMap(),this);
    }
  CustomMarker.prototype.onMouseOut = function(){
      $(this.div_).children('.harbourOver').hide(300);
    }
  CustomMarker.prototype.onMouseOver = function(){
      $(this.div_).children('.harbourOver').show(300);
    }

  CustomMarker.prototype.setEventListener = function (event) {
      switch(event)
      {
          case "click":
            functie = this.onClick;
            break;
          case "mouseover":
              functie = this.onMouseOver;
              break;
          case "mouseout":
              functie = this.onMouseOut;
              break;
          default:
              functie = this.onClick;
              break;
      }
   google.maps.event.addListener(this, event, functie);

  }
  
  CustomMarker.prototype.remove = function() {
    // Check if the overlay was on the map and needs to be removed.
    if (this.div_) {
      this.div_.parentNode.removeChild(this.div_);
      this.div_ = null;
    }
  };

  CustomMarker.prototype.getPosition = function() {
   return this.latlng_;
  };

//END CUSTOM MARKER CLASS

Array.prototype.find = function (element)
{
for (var keys in this)
{
if (this[keys] == element)
{
return keys;
break;
}
}
return -1;
};
