

$(function(){
   
   /**
    * This section hides the dropdown lists when the page is clicked on 
    * anywhere else
    */
   $(".site-container").click(function(){
       $("#car-list-wrapper").hide();
       $("#make-list-wrapper").hide();
   });
   var lastHighlighted = -1;



/**
 * This section manages the keyboard interaction with the search all vehicles 
 * text field.
 * This enables the ajax calls to get the list of makes and models from the PHP 
 * store file.
 * Each time a user types in a letter a call is made tot he PHP store file to find
 * a match of the letters in the text field. The returned list is then displayed.
 * The up and down arrow keys are also captured to navigate through the list
 * using the keyboard.
 */
    $("#keywords").keyup(function(key){
        
         switch(key.which){ // which key have we pressed

            case 38: // this is the up arrow key

                listSize = $.find(".car-list-item").length; // find the length of the list

                // set which item to highlight in the list
                nextHighlighted = lastHighlighted-1;
                if(nextHighlighted == -1){
                    nextHighlighted = listSize-1;
                }

                $("#car-list-item-"+nextHighlighted).css("background-color", "#eee");
                $("#car-list-item-"+lastHighlighted).css("background-color", "#fff");

                // set the text to be searched on in the text field
                $("#keywords").val($("#car-list-item-"+nextHighlighted+"-text").html());   
				$("#search_q").val($("#car-list-item-"+nextHighlighted+"-id").html());
                lastHighlighted = nextHighlighted;

            break;
            case 40: // this is the down arrow key
                listSize = $.find(".car-list-item").length; // find the length of the list

                // set which item to highlight in the list
                nextHighlighted = lastHighlighted+1;
                if(nextHighlighted >= listSize){
                    nextHighlighted = 0;
                }

                $("#car-list-item-"+nextHighlighted).css("background-color", "#eee");
                $("#car-list-item-"+lastHighlighted).css("background-color", "#fff");
                // set the text to be searched on in the text field
                $("#keywords").val($("#car-list-item-"+nextHighlighted+"-text").html()); 
				$("#search_q").val($("#car-list-item-"+nextHighlighted+"-id").html());
                lastHighlighted = nextHighlighted;

            break;
            default: // when typing in text
				
                $("#car-list-wrapper").remove(); // remove the list if it is already displayed
                // create the wrapper to hold the list items
                $(this).after('<div id ="car-list-wrapper" style="width: 373px;position:absolute;left:0px;border: 1px solid #eee;color:#666;background-color:#fff;z-index: 500;"></div>');
                
                // get the text typed into the text field
               var text = $(this).val();
               var file = "all_vehicles.php?text="+text; // add the text as a parameter to the call to the PHP store file
                $.getJSON(file, function(list){ // call the file, passing in the parameter and getting the JSONed result
                        $("#car-list-wrapper").html('');
                       $.each(list, function(i,item){ // for each items returned
                           // create styled element
                           var listItem = '<div class = "car-list-item" id="car-list-item-'+i+'" style="float:left;padding:5px;width:362px;"><div id="car-list-item-'+i+'-icon" style="float:left;width: 35px;" class="'+item.icon+'"></div><div style="float:left">'+item.styled_text+'</div></div>';
					
                           listItem += '<div id="car-list-item-'+i+'-text" style="display:none;">'+item.plain_text+'</div>';
						   listItem += '<div id="car-list-item-'+i+'-id" style="display:none;">'+item.id+'</div>';
                           $("#car-list-wrapper").append(listItem);
                          i++;
                       });
                });
            break;
         }
    });
    /**
     * deal with mouse events on the list
     */
    $(".car-list-item").live("mouseover", function(){
        $(this).css("background-color", "#eee");
    });
    $(".car-list-item").live("mouseout", function(){
        $(this).css("background-color", "#fff");
    });
    $(".car-list-item").live("click", function(event){
        // set the selected text into the text field
		
        $("#keywords").val($("#"+$(this).attr('ID')+"-text").html());       
		$("#search_q").val($("#"+$(this).attr('ID')+"-id").html());
        $("#car-list-wrapper").hide();
		$("#search_form").submit();
    });
      
       /**
        * This section manages the dropdown list for the browse all vehicles box.
        * This swaps out the default rendering of the select control so that if
        * javascript is not enabled the select control will be rendered.
        * Whatever is selected by the javascript dropdown is sent to the select control
        * (which is hidden) for unifomity of parameter value passing.
        */
       $("#make").hide(); // hide the select control
       $("#make_dropdown_trigger").html($("#make option:selected").text()); // if we have selected an option, display the selection
       $("#make_dropdown_trigger").css("display", "block"); // display the trigger (which was hidden by default in the template)
       
      $("#make_dropdown_trigger").click(function(event){
          // create the wrapper to hold the list items
           $("#make_dropdown_trigger").after('<div id ="make-list-wrapper" style="width: 146px;position:absolute;left:0px;top:0px;margin-top: 30px;max-height:300px;overflow:auto;border: 1px solid #eee;color:#666;background-color:#fff;z-index: 500;"></div>');

           /**
            * get all the options in the select control and make new list items to display
            */
          $("#make").children().each(function(){
               var listItem = '<div class = "make-list-item" id="make-list-item-'+$(this).val()+'" style="float:left;padding:5px;width:119px;">'+$(this).html()+'</div>';
               $("#make-list-wrapper").append(listItem);
               $("#make-list-wrapper").focus();
            });
            event.stopPropagation(); // this stops the call above to hide the list when the page is clicked on
      });
      /**
       * Handle the nouse events for the list
       */
    $(".make-list-item").live("mouseover", function(){
    $(this).css("background-color", "#eee");
    });
    $(".make-list-item").live("mouseout", function(){
        $(this).css("background-color", "#fff");
    });
    $(".make-list-item").live("click", function(event){

        $("#make_dropdown_trigger").html($(this).html());    // set the selected option in the display         
        $("#make-list-wrapper").hide();
        var selectedIndex = $(this).attr("ID").replace("make-list-item-", ""); // get the value (numeric) of the selected option
        $("#make").val(selectedIndex); // set the selected option. This will now be passed through on the form submit
		$("#make_form").submit();
    }); 
	
	
	/*
	 * five of the safest panel on the home page
	 **/
	$(".safest_link").click(function(){
		
		
		// get the href value
		// remove the ? and everying after the #
		
		var queryString = $(this).attr('href');
		var parameter = queryString.substring((queryString.indexOf("?")), queryString.indexOf("#"));
		
	
		
		 var file = "safest_vehicles.php"+parameter; // add the text as a parameter to the call to the PHP store file
			$.getJSON(file, function(list){ // call the file, passing in the parameter and getting the JSONed result
					$(".vehicle-boxes").html('');
				   $.each(list, function(i,item){ // for each items returned
					   // create styled element
					   var listItem = '<div class="vehicle-box">';
							listItem += '<a href="/find.html?q='+item.item_like+'">';
								listItem += '<img src="'+item.photo+'" alt="'+item.model+'" class="result-image photo"/>';
								listItem += '<h5>'+item.model+'</h5>';
								listItem += '<p>Driver safety</p>';
								listItem += '<div class="rating-bg orange tiny"><div class="rating '+item.driver_stars+'"></div></div>';
							listItem += '</a>';
							listItem += '<p><a href="/find.html?q='+item.item_like+'" class="more-info">Vehicle details</a></p>';
						listItem += '</div>';
						 $(".vehicle-boxes").append(listItem);

					  i++;
				   });
			});
				
			//change the highlisted option
				
			$("#car_menu").children().removeClass("selected");	
			$("#car_menu").children().removeClass("after-selected");
			
			
			
			$(this).parent().addClass("selected");
			$(this).parent().next().addClass("after-selected");	
			return false;	
	});
	
	
	/*
	 *	this section manages the left hand  filters toggleing on the find page
	 **/
	
	$(".dropdown").click(function(){
		
		if($(this).hasClass("up")){
			$(this).removeClass("up");
			$(this).addClass("down");
			$(this).next("ul").removeClass("hidden");
		}else{
			$(this).removeClass("down");
			$(this).addClass("up");
			$(this).next("ul").addClass("hidden");
		}
	});
	
});

