var icon = new GIcon();
var icon2 = new GIcon();
var mgr;

icon.image = "http://www.google.com/intl/en_ALL/mapfiles/marker.png";
icon.shadow = "http://www.google.com/intl/en_ALL/mapfiles/shadow50.png";
icon.iconSize = new GSize(20, 34);
icon.shadowSize = new GSize(37, 34);
icon.iconAnchor = new GPoint(6, 20);
icon.infoWindowAnchor = new GPoint(5, 1);

icon2.image = "assets/images/icons/RomanIcon.png";
icon2.iconSize = new GSize(32, 32);
icon2.iconAnchor = new GPoint(15, 15);
icon2.infoWindowAnchor = new GPoint(5, 1);

var geoMarker = new GMarker(new GLatLng(54.603712,-1.573693), {title: "Roman Ltd", icon: icon2, draggable: false});

//GEvent.addListener(geoMarker,"dragend",function(){
//								document.getElementById("geo_x").value = this.getLatLng().lat();
//								document.getElementById("geo_y").value = this.getLatLng().lng();
//								});

function genLatLong(postcode) {
	var newGeo;

	if(postcode=="")
	{
		newGeo = new GLatLng(54.603712,-1.573693);
	}else{
	    var geoCode = new GlocalSearch();
	    //console.log('getStoreList: ' + typeof(PageMethods.getStoreList));
		geoCode.setSearchCompleteCallback(null, 
		        function() {
		            //console.log('lat: ' + geoCode.results[0].lat);
		            //console.log('long: ' + geoCode.results[0].lng);
		            //console.log('dist: ' + geoCode.results[0].dist);
                    PageMethods.getStoreList(geoCode.results[0].lat, geoCode.results[0].lng,      
                        // onsuccess function
                        function(result, userContext, methodName) {
                            markerMan.clearMarkers();
                            addMapMarker(geoCode.results[0].lat, geoCode.results[0].lng, "You Are Here", icon);
                            map.setCenter(new GLatLng(geoCode.results[0].lat, geoCode.results[0].lng), 11);

                            var markerCount=0;
                            for (var i in result) {
                                //console.log('result[' + i + ']: ' + result[i]);
                                addMapMarker(result[i]["glat"],
                                                result[i]["glong"],
                                                result[i]["name"],
                                                icon2,
                                                result[i]["addr"],
                                                result[i]["postCode"],
                                                result[i]["tel"],
                                                result[i]["web"],
                                                result[i]["dist"]
                                                );
                                markerCount++;
                            }

                            i = 0;
                            while (i < 12 || markerMan.getMarkerCount(i) < markerCount){
                                i++;
                            }
                            map.setZoom(i-1);
                            
                            //alert("Successful GeoCode");
                            displayShowroomInformation(result);
                        },
                        // onerror function
                        function(error, userContext, methodName) {
                            alert(error.get_message());
                        });
                }
        );


		geoCode.execute(postcode + ", UK");
	}
}

function geocallbackFunction(newGeo){
	var markerlocation = new GLatLng(newGeo.lat(),newGeo.lng());
	document.getElementById("geo_x").value = newGeo.lat();
	document.getElementById("geo_y").value = newGeo.lng();
	geoMarker.setLatLng(markerlocation);
	parent.map.setCenter(markerlocation,9);
}

function getDirections(from, to_lat, to_lng){
    var directionsPanel = document.getElementById("dir"+to_lat);
    var directions = new GDirections(directionsPanel);
    var dir_query = "from: "+from+" to: "+to_lat+","+to_lng;
    directions.load(dir_query, {getPolyline: false, getSteps: true});
    directions.getStatus();
}

var distanceArray = new Array();
var meterArray = new Array();
var to="";
var dstIndex = 0;
var showroomCount = 0;

function displayShowroomInformation(showrooms){
    var html = "";
    var web = "";

    for( var i in showrooms ){
		var address = String(showrooms[i]["addr"]).replace(/(,)/gi, "<br/>\n");
		if (showrooms[i]["web"] == null){web="";}else{web="<p>WWW: "+web+"</p>";};
		
		var distkm = showrooms[i]["dist"];
		var distmiles = (distkm * 5 / 8);
		distmiles = distmiles.toFixed(2);
		
        var _id = showrooms[i]["postCode"].replace(/ /g, "_");
        //html += "<div id=\"spacer\"></div>";
        html += "<div id=\"showroom\" class=\"showroom_"+_id+"\" style=\"border-top:1px solid #C8C8C8;padding-top:10px;\">";
        html += "<div id=\"distance\">";
        //html += "<h1>Distance from you: "+distmiles+" miles ("+distkm+"km)</h1>";
        //html += "<h1><span id='span_post_"+span_id+"' class='"+showrooms[i]["postCode"]+"'>"+distanceArray[i]+"</span></h1>";
        html += "<h1><span style=\"display:none;\" class=\"spanDistance\">"+_id+"</span><span id='span_post_"+_id+"' class='"+showrooms[i]["postCode"]+"'></span></h1>";

        html += "</div>";
        html += "   <h1>"+showrooms[i]["name"]+"</h1>";
        html += "   <p>"+address+"<br/>"+showrooms[i]["postCode"]+"</p>";
        html += "   <p>Tel: "+showrooms[i]["tel"]+"</p>";
        html += web;
        //html += "   <p><a target=\"_blank\" href=\"http://maps.google.com/maps?ll="+showrooms[i]["glat"]+","+showrooms[i]["glong"]+"&q="+showrooms[i]["name"]+", "+showrooms[i]["postCode"]+", UK\">Google Maps link</a></p>";
        //html += "   <p><a href=\"http://maps.google.com/maps?q=from: "+document.getElementById("postCode").value+" to: "+showrooms[i]["glat"]+","+showrooms[i]["glong"]+"\" alt=\"Directions to "+showrooms[i]["name"]+"\" target=\"_blank\">Get Directions</a></p>";
        html += "   <p><a href=\"http://maps.google.com/maps?q=from: "+document.getElementById("postCode").value+" to: "+showrooms[i]["postCode"]+"\" alt=\"Directions to "+showrooms[i]["name"]+"\" target=\"_blank\">Get Directions</a></p>";
        html += "</div>";
    }
    html += "<span id=\"distances\" style=\"display:none;\"></span>";
    $('div [@id="showroominformation"]').hide();
    $('div [@id="showroominformation"]').html(html);

    showroomCount = $('.spanDistance').length;

    calculateDistance();

    $('div [@id="showroominformation"]').show();
}

function calculateDistance() {
    var meters_spans = $('span.spanDistance');
    var spans = $("span[id*='span_post_']");
    var meters_span = meters_spans[dstIndex];
    var span = "#" + $(spans[dstIndex]).attr("id");
    var to = $(span).attr("class");
    distance(document.getElementById("postCode").value, to, span, meters_span, "#distances");
}


var dst, mtr, _distances = "";
var sortedDistances = new Array();

function distance(from, to, spanDst, spanMtr, distances){
    var gdir = new GDirections();
    dst = spanDst;
    mtr = spanMtr;
    GEvent.addListener(gdir, "load", function() {
        var meters = gdir.getDistance().meters;
        $(dst).html("Distance from you: " + gdir.getDistance().html + "les (" + (meters / 1000) + " km)");
		_distances = $(distances).text();
		if (dstIndex==0) {
		    $(distances).text($(mtr).text() + "," + meters);
		} else {
		    $(distances).text(_distances + "|" + $(mtr).text() + "," + meters);
		}
        dstIndex++;

		if (showroomCount == dstIndex) {
    		sortByDistance();
    		var modifiedHtml = "";
    		for (var i=0; i<sortedDistances.length; i++) {
    		    modifiedHtml += "<div id=\"showroom\" class=\"showroom_"+sortedDistances[i]+"\" style=\"border-top:1px solid #C8C8C8;padding-top:10px;\">";
    		    modifiedHtml += $('.showroom_' + sortedDistances[i]).html();
    		    modifiedHtml += "</div>";
    		}
    		$('div [@id="showroominformation"]').html(modifiedHtml);
    		dstIndex = 0;
    	} else {
            calculateDistance();
        }
    });
    gdir.load("from: " + from + " to: " + to);
}

function sortByDistance() {
    var distances = $('#distances').text().split('|');
    var meters = new Array();
    for (var i=0; i<distances.length; i++) {
        meters[i] = distances[i].split(',')[1];
    }
    var sortedMeters = meters.sort(sortNumber);
    var tempMeters, tempPostcode;

    for (var i=0; i<distances.length; i++) {
        tempPostcode = distances[i].split(',')[0];
        tempMeters = distances[i].split(',')[1];
        for (var j=0; j<sortedMeters.length; j++) {
            if (tempMeters==sortedMeters[j]) {
                sortedDistances[j] = tempPostcode;
                break;
            }
        }
    }
}

function sortNumber(a, b) {
    return a - b;
}


function addMapMarker(geo_lat, geo_lng, title, icon_type, address, postcode, telephone, web, distance){
		//map.addOverlay(new GMarker(new GLatLng(geo_lat, geo_long), {title: title, icon: icon_type, draggable: false}));
		//var marker = new GMarker(new GLatLng(marker_info["lat"], marker_info["lng"]), {title: marker_info["name"], icon: icon_type, draggable: false});
		var marker = new GMarker(new GLatLng(geo_lat, geo_lng), {title: title, icon: icon_type, draggable: false, clickable: true});
		address = String(address).replace(/(,)/gi, "<br/>\n");
		if (web == null){web="";}else{web="WWW: "+web;};
		
		var windowTabs = Array(new GInfoWindowTab("Showroom", 
		                                '<div id="gMapInfo">\
		                                <h1>'+title+'</h1>\
		                                <ul>\
		                                <li>'+address+'</li>\
		                                <li>'+postcode+'</li>\
		                                <li>&nbsp;</li>\
		                                <li>Tel: '+telephone+'</li>\
		                                <li>'+web+'</li>\
		                                <li>&nbsp;</li>\
                                        <li><a href="http://maps.google.com/maps?q=from: '+document.getElementById("postCode").value+' to: '+geo_lat+','+geo_lng+'" alt="Directions to '+title+'" target="_blank">Get Directions</a></li>\
		                                </ul>\
		                            </div>\n'));
//		                            new GInfoWindowTab("Directions", '<div style="display:block;" id="dir'+geo_lat+'">\
//		                                                <label onclick="getDirections(\''+document.getElementById("postCode").value+'\',\
//		                                                '+geo_lat+','+geo_lng+'); return false;">\
//		                                                Get Directions</label>\
//		                                                </div>')
//		                            );
//		                            new GInfoWindowTab("Directions", '<div style="display:block;" id="dir'+geo_lat+'">\
//                                                        <a href="http://maps.google.com/maps?q=from: '+document.getElementById("postCode").value+'\
//                                                        to: '+geo_lat+','+geo_lng+'" alt="Directions to '+title+'" target="_blank">Get Directions</a>\
//		                                                </div>'));
		marker.bindInfoWindowTabsHtml(windowTabs, {maxWidth: 75});
		markerMan.addMarker(marker, 1);
		markerMan.refresh();

		// Directions
		//directions = directions;
}

function geoMarkerMoved(){
}

function mapLoad() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("gmap"));

		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(54.603712,-1.573693), 9);
		map.addOverlay(geoMarker);
	    markerMan = new MarkerManager(map);
		//console.log('assigning onclick handler');
		$('#submitBtn').click(function(){
            //console.log('getting lat / long');
            genLatLong($('input[@id="postCode"]').get(0).value);
            //console.log('exiting');
            return false;
		});
	}
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function addUnLoadEvent(func) {
	var oldonunload = window.onunload;
	if (typeof window.onunload != 'function') {
	  window.onunload = func;
	} else {
	  window.onunload = function() {
	    oldonunload();
	    func();
	  }
	}
}

addLoadEvent(mapLoad);
addUnLoadEvent(GUnload);