function PreOwnedAjaxRequest(querystring)
{
    var url = siteUrl + '/Ajax/PreOwned.ashx' + querystring;
    $.ajax({
      url: url,
      cache: false,
      success: function(data, textStatus){
        
      },
      error: function(XMLHttpRequest, textStatus, errorThrown){
        alert('Something went wrong with the AJAX request: ' + textStatus);
      }
    });
}

function PreOwnedAjaxShortlistRequest(querystring)
{
    var url = siteUrl + '/Ajax/PreOwned.ashx' + querystring;
    $.ajax({
      url: url,
      cache: false,
      success: function(data, textStatus){
      
        var _disabledOpacity = 0.4;
	    var _normalOpacity = 1;
	    var _disabledClass = 'disabled';
	    var _btnList = $('#btn-shortlist')
        
        if (_btnList)
        {
            if (data > 0)
	            _btnList.css({opacity:_normalOpacity}).removeClass(_disabledClass);
	        else
	            _btnList.css({opacity:_disabledOpacity}).addClass(_disabledClass);
	    }
      },
      error: function(XMLHttpRequest, textStatus, errorThrown){
        alert('Something went wrong with the AJAX request: ' + textStatus);
      }
    });
}

function PreOwnedAjaxCompareRequest(querystring)
{
    var url = siteUrl + '/Ajax/PreOwned.ashx' + querystring;
    $.ajax({
      url: url,
      cache: false,
      success: function(data, textStatus){
        
        var _disabledOpacity = 0.4;
	    var _normalOpacity = 1;
	    var _disabledClass = 'disabled';
	    var _btnList = $('#btn-compare')
        
        if (_btnList)
        {
            if (data > 1)
    	        _btnList.css({opacity:_normalOpacity}).removeClass(_disabledClass);
	        else
	            _btnList.css({opacity:_disabledOpacity}).addClass(_disabledClass);
	    }
        
      },
      error: function(XMLHttpRequest, textStatus, errorThrown){
        alert('Something went wrong with the AJAX request: ' + textStatus);
      }
    });
}

shortList = {
    setTarget : function(obj) {
          
        var selected = this.getSelected();
        
        if(replace != true)
        {
          if(selected.indexOf("%") == -1)
            {
                    alert('You need to select more than one vehicle to compare.');
                 
                        $('div[class="lightbox"]').fadeOut(200, function(){
							    _fader.fadeOut(200);
							    _scroll = false;
			        });
			        return false;
             }
        }
       
        if(selected.length>0) {
             obj.href += (obj.href.indexOf("?") > -1 ? "&" : "?") + "vehicleIds=" + selected;
        }
        return true;
        
    },
    email : function() {
        var qs = new String("?mode=emailshortlist");
        $("#EmailStatus").text("Sending email ...");
        qs+= "&vehicleIds=" + $("#txtVehicleIds")[0].value;
        qs+= "&rcpName=" + escape($("#txt-sent-recipients-name")[0].value);
        qs+= "&rcpEmail=" + escape($("#txt-sent-recipients-email")[0].value);
        qs+= "&yourName=" + escape($("#txt-sent-you-name")[0].value);
        qs+= "&yourEmail=" + escape($("#txt-sent-you-email")[0].value);
        qs+= "&comments=" + escape($("#area-comments")[0].value);
        
        var url = siteUrl + '/Ajax/PreOwned.ashx' + qs;
        $.ajax({url: url,cache: false, success: shortList.emailReturn});
        return false;
    },
    emailReturn : function(data, text) {
        var email = eval("({"+data+"})");
        $("#EmailStatus").text(email.msg);
        if(email.success == '1'){
            $("#txt-sent-recipients-email")[0].value = "";
            $("#txt-sent-recipients-name")[0].value = "";
        }
    },
    getSelected : function() {
        var selected = new String("");
        $(".main-column li input[type=checkbox]:checked").each(function() {selected += this.value + ",";});
        return (selected.length==0 ? selected :  escape(selected.substr(0,selected.length-1)));
    }
}

ExperienceForm  = {
    details : {
        NameOfParty : "",
        OrganisersName : "",
        TelephoneDay : "",
        Email : "",
        ReasonForInterest : "",
        ReferrerInfo : "",
        SpecialRequirements : "",
        DatePreferences : "",
        GenericDisclaimer : false,
        validate : function() { 
        
            var throwThis = false;
            if(this.NameOfParty.length == 0)
            {
                $("#NameOfPartyError").text("Name of party is required");
                throwThis = true;
            } 
            else
            {
                $("#NameOfPartyError").text("");
                throwThis = false;
            }
            
            if(this.OrganisersName.length == 0)
            {
                $("#OrganisersNameError").text("Organiser's name is required");
                throwThis = true;
            }
             else
            {
                $("#OrganisersNameError").text("");
                throwThis = false;
            }
            
            if(this.NumberInGroup.length > 3)
            {
                $("#NumberInGroupError").text("Number in group is required");
                throwThis = true;
            }
             else
            {
                $("#NumberInGroupError").text("");
                throwThis = false;
            }
            
            if(this.TelephoneDay.length == 0)
            {
                $("#TelephoneError").text("Contact telephone required"); 
                throwThis = true;
            } 
             else
            {
                $("#TelephoneError").text("");
                throwThis = false;
            }
            
            if(this.Email.length == 0)
            {
                $("#EmailError").text("Email is required"); 
                throwThis = true;
            } 
               else
            {
                $("#EmailError").text("");
                throwThis = false;
            }
              
            if(!this.GenericDisclaimer)
            {
                $("#GenericDisclaimerError").text("You must accept the Terms and Conditions"); 
                throwThis = true;
            }   
             else
            {
                $("#GenericDisclaimerError").text("");
                throwThis = false;
            }
            
            if (throwThis) throw "error";             
                
        },
        serialise : function() {
            var s = new String("");
            for(var att in this) {
                if(att != "serialise")
                    s+="&"+ att + "=" + escape(this[att]);
            }
            return s;
        }
        
    },
    book : function(ajax) {
    
        var qs = new String("?mode=experienceBookingForm");
        
        var details = this.details;
        details.NameOfParty = $("#NameOfParty")[0].value;
        details.OrganisersName = $("#OrganisersName")[0].value;
        details.NumberInGroup = $("#NumberInGroup")[0].value;
        details.TelephoneDay = $("#TelephoneDay")[0].value;
        details.Email = $("#Email")[0].value;
        details.ReasonForInterest = $("#ReasonForInterest")[0].value;
        details.ReferrerInfo = $("#ReferrerInfo")[0].value;
        details.SpecialRequirements = $("#SpecialRequirements")[0].value;
        details.DatePreferences = $("#DatePreferences")[0].value;
        details.GenericDisclaimer = $("#GenericDisclaimer").attr('checked');
        
        try  {
            details.validate();
            $("#Status").text("Booking ...");
        }
        catch(ex) {
            return false;
        }
        
        if(ajax) {
        
            qs += details.serialise();
            var url = siteUrl + '/Ajax/PreOwned.ashx' + qs;
            $.ajax({url: url,cache: false, success: shortList.emailReturn});
        }else {
            $("#submit").click();
        }
        
        return false;
    }
}

function ShowDealerMapRequest()
{
    $('.find-box').each(function()
    {
        var _holder = $(this);
        var postcode = _holder.find('.postcodeTextbox');
        
        var postCodeValue = "Enter post code";
        var region = $("input[@name='find-dealer']:checked").val();
        
        var market = "1446"; // Market for UK
            
        if (region == "1117")
            market = "1447" // Market for US
        
        postCodeValue = postcode[0].value;
        
        if (postCodeValue != "Enter post code" && postCodeValue != "Enter zipcode")
        {            
            var url = siteUrl + '/Ajax/ConsoleMap.aspx?postcode=' + postCodeValue + "&market=" + market + "&region=" + region;
        
            $.ajax({
              url: url,
              cache: false,
              success: function(data, textStatus){
                var _fadeSpeed = 400;
	            var _slideSpeed = 300;

	            var _step2 = _holder.find('.full-open');
	            _step2.css({display:'none'});
    		    
	            _step2.slideDown(_slideSpeed,function(){
		            _submitFlag = true;
	            });
	            
	            var _consoleMap = _holder.find('.consoleMap');
                _consoleMap.html(data);
                
              },
              error: function(XMLHttpRequest, textStatus, errorThrown){
                alert('Something went wrong with the AJAX request: ' + textStatus);
              }
            });
        }
        else
        {
            //window.location.href = '/ownership/locate_a_dealer/?market=' + market;
        }                
    });
}

function ChangePostcodeText(text)
{    
    $('.find-box').each(function()
    {
        var _holder = $(this);
        var postcode = _holder.find('.postcodeTextbox');
        
        postcode[0].value = text;
        
    });
}

function ShowMap(lat, lon, isLatLon, postalcodeVar, countryCodeVar)
{        
    //var dealerAddress = new MMLocation(new MMLatLon(51.51016,-0.14502));
    var dealerAddress = new MMLocation(new MMLatLon(lat,lon));
    if (!isLatLon)
    {
        dealerAddress = new MMLocation(new MMAddress({ postal_code : postalcodeVar, country_code : countryCodeVar }));
    }
    
    var mapviewer, geocoder

    var icon = new MMIcon('/i/map_icon.gif');
    icon.iconSize = new MMDimensions( 78, 25 );
    icon.iconAnchor = new MMPoint( 16, 16 );
    
    $('.find-box').each(function()
    {
        var _holder = $(this);
        var map = _holder.find('.mapviewer');
                      
        if (map[0])
        {
            // Construct Map Viewer and display default location:
            mapviewer = new MultimapViewer( map[0] );
            
            //	add location marker
            //  this arbitrary piece of logic is a work arround for multimaps poor API
            //	as it won't handle creating a custom marker consistantly for any MMLocation type
            if (!isLatLon)
            {
                mapviewer.addEventHandler('endGeocode', function()
                {
                    mapviewer.createMarker(dealerAddress, {'label': 'Dealer', 'icon' : icon});
                });
            }
            else
            {
                mapviewer.createMarker(dealerAddress, {'label': 'Dealer', 'icon' : icon});
            }
            
            mapviewer.goToPosition(dealerAddress);
        }
    });
}

function callGeocoder()
{
    //	validation
    if (postal_code.value == "" && (street.value == "" || city.value== "")) 
	      {
			    error_message.innerHTML = '<h2></h2>';
			    return false;
		    }
    		
		    //	clear previous errors
		    error_message.innerHTML = '';
    		
		    // create a new address object
		    userAddress = new MMAddress();
		    userAddress.street = street.value;
		    userAddress.city = city.value;
		    userAddress.postal_code = postal_code.value;
		    userAddress.country_code = 'US';
    	    
		    // clear any existing items from previous geocoding requests
		    cleanUp();

		    // perform the geocode
		    geocoder.count = max_results;
		    geocoder.geocode(userAddress);
	    }
    	      
	    function processResults()
	    {
		    // callback function registered with the geocoder to handle geocoding results
    		
            // if an error occurred, inform the user
		    if (geocoder.error_code && geocoder.error_code != 'MM_GEOCODE_MULTIPLE_MATCHES')
		    {
			    error_message.innerHTML = 'We are sorry - the following error occurred: <br></br><em>' + geocoder.error_code + '</em>';
			    return false;
		    }
    		
		    //	clear previous errors
		    error_message.innerHTML = '';
    		
		    results = geocoder.result_set;
    		
		    if (results.length == 1) // if there is only one result, then use it
		    {
			    moveToResult(0)
		    }
		    else if (results.length > 1) // if there is more than one display a list to pick from
		    {
			    var ol = document.createElement('ol');
    		    
			    //loop through the result set
			    for (var count=0; count < results.length; count++)
			    {
				    var address = results[count].address;
				    var li = document.createElement('li');
    				
                    //add a link for each result
				    var anchor = document.createElement('a');

				    anchor.href = '#';
				    anchor.result_count = count;
				    anchor.onclick = function () { moveToResult(this.result_count); return false; };
				    anchor.appendChild(document.createTextNode(address.display_name));
				    li.appendChild(anchor);
				    ol.appendChild(li);

				    //add a marker for each result
				    var marker = mapviewer.createMarker(results[count], { 'label' : address.display_name, 'text' : (count+1) });
    				
                        //add an infobox for each result
				    marker.setInfoBoxContent('<p>' + address.display_name + '</p>');
                    markers.push(marker);
      }

      message.appendChild(ol);
      message.style.display = 'block';

      //display all the results
      var location = mapviewer.getAutoScaleLocation( markers );

      if( location.zoom_factor > 17 )	location.zoom_factor = 17;

      mapviewer.goToPosition( location );
    }
}

function moveToResult (count)
{
	//move the map specified location
	userAddress = results[count];
	callRoute();
}
