/*!
 * EmbedGm v0.0.1
 *
 * Copyright 2011, Taste The Concept
 *
 * Date: 18 feb 2011
 *
 * v0.1.0 - load google maps api
 *
 * jQuery needed!!!
 */
(function (jQuery) {
   
  


    jQuery.embedGm = function (lang) {
        if(lang === undefined)
        {
            lang = "nl";
        }
        //Load google maps api
        jQuery.getScript('http://maps.google.com/maps/api/js?sensor=false&language=' + lang + '&callback=jQuery.embedGm.startEmbed');
    }
    jQuery.embedGm.version = 0.1;
    jQuery.embedGm.maps = new Array();
    jQuery.embedGm.directions = new Array();
    jQuery.embedGm.startEmbed = function()
    {
        
        var containerId = 0;
        jQuery('.embedgm').each(function () {
            var location = 'dorpsplein 30 anzegem';
            var icon = '';
            var width = -1;
            var height = -1;
            var zoom = 14;     
            var element = this;
            var route = '';
            var id = jQuery(element).attr('id');
            if (id.length == 0) {
                id = 'gmcontainer' + containerId;
                jQuery(element).attr('id', id);
                
            }
            var attributes = jQuery(element).children('.data').html().split(';');

            var flashvars = {};

            for (var i = 0; i < attributes.length; i++) {


                var index = attributes[i].indexOf(':');
                var name = attributes[i].substr(0, index);
                name = trim(name);
                var value = attributes[i].substr(index + 1);
                value = trim(value);
                value = replace(value);


                switch (name) {
                    case 'location':
                        location = value;
                        break;
                    case 'width':
                        width = value;
                        break;
                    case 'height':
                        height = value;
                        break;
                    case 'icon':
                        icon = value;
                        break;
                    case 'zoom':
                        zoom = value;
                        break;
                    case 'route':
                        route = value;
                        break;
                    default:
                        flashvars[name] = value;
                        break;
                }
            }
            if(width == -1)
            {
                width = jQuery(this).width();
            }
            if(height == -1)
            {
                height = jQuery(this).height();
            }
            
            latlng = new google.maps.LatLng(50.8573695, 3.371787);
            
            var myOptions = {
                zoom: zoom,
                center: latlng,
                disableDefaultUI: true,
                //MapType
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                //Navigation Control
                navigationControl: true,
                navigationControlOptions: {
                    style: google.maps.NavigationControlStyle.ZOOM_PAN
                },
                //MapType Control
                mapTypeControl: true,
                mapTypeControlOptions: {
                    style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
                }
            };
    
 
            var map = new google.maps.Map(document.getElementById(id), myOptions);
            jQuery.embedGm.maps[containerId] = map;
            jQuery("#" + id).css("width",width).css("height",height);

            var geocoder = new google.maps.Geocoder();
            if (geocoder) {
                //alert(location);
                geocoder.geocode({
                   
                    'address': location
                }, function(results, status) {
                    
                    if (status == google.maps.GeocoderStatus.OK) {
                        //alert("center");
                        latlng = results[0].geometry.location;
                       
                    }
                    map.setCenter(latlng);
                    var marker = new google.maps.Marker({
                        map: map,
                        position: latlng,              
                        icon: icon
                                
                    
                        
                    });
                    
                   
                });
                
            }



            if(route != '')
            {
                var routeDiv =  jQuery(route);
                routeDiv.html("Bereken uw route: <input type='text' id='txtRouteFrom_" + containerId + "' value='' />");
                routeDiv.append("<input type='hidden' id='txtRouteTo_" + containerId + "' value='" + location + "' />");
                routeDiv.append("<input type='button' class='btnCalculateRoute' id='btnRouteCalculate_" + containerId + "' value='ok' />");
                routeDiv.append("<div id='txtRouteCalculate_" + containerId + "'>&nbsp</div>");
                 
                jQuery("#btnRouteCalculate_" + containerId + "").click(function() {
                
               
                    var id = jQuery(this).attr('id');
                    id = id.split('_')[1];
           
            
            
                    var start = jQuery('#txtRouteFrom_' + id + '').val();
                    var end = jQuery('#txtRouteTo_' + id + '').val();
                    //                //var end = adress;
                    var map = jQuery.embedGm.maps[id];
                 
                    var direction = jQuery.embedGm.directions[id];
                    if(direction != null)
                    {
                        direction.setMap(null);
                    }
                    directionsDisplay = new google.maps.DirectionsRenderer();
                
                    jQuery.embedGm.directions[id] = directionsDisplay;
               
                    directionsDisplay.setMap(map);
                
                    var target = document.getElementById("txtRouteCalculate_" + id);
                    target.innerHTML  = '';
                    directionsDisplay.setPanel(target);
            
                    calculateRoute(start, end, directionsDisplay);
                });
            
            }

            
           
            containerId += 1;

        })
        function trim(s) {
            s = s.replace(/(^\s*)|(\s*jQuery)/gi, "");
            s = s.replace(/[ ]{2,}/gi, " ");
            s = s.replace(/\n /, "\n");
            return s;
        }
        function replace(s)
        {

            if(typeof(siteUrl) == 'undefined')
            {
                siteUrl = location.href;
            }
            s = s.replace("{siteUrl}",siteUrl);
            return s;

        }
        function createUrl(url) {

            if(typeof(siteUrl) == 'undefined')
            {
                siteUrl = location.href;
            }
            if (url.indexOf('http://') == -1) {
                url = siteUrl + url;
            }
            return url;
        }
    };
})(jQuery);

function calculateRoute(start, end, directionsDisplay)
{

    var directionsService = new google.maps.DirectionsService();

    var request = {
        origin:start, 
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function(result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(result);
        }
    });


}
