var results = new Array();
var startingRow = 0;
var resultHeight = 257;
var initSearch = false;

//checkbox function
function updateChecks(which){
  //uncheck other boxes
  if( which != 'any' && $('#search_h3_c input[checked]:not(#search_color_any)').length > 0 ){
    $('#search_color_any[checked]').click();
  }else if( $('#search_color_any').attr('checked') == true ){
    $('#search_h3_c input[checked]:not(#search_color_any)').attr('checked','');
  }
  //update images
  $('#search_h3_c input[checked]').parent().children('img').attr('src',basedir+'/images/form_check_on.gif');
  $("#search_h3_c input:not([checked])").parent().children('img').attr('src',basedir+'/images/form_check_off.gif');
}

function toggleCheck(which){
  //click's the checkbox
  $('#search_color_'+which).click();
  updateChecks(which);
}

//displays a page of results based on a starting row
function displayResults(startr){
  startingRow = startr;
  checkButtons();
  $("#results").html("<table cellspacing='4' cellpadding='0'></table>");
  for( i=0; i<results.length-(startingRow*5) && i<maxrows*5; i++ ){
    r = startingRow*5 + i;
    if( !((i+5) % 5) ){
      $("#results table").append("<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>");
    }
    $("#results td:eq("+i+")")
      .addClass("result")
      .html(
        "<div id='car_"+results[r]['id']+"'>"+
        " <span class='nav'>"+
        "   <button class='info' label='Get more info about this car.'>Info</button>"+
        "   <button class='add' label='Add this car to your garage.'>Add</button>"+
        "   <button class='remove' label='Hide this from your search results.'>Remove</button>"+
        " </span><br />"+
        " <span class='details'>"+
        "   <img src='"+basedir+"/images/"+results[r]['img']+"' alt='' />"+
        "   <h3>"+
        "     "+results[r]['name']+"<br />"+
        "     <span>"+results[r]['price']+"</span>"+
        "   </h3>"+
        "   <p>"+results[r]['descr']+"</p>"+
        " </span>"+
        "</div>");
    if( results[r]['sale_price'] ){
      $("#results td:eq("+i+") .details h3 span:first")
        .css('textDecoration','line-through')
        .before("<span>Was </span>")
        .after(
          "<br/><span style='color: #ff3030;font-weight:normal;'>Now</span> "+
          "<span style='color: #ff3030;font-weight:normal;font-size:130%;'>"+results[r]['sale_price']+"</span>");
      $("#results td:eq("+i+") .details img:first")
        .before("<img src='"+basedir+"/images/saletag.gif' alt='On Sale!' class='saletag' />");
    }
    
    //hover events
    $("#results td div:eq("+i+") span.details").mouseover(function(){
      $(this).parent().children("span.nav").children("button.info").addClass("hover");
    });
    $("#results td div:eq("+i+") span.details").mouseout(function(){
      $(this).parent().children("span.nav").children("button.info").removeClass("hover");
    });
    $("#results td div:eq("+i+"), #results td div:eq("+i+") button").mouseover(function(){
      $(this).addClass("hover");
    });
    $("#results td div:eq("+i+"), #results td div:eq("+i+") button").mouseout(function(){
      $(this).removeClass("hover");
    });
    
    //info button
    $("#results td div:eq("+i+") button.info").click(function(){
      id = $(this).parent().parent().attr("id").split("_");
      document.location = basedir+"/detail/"+id[1];
    });
    $("#results td div:eq("+i+") span.details").click(function(){
      id = $(this).parent().attr("id").split("_");
      document.location = basedir+"/detail/"+id[1];
    });
    
    //add button
    $("#results td div:eq("+i+") button.add").click(function(){
      id = $(this).parent().parent().attr("id").split("_");
      document.location = basedir+"/actions/addToGarage.php?id="+id[1];
    });
    
    //remove button
    $("#results td div:eq("+i+") button.remove").click(function(){
      $(this).parent().parent().fadeTo(300,0.1,function(){
        //remove selected item...
        thisId = $("#results td div").index(this);
        $(this).parent().remove();
        rowCount = $("#results tr").length;
        thisRow = Math.floor(thisId / 5);
        
        //shift results backward to fill the empty slot...
        for( i=thisRow; i<rowCount-1; i++ ){
          $("#results tr:eq("+(i+1)+") td:first").clone(true).appendTo("#results tr:eq("+i+")");
          $("#results tr:eq("+(i+1)+") td:first").remove();
          //make sure that the copied result is in full view
          $("#results tr:eq("+i+") td:last div").css({height: resultHeight+'px', opacity: 1});
        }
        //remove empty row (if more than one row left)
        if( Math.ceil($("#results td div").length / 5) < rowCount && $("#results tr").length > 1 ){
          $("#results tr:last").remove();
                      
        //add empty cell to last row
        }else{
          $("#results tr:last").append("<td>&nbsp;</td>");
        }
      });
    });
  }
  //animate results into view
  $("#results td div").hide().css('height','1px');
  for( i=0; i<results.length-(startingRow*5) && i<maxrows*5; i++ ){
    $("#results td div:eq("+i+")")
      .animate({opacity: 0}, (i+1)*200)
      .animate({height: resultHeight+'px', opacity: 1}, 500);
  }
  //only one page of results, hide functions
  if( results.length <= maxrows*5 ){
    $("#controls .right").hide();
    
  //add the page number links
  }else{
    $("#pagelinks").html("");
    pg = startingRow/maxrows+1;
    pgs = Math.ceil((results.length/5)/maxrows);
    if( pgs > 5 ){
      if( pg < 3 ){
        firstLink = 1;
        useFirstLink = false;
        useLastLink = true;
      }else if( pg > pgs-3 ){
        firstLink = pgs-4;
        useFirstLink = true;
        useLastLink = false;
      }else{
        firstLink = pg-2;
        useFirstLink = true;
        useLastLink = true;
      }
    }else{
      firstLink = 1;
      useFirstLink = false;
      useLastLink = false;
    }
    //use x to help calculate which element is selected
    x=0;
        
    //first page link?
    if( useFirstLink ){
      x++;
      $("#pagelinks").append("<a href='javascript:displayResults(0)' title='First Page'>&laquo;</a>");
    }
    //page links in between...
    for( i=firstLink; i<firstLink+5 && i<=pgs; i++ ){
      $("#pagelinks").append("<a href='javascript:displayResults("+((i-1)*maxrows)+")'>"+i+"</a>");
      if( pg == i ){
        $("#pagelinks a:eq("+x+")").addClass("select");
      }
      x++;
    }
    //last page link?
    if( useLastLink ){
      $("#pagelinks").append("<a href='javascript:displayResults("+((pgs-1)*maxrows)+")' title='Last Page'>&raquo;</a>");
    }
    $("#controls .right").show();
  }
  
  $("#results").append("<br />");
}

//button functions
function disable(what){
  $(what)
    .removeClass("hover")
    .fadeTo(1,0.3)
    .css("cursor","default")
    .attr("disabled","disabled");
}
function enable(what){
  $(what)
    .fadeTo(1,1)
    .css("cursor","pointer")
    .removeAttr("disabled");
}
function checkButtons(){
  if( startingRow - maxrows >= 0 ){
    enable("#controls .right button.previous");
  }else{
    disable("#controls .right button.previous");
  }
  if( startingRow + maxrows*1 < Math.ceil(results.length/5) ){
    enable("#controls .right button.next");
  }else{
    disable("#controls .right button.next");
  }
}

//map functions
function loadMap(){
  if( GBrowserIsCompatible() ){
    map = new GMap2(document.getElementById("map"));
    map.addControl(new GSmallMapControl());
    showAddress('412 S. Ely, Kennewick, WA 99336');
  }
  $("body").unload(function(){ GUnload(); });
}
function showAddress(address) {
  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        alert(address + " not found");
      } else {
        map.setCenter(point, 10);
        var marker = new GMarker(point);
        map.addOverlay(marker);
      }
    }
  );
}



$(document).ready(function(){

  //the css height of a result in ie6
  if( $.browser.msie && $.browser.version <= 6 ){ resultHeight = 261; }
  
  //links with rel=external now open in a new window
  $("a[@rel='external']").attr("target","_blank");
  
  //make select boxes
  $('#search_type').selectbox();
  $('#search_make').selectbox();
  $('#search_year_min').selectbox();
  $('#search_year_max').selectbox();
  $('#search_price_min').selectbox();
  $('#search_price_max').selectbox();
  
  //hide the selection rectangle by firing the blur function
  $("button").click(function(){ $(this).blur(); });
  
  //hide the result controls
  $("#controls .right").hide();
  disable("#controls .right button.previous");
  
  //alternate left & right float on images
  $("img.bodyimg:odd").css("float","right");
  $("img.bodyimg:even").css("float","left");
  
  //button events for the result controls
  $("#controls .right button").mouseover(function(){ $(this).addClass("hover"); });
  $("#controls .right button").mouseout(function(){ $(this).removeClass("hover"); });
  $("#controls .right button.next").click(function(){
    nextRow = startingRow*1 + maxrows*1;
    if( nextRow < Math.ceil(results.length/5) ){
      displayResults(nextRow);
    }
  });
  $("#controls .right button.previous").click(function(){
    nextRow = startingRow - maxrows;
    if( nextRow >= 0 ){
      displayResults(nextRow);
    }
  });
  
  //button events for the garage
  $("#garage .car img, #garage .car p, #garage .car button").mouseover(function(){$(this).parent().addClass("hover"); });
  $("#garage .car img, #garage .car p, #garage .car button").mouseout(function(){ $(this).parent().removeClass("hover"); });
  $("#garage .car button").mouseover(function(){ $(this).addClass("hover"); });
  $("#garage .car button").mouseout(function(){ $(this).removeClass("hover"); });
  $("#garage .car img, #garage .car p, #garage .car button.info").click(function(){
    //view car details
    id = $(this).parent().attr("id").split("_");
    document.location = basedir+"/detail/"+id[1];
  });
  $("#garage .car button.tdrive").click(function(){
    //test drive car
    id = $(this).parent().attr("id").split("_");
    document.location = basedir+"/test_drive/"+id[1];
  });
  $("#garage .car button.remove").click(function(){
    //remove a car from the garage
    $(this).parent().slideUp("fast",function(){
      id = $(this).attr("id").split("_");
      document.location = basedir+"/actions/removeFromGarage.php?id="+id[1];
    });
  });
  
  //maxrow selectbox
  $("#controls .left select").change(function(){
    //go to the correct page (depends on where you were before the maxrow var was changed)
    curpg = Math.floor(startingRow/maxrows);
    maxrows = $(this).val();
    newpg = Math.floor(startingRow/maxrows);
    displayResults(newpg*maxrows);
  });  
  
  //make the form an ajax form. woohoo!
  $('#searchbar form').ajaxForm(function(returnval){
    $("#controls").show();
    results = unserialize(returnval);
    maxrows = $("#controls p.left select").val();
    startingRow = 0;
    
    //no results message
    if( !results.length ){
      $("#results").html("<p>There were no vehicles found that meet your search criteria.  Try broadening your search.</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p>");
    
    }else{
      disable("#controls .right button.previous");
      displayResults(startingRow);
    }
  });
  $('#searchbar form').submit(function(){
    $("#results_bar, #results").show();
    $("#results").html("<div id='loading_graphic'>&nbsp;</div>");
  });
  //some pages will display search results automatically
  if( initSearch ){
    $('#searchbar form').submit();
  }
  
  //fix promotions h1 link
  $("#promotions h1").mouseover(function(){ $("#but_allpromos").addClass('hover'); });
  $("#promotions h1").mouseout(function(){ $("#but_allpromos").removeClass('hover'); });
  
  //load the map if needed
  if( $("#map").attr("id") ){ loadMap(); }
});
