var newInvSearch;
var locateVehicleSearch;
var makeSelect;
var yearSelect;
var modelSelect;

/**
 * Common init function for all pages
 */
function initLetUsFindItPage()
{
  makeSelect = new SelectBox('Make', 'make', 'make', true, ' ', true);
  yearSelect = new SelectBox('Year', 'year', 'year', true);
  modelSelect = new SelectBox('Model', 'name', 'id',  true);
  newInvSearch = new ModelSearch('newInvFilter', [yearSelect,makeSelect,modelSelect], arrModels,false);
  newInvSearch.init();
  vehicleYearChanged();
}

/**
 * Init function for the initial landing page
 */
function letUsFindItLandingPageInit() 
{
   initLetUsFindItPage(); 
   applyInventoryDefaults();
   var model = getSelectedModel();
   vehicleChanged(model);
}

/**
 * Sets the inventory default vehicle to the drop downs
 */
function applyInventoryDefaults()
{
  setInventoryDefaultValue("yearSelect", defaultYear);
}

/**
 * Sets the given default value to the select box with the given id 
 * @param selectBoxId the select box id
 * @param defaultValue the default value
 */
function setInventoryDefaultValue(selectBoxId, defaultValue)
{
  var selectBox = YAHOO.util.Dom.get(selectBoxId);
  headerSelectValue(selectBox, defaultValue);
  selectBox.onchange();
}

/**
 * Gets the currently selected Model object. Returns a null if not found
 */
function getSelectedModel()
{
    return YAHOO.util.Dom.get('modelSelect').value;
}

/**
 * Invoked when the year dropdown changes.
 */
function vehicleYearChanged()
{
  newInvSearch.filterModels(0);
  newInvSearch.refreshSelects(0);
  vehicleMakeChanged();
}

/**
 * Applies the inventory defaults for the model 
 */
function applyInvModelDefaultsIfApplicableLUFIFY()
{
  var defaultModelText = invDefaultsByMake[makeSelect.getVal(newInvSearch.invForm)].name;
  selectValue("newInvFilter","Model", defaultModelText,"text");
}

/*
 * Called When Make Dropdown changes
 */
function vehicleMakeChanged()
{
  newInvSearch.filterModels(1);
  newInvSearch.refreshSelects(1);
  applyInvModelDefaultsIfApplicableLUFIFY();
  vehicleChanged(document.forms['newInvFilter']['Model'].value);
}

/*
 * Function changes vehicle image on vehicle select change
 * @param model the vehicle model
 * 
 */
function vehicleChanged(model)
{
  try
  {
    var imgPath = arrImages[model];
    YAHOO.util.Dom.get('vehicleImage').src = imgPath;
  }
  catch (err)
  {
    // Nothing to do here. Happens on features page, where no arrImages is defined
  }
  document.forms['newInvFilter']['modelId'].value = model;
}

/*
 * Function submits a vehicle search form
 */
function findItForYou()
{  
  document.forms['newInvFilter'].submit();
}

/*
 * Function shows preferences popup
 * @param intIndex the index of the preferences
 * @param count the popu index
 */
function showPreferencesPopup(intIndex, count)
{
  popupIndex = count;
  var name = arrPreferences[intIndex].name;
  var description = arrPreferences[intIndex].description;
  var image = vfsBase + "/apps/vimg/features/94x45/" + arrPreferences[intIndex].image;
  showPopup(name, description, image, "left", "15px","94px","45px","preferences");
}

/*
 * Function shows options popup
 * @param intIndex the index of the preferences
 * @param count the popup index
 */
function showOptionsPopup(intIndex, count)
{
  popupIndex = count;
  var name = arrOptions[intIndex].name;
  var description = arrOptions[intIndex].description;
  var image = vfsBase + "/apps/vimg/features/207x100/" + arrOptions[intIndex].image;
  showPopup(name, description, image, "left", "15px","207px","100px","options");
}

/*
 * Function closes popup
 */
function closePopup()
{  
  if (elemDivContent != undefined && shadow)
  {
    elemIframeContent.style.display = "none";
    elemDivContent.style.display = "none";
  }
  shadow = false;
  qqHideOption();
}

/*
 * Function show next/prev popup
 * @param index 
 */
function showNextPrevPopup(index)
{
  var key = popupNextPrev [index] [0];
  var group = popupNextPrev [index] [1];
    
  switch(group)
  {
    case 0: showTrimPopup(key, index); break;
    case 1: showExteriorColorPopup(key, index); break;
    case 2: showInteriorColorPopup(key, index); break;
    case 3: showPreferencesPopup(key, index); break;
    case 4: showOptionsPopup(key, index); break;
  }
}

/*
 * Function changes the list of user selected options when radiobutton is clicked
 * @param array - the array that contains the list of objects belonging to the group represented by the param 'group'.
 * @param index - integer representing the position of the object in the group represented by the param 'group'.
 *                Eg: 0 means the first object in the list of attributes.
 * @param status - possible values are 0,1,2.. 0 represents 'I must have', 1 represents 'I am flexible', 2 represents 'I dont want'.
 * @param group - represents which attribute this element belongs to.. eg: 1 represens exterior color group.
 * @param prefix - represents the prefix used to identify the element in the HTML DOM  
 */
function selectOption(array, index, status, group, prefix)
{
  name = prefix + '_' + index + '_';

  //ensures only one checkbox is enabled of the three options.
  for(i=0; i<3; i++)
  {
    YAHOO.util.Dom.get(name + i).checked = status==i;
  }

  if(group!=3)//preferences  
  {
    selectedOptionsStatus[array[index].name] = status;
    selectedOptionsGroup[array[index].name] = group;
  }
  else
  {
    selectedOptionsStatus[array[index].description + " "] = status;
    selectedOptionsGroup[array[index].description + " "] = group;
  }
}

/*
 * Function sets up form system comments field
 */
function getSysComments()
{
  var mustHaves = '';
  var mustNotHaves = '';

  for (var i in selectedOptionsStatus)
  {
    switch (selectedOptionsStatus [i])
    {
      case 0: mustHaves += i + ', '; break;
      case 1: break;
      case 2: mustNotHaves += i + ', '; break;
    }
  }
  sysComments = 'LIKES ' + mustHaves + '; ' + 'DISLIKES ' + mustNotHaves;
  return sysComments;
}

/*
 * Function sets hidden fields for used selected options
 */
function setHiddenFields()
{
  var modelMustHave = YAHOO.util.Dom.get('modelsMustHave');
  var modelFlexible = YAHOO.util.Dom.get('modelsFlexible');
  var exColorsMustHave = YAHOO.util.Dom.get('exColorsMustHave');
  var exColorsFlexible = YAHOO.util.Dom.get('exColorsFlexible');
  var inColorsMustHave = YAHOO.util.Dom.get('inColorsMustHave');
  var inColorsFlexible = YAHOO.util.Dom.get('inColorsFlexible');
  var optionsMustHave = YAHOO.util.Dom.get('optionsMustHave');
  var optionsFlexible = YAHOO.util.Dom.get('optionsFlexible');
  var preferencesMustHave = YAHOO.util.Dom.get('preferencesMustHave');
  var preferencesFlexible = YAHOO.util.Dom.get('preferencesFlexible');
    
  modelMustHave.value = "";
  modelFlexible.value = "";
  exColorsMustHave.value = "";
  exColorsFlexible.value = "";
  inColorsMustHave.value = "";
  inColorsFlexible.value = "";
  optionsMustHave.value = "";
  optionsFlexible.value = "";
  preferencesMustHave.value = "";
  preferencesFlexible.value = "";
    
  for (var i in selectedOptionsStatus)
  {
    var name = i;
    var status = selectedOptionsStatus [i];
    var group = selectedOptionsGroup[i];
    name = name.replace(",","~");
    switch (status)
    {
      case 0: 
        switch(group)
        {
          case 0: modelMustHave.value += ' ' + name + ','; break; 
          case 1: exColorsMustHave.value += ' ' + name + ','; break;
          case 2: inColorsMustHave.value += ' ' + name + ','; break;
          case 3: preferencesMustHave.value += ' ' + name + ','; break;
          case 4: optionsMustHave.value += ' ' + name + ','; break;
        }
        break;
      case 1:
        switch(group)
        {
          case 0: modelFlexible.value += ' ' + name + ','; break; 
          case 1: exColorsFlexible.value += ' ' + name + ','; break;
          case 2: inColorsFlexible.value += ' ' + name + ','; break;
          case 3: preferencesFlexible.value += ' ' + name + ','; break;
          case 4: optionsFlexible.value += ' ' + name + ','; break;
        }
        break;
    }
  }
}

/*
 * Function submits LeadInfo form
 * @param form the quick quote form
 */
function formSubmit(form)
{
  if (!validateOtherFields(document.forms['qqForm'], "qqErrorDiv")) return;
    
  setHiddenFields();
  document.forms[form].elements['_sendOffersMail'].value = document.forms[form].elements['_sendOffersMail'].checked;
  document.forms[form].elements['systemComments'].value = "Customer is interested in: " + getSysComments();
  document.forms[form].submit();
}

/*
 * Function shows exterior color popup
 * @param key the key to identify the exterior colors 
 * @param count the popup index
 */
function showExteriorColorPopup(key, count)
{
  var description = arrExteriorColors[key].name + colorDesc;  
  popupIndex = count;
  var image = arrExteriorColors[key].url;
  showPopup(arrExteriorColors[key].name, description, image, "center", "0px","346px","184px","exterior");
}

/*
 * Function shows interior color popup
 * @param key the key to identify the interior colors 
 * @param count the popup index
 */
function showInteriorColorPopup(key, count)
{
  popupIndex = count;
  var description = arrInteriorColors[key].name + colorDesc;
  var image = arrInteriorColors[key].url;
  showPopup(arrInteriorColors[key].name, description, image, "center", "0px","346px","184px","interior");
}

/*
 * Function show trim popup
 * @param key the key to identify the trims
 * @param count the popup index
 */
function showTrimPopup(intIndex, count)
{
  popupIndex = count;
  var name = arrTrims[intIndex].name;
  var image = arrTrims[intIndex].url;
  var description = arrTrims[intIndex].desc;
  showPopup(name, description, image, "center", "0px","346px","184px","trim");
}

/*
 * Function shows info popup
 * @param name the name of the popup
 * @param description the description of the popup
 * @param image the image to be displayed in the popup
 * @param imageAlign the image alignment
 * @param imagePadding the image padding
 * @param width the width of the popup
 * @param height the height of the popup
 * @param attribute
 * 
 */
function showPopup(name, description, image, imageAlign, imagePadding, width, height, attribute)
{
  var optionDiv = YAHOO.util.Dom.get("qqOptionLarge");
  var nameDiv = YAHOO.util.Dom.get("qqOptionLargeName");
  var descDiv = YAHOO.util.Dom.get("PopupDesc");
  var imageDiv = YAHOO.util.Dom.get("OptionLargeImage");
  var parentImageDiv = YAHOO.util.Dom.get("ImageDiv");
    
  //Get the new co-ordinates.
  var qqOptionLarge = YAHOO.util.Dom.get("qqOptionLarge");
  var belowOptionLarge = YAHOO.util.Dom.get("belowOptionLarge");
    
  //Center the div to the center of the browser window
  centerElement(qqOptionLarge, 435, 342);
  belowOptionLarge.style.top = qqOptionLarge.style.top;
  belowOptionLarge.style.left = qqOptionLarge.style.left;
  
  // Hide next/prev links
  if(popupIndex == 0)
  {
    // hide prev link
    YAHOO.util.Dom.get('prevP').style.display = "none";
  } else {
    YAHOO.util.Dom.get('prevP').style.display = "block";
  }
   
  if(popupIndex == count-1)
  {
    //hide next link
    YAHOO.util.Dom.get('nextP').style.display = "none";
  } else { 
    YAHOO.util.Dom.get('nextP').style.display = "block";
  }
  
  // Set numeration info
  YAHOO.util.Dom.get('num').innerHTML = "<b>" + (popupIndex+1) + "</b> of " + count;
  
  //get iframe and div for pop-up menu
  elemIframeContent = YAHOO.util.Dom.get('iframe-shadow');
  elemDivContent = YAHOO.util.Dom.get('popup-shadow');
  
  //if not exist create them
  if (null == elemIframeContent )
  {
    elemIframeContent = document.createElement('iframe');
    elemIframeContent.id = 'iframe-shadow';
    elemIframeContent.style.height = "1050px"; 
    elemIframeContent.style.width = "1300px";
    elemIframeContent.style.position = "absolute"; 
    elemIframeContent.style.top = "0px"; 
    elemIframeContent.style.left = "0px"; 
    elemIframeContent.src = ""; 
    elemIframeContent.frameBorder = "0"; 
    elemIframeContent.scrolling = "no"; 
    elemIframeContent.style.zIndex = "90"; 
    elemIframeContent.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)'; 
    elemDivContent = document.createElement('div');
    elemDivContent.id = 'popup-shadow';
    elemDivContent.style.height = "1050px"; 
    elemDivContent.style.width = "1300px";
    elemDivContent.style.zIndex = "91"; 
    
    document.body.appendChild(elemIframeContent);
    document.body.appendChild(elemDivContent);
  } else
  {
      elemIframeContent.style.display = "block";
      elemDivContent.style.display = "block";
  }
  // Show shadow
  if (! shadow)
  {
    shadow = true;    
  }
    
  //Modify the data
  nameDiv.innerHTML = name;
  descDiv.innerHTML = description;
  descDiv.style.overflowY = "auto";
  
  if ( attribute == "trim" || attribute == "exterior" || attribute == "interior")
  {
      descDiv.style.height = "55px";
  }
  else
  {
      descDiv.style.height = "122px";
  }
  
  imageDiv.src = image;
  imageDiv.parentNode.align = imageAlign;
  parentImageDiv.style.paddingLeft = "0px";
  if ( imageAlign == "center")
  {
      parentImageDiv.style.paddingLeft = "30px";
  }
  
  imageDiv.style.paddingTop = imagePadding;
  imageDiv.style.paddingBottom = imagePadding;
  imageDiv.style.width = width;
  imageDiv.style.height = height;
  parentImageDiv.style.width = width;
  parentImageDiv.style.height = height;
  optionDiv.style.visibility = "visible";
  showIFrameMask("belowOptionLarge", "qqOptionLarge");
}

/*
 * Funtction is used to switch to previous info popup
 */
function prev()
{
  if(popupIndex -1 >= 0)
  {
    popupIndex --; 
  }
  showNextPrevPopup(popupIndex);
}

/*
 * Switch to the next info popup
 */
function next()
{
  if(popupIndex + 1 < count)
  {
    popupIndex ++;
  }
  showNextPrevPopup(popupIndex);
}