var OzExPassMap = Class.create();
OzExPassMap.applyTo(".OzExPassMapComponent");
OzExPassMap.handlers = function(map) {
    map.addMapDataHandler("XELocation", XELocation);
    map.addMapDataHandler("XEDestination", XEProduct);
    map.addMapDataHandler("XEHotel", XEProduct);
    map.addMapDataHandler("XEProduct", XEProduct);
    map.addMapDataHandler("XEMapDataSet", XEMapDataSet);
    map.addMapDataHandler("XEActivity", XEProduct);
    map.addMapDataHandler("OzExFlight", OzExFlight);
    map.addMapDataHandler("OzExRoute", OzExRouteHandler);
    OzExPassMap.icons();
};
OzExPassMap.icons = function() {
    var actIcon = createIcon("activity");
    XELocation.icons.XEActivity = createIcon("activity", 64,64);
    XELocation.icons.XEDestination = XELocation.icons.XELocation = createIcon("destination2", 64, 64);
    XELocation.icons.XEHotel = createIcon("accomodation", 64, 64);
};

OzExPassMap.prototype = {
  data: null,
  elements: [],
  initialize: function() {
    var map = new XEMap(this.down(".map"));
    this.map = map;
    this.map.owner = this;
    
    if(this.down('a.next') ) this.down('a.next').onclick = this.select.bind(this, "next");
    if(this.down('a.previous') ) this.down('a.previous').onclick = this.select.bind(this, "previous");
    
    OzExPassMap.handlers(this.map);
    
    var data = passdata;
    this.map.addMapData(data, {centre:true});
    this.data = data;
    
    if(this.data.ClassName == "OzExRoute") this.setUpRoute();
    else this.getRelated(data.ID);
    dhtmlHistory.initialize();
    dhtmlHistory.addListener(function(newLocation, hashData){
      var results, reg = /Map-(.*)/;
      if(reg.test(newLocation)) {
        return this.select($(newLocation.match(reg)[1]));
      }
        //if(this.data) this.map.centreMapData(this.data);
      if(this.down('.introduction') ) this.select(this.down(".introduction"));
    }.bind(this));
    if(!this.getCurrent() && this.down(".introduction"))
      this.select(this.down(".introduction"));
    
    var loc = this.down(".Location");
    if(loc) {
    	map.clearControls();
    	
    	var control = loc.down('.control');
    	control.addClassName('closed');
    	
    	control.observe('click', function(event) {
    		var control = Event.element(event);
    		var mapHolder = control.up().down('div.mapHolder');
    		var map = control.up('.OzExPassMapComponent').map;
    		
    		if (control.hasClassName('closed')) {
    			mapHolder.morph(this, {
    				style: 'width:570px;', 
    				afterFinish: function() { 
    					map.checkResize();
  		  			control.removeClassName('closed');
  		  			control.addClassName('open');
  		  			control.update('&raquo; Minimise map');
  		  			map.resetControls();
    				} 
    			});
    		} else {
  		  	map.clearControls();
    			mapHolder.morph(this, { 
    				style: 'width:160px;', 
    				afterFinish: function() { 
    					map.checkResize();
  		  			control.removeClassName('open');
  		  			control.addClassName('closed');
  		  			control.update('&laquo; Expand map');
    				} 
    			});
    		}
  			Event.stop(event);
  	});

    	
    	// Insert rounded corners
    	$w('ne se sw nw').each(function(corner) {
				new Insertion.Bottom(
					loc.down("div.mapHolder"),
					 "<img src='ozexperience/images/"+corner+".png' class='overlay "+corner+"' />"
				);
    	});
    }

  },
  selectIntro: function() {
//    dhtmlHistory.add("intro", "");
    
    //Need to figure out if we actually want to centre here... the first time we selectIntro almost certainly not
    this.sifrizeHeadings();
    return false;
  },

  setUpRoute: function() {
    this.getElementsBySelector("li.OzExFlight").invoke("remove");
    var item = this.getElementsBySelector("li.item").first();
    
    var map = this.map;
    var me = this;
    
     this.data.Elements.findAll(function(i) {return i.ClassName != "OzExFlight";})
      .each(function(i, index){
        item.MapData = i;
        var options = {onAdded: function(marker) {
          GEvent.bind(marker, 'click', me, function() {
            me.selectItem(i.ID);
          });
        }};
        if(index == 0) options.centre = true;
        map.addMapData(i, options);
        item = item.next();
      });
  },
  getItem: function(id) {
    return this.getElementsBySelector("li.Item-"+id).first();
  },
  
  selectItem: function(id) {
    this.select(this.getItem(id));
  },
  
  getCurrent: function() {
    return this.down("li.current");
  },
  select: function(el) {
    var cur = this.getCurrent() ;
    var newEl;
    if(typeof(el) == "string") { //this supports supply 'next' or 'previous' as an argument
      newEl = cur[el]();
    } else {
      newEl = el;
    }
    if(cur) cur.removeClassName("current");
    newEl.addClassName("current");
    
    if(newEl.hasClassName("introduction")) return this.selectIntro();
    
    var res = /([0-9]+)/.exec(newEl.id);
    dhtmlHistory.add("Map-Product"+res[1], "");
    
    
   
    this.map.centreMapData(newEl.MapData);
    

    this.getRelated(res[1]);
    this.sifrizeHeadings();
    return false;
  },

  getRelated: function(id) {
    var selected = this.getItem(id);
    
    if(!selected || !selected.RelatedData) { //Check for selected here. cause there won't be selected in Destination maps
    
      var me = this;
      new Ajax.Request("OzExPassMapComponent/getRelated/"+id, {
        onSuccess: function(req) {
          selected.RelatedData = req.responseText.evalJSON();
          me.map.addMapData(selected.RelatedData);
        }
      });
    }
  },
  
  sifrizeHeadings: function() {
			sIFR.replace(rockwell, { selector: ".OzExPassMapComponent .current h3"
        ,css: [ '.sIFR-root { color: #FD8419; text-transform: uppercase; font-weight: bold; }',
				,'a { text-decoration: none; }'
				,'a:link { color: #FD8318; }'
				,'a:hover { color: #FD8318; text-decoration: underline; }' ]
				,transparent: 'transparent' });
	}
};


var OzExFlight = Class.create();
OzExFlight.addMapDataHandler = function(mapData, options) {
  mapData.Elements = mapData.Elements.map(function(i) {
    return i.MapData;
  });
  
  XELine.addMapDataHandler.call(this, mapData, {color: "#ffb03b", geodesic: true});
}

var OzExRouteHandler = Class.create();
Object.extend(OzExRouteHandler, XEMapRoute);
OzExRouteHandler.centreOnMarker = XEMapRoute.centreOnMarker;
OzExRouteHandler.addMapDataHandler = function(mapData, options) {
  var me = this;
  var map = this.map;
  
  var routes = [];
  var drawnRoutes = [];
  var current = [];
  mapData.Elements.each(function(i) { 
    if(i.ClassName == "OzExFlight") {
      routes.push(current);
      current = [];
    } else {
      current.push(i);
    }
  });
  routes.push(current);
  
  
  routes.each(function (el) {
    var normalRoute = el.map(function(data) {
      data.MapData.Name = data.Name;
      return data.MapData;
    });
    
    drawnRoutes.push( XEMapRoute.addMapDataHandler.call(me, {Elements: $A(normalRoute)}, {
      preserveViewport: true,
      toString: function() {
        return XELocation.toString.call(this.MapData);
      }, 
      polyline: (window.location.href.indexOf('Stage') > -1),
      onload: function(line) {
        me.centreMapData(mapData);
      }
    }));;
  });
  
  routes.each(function(route, i) {
    if(route !== routes.last() && routes[i+1].first()) {
      drawnRoutes.push(me.addMapData({ClassName: "OzExFlight", Elements:[route.last(), routes[i+1].first()]}));
    }
  });
  return drawnRoutes;
}


function createIcon(iconName, width, height) {
  width = width ? width : 48;
  height = height ? height : 48;

  var icon = MapIconMaker.createMarkerIcon({'width':width, 'height':height,primaryColor:"#ffb401", cornerColor: "#ffb401"});
  
  var iconLocation = $$("base").first().href + "ozexperience/images/map/";
  icon.image = iconLocation+iconName + ".png";
  icon.printImage = icon.mozPrintImage;

  return icon;
}
XEProduct.travelPlannerTab = function(marker, product) {
  var name = Dict.get("TP.Name");
  var tabName = "ProductTab"+product.ID;
  
  GEvent.addListener(marker, "infowindowopen", function() {
    new Ajax.Updater($(tabName).next('h6'), "OzExPassMapComponent/getBooking/"+product.ID, {
      onComplete: OzExBookNow.processLinks,
      insertion: Insertion.After
    }
    );
  });
  
}

