function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

var gXML = "";
var strURL = 'http://request.fiat.ie/api/dealer/?t=gxml&b=2&callback=getXML';
var strBrand = 'Alfa Romeo Ireland';
var gpxXML = "";

function getXML(xmlData){
	gXML = xmlData.replace(/--/g,"\"");
}

function testXMLData(){
	if (gXML == ""){
		setTimeout("testXMLData()",5);
	}else{
		if (window.DOMParser){
		   parser=new DOMParser();
		   xmlDoc=parser.parseFromString(gXML,"text/xml");
		}else{// Internet Explorer
		   xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		   xmlDoc.async="false";
		   xmlDoc.loadXML(gXML); 
		}
		
		if (xmlDoc.documentElement.nodeName=="parsererror"){
			 errStr=xmlDoc.documentElement.childNodes[0].nodeValue;
			 errStr=errStr.replace(/</g, "&lt;");
			 document.getElementById("divDealerDetail").innerHTML = "An error has occurred. Please try again.";
			 //alert(errStr);
		}
		else{
		 googleMapsLoad();
		} 		
	}
}

function getXMLData(){	
	// The web service call
	var req  = strURL; 
	// Create a new request object
	bObj = new JSONscriptRequest(req); 
	// Build the dynamic script tag
	bObj.buildScriptTag(); 
	// Add the script tag to the page
	bObj.addScriptTag();
	
	testXMLData();
}

function googleMapsLoad() {
        if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("divDealerMap"));
            map.addControl(new GLargeMapControl());
            map.addControl(new GMapTypeControl());
            //map.setCenter(new GLatLng(53.409532, -7.844238), 6);
			map.setCenter(new GLatLng(53.021392, -7.421265), 6);
			
            //GDownloadUrl("locations_lcv.xml", function(data) {
			//GDownloadUrl("http://request.fiat.ie/api/dealer/?t=gxml&amp;b=3", function(data) {
                var xml = GXml.parse(gXML);
                var markers = xml.documentElement.getElementsByTagName("marker");
                for (var i = 0; i < markers.length; i++) {
                    var name = markers[i].getAttribute("name");
                    var address = markers[i].getAttribute("address");
					var phone = markers[i].getAttribute("phone");
					var fax = markers[i].getAttribute("fax");
					var email = markers[i].getAttribute("email");
					var web = markers[i].getAttribute("web");
					var comment = markers[i].getAttribute("comment");
					var brand_comment = markers[i].getAttribute("brand_comment");
                    var type = markers[i].getAttribute("type");
					var lat = markers[i].getAttribute("lat");
					var lng = markers[i].getAttribute("lng");
                    var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
					var sales = markers[i].getAttribute("sales");
					var service = markers[i].getAttribute("service");
					var parts = markers[i].getAttribute("parts");
                    var marker = googleMapsCreateMarker(point, name, address, phone, fax, email, web, comment, brand_comment, type, sales, service, parts, lat, lng);
                    
					gpxXML = gpxXML + "<wpt lat=\""+ lat +"\" lon=\""+ lng +"\">";
					gpxXML = gpxXML + "<name>"+ name +"</name>";
					gpxXML = gpxXML + "<cmt>"+ address.replace("<br/>",",") +"</cmt>";
					gpxXML = gpxXML + "<desc>"+ strBrand +" Dealer</desc>";
					gpxXML = gpxXML + "</wpt>";						
					
					map.addOverlay(marker);
                }
            //});
        }
    }


    function googleMapsCreateMarker(point, name, address, phone, fax, email, web, comment, brand_comment, type, sales, service, parts, lat, lng) {
        var gIconBlue = new GIcon();
        gIconBlue.image = 'http://dealer.fiat.ie/images/mm_20_red.png';
        gIconBlue.shadow = 'http://dealer.fiat.ie/images/mm_20_shadow.png';
        gIconBlue.iconSize = new GSize(12, 20);
        gIconBlue.shadowSize = new GSize(22, 20);
        gIconBlue.iconAnchor = new GPoint(6, 20);
        gIconBlue.infoWindowAnchor = new GPoint(5, 1);

        var gIconRed = new GIcon();
        gIconRed.image = 'http://dealer.fiat.ie/images/mm_20_red.png';
        gIconRed.shadow = 'http://dealer.fiat.ie/images/mm_20_shadow.png';
        gIconRed.iconSize = new GSize(12, 20);
        gIconRed.shadowSize = new GSize(22, 20);
        gIconRed.iconAnchor = new GPoint(6, 20);
        gIconRed.infoWindowAnchor = new GPoint(5, 1);

        var gCustomIcons = [];
        gCustomIcons["fiat_dealer"] = gIconBlue;
		gCustomIcons["alfa_dealer"] = gIconRed;
        gCustomIcons["lcv_dealer"] = gIconRed;
		gCustomIcons["dealer"] = gIconRed;

        var marker = new GMarker(point, gCustomIcons[type]);
        var html = "<b>" + name + "</b> <br/>" + address +"<br/>";
		if(phone.length > 0 ){html = html +"<br/><b>Phone: </b>"+ phone;}
		if(fax.length > 0){html = html +"<br/><b>Fax: </b>"+ fax;}
		if(email.length > 0){html = html +"<br/><b>Email: </b><a href='mailto:"+ email +"'>"+ email +"</a>";}
		if(web.length > 0){html = html +"<br/><b>Website: </b><a href='"+ web +"' target='_blank'>"+ web +"</a>";}
		html = html +"<br/><br/><br/><br/>";
		GEvent.addListener(marker, 'click', function() {
			displayDealerDetail(name, address, phone, fax, email, web, comment, brand_comment, sales, service, parts, lat, lng);
            marker.openInfoWindowHtml(html);
        });
        return marker;
    }

	function displayDealerDetail(name, address, phone, fax, email, web, comment, brand_comment, sales, service, parts, lat, lng){
		var display = "<h2>"+ name +"</h2>"+ address +"<br/>";
		if(phone.length > 0 ){display = display +"<br/><b>Phone: </b>"+ phone;}
		if(fax.length > 0){display = display +"<br/><b>Fax: </b>"+ fax;}
		if(email.length > 0){display = display +"<br/><b>Email: </b><a href='mailto:"+ email +"'>"+ email +"</a>";}
		if(web.length > 0){display = display +"<br/><b>Website: </b><a href='"+ web +"' target='_blank'>"+ web +"</a>";}
		
		if(sales == "True" || service == "True" || parts == "True"){
			display = display + "<br/><br/><b>"+ strBrand +" Services:</b><br/><i> ";
		}
		if(sales == "True"){display = display + strBrand +" Sales<br/>";}
		if(service == "True"){display = display + strBrand +" Service<br/>";}
		if(parts == "True"){display = display + strBrand +" Parts";}
		
		if(sales == "True" || service == "True" || parts == "True"){
			display = display + "</i><br/>";
		}
		
		if(brand_comment.length > 0 ){display = display +"<br/><br/><i>"+ Encoder.htmlDecode(brand_comment) +"</i>";}
		if(comment.length > 0 ){display = display +"<br/><br/>"+ Encoder.htmlDecode(comment);}
		
		display = display + "<div class='satnav'>";
			display = display + "<div class='garmin'>";
			//display = display + "<input type=\"image\" onclick=\"initSatNav('"+ lat +"','"+ lng +"','"+ name +"');\" title=\"Download POI to Garmin Device\" alt=\"Download POI to Garmin Device\" src=\"images/sat_garmin.png\">";
			display = display + "<a href=\"javascript:;\" onclick=\"initSatNav('"+ name +"','"+ lat +"','"+ lng +"');\" title=\"Download POI to Garmin Device\" alt=\"Download POI to Garmin Device\"><img src=\"images/sat_garmin.png\" border=\"0\"></a>";
			display = display + "</div>";		
			display = display + "<div class='tomtom'>";
			display = display + "<a href=\"http://addto.tomtom.com/api/home/v2/georeference?action=add&apikey=36d321a7-b652-46cd-bf6e-bbb7ffeacbfc&latitude="+ lat +"&longitude="+ lng +"&name="+ name +"\" target=\"_blank\"><img src=\"images/sat_tomtom.png\" alt=\"Add-To-TomTom\" border=\"0\"/></a>";
			display = display + "</div>";
		display = display + "</div>";
		
		document.getElementById("divDealerDetail").innerHTML = display;
	}

function initSatNav(way_name, lat, lng){
	var display = new Garmin.DeviceDisplay("garminDisplay", {
		pathKeyPairsArray: ["http://dealer.alfaromeo.ie","db7544f15ebfeae52d5306097142b625"],
		unlockOnPageLoad: false,                       //delays unlocking to avoid authorization prompt until action
		hideIfBrowserNotSupported: true,                              
		showStatusElement: true,                       //provide minimal feedback
		autoFindDevices: true,                        //it will search for devices upon action                      
		showCancelFindDevicesButton: false,            //no need to cancel small data transfers
		autoSelectFirstDevice: false,                   //pick the first device if several are found
		autoReadData: true,                           //don't automatically read the tracks/etc
		autoWriteData: true,                           //automatically write the data once devices found
		showReadDataElement: false,
		getWriteData: function() {
			var waypoint = new Garmin.WayPoint(lat, lng, null, way_name, "go find it...");
			var factory = new Garmin.GpsDataFactory();
			var gpx = factory.produceGpxString(null, [waypoint]);
				return gpx;
		},
		afterFinishWriteToDevice: function(success, display) {
			  alert((success ? "POI added to your 'favourites' on your sat-nav!" : "POI wasn't added to your sat-nav!"));
		}
	});
}

function initFullSatNav(){
	var headerXML;
	headerXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
	headerXML = headerXML + "<gpx version=\"1.1\"";
    headerXML = headerXML + "creator=\"Vuepoint Ltd - http://www.vuepoint.ie/\"";
    headerXML = headerXML + "xmlns=\"http://www.topografix.com/GPX/1/1\"";
    headerXML = headerXML + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"";
    headerXML = headerXML + "xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">";
	 
	gpxXML = headerXML + gpxXML + "</gpx>";

	var display = new Garmin.DeviceDisplay("garminDisplay", {
		pathKeyPairsArray: ["http://dealer.alfaromeo.ie","db7544f15ebfeae52d5306097142b625"],
		unlockOnPageLoad: false,                       //delays unlocking to avoid authorization prompt until action
		hideIfBrowserNotSupported: true,                              
		showStatusElement: false,                       //provide minimal feedback
		autoFindDevices: true,                        //it will search for devices upon action                      
		showCancelFindDevicesButton: false,            //no need to cancel small data transfers
		autoSelectFirstDevice: false,                   //pick the first device if several are found
		autoReadData: false,                           //don't automatically read the tracks/etc
		autoWriteData: true,                           //automatically write the data once devices found
		showReadDataElement: false,
		getWriteData: function() { return gpxXML;  },
		afterFinishWriteToDevice: function(success, display) {
			  alert((success ? "POI added to your 'favourites' on your sat-nav!" : "POI wasn't added to your sat-nav!"));
		}
	});	
}
