
function mouseoverCB(e)
{
  if (e.elementID != null)
  {
	//Cancel default action
	return true;
  }
}

function mouseoutCB(e)
{
  if (e.elementID != null)
  {
	//Cancel default action
	return true;
  }
}


var map = null;
function loadMyMap() {
	// load script required for map
	//http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2
	(function() {
			
		if (channel.indexOf("m-") > -1){
			return false;
		};
        var e = document.createElement('script');
        e.type = 'text/javascript';
        e.src = document.location.protocol +'//dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2';
        e.async = true;
        document.getElementById('map-root').appendChild(e);
        // wait few seconds then load map
        window.setTimeout(loadMyMapDefer,500);
      }());
      
}
function loadMyMapDefer(){

	if(typeof(VEMap) != "function"){
		window.setTimeout(loadMyMapDefer,500);
		return false;
	}else{
		loadVEMap();
	}
}
function loadVEMap(){
	$('#hotelsDetail').html("");
	
	var mapHotels = new Array();
    map = new VEMap('myMap');
    //the VEMap.onLoadMap
   // map.onLoadMap = correctEvents;
    map.LoadMap(new VELatLong(-28.0297, 153.4319), 16 ,'r' ,false,VEMapMode.Mode2D,true,0);
    var layer = new VEShapeLayer();
    var veLayerSpec = new VEShapeSourceSpecification(VEDataType.VECollection, '1D3DFA9B90839F60!211', layer);
    map.ImportShapeLayerData(veLayerSpec, function() {
        var numShapes = layer.GetShapeCount();
        
        for (var i = 0; i < numShapes; ++i) {
        	
            s = layer.GetShapeByIndex(i);
			var pts = s.GetPoints();

			var description = s.GetDescription();
			var title = s.GetTitle();
			var hotelPhoto = s.GetPhotoURL();
			var hotelUrl = s.GetMoreInfoURL();
			
						
			desc = description.split(";");
			// address is description[0]
			// star rate is description[1]
			// the rest is information to show as is
			
			var add = desc[0];
			
			var star =  parseFloat(desc[1].replace("<br>","")) * 10;
			
			var isMain = false;
			if (isNaN(star)) star = 0;
			if (desc[1].indexOf("Event Location") > -1){
				// no stars, just "event locaiton"
				isMain = true;
			}
			var info = new Array();
			var b =0;
			for (x=2; x<desc.length; x++){
				var infbit = desc[x].split(":");
				info[b++] = {title: infbit[0].replace("<br>",""), content: infbit[1]};
			}
			
			var icon = ("<span hotelid='{0}' ismain='{1}'></span>").replace("{0}",s.GetID()).replace("{1}",isMain);
			s.SetCustomIcon(icon);

			mapHotels[i] = {index: s.GetID(),
							title: title, 
							address: add,
							star: star,
							information: info,
							photo: hotelPhoto,
							url: hotelUrl,
							isMain: isMain,
							lon: pts[0].Longitude,
							lat: pts[0].Latitude
							};		
       }
		
		createContent(mapHotels);
        
   		map.AttachEvent("onmouseover", mouseoverCB);
		map.AttachEvent("onmouseout", mouseoutCB);
		map.AttachEvent("onchangeview",correctEvents);
        //map.SetZoomLevel(16);
    }, true);
	
	
}
function correctEvents(e){
	// reattached onclick events of the new pio pins
	window.setTimeout(setPins,20);

}
function setPins(){
	poiPins = $('#myMap a.VEAPI_Pushpin');
	
	$.each(poiPins,function(){
		// if span has isMain set to true, change class of this poipin
		if ($(this).find("span").attr("ismain") == "true"){
			$(this).addClass("main");
		}
	});
	setMapClick();
	
	// if bClick is true, do click
}
function createContent(mapHotels){
	// build content using object array
	
	/* build this 
	<li>
		<div class="img" style="background-image:http://australia.msteched.com/p/TEAU10/resources/freshwater_point_apts.gif"></div>
		<div class="right">
			<h4>SOFITEL GOLD COAST</h4>
			<span class="add">81 Surf Parade, Broadbeach QLD 4218</span>
			<span class="istar istar-45"></span>
			<dl>
				<dt>Phone:</dt>
				<dd>07 5592 2250</dd>
				<dt>Rate:</dt>
				<dd>from $220</dd>
				<dt>Distance:</dt>
				<dd>3 minute walk to Convention Centre, 30-40 minute drive from airport</dd>
			</dl>
			<a href="#" class="link">Visit Website</a>
		</div>
	</li>

	*/
	$("#listContainer").html("");
	$("#listContainer").append("<ul>");
	var allHotels = $("#listContainer ul");
	totalH = 0;
	for(var i=0; i<mapHotels.length; i++){
		elem = mapHotels[i];
		// create html then append
		var str = "";
		str += ('<img src="{0}" class="imgFull" />').replace("{0}",elem.photo);
		str += ('<div class="img" style="background-image:url({0})"></div>').replace("{0}",elem.photo);
		str += '<div class="right">';
		str += ('<h4>{0}</h4>').replace("{0}",elem.title);
		str += ('<span class="add">{0}</span>').replace("{0}",elem.address);
		str += (!elem.isMain) ? ('<span class="istar istar-{0}"></span>').replace("{0}",elem.star) : '<span class="smaller">Event Location</span>';
		
		if (elem.information.length > 0){
			str += '<dl>';
			for (var x=0 ; x<elem.information.length; x++){
				var xelem = elem.information[x];
				str += ('<dt>{0}</dt><dd>{1}</dd>').replace("{0}",xelem.title).replace("{1}",xelem.content);
			}
			str += '</dl>';
		}	
		str += ('<span class="link"><a href="{0}">Visit website</a> | <a href="javascript://" class="viewmap" hotelid="{1}" lat="{2}" lon="{3}">View on map</a></span>').replace("{0}",elem.url).replace("{1}",elem.index).replace("{2}",elem.lat).replace("{3}",elem.lon);
		
		str += '</div>';
		var listr = ('<li id="{0}" itop="{1}">').replace("{0}",elem.index).replace("{1}",totalH);
		
		var tx = $(listr).appendTo(allHotels).html(str);
		
		totalH += parseInt(tx.height()); // assign new position
		
	}
	
	
	setPins();
	
	$("#listContainer .img").click(function(){
		// show hide image in full, hide all imgfulls first, set as global too
		if (activeFullImg) activeFullImg.hide();
		activeFullImg = $(this).prev("img");
		activeFullImg.show();
	});
	
	$(document).click(function(event){
		if(event.target.className == 'img') return;
		if (activeFullImg) activeFullImg.hide();
	});
	$(".viewmap").click(function(){
		// create a click effect on poi icon
		
		map.AttachEvent("onendpan",doPan);
		globalViewMap = $(this);
		var latLong = new VELatLong(globalViewMap.attr("lat"),globalViewMap.attr("lon"));
        map.PanToLatLong(latLong);
        
        
        
		
	});
}
function doPan(e){
	// this fire before changeview, so it needs to click AFTER changeview takes care of icons
	setTimeout(function(){
		$.each(poiPins.find("span"),function(){
				if ($(this).attr("hotelid") == globalViewMap.attr("hotelid")){
				
					// click its parent and break
					$(this).parents("a.VEAPI_Pushpin").click();
					return;
				}
			});
		map.DetachEvent("onendpan",doPan);
	},100);
	
}
var globalViewMap;

var activePoi, activePoiLi, activeFullImg, poiPins, totalH;

function setMapClick() {
	// do not bind to the same pin twice!!!!
	poiPins.unbind("click");
	poiPins.bind("click",function() {
		// a cleaner way: save globally the selected items
		if (activePoiLi){
			activePoiLi.removeClass("hilight");
		}
		if (activePoi){
			activePoi.removeClass("active");
		}
		// get id from within icon, match to li id and hilight, remove old highligh
		if (activeFullImg) activeFullImg.hide();
		
		activePoi = $(this);
		var hotelid = activePoi .find("span").attr("hotelid");
		activePoiLi= $("#"+ hotelid);
		activePoiLi.addClass("hilight");
		// scroll into view
		
		// i need to keep this active as well
		activePoi.addClass("active");
		// scroll top by height of li * index;
		var x = activePoiLi.attr("itop");
		$("#listContainer").animate({scrollTop: x},1000);
	});
}
