var point_glasgow,map,touring_timeout_id,dom_glasgow,whitepin,blackpin;
var tours = new Array();
var time_between = 3000;
var now_playing = false;
var now_tour = 0;
var now_location = 0;

function clear() {
  map.setCenter(point_glasgow, 4);
  map.closeInfoWindow();
}
function startTour(tourId) {
	now_playing = true;
	clear();
	setLocation(tourId,0);
	showLocation();
	touring_timeout_id = setTimeout('nextLocation()',time_between);
}
function nextLocation() {
	setLocation(now_tour,((now_location+1)%tours[now_tour].length));
	showLocation();
	if(now_playing) {
		touring_timeout_id = setTimeout('nextLocation()',time_between);
	}
}
function previousLocation() {
	setLocation(now_tour,(((now_location-1)+tours[now_tour].length)%tours[now_tour].length));
	showLocation();
}
function pauseTour() {
	now_playing = false;
	clearTimeout(touring_timeout_id);
}
function resumeTour() {
	now_playing = true;
	nextLocation();
}
function setLocation(tourId,locationId) {
	now_tour = tourId;
	now_location = locationId;	
}
function showLocation() {
  map.openInfoWindow(tours[now_tour][now_location]["latlng"] ,tours[now_tour][now_location]["dom"]);
}
function reset() {
	clearTimeout(touring_timeout_id);
	now_playing = false;
  map.setCenter(point_glasgow, 4);
  // map.openInfoWindow(point_glasgow,dom_glasgow);
}
function pp() {
	if(now_playing) {
	  pauseTour();
  } else {
    resumeTour();
  }
}
function updatePlayPause() {
	if(now_playing) {
		document.getElementById('subplaypause').innerHTML = 'pause';
    // attach(document.getElementById('subplaypause'),'click',pauseTour);
	} else {
		document.getElementById('subplaypause').innerHTML = 'play';
    // attach(document.getElementById('subplaypause'),'click',resumeTour);
	}
	setTimeout('updatePlayPause()',500);
}

function show(tour) {
  if(tour=='all') {
    for(var i=0;i<tours.length;i++) { //for all tours
  		for(var j=0;j<tours[i].length;j++) { //for all locations on the tour
  		  tours[i][j]['marker'].show();
  		}
  	}
  } else {
		if (tours[tour]) {
			for(var j=0;j<tours[tour].length;j++) { //for all locations on the tour
				tours[tour][j]['marker'].show();
			}
		}
  }
}

function hide() {
	for(var i=0;i<tours.length;i++) { //for all tours
		for(var j=0;j<tours[i].length;j++) { //for all locations on the tour
		  tours[i][j]['marker'].hide();
		}
	}
	ew.hide();
  map.closeInfoWindow();
}
function initialize() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
  	map.setMapType(G_SATELLITE_MAP);
  	map.addControl(new GLargeMapControl());
    ew = new EWindow(map, E_STYLE_7);      
    map.addOverlay(ew);
    
    whitepin = new GIcon(G_DEFAULT_ICON,'/release/images/white-pin.png');
    blackpin = new GIcon(G_DEFAULT_ICON,'/release/images/black-pin.png');
    markeropts={'icon':whitepin};
    
		//Create Glasgow Point
    point_glasgow = new GLatLng(55.85831,-4.237547, 1);
    point_intro = new GLatLng(55.85831,-40, 1);
    // dom_glasgow = document.getElementById('glasgow-infowindow');
		
		dom_tours = $('tours');
		var children = dom_tours.childElements();
		for(var i=0;i<children.length;i++) { //for  all tours
			var dash1Index = children[i].id.indexOf('-');
			var tournum = children[i].id.substring(dash1Index + 1);
			tours[tournum] = new Array();
			var locnum=0;
			if(children[i].id!="undefined"&&children[i].childNodes.length>0) {
				var dom_tour = children[i];
				for(var j=0;j<dom_tour.childNodes.length;j++) { //for all locations on the tour
					if(document.getElementById('tour-'+tournum+'-'+locnum+'-lat')) {
						tours[tournum][locnum] = new Array();
						tours[tournum][locnum]["latlng"] = new GLatLng(document.getElementById('tour-'+tournum+'-'+locnum+'-lat').innerHTML,document.getElementById('tour-'+tournum+'-'+locnum+'-lng').innerHTML,4);
						tours[tournum][locnum]["dom"] = document.getElementById('tour-'+tournum+'-'+locnum+'-html');
						tours[tournum][locnum]["marker"] = new GMarker(tours[tournum][locnum]["latlng"],markeropts);
						tours[tournum][locnum]["marker"].tour=tournum;
						tours[tournum][locnum]["marker"].loc=locnum;
            GEvent.addListener(tours[tournum][locnum]["marker"], "click", function() {
              ew.openOnMarker(this,tours[this.tour][this.loc]["dom"].innerHTML);
              // this.openInfoWindow(tours[this.tour][this.loc]["dom"]);
            });
            GEvent.addListener(tours[tournum][locnum]["marker"], "mouseover", function() {
              this.setImage('/release/images/black-pin.png');
            });
            GEvent.addListener(tours[tournum][locnum]["marker"], "mouseout", function() {
              this.setImage('/release/images/white-pin.png');
            });
          	
          	map.addOverlay(tours[tournum][locnum]["marker"]);
						locnum++;
					}
				}
			}
		}
		for (var i = 0; i < tours.length; ++i) {
			if (undefined === tours[i]) {
				tours[i] = new Array();
			}
		}
		
		GEvent.addListener(map, "click", function(overlay,point) {
            if (!overlay) {
              ew.hide();
            }
          });
    if(document.getElementById('glasgow-infowindow')) {
      ew.openOnMap(point_intro,document.getElementById('glasgow-infowindow').innerHTML);
    }
		startlinkUL = document.getElementById('tourstartlinks');
		tourcount=-1;
		for(var i=0;i<startlinkUL.childNodes.length;i++) { //for  all start link
			// attach behavious here
			if(startlinkUL.childNodes[i].nodeName=='LI') {
				startlinkUL.childNodes[i].idx=tourcount;
				if(tourcount==-1) {
	  				attach(startlinkUL.childNodes[i], 'click', function() {
	  					hide();
	  					show('all');
	  					return false;
	  				});
				} else {
	  				attach(startlinkUL.childNodes[i], 'click', function(e) {
	  					var target, index, li;
	  					
	  					e = e || window.event();
	  					target = e.target || e.srcElement;
	  					
	  					//get the LI
	  					li = target.parentNode;
							li = $(li);
	  					
	  					while (target.parentNode && target.parentNode.tagName != "LI") {
	  						li = target.parentNode;
	  					}
	  					
	  					if (li.tagName == "LI" && li.idx !== undefined) {
	  						//all good - show tour
		  					//index = li.idx;
								index = li.down('a').href.substring(li.down('a').href.indexOf('#tour') + 5);
							hide();
							show(index);
						}
						
						return false;
					});
				}
				tourcount++;
			}
		}
		reset();
  }
}
function attach(element, eventType, listener, capture) {
	if (element.addEventListener) {
		element.addEventListener(eventType, listener, capture);
	} else if (element.attachEvent) {
		element.attachEvent("on" + eventType, listener);
	}
}
function resizeMap() {
	var h=(pageHeight()-88);
	document.getElementById('map').style.height=h+"px";
}
pageHeight=function() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return myHeight;
};
// attach(window,'resize',function(e){
//   resizeMap();
// });
chain=function(f) {
  var o=window.onload;window.onload=function() {if(o) o();f();}
};

chain(initialize);
