// private functions
function debug(o) {
	if(window.console && window.console.log) {
		window.console.log(o);
	}
}

if(typeof jQuery !== 'undefined') {
	jQuery.noConflict();
	jQuery(document).ready(function($) {
	
		var $body;
		$body = $('body').addClass('jquery');
	
		if($.fn.colorbox) {
			$body.addClass('has-lightbox');

			var $dealerHide			= $('#dealerDirections, #dealerSearchInfo, #dealerSearchForm, #dealerSearchResults'),
				$featuredDealer		= $('#features-participating-dealer'),
				$findaDealer		= $('#find-a-dealer, .find-a-dealer');

			$dealerHide.hide();
			$featuredDealer.find('a').colorbox({
				opacity: 0.9
			}, function(){
				dealerMapLoad(jQuery);
			});

			$findaDealer.bind('click', function (event) {
				var $postcode = $('#find-dealer-postcode'),
					html = [], h = 0;

				if ($postcode.length === 0) {
					$postcode = $('<div />').attr('id', 'find-dealer-postcode').hide()

					html[h++] = '<form action="" method="post">';
					html[h++] = '<div class="formField">';
					html[h++] = '<label id="postcodeSearchLabel" for="city">Please enter your postcode</label>';
					html[h++] = '<input type="text" autocomplete="off" id="postcodeSearch" maxlength="100" name="txtQuery" />';
					html[h++] = '</div>';
					html[h++] = '<div class="formSubmit">';
                    html[h++] = '<input type="submit" class="enter" title="Search" id="searchButton" value="Go" />';
                    html[h++] = '</div>';
					html[h++] = '</form>';

					$postcode.append(html.join('')).appendTo('#container');
					$postcode.bind('submit', function (event) {
						//ClickGeocode();
						flashDealerPopup();
						event.preventDefault();
						$postcode.hide();
					});
				}
                var t,r, b;
				if(event.currentTarget.tagName == "DIV"){
				   var containerW = 717;
				   var boxW = 186;

				   if($(event.currentTarget).attr("id") == "findDealer"){
					   t = $(event.currentTarget).offset().top + 5;
					   r = containerW - $(event.currentTarget).position().left - boxW + 11;
					   b = "1px solid #000000";
				   }else{
					   t = $(event.currentTarget).offset().top + 12;
					   r = containerW - $(event.currentTarget).position().left - boxW + 21;
					   b = "1px solid #FFD400";
				   }
				   
                }else{
                   t = $(event.currentTarget).offset().top + 6;
				   r = 0;
                   b = "none";
                }
			   
				$postcode.css('top', t + 'px').css('right', r + 'px').css('border',b);


				$postcode.show();

				event.preventDefault();
			});

			flashDealerPopup = function () {
                $.colorbox({
                    opacity: 0.9,
                    href:"/dealer_map.php"
                }, function(){
                    dealerMapLoad(jQuery);
                });
				//$featuredDealer.find('a').trigger('click');
			}
		}
	});
}


/******
 * Dealer map
 ******/

if(typeof jQuery !== 'undefined') {
    var map = null,
		bbox = null,
		dealers = null,
        drivingStart = '',
		viewBoundaries = null;

        var dealerMapLoad = function($) {
            $map	= $('#dealer-map');

            if(typeof $map !== 'undefined' && $map.length>0){
                jQuery('#dealerDirections, #dealerSearchInfo, #dealerSearchFormNoResults, #dealerSearchResults').hide();
                map = new Microsoft.Maps.Map($map[0], {
                    credentials: "AvuIcJb4mpjKcHsY44qIo_IVOX3U-8NQ5uF3-ZhwUikq2MEHIQGRxcTXYyxVSBJx",
                    showDashboard:false,
                    mapTypeId: Microsoft.Maps.MapTypeId.road
                });

                Microsoft.Maps.Events.addHandler(map,"viewchangestart",function(){
                    if(jQuery('#infoBox').length>0){  
                        jQuery('#infoBox')[0].style.visibility = "hidden";
                    }
                });
            }

            if(jQuery('#postcodeSearch').length>0 && jQuery('#postcodeSearch').val().length>0){
                jQuery('#txtQuery').val(jQuery('#postcodeSearch').val());
		        ClickGeocode();
            }
        };



		function ClickGeocode(credentials)
		{
            map.entities.clear(); 
            jQuery('#dealerSearchForm').hide()
            jQuery('#dealerDirections').hide()
            jQuery('#dealerDirectionsContainer').hide()
            jQuery('#dealerDirectionsNoResults').hide();  // make sure error is hidden
            jQuery('#dealerDirectionsDirections').hide();
		   map.getCredentials(MakeGeocodeRequest);
		}

        function MakeRouteRequest(result){
			if (result &&
				   result.resourceSets &&
				   result.resourceSets.length > 0 &&
				   result.resourceSets[0].resources &&
				   result.resourceSets[0].resources.length > 0) 
			{
                var d = dealers[jQuery('#endID').val()];
                var request =  "http://dev.virtualearth.net/REST/V1/Routes?wp.0=";
                request += result.resourceSets[0].resources[0].point.coordinates[0] + ",";
                request += result.resourceSets[0].resources[0].point.coordinates[1] + "&wp.1="
                request += d.Latitude + "," 
                request += d.Longitude 
                request += "&optimize=distance&routePathOutput=Points&output=json&jsonp=RouteCallback&key=AvuIcJb4mpjKcHsY44qIo_IVOX3U-8NQ5uF3-ZhwUikq2MEHIQGRxcTXYyxVSBJx";

                CallRestService(request);
            }
        }
	
        function GetRouteMap() {
            drivingStart = jQuery('#start').val();
            map.entities.clear(); 
            jQuery('#dealerDirections').hide()
            jQuery('#dealerDirectionsContainer').hide()
            jQuery('#dealerDirectionsNoResults').hide();  // make sure error is hidden
            jQuery('#dealerDirectionsDirections').hide();
            if (drivingStart != '' && drivingStart != "Enter address here") {
                var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations/" + escape(drivingStart + ', UK') + "?output=json&jsonp=MakeRouteRequest&key=AvuIcJb4mpjKcHsY44qIo_IVOX3U-8NQ5uF3-ZhwUikq2MEHIQGRxcTXYyxVSBJx";
                jQuery('dealerDirections').hide();
			    CallRestService(geocodeRequest);
            }
		}

        function showSearchForm(){
                jQuery('#dealerDirections, #dealerSearchInfo, #dealerSearchForm, #dealerSearchResults').hide();
                jQuery('#dealerDirectionsNoResults').hide();  // make sure error is hidden
                jQuery('#dealerDirectionsContainer').html('');
                jQuery('#dealerSearchFooter').hide();
                jQuery('#dealerSearchForm').show();
                jQuery('#txtQuery').select();
        }

		function MakeGeocodeRequest(credentials)
		{
            var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations/" + escape( jQuery('#txtQuery').val() + ', UK') + "?output=json&jsonp=GeocodeCallback&key=" + credentials;
			CallRestService(geocodeRequest);
		}

            function ShowDrivingDirectionsForm(id) {
                ShowDirectionsView();
                jQuery('#endID').attr('value', id);
                jQuery('#endText').html(dealers[id].Name + "<br />DIRECTIONS");
            }

            function ShowDrivingDirectionsFormByShapeIndex(i) {
                ShowDrivingDirectionsForm(i);
            }

            function RouteCallback(result){
                if(typeof result.resourceSets === "undefined" ||
                    result.resourceSets.length == 0 ||
                    typeof result.resourceSets[0].resources === "undefined" ||
                    result.resourceSets[0].resources.length == 0 )
                {
                    
                    
                    
                    jQuery('#dealerDirectionsContainer').html('');
                    jQuery('#dealerDirectionsNoResults').show();  // make sure error is hidden
                    jQuery('#start').select();
                    return;
                }
                
                var route = result.resourceSets[0].resources[0]; 
                var bbox = route.bbox; 
                viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(
                new Microsoft.Maps.Location(bbox[0], bbox[1]), new Microsoft.Maps.Location(bbox[2], bbox[3])); map.setView({ bounds: viewBoundaries });
                var totalTime = route.travelDuration; 
                var timeUnit = route.durationUnit; 
                var totalDistance = route.travelDistance; 
                var distanceUnit = route.distanceUnit;
               
                ShowTurns(route);
            // Draw the route
                var routeline = route.routePath.line;
                var routepoints = new Array();
                for (var i = 0; i < routeline.coordinates.length; i++){
                    routepoints[i] = new Microsoft.Maps.Location(
                        routeline.coordinates[i][0],
                        routeline.coordinates[i][1]
                    );
                }
                // Draw the route on the map
                
                var routeshape = new Microsoft.Maps.Polyline(
                    routepoints, {
                        strokeColor: new Microsoft.Maps.Color(200, 0, 0, 200)
                });

                map.entities.push(routeshape);
            }

            function ShowTurns(route) {
                var leg = (route == null) ? route : route.routeLegs[0];
                var turns;
                var turn = null;  // The itinerary leg
                var legDistance = null;  // The distance for this leg
            

                if (route != null)
                    turns = '<div class="tripDetails">Trip: ' + route.travelDistance.toFixed(1) + ' miles' + ', ' + GetTime(route.travelDuration) + '</div>';
                    
                    
                if (leg != null) {

                    turns += '<ol>';

                    jQuery(leg.itineraryItems).each(function(i,turn) {
                        turns += '<li><span class="step">' + (i + 1) + '</span>' + turn.instruction.text;

                        legDistance = turn.travelDistance;

                        // So we don't show 0.0 for the arrival
                        if (legDistance > 0) {
                            // Round distances to 1/10ths
                            turns += '<br /><span class="distance">' + legDistance.toFixed(1) + ' miles</span>';
                        }
                        turns += '</li>';
                    });

                    turns += '</ol>';
                    jQuery('#endText').html(jQuery('#endText').html() +"<p id=\"startp\">Start: "+jQuery('#start').val()+"</p>");
                    jQuery('#dealerDirections').show()
                    jQuery('#dealerDirectionsContainer').html(turns).show();
                    jQuery('#dealerDirectionsForm').hide();
                    jQuery('#dealerDirectionsFooter').show();
                    jQuery('#dealerDirectionsNoResults').hide();  // make sure error is hidden
                    jQuery('#dealerDirectionsDirections').show();
                }
                else {
                    jQuery('#dealerDirectionsContainer').html('');
                    jQuery('#dealerDirectionsNoResults').show();  // make sure error is hidden
                    jQuery('#dealerDirectionsForm').show();
                    jQuery('#start').select();
                }

            }

            function GetTime(time) {
                seconds = time % 60;
                time = Math.floor(time / 60);
                minutes = time % 60;
                hours = Math.floor(time / 60);

                if(hours > 0){
                    return (hours + " hour(s), " + minutes + " min");
                }

                return (minutes + " min");
            }
        
            ShowDirectionsView = function() {
                jQuery('#dealerDirections, #dealerSearchInfo, #dealerSearchForm, #dealerSearchResults').hide();
                jQuery('#dealerDirectionsNoResults').hide();  // make sure error is hidden
                jQuery('#dealerDirectionsFooter').hide();  // make sure error is hidden
                jQuery('#dealerDirectionsContainer').html('');
                jQuery('#dealerDirections').show();
				jQuery('#dealerDirectionsForm').show();//Laura Fix 29-07-211
                jQuery('#start').select();
            }
            


        function QueryAPIRequest(lat,lng,credentials){
            jQuery.getJSON(
              "/search.php",
              {lat:lat,lng:lng, dist:75,site:(jQuery('body').is('.tv_deal')?'redTop':'scruffs')},
              function(data) {
                  dealers = data.d.results;
                  var list = '<ol>';
                  var minLat = null;
                  var maxLat = null;
                  var minLng = null;
                  var maxLng = null;

                  if(dealers.length <= 0){
                    jQuery('#dealerSearchResults, #dealerSearchResultsNoResults').show();
                    jQuery('#dealerSearchResultsContainer').hide();
			        map.setView({ bounds: bbox});
                    return;
                  }

                  jQuery(dealers).each(function(index,dealer){
                      list += "<li id=\"dealer_"+dealer.EntityID+"\"><h3><a href=\"javascript: ZoomToPoint("+index+")\" >" + dealer.Name + "</a></h3>";
                      list += "<p>" + dealer.AddressLine + "</p>"
                      list += "<p>"+ dealer.PrimaryCity+" "+dealer.PostalCode +"</p>";
                      list += "<strong>"+dealer.Phone + "</strong>";
                      list += "<a class=\"getDirections\" href=\"javascript: ShowDrivingDirectionsFormByShapeIndex("+index+")\">Get Directions</a>"; 
			            var location = new Microsoft.Maps.Location(dealer.Latitude, dealer.Longitude);
        			    var pin = new Microsoft.Maps.Pushpin(location,{"icon":"/images/dealer/misc/marker.png","width":30,"height":44});
                        pin.title = dealer.Name;
                        pin.description = "<p>" + dealer.AddressLine + "</p><p>"+ dealer.PrimaryCity+" "+dealer.PostalCode +"</p><strong>"+dealer.Phone + "</strong>";

        				Microsoft.Maps.Events.addHandler(pin, 'click', displayEventInfo);

                        
                        minLat = (minLat==null || minLat>dealer.Latitude)?dealer.Latitude:minLat;
                        minLng = (minLng==null || minLng>dealer.Longitude)?dealer.Longitude:minLng;

                        maxLat = (maxLat==null || maxLat<dealer.Latitude)?dealer.Latitude:maxLat;
                        maxLng = (maxLng==null || maxLng<dealer.Longitude)?dealer.Longitude:maxLng;

        			    map.entities.push(pin);
                  });
                  list += '</ol>';



                  jQuery('#dealerSearchResultsNoResults').hide();
                  jQuery('#dealerSearchResults, #dealerSearchResultsContainer').show();
                  var s = jQuery('#txtQuery').val().replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
                  
//                  jQuery('#dealerSearchResultsContainer').html("<div id=\"resultsHeader\">Search results for: <strong>"+s+"</strong><a class=\"change\" onclick=\"showSearchForm()\" href=\"javascript:void(0)\" >Change</a><br /></div>"+ list);
                  jQuery('#dealerSearchResultsContainer').html(list);
                        
                  borderX =  ((maxLng - minLng) * 1.01)/2
                  borderY =  ((maxLat - minLat) * 1.01)/2


                  var mapBoundsTL = new Microsoft.Maps.Location(minLat-borderX, minLng-borderY);
                  var mapBoundsBR = new Microsoft.Maps.Location(maxLat+borderX, maxLng+borderY);

			      viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(mapBoundsTL, mapBoundsBR);
			      map.setView({ bounds: viewBoundaries});
              }
            );
        }

        function ZoomToPoint(index){
            var d = dealers[index];
            var tp = null;
            for(var i = 0; i<map.entities.getLength(); i++){
                p = map.entities.get(i)
                if(p.toString() == "[Pushpin]" && d.Latitude==p.getLocation().longitude && d.Longitude==p.getLocation().latitude){
                    p.setOptions({"visible":true});
                    tp = p;
                }else{
                    p.setOptions({"visible":false});
                }
            }
            var handlerid = null;
            handlerid = Microsoft.Maps.Events.addHandler(map,"viewchangeend",function(){
                ShowInfo(tp);
                Microsoft.Maps.Events.removeHandler(handlerid);
            });
            map.setView({"center":tp.getLocation(), "zoom":16});

        }

        function ZoomFromPoint(){
            for(var i = 0; i<map.entities.getLength(); i++){
                p = map.entities.get(i)
                if(p.toString() == "[Pushpin]"){
                    p.setOptions({"visible":true});
                }
            }

			map.setView({ bounds: viewBoundaries});
        }

        function changeView(view){
			switch(view){
				case 'birdseye':
					map.setView({ mapTypeId: Microsoft.Maps.MapTypeId.birdseye});
					break;
				case 'road':
					map.setView({ mapTypeId: Microsoft.Maps.MapTypeId.road});
					break;
				case 'aerial':
					map.setView({ mapTypeId: Microsoft.Maps.MapTypeId.aerial});
					break;
				default:
					map.setView({ mapTypeId: Microsoft.Maps.MapTypeId.road});
					break;
			}
        }

		function CallRestService(request) 
		{
			var script = document.createElement("script");
			script.setAttribute("type", "text/javascript");
			script.setAttribute("src", request);
			document.body.appendChild(script);
		}
  
		function GeocodeCallback(result) 
		{
			if (result &&
				   result.resourceSets &&
				   result.resourceSets.length > 0 &&
				   result.resourceSets[0].resources &&
				   result.resourceSets[0].resources.length > 0) 
			{
			    bbox = result.resourceSets[0].resources[0].bbox;
                map.entities.clear(); 
				Microsoft.Maps.Pushpin.prototype.title = null;
				Microsoft.Maps.Pushpin.prototype.description = null;

                QueryAPIRequest(result.resourceSets[0].resources[0].point.coordinates[0], result.resourceSets[0].resources[0].point.coordinates[1],'AvuIcJb4mpjKcHsY44qIo_IVOX3U-8NQ5uF3-ZhwUikq2MEHIQGRxcTXYyxVSBJx');
			}
		}

		function displayEventInfo(e) {
			if (e.targetType = "pin") {
                var t = e.target;
                for(var i = 0; i<map.entities.getLength(); i++){
                    p = map.entities.get(i)
                    if(p == t){
                        p.setOptions({"visible":true});
                        tp = p;
                    }else{
                        p.setOptions({"visible":false});
                    }
                }
                var handlerid = null;
                handlerid = Microsoft.Maps.Events.addHandler(map,"viewchangeend",function(){
                    ShowInfo(tp);
                    Microsoft.Maps.Events.removeHandler(handlerid);
                });

                map.setView({"center":tp.getLocation(), "zoom":16});
                ShowInfo(e.target);
			}
		}


		function ShowInfo(pin) {
              var pix = map.tryLocationToPixel(pin.getLocation(), Microsoft.Maps.PixelReference.control);
              var infoboxTitle = document.getElementById('infoboxTitle');
              infoboxTitle.innerHTML = pin.title;
              var infoboxDescription = jQuery('#infoboxDescription');
              infoboxDescription.html(pin.description);
              var infobox = document.getElementById('infoBox');
              if(infobox){
                  infobox.style.top = (pix.y - 60) + "px";
                  infobox.style.left = (pix.x + 5) + "px";
                  infobox.style.visibility = "visible";
                  document.getElementById('dealer-map').appendChild(infobox);
              }
		}

		function closeInfoBox() {
			  var infobox = document.getElementById('infoBox');
              ZoomFromPoint();
			  infobox.style.visibility = "hidden";
		}


	jQuery(document).ready(function($) {
		dealerMapLoad(jQuery);
	});
}


/*****
 * End Dealer map
 *****/

