var ready1 = false;
var ready2 = false;

function log( x ) {
}

/**
 * Destination Selector kan crashen in FF als
 * * Deze zich in het zichtbare deel van het scherm bevindt tijdens laden (style visibility:hidden maakt niet uit)
 * * wmode == opaque
 * * de punten op de kaart worden gezet als deze nog niet geheel geladen is.
 * 
 * Om dit te voorkomen moet zowel chartevent.ready zijn afgevuurd als de callback-functie zijn aangeroepen.
 * @return
 */
function doit() {
	if ( ready1 && ready2 ) {
		log("both ready");
		HollandCom.DestinationSelector.construct();
	}
	else {
		setTimeout('doit();',100 );
	}
}

doit();

function callbackFn(e) {
	log('callback' );
	ready2 = true;
	log('end callback.');
}

HollandCom.DestinationSelector = (function() {
	
	// marker lists holds the marker data
	var markerLists = [];
	
	// Setting up the data object and add chart and listeners when ready
	var setup = function(data) {
		if (jQuery.browser.msie) {
			xmlData = data;
	        data = new ActiveXObject( 'Microsoft.XMLDOM');
	        data.async = false;
	        data.loadXML( xmlData); 
        }

		// get marker groups from data
		$(data).find('markergroup').each(function() {
			markerLists.push(new MarkerList($(this)));
		});
		
		// call for Chart and wait for ready before starting the DOM construction
		Chart.bind(ChartEvent.READY,function(){log('ChartEvent.READY');ready1=true;});
		Chart.bind(ChartEvent.HIGHLIGHT,function(e,id){log('ChartEvent.HIGHLIGHT');highlightTextMarkerById(id);});
		Chart.bind(ChartEvent.RESTORE,function(e){log('ChartEvent.RESTORE');restoreTextMarkers();});
		Chart.bind(ChartEvent.OPEN,function(e,url){log('ChartEvent.OPEN');navigateTo(url);});
		Chart.load();
		
	};
	
	// constructing the DOM
	var construct = function() {
		log('starting construct');
		// build DOM of destination selector(s)
		$('.destination-selector').each(function(){
			
			// remove current static content
			$('.no-flash',this).remove();

			// define dropdown items
			var dropdownItems = [];
			for (var i=0;markerLists[i]!==undefined;i++) {
				dropdownItems.push({label:markerLists[i].label,value:markerLists[i].id});
			}
			
			// define marker category dropdown
			var dropdown = HollandCom.FauxDropdown.generate('marker-categories',dropdownItems);
			dropdown.bind('change',function(e){onMarkerCategoryChange(e)});
			
			

			// define marker list
			var list = $('<ul class="markers"></ul>');
			
			// define more link
			var link = $('<a class="more" href="#"></a>');
			
			// add items to DOM
			$('.content',this).append(dropdown,list,link);
			
		});
		
		// set initial markerset
		updateByMarkerListById(markerLists[0].id );
		log('finished construct');
	};
	
	var onMarkerCategoryChange = function(e) {
		log('onMarkerCategoryChange');
		
		// get id
		var id = $('.selected',e.target).attr('href').split('#')[1];
		
		// update the list by passing id
		updateByMarkerListById(id);
	}
	
	var updateByMarkerListById = function(id) {
		log('updateByMarkerListById ' + id );
		
		
		// define vars
		var item,list,listItems,btn = null;
		
		// get list with supplied id
		
		for (var i=markerLists.length;i--;) {
			if (id == markerLists[i].id) {
				list = markerLists[i];
				listItems = markerLists[i].items;
			}
		}
		
		
		
		// clear current markers
		var markerList = clearMarkers();
		
		// update more link
		var moreLink = $('.destination-selector a.more');
			
		var linkText = 'View all';
		
		if ($("#show_all_x").attr("value") != null) {
			
			linkText = $("#show_all_x").attr("value");
		}
		
		moreLink.text(linkText + list.linktext);
		moreLink.attr('href', list.url);
		
		moreLink.css('display', list.url ? 'block' : 'none');
			
			
		
		// add new markers
		for (var i=0;listItems[i]!==undefined;i++) {
			
			// define button
			btn = $('<a id="marker-' + listItems[i].id + '" href="' + listItems[i].url + '">' + listItems[i].name + '</a>');
			btn.bind('mouseover',overTextMarker);
			btn.bind('mouseout',outTextMarker);
			
			// define list item
			item = $('<li></li>').append(btn);
			
			// Add odd className to second item
			if ( (i % 2) == 1) {
				item.addClass('odd');
			}
			
			// append item to cleared marker list
			markerList.append(item);
		}
		
		// update chart
		log(listItems );
		Chart.update(listItems);
	};
	
	var highlightTextMarkerById = function(id) {
		
		// restore all text markers
		restoreTextMarkers();
		
		// highlight supplied text marker
		$('a#marker-' + id).addClass('highlighted');
		
		// highlight chart marker
		Chart.commandHighlightMarkerById(id);
	};
	
	var restoreTextMarkers = function() {
		var markerList = $('.destination-selector .markers');
		$('a',markerList).removeClass('highlighted');
		
		// restore chart markers
		Chart.commandRestoreMarkers();
	};
	
	var navigateTo = function(url) {
		window.location = url;
	};
	
	var overTextMarker = function(e) {
		
		// get id from btn
		var id = $(e.target).attr('id').split('marker-')[1];
		
		// highlight text marker
		highlightTextMarkerById(id);
	};
	
	var outTextMarker = function(e) {
		// restore text markers
		restoreTextMarkers();
	};
	
	var clearMarkers = function() {
		var markerList = $('.destination-selector .markers');
			markerList.empty();
		return markerList;
	};
	
	var UIDSupplier = {
		uid:1,
		getUID:function() {
			return this.uid++;
		}
	};
	
	// Chart related
	var ChartEvent = {
		READY:'ready',
		HIGHLIGHT:'highlight',
		RESTORE:'restore',
		OPEN:'open'
	};
	
	var Chart = {
		
		swf:null,
		
		load:function() {
			
			var params = {
				menu: "false",
				scale: "noScale",
				wmode: "opaque",
				allowscriptaccess: 'always'
			};
			
			swfobject.embedSWF(
				"/static/flash/DestinationChart.swf?country=" + 'JP', 
				"destinationchart", 
				"240", 
				"292", 
				"9.0.0", 
				"expressInstall.swf", 
				{}, 
				params,
				null,
				callbackFn
			);
		},
		
		update:function(list) {
			
			// clear current markers
			this.commandClearMarkers();

			// add new markers
			var item = null;
			
			for (var i=0;list[i]!==undefined;i++) {
				item = list[i];
				this.commandSetMarker(
					item.id,
					item.x,
					item.y,
					item.name,
					item.url,
					item.resource
				);
			}
			
		},
		
		commandSetMarker:function(id,x,y,name,url,resource) {
			if (this.swf) {
				if (resource==null) {
					this.swf.setPointMarker(id,x,y,name,url);
				}
				else {
					this.swf.setAreaMarker(id,x,y,name,url,resource);
				}
			}
		},
		
		commandHighlightMarkerById:function(id) {
			if (this.swf) {
				this.swf.highlightMarkerById(id);
			}
		},
		
		commandRestoreMarkers:function() {
			if (this.swf) {
				this.swf.restoreMarkers();
			}
		},
		
		commandClearMarkers:function() {
			if (this.swf) {
				this.swf.clearMarkers();
			}
		},
	
		responseNavigate:function(url) {
			Chart.trigger(ChartEvent.OPEN,[url]);
		},
		
		responseHighlight:function(id) {
			Chart.trigger(ChartEvent.HIGHLIGHT,[id]);
		},
		
		responseRestore:function() {
			Chart.trigger(ChartEvent.RESTORE);
		},
			
		responseReady:function() {
			var chart = swfobject.getObjectById('destinationchart');
			
			Chart.swf = chart;
			Chart.trigger(ChartEvent.READY);
		},
		
		// jquery conversion functions
		bind:function(type,callback) {$(this).bind(type,callback);},
		trigger:function(type,data) {$(this).trigger(type,data);}
	}
	
	// Data Provider related
	var DataProviderEvent = {
		READY:'ready'
	}
	
	var DataProvider = {
		data:null,
		
		load:function(src) {
			$.get(src,function(data){DataProvider.ready(data);});
		},
		
		ready:function(data) {
			this.data = data;
			this.trigger(DataProviderEvent.READY,[data]);
		},
		
		// jquery conversion functions
		bind:function(type,callback) {$(this).bind(type,callback);},
		trigger:function(type,data) {$(this).trigger(type,data);}
	}
	
	
	// marker list and marker item data classes
	var MarkerList = function(xmlNode) {
		this.label;
		this.url;
		this.id;
		this.linktext;
		this.items = [];
		
		this.parseNode(xmlNode);
	};
	
	MarkerList.prototype.parseNode = function(markergroup) {
		
		var children = $(markergroup).children();
		
		this.label = $(children.get(0)).text();
		this.url = $(children.get(1)).text();
		this.id = UIDSupplier.getUID();
		if ( this.url ) { this.linktext = $(children.get(2)).text(); }
		
		var markers = $('marker',markergroup);
		for (var i=0;markers[i]!==undefined;i++) {
			this.addItem(markers[i]);
		}
	};
	
	MarkerList.prototype.addItem = function(marker) {
		this.items.push(new MarkerItem(marker));
	};
	
	function MarkerItem(marker) {
		this.id;
		this.x;
		this.y;
		this.name;
		this.url;
		this.resource = null;
		
		this.parseNode(marker);
	}
	
	MarkerItem.prototype.parseNode = function(marker) {
		this.id = UIDSupplier.getUID();
		this.x = $(marker).attr('x');
		this.y = $(marker).attr('y');
		
		var children = $(marker).children();
		this.name = $(children.get(0)).text();
		this.url = $(children.get(1)).text();
		
		var resource = $(marker).attr('resource');
		if (typeof(resource) != 'undefined') {
			this.resource = resource;
		}
	};
	
	// init
	var init = function() {
		$(document).ready(function(){
			if (typeof(destinationXmlLocation) != 'undefined') {
				var root = '/nl/';
				
				if ($("#root").attr("value") != null) {
					root = $("#root").attr("value");
				}
			
				// start loading data and setup destination selector when ready
				DataProvider.load( destinationXmlLocation  );
				DataProvider.bind(DataProviderEvent.READY,function(e,data){setup(data)});
			}
		});
	};
	
	return {
		init: init,
		construct: construct,
		chartReady: Chart.responseReady,
		chartNavigate: Chart.responseNavigate,
		chartHighligth: Chart.responseHighlight,
		chartRestore: Chart.responseRestore
	};
	
})();


//setTimeout('HollandCom.DestinationSelector.init();',1500 );
HollandCom.DestinationSelector.init();

