var d = new Date();

function build_man_list(v_page_type, v_curr_make, v_curr_model){

  if (v_page_type == 'C'){

    for(i=1; i < man_used.length+1; i++){
      document.finder.make_F.length++;
      document.finder.make_F.options[i].text = man_used[i - 1];
      document.finder.make_F.options[i].value = man_used[i - 1];

      if (man_used[i - 1] == v_curr_make){
        document.finder.make_F.selectedIndex = i;
      }
    }
  }
  else if (v_page_type == 'V'){

    for(i=1; i < man_van.length+1; i++){
      document.finder.make_F.length++;
      document.finder.make_F.options[i].text = man_van[i - 1];
      document.finder.make_F.options[i].value = man_van[i - 1];

      if (man_van[i - 1] == v_curr_make){
        document.finder.make_F.selectedIndex = i;
      }
    }
  }
  else if (v_page_type == 'N'){

    for(i=1; i < man_new.length+1; i++){
      document.finder.make_F.length++;
      document.finder.make_F.options[i].text = man_new[i - 1];
      document.finder.make_F.options[i].value = man_new[i - 1];

      if (man_new[i - 1] == v_curr_make){
        document.finder.make_F.selectedIndex = i;
      }
    }
  }

  if (v_curr_make != '' || v_curr_make != 'ANY'){
    build_model_list(v_page_type, v_curr_model);
  }
}

function build_model_list(v_page_type, v_curr_model){

  v_curr_make = document.finder.make_F.options[document.finder.make_F.selectedIndex].value;

  var j = 1;

  document.finder.model_F.length = 1;
  document.finder.model_F.options[0].text = 'Model';
  document.finder.model_F.options[0].value = 'ANY';

  for(i=1; i < model_options.length; i++){
    if (model_options[i][2] == v_page_type && model_options[i][0] == v_curr_make){
      document.finder.model_F.length++;
      document.finder.model_F.options[j].text = model_options[i][1];
      document.finder.model_F.options[j].value = model_options[i][1];

      if (model_options[i][1] == v_curr_model){
        document.finder.model_F.selectedIndex = j;
      }
      j++;
    }
  }
}
var g_sortorder;
function set_chosen_sort_value(sort_order, vehicle_count){
  g_sortorder = sort_order;
  for (i=0; i < document.forms[1].vehicle_count_request_F.options.length; i++){
    if (document.forms[1].vehicle_count_request_F.options[i].value == vehicle_count){
      document.forms[1].vehicle_count_request_F.selectedIndex = i;
      document.forms[2].vehicle_count_request_F.selectedIndex = i;
      break;
    }
  }

  for (i=0; i < document.forms[1].sort_order_F.options.length; i++){
    if (document.forms[1].sort_order_F.options[i].value == sort_order){
      document.forms[1].sort_order_F.selectedIndex = i;
      document.forms[2].sort_order_F.selectedIndex = i;
      break;
    }
  }
}

var curr_fuel;
var curr_c_type;

function set_chosen_panel_options(v_postcode, v_distance, v_min_price, v_max_price, v_mileage, v_fuel_type, v_tranmission, v_car_type, v_email, v_keyword, v_door){

  curr_fuel = v_fuel_type;
  curr_c_type = v_car_type;

  var found = false;

  if (v_postcode != 'DE1 2BH' && v_postcode != ''){
    document.finder.postcode_F.value = v_postcode;
  }else{
    document.finder.postcode_F.value = 'Enter Postcode...';
  }

  if (v_email != ''){
    document.finder.email_F.value = v_email;
  }

  if (document.finder.keyword_F){
    document.finder.keyword_F.value = v_keyword;
  }

  for (i=0; i < document.finder.distance_F.options.length; i++){
    if (document.finder.distance_F.options[i].value == v_distance){
      document.finder.distance_F.selectedIndex = i;
      found = true;
      break;
    }
  }
  if (!found){document.finder.distance_F.selectedIndex = 0;} //The default is 100

  for (i=0; i < document.finder.min_price_F.options.length; i++){
    if (document.finder.min_price_F.options[i].value == v_min_price){
      document.finder.min_price_F.selectedIndex = i;
    }
  }

  for (i=0; i < document.finder.max_price_F.options.length; i++){
    if (document.finder.max_price_F.options[i].value == v_max_price){
      document.finder.max_price_F.selectedIndex = i;
    }
  }

  if (document.finder.mileage_F){
    for (i=0; i < document.finder.mileage_F.options.length; i++){
      if (document.finder.mileage_F.options[i].value == v_mileage){
        document.finder.mileage_F.selectedIndex = i;
      }
    }
  }

  if (document.finder.fuel_type_F){
    for (i=0; i < document.finder.fuel_type_F.options.length; i++){
      if (document.finder.fuel_type_F.options[i].value == v_fuel_type){
        document.finder.fuel_type_F.selectedIndex = i;
      }
    }
  }

  if (document.finder.transmission_F){
    for (i=0; i < document.finder.transmission_F.options.length; i++){
      if (document.finder.transmission_F.options[i].value == v_tranmission){
        document.finder.transmission_F.selectedIndex = i;
      }
    }
  }

  if (document.finder.car_type_F){
    for (i=0; i < document.finder.car_type_F.options.length; i++){
      if (document.finder.car_type_F.options[i].value == v_car_type){
        document.finder.car_type_F.selectedIndex = i;
      }
    }
  }

  if (document.finder.door_count_F){
    for (i=0; i < document.finder.door_count_F.options.length; i++){
      if (document.finder.door_count_F.options[i].value == v_door){
        document.finder.door_count_F.selectedIndex = i;
      }
    }
  }
}

var box_changed = new Array();

function clearBox(box,values) {
//  if (!box_changed[box.name]) {
//    box_changed[box.name] = box.value;
  if (box.value == values){
    box.value = '';
  }
//  }
}

function fillBox(box, values) {
  if (box.value == '') {
//        box.value = box_changed[box.name];
//        box_changed[box.name] = '';
    box.value = values;
  }
}

function swapImage(new_main){
  document.images.main_photo.src = new_main;
}

function create_bookmark(){
  if (window.sidebar){
    window.sidebar.addPanel(document.title, document.location,"");
  }else if(document.all){
    window.external.AddFavorite( document.location, document.title);
  }else if (window.opera && window.print){
    alert('Press and hold "CTRL + D" to bookmark this page');
  }else{
    alert('Press and hold "CTRL + D" to bookmark this page');
  }
}

function highlight_sdr_ele(uri){
  var list_element = document.getElementById('sidebar-right').getElementsByTagName('li');
  for (var i = 0; i < list_element.length; i++){
    if (list_element[i].getElementsByTagName('a')[0].getAttribute('href') == '/' + uri){
      list_element[i].setAttribute("class", 'act');
    }
  }
}

function validate_email(field) {

  field=trim(field); 
  var emailFilter=/^.+@.+\..{2,3}$/;
  var illegalChars= /[\!\"\£\$\%\^\&\*\+\=\{\}\~\#\?\(\)\<\>\,\;\:\\\/\"\[\]\ ]/;

  if ((!(emailFilter.test(field))) || (field.match(illegalChars))) {
    return false;
  } else {
    return true;
  }
}

function trim (str) {
         str = this != window? this : str;
         return str.replace(/^\s+|\s+$/g,"");
}

function validate_postcode(field) {

  var postcodeFilter = /[a-z0-9]/i;
  var illegalChars = /[\!\"\`\$\%\^\@\_\-\'\|\&\*\+\=\{\}\~\#\?\(\)\<\>\,\.\;\:\\\/\[\]]/;
  var first_char = field.substr(0, 1);
  var numbers = '1234567890';
  var postcode_value = '';
  var counter = 0;
  var positions = new Array (field.length);  

  for (x = 0; x < field.length; x++) {
    if (numbers.indexOf(field.substr(x, 1)) != -1) {
      positions[counter] = x;
      counter = counter + 1;
    }
  }    

  if (!postcodeFilter.test(field) || field.match(illegalChars) || numbers.indexOf(first_char) != -1 || counter > 3 || (counter == 0 && field.length > 2) || (positions[0] > 2 && field.length > 2) || (counter < 2 && field.length > 4)) {
    return false;
  } else {
    return true;
  }

}

function validateSearch(){

  var valid = true;
  var mesg = '';
//  if (document.finder.pc_fieldset.getAttribute('class') != 'hide'){
  if (document.finder.pc_fieldset.style.display != 'none'){
    if (!(document.finder.postcode_F.value != 'Enter Postcode...' && document.finder.postcode_F.value != '')){
      valid = false;
      mesg = mesg + 'Please enter a valid UK Postcode.\n';
    }else{
      if (!(validate_postcode(document.finder.postcode_F.value))){
        valid = false;
        mesg = mesg + 'Please enter a valid UK Postcode.\n';
      }
    }
//    if (document.finder.postcode_F.value == 'Enter Postcode...' &&
//        document.finder.distance_F.options[document.finder.distance_F.selectedIndex].value != '100'){//Distance (Choose)'){
//      valid = false;
//      mesg = mesg + 'Please enter your postcode if you wish to search using distance.\n'
//    }
  }
  var meval = document.finder.max_price_F.options[document.finder.max_price_F.selectedIndex].value - document.finder.min_price_F.options[document.finder.min_price_F.selectedIndex].value;

  if (!(document.finder.make_F.value != 'ANY' || meval <= 2000)){
    valid = false;
    mesg = mesg + 'Please select a Manufacturer or a price range with a maximum '+String.fromCharCode(163)+'2000 spread.\n';
  }

  if (!(document.finder.email_F.value == 'Enter email address here...')){
    if (!(validate_email(document.finder.email_F.value))){
      valid = false;
      mesg = mesg + 'Please enter a valid email address.\n';
    }
  }

  if (!(valid)){
    alert(mesg);
    return valid;
  }else{
    return valid;
  }
}

function validateAdForm(){
  var valid = true;
  var mesg = '';
  
  if (!(validate_postcode(document.ca_ad_form.ca_postcode_F.value))){
    valid = false;
    mesg = mesg + 'Please enter a valid UK Postcode.\n';
  }

  if (!(validate_email(document.ca_ad_form.ca_email_F.value))){
    valid = false;
    mesg = mesg + 'Please enter a valid email address.\n';
  }

  if (!(valid)){
    alert(mesg);
    return valid;
  }else{
    return valid;
  }

}

function isPostcode(form){
  form.postcode_F.value = document.finder.postcode_F.value;
  if (form.sort_order_F.value != 'd'){
    form.submit();
  }else{
    if (document.finder.postcode_F.value == 'Enter Postcode...'){
      alert('Enter your postcode on left and\nsearch before sorting results by distance.');
      form.sort_order_F.selectedIndex = g_sortorder == 'p' ? 0 : 1;
    }else{
      form.submit();
    }
  }
}

function getNewAmount(form){
var url_sections = location.href.split('/');
var new_action_url = location.href;
  form.postcode_F.value = document.finder.postcode_F.value;
  if (url_sections.length == 7){
    new_action_url = '';
    for (i=0; (i+1) < url_sections.length; i++){
      new_action_url = new_action_url + url_sections[i];
    }
    new_action_url = new_action_url + '1';

  }
  else if (url_sections.length == 5) {
    new_action_url = '';
    for (i=0; (i+1) < url_sections.length; i++){
      new_action_url = new_action_url + url_sections[i] + '/';
    }
    new_action_url = new_action_url + '1';
  }

  form.action = new_action_url;
  form.submit();
}

function canPickDistance(){
  if (document.finder.postcode_F.value == 'Enter Postcode...' && 
      document.finder.distance_F.options[document.finder.distance_F.selectedIndex].text != 'Distance (Choose)'){
    alert('Please enter your postcode\nif you wish to search using distance.');
  }
}

function print_page(){
  window.open(location.href + '-print', '', ' width=740,scrollbars=yes');
}

function show_map(){
  window.open(location.href+'-map','','width=735,height=610,scrollbars=yes');
}

/***********************************************
* Basic Ajax Routine- Copyright Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

//Basic Ajax Routine- Author: Dynamic Drive (http://www.dynamicdrive.com)
//Last updated: Jan 15th, 06'

function createAjaxObj(){
  var httprequest=false
  if (window.XMLHttpRequest){ // if Mozilla, Safari etc
    httprequest=new XMLHttpRequest()
    if (httprequest.overrideMimeType)
    httprequest.overrideMimeType('text/xml')
  }
  else if (window.ActiveXObject){ // if IE
    try {
      httprequest=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e){
      try{
        httprequest=new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e){}
    }
  }
  return httprequest
}

var ajaxpack=new Object()
ajaxpack.basedomain="http://"+window.location.hostname
ajaxpack.ajaxobj=createAjaxObj()
ajaxpack.filetype="txt"
ajaxpack.addrandomnumber=0 //Set to 1 or 0. See documentation.
var targetID;

ajaxpack.getAjaxRequest=function(url, parameters, callbackfunc, filetype){
  ajaxpack.ajaxobj=createAjaxObj() //recreate ajax object to defeat cache problem in IE
  if (ajaxpack.addrandomnumber==1) //Further defeat caching problem in IE?
  var parameters=parameters+"&ajaxcachebust="+new Date().getTime()
  if (this.ajaxobj){
    this.filetype=filetype
    this.ajaxobj.onreadystatechange=callbackfunc
    this.ajaxobj.open('GET', url+"?"+parameters, true)
    this.ajaxobj.send(null)
  }
}

function processEfPopup() {
  var myajax=ajaxpack.ajaxobj
  var myfiletype=ajaxpack.filetype
  if (myajax.readyState == 4){ //if request of file completed
    if (myajax.status==200 || window.location.href.indexOf("http")==-1){
      if (myfiletype=="txt") {
        document.getElementById(targetID).innerHTML = myajax.responseText;
        document.getElementById('mask').style.display = 'block';
        document.getElementById(targetID).style.display = 'block';
        document.getElementById('pop-up').style.top = (f_scrollTop())+'px';
      } else {
        alert(myajax.responseXML)
      }
    }
  }
}

function processEfData() {
  var myajax=ajaxpack.ajaxobj
  var myfiletype=ajaxpack.filetype
  if (myajax.readyState == 4){ //if request of file completed
    if (myajax.status==200 || window.location.href.indexOf("http")==-1){
      if (myfiletype=="txt") {
        document.getElementById('mask').style.display = 'none';
        document.getElementById('out').style.display = 'none';
      } else {
        alert(myajax.responseXML)
      }
    }
  }
}

//function processUpdatedOption(fName) {
function processUpdatedOption() {
  var myajax=ajaxpack.ajaxobj
  var myfiletype=ajaxpack.filetype
  if (myajax.readyState == 4){ //if request of file completed
    if (myajax.status==200 || window.location.href.indexOf("http")==-1){
      if (myfiletype=="txt") {
        var data1 = myajax.responseText.split('|');
        var data = data1[0].split('#');
        var data2 = data1[1].split('#');
//        var data = myajax.responseText.split('#');
        var fName = data[0];
        var fName1 = data2[0];
        document.getElementById(fName).length = 1;
        document.getElementById(fName1).length = 1;


        for (i=1; i < data.length; i++){
          document.getElementById(fName).length++;
          if (data[i] == 'Open Car'){
            document.getElementById(fName).options[i].text = 'Convertible';
          }else{
            document.getElementById(fName).options[i].text = data[i];
          }
          document.getElementById(fName).options[i].value = data[i];
          if (data[i] == curr_c_type){
            document.getElementById(fName).options.selectedIndex = i;
          }
        }

        for (i=1; i < data2.length; i++){
          document.getElementById(fName1).length++;
          document.getElementById(fName1).options[i].text = data2[i];
          document.getElementById(fName1).options[i].value = data2[i].substring(0,1);
          if (data2[i].substring(0,1) == curr_fuel){
            document.getElementById(fName1).options.selectedIndex = i;
          }
        }

      } else {
        alert(myajax.responseXML)
      }
    }
  }      
}

function closepop(){
  document.getElementById('mask').style.display = 'none';
  document.getElementById('out').style.display = 'none';
}

function showEnquiryForm(cid){
  if (document.getElementById('dblock-'+cid).innerHTML != '<b>Your enquiry has been sent</b>'){
    if (!document.getElementById('mask')){
      var fadediv =  document.createElement ("div");
      var fhtml = '<div id="mask" class="mask"></div>';
      fadediv.innerHTML = fhtml;
      document.body.appendChild(fadediv);
    }
  
    if (!document.getElementById('out')){
      var newdiv = document.createElement ("div");
      var html = '<div id="out" class="out" name="out" style="display:none"></div>';
      newdiv.innerHTML = html;
      document.body.appendChild(newdiv);
    }
    targetID = 'out';
  
    ajaxpack.getAjaxRequest('/new-car-enquiry', 'cid='+cid, processEfPopup, 'txt');
    return true;

  }
}
var option_para;
function updateOption(){
  if (document.finder.action.indexOf('new-search-results') == -1){
    var used = 1;
  }else{
    var used = 0;
  }
  option_para = 'man='+document.finder.make_F.value+'&mod='+document.finder.model_F.value+'&used='+used+'&type=';

  if (document.finder.make_F.value != 'ANY' && document.finder.make_F.value != '' && document.finder.vehicle_type_F.value != 'V'){
    ajaxpack.getAjaxRequest('/get-options',option_para+'B&fname=car_type_F',processUpdatedOption,'txt');
  }
}

function sendEnquiryData(form){
  var valid = true;
  var mess = '';

  parameters = getFormElements(form);
  if (!(validate_postcode(form.postcode_F.value))){
    valid = false;
    mess = mess + 'Enter a valid UK postcode\n';
  }
  if (!(validate_email(form.email_F.value))){
    valid = false;
    mess = mess + 'Enter a valid email address\n';
  }
  if (c < 1){
    valid = false;
    mess = mess + 'Please choose at least one dealer\n';
  }

  if (!valid){
    alert(mess);
  }else{
    document.getElementById('mask2').style.display = 'block';
    ajaxpack.getAjaxRequest('/new-car-enquiry', parameters, processEfData, 'txt');
    document.getElementById('dblock-'+form.cap_id_F.value).innerHTML = '<b>Your enquiry has been sent</b>';
  }
  return false;
}

var c=0;

function checkmax(box, form){
  var max = 3;
  c=0;

  for (i=0; i<form.elements.length; i++){
    if (form.elements[i].type == 'checkbox' && form.elements[i].name != 'nofity_yn_F'){
      if (form.elements[i].checked) c += 1;
    }
  }

  if (c > max){
    alert ('Only a max of 3 dealers can be selected');
    box.checked = false;
  }

}

function getFormElements(form){
  var forme = '';
  var url_para = '';

  for (i=0; i<form.elements.length; i++){
    if (form.elements[i].type == 'checkbox'){
      if (form.elements[i].checked == 1){
        url_para = url_para + form.elements[i].name + '=on&';
      }
    }else{
    url_para = url_para + form.elements[i].name + '=' +
                          form.elements[i].value + '&';
    }
  }

  url_para = url_para.slice(0,url_para.length - 9);

  return url_para;
}

function f_clientWidth() {
  return f_filterResults (
    window.innerWidth ? window.innerWidth : 0,
    document.documentElement ? document.documentElement.clientWidth : 0,
    document.body ? document.body.clientWidth : 0
  );
}
function f_clientHeight() {
  return f_filterResults (
    window.innerHeight ? window.innerHeight : 0,
    document.documentElement ? document.documentElement.clientHeight : 0,
    document.body ? document.body.clientHeight : 0
  );
}
function f_scrollLeft() {
  return f_filterResults (
    window.pageXOffset ? window.pageXOffset : 0,
    document.documentElement ? document.documentElement.scrollLeft : 0,
    document.body ? document.body.scrollLeft : 0
  );
}
function f_scrollTop() {
  return f_filterResults (
    window.pageYOffset ? window.pageYOffset : 0,
    document.documentElement ? document.documentElement.scrollTop : 0,
    document.body ? document.body.scrollTop : 0
  );
}
function f_filterResults(n_win, n_docel, n_body) {
  var n_result = n_win ? n_win : 0;
  if (n_docel && (!n_result || (n_result > n_docel)))
    n_result = n_docel;
  return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

function updatePrice(changed){
  var minp = 0;
  var maxp = document.finder.max_price_F.length -1;
  var curr_maxp = document.finder.max_price_F.options[document.finder.max_price_F.selectedIndex].value;
  var curr_minp = document.finder.min_price_F.options[document.finder.min_price_F.selectedIndex].value;

  if (changed.name == 'min_price_F'){
    if (parseInt(changed.value) >= curr_maxp){
      document.finder.max_price_F.selectedIndex = maxp;
    }
    for (i=0; i < document.finder.max_price_F.length; i++){
      if (parseInt(document.finder.max_price_F.options[i].value) < parseInt(changed.value)){
        document.finder.max_price_F.options[i].setAttribute("class", 'hide');
      }else{
        document.finder.max_price_F.options[i].removeAttribute("class");
      }
    }
  }else if (changed.name == 'max_price_F'){
    if (curr_minp > parseInt(changed.value)){
      document.finder.min_price_F.selectedIndex = (document.finder.max_price_F.selectedIndex -1) >= 0 ? (document.finder.max_price_F.selectedIndex -1) : 0;
    }
  }
}
