function redir (page,option) {
  window.location = '/'+page+'/'+option;
}

function dropdown_controller(module,instance,dbf,dbt,where_field,where_value,depends,clear,only_new_yn,sql_where) {
  if (dbf == 'model') {
    // if loading the model select then clear the cap_derivative select
    $("[class^="+module+"_"+instance+"] select[name=cap_derivative]").html('<option value="">Trim</option>');
  }

  $.getJSON("/cars/ajax/getdbvalues.php?module="+module+"&instance="+instance+"&dbf="+dbf+"&dbt="+dbt+"&where_field="+where_field+"&where_value="+where_value+"&depends="+depends+"&only_new_yn="+only_new_yn+"&sql_where="+sql_where,function(data){
    var first = $("[class^="+module+"_"+instance+"] select[name="+dbf+"] option:first").text();
    var options = '<option value="">'+first+'</option>';
    $.each(data, function(i,element){
      options += '<option value="' + element.value + '">' + element.value + '</option>';
    });
    $("[class^="+module+"_"+instance+"] select[name="+dbf+"]").html(options);
  });
  $.ajax({
    type: "POST",
    url: "/cars/ajax/sessionupdater.php",
    data: "mode=module&module="+module+"&instance="+instance+"&var="+where_field+"&val="+where_value
  });
}

function dropdown_div_controller(module,instance,dbf,dbt,where_field,where_value,depends,clear,only_new_yn,sql_where) {
//alert('testmike');
//alert(where_field+":"+where_value);
//alert("/cars/ajax/getdbvalues.php?module="+module+"&instance="+instance+"&dbf="+dbf+"&dbt="+dbt+"&where_field="+where_field+"&where_value="+where_value+"&depends="+depends+"&only_new_yn="+only_new_yn+"&sql_where="+sql_where);
  $.getJSON("/cars/ajax/getdbvalues.php?module="+module+"&instance="+instance+"&dbf="+dbf+"&dbt="+dbt+"&where_field="+where_field+"&where_value="+where_value+"&depends="+depends+"&only_new_yn="+only_new_yn+"&sql_where="+sql_where,function(data){
    var first = $("[class^="+module+"_"+instance+"] input[name="+dbf+"]").parent().children("ul").children("li:first").text();
    var options = '<li title="">'+first+'</li>';
    var div_id = $("[class^="+module+"_"+instance+"] input[name="+dbf+"]").parent().attr('id');
    styledSelect.addNewItems(document.getElementById(div_id), data);
  });
  $.ajax({
    type: "POST",
    url: "/cars/ajax/sessionupdater.php",
    data: "mode=module&module="+module+"&instance="+instance+"&var="+where_field+"&val="+where_value
  });
}

function session_controller(module,instance,variable,value,clear) {
  $.ajax({
    type: "POST",
    url: "/cars/ajax/sessionupdater.php",
    data: "mode=module&module="+module+"&instance="+instance+"&var="+variable+"&val="+value
  });
}
function return_new_search_url(module,instance,curr_route){
  // reset page to 1 first
  $.ajax({
    type:"POST",
    url:"/cars/ajax/sessionupdater.php",
    data:"mode=module&module="+module+"&instance="+instance+"&var=page&val=1",
    success: function(data) {
      // fix for dealer search pages which should not reload as car-search or van-search
      // and remove ajax call to php which appears unnecessary 
      // use the Textpattern URL passed in as curr_route, to work out URL to reload
      var eles = curr_route.split("/",4);
      var newurl = "/"+eles[1]+"/"+eles[2]+"/"+eles[3];
      location.href = newurl;

      // not sure why we're submitting the form here, it resets the checkboxes for dealer searches
      // so removed and using location.href to refresh the page instead.
      // document.forms["searchFormName"].submit();
/***
      $.ajax({
        type:"POST",
        url:"/cars/ajax/getsearchurl.php",
        data:"module="+module+"&instance="+instance,
        success:function(data) {
          location.href = data;
        }
      });
***/
    }
  });

  /*if (curr_url.indexOf('/') > 0) {
    location.href = '/'+curr_url;
  } else {
    location.href = '/'+curr_url+'/'+module+'/'+instance;
  }*/
}
function modules_controller(module,instance,variable,value,id,clear,section){
  if (clear != '') {
    var clear = "&clear=clear";
  }
//alert("mode=module&module="+module+"&instance="+instance+"&var="+variable+"&val="+value+clear);
  $.ajax({
    type: "POST",
    url: "/cars/ajax/sessionupdater.php",
    data: "mode=module&module="+module+"&instance="+instance+"&var="+variable+"&val="+value+clear,
    success: function(data) {
      $.getJSON("/cars/ajax/elementsupdater.php?module="+module+"&instance="+instance,function(data){
        $.each(data, function(i,element){
          var cls = element.mod+"_"+element.ins;
          var output = call_module(element.mod,element.ins,section);
          $("."+cls+"_"+section).html(output);
        });
      });
    }
  });
}
function call_module(module,instance,section) {
  var ts = new Date();
  var mod = $.ajax({
    type: "POST",
    url: "/cars/ajax/runmodule.php",
    data: "module="+module+"&instance="+instance+"&section="+section+"&timestamp="+ts.getTime(),
    async: false,
    success: function(){
      if(styledSelect){
//MM - console not supported by IE and breaks the search functionality switching between cars and vans
//console.log(module + ',' + instance + ',' + section);
        var t = window.setTimeout("styledSelect.setFSelects()", 0);
      }
    }
  }).responseText;

  return mod;
}
//new javascript for on-the-fly edit features
function initializeMCE() {
  tinyMCE.init({
    language : "en",
    theme : "simple",
    convert_fonts_to_spans : "true",
    relative_urls : "false",
    remove_script_host : "false",
    mode : "specific_textareas",
    editor_selector : "mceEditor",
    strict_loading_mode : "true"
  });
}
function generateEditableBox(id,mode,type){
  var elem1 = 'article_'+id;
  var elem2 = 'edit_'+id;
  if (mode == 'open') {
    $('.'+elem1).hide();
    $('.'+elem2).show();
    if (type == 'html') {
        initializeMCE();
    }
  }
  else {
    $('.'+elem2).hide();
    $('.'+elem1).css('display','inline');
  }
}
function ajaxLiveEdit(fieldname,dbt,content) {
  $.ajax({
      type: "GET",
      url: "/cars/ajax/liveedit.php",
      data: "fieldname="+fieldname+"&dbt="+dbt+"&content="+content,
      success: function(data) {
	var field=fieldname.split("_");
        generateEditableBox(fieldname,'close')
	if (field[0] == 'price1' || field[0] == 'price2' || fieldname[0] == 'price3') {
          var prefix = '&pound;';
        }
        else {
          var prefix = '';
        }
        var a = prefix+addCommas(content);
        $("#"+fieldname).html(a);
      }
    });
}
function addCommas(strValue) {
  var objRegExp = new RegExp('(-?[0-9]+)([0-9]{3})');
  while(objRegExp.test(strValue)) {
    strValue = strValue.replace(objRegExp, '$1,$2');
  }
  return strValue;
}

function addtoforecourt(instance,cars_id,newused) {
  $.ajax({
    type: "GET",
    url: "/cars/ajax/manageforecourt.php?mode=add&cars_id="+cars_id+"&newused="+newused+"&instance="+instance,
    success: function(data) {
      $.each($("[class^=forecourt_default]"),function(i,v) {
	var output = call_module('forecourt',instance,i+1);
        $(v).html(output);
      });
    }
  });
}
function removefromforecourt(instance,cars_id,newused) {
  $.ajax({
    type: "GET",
    url: "/cars/ajax/manageforecourt.php?mode=remove&cars_id="+cars_id+"&newused="+newused+"&instance="+instance,
    success: function(data) {
      $.each($("[class^=forecourt_default]"),function(i,v) {
        var output = call_module('forecourt',instance,i+1);
        $(v).html(output);
      });
    }
  });
}
function validate_survey_form(form) {
  var valid = true;
  $.each(form,
    function(){
	if($(this).is(".mandatory") && $(this).val() == '') {
	  msg = 'Please fill all the mandatory fields in.';
	  valid = false;
        }
    });
  if (!valid) alert(msg);
  return valid; 
}

// Backend old update functions - needs to be removed as new backend code is finished
function dsubmit(func,val) {
  document.getElementById('dsub').dsubmit_func.value=func;
  document.getElementById('dsub').dsubmit_val.value=val;
  setTimeout("document.getElementById('dsub').submit()",15);
}
function ajaxlookup(database,search,update_id) {
  var url="/cars/ajax/lookup.php?database="+database+"&search="+search+"&update_id="+update_id;
  var getmodule = new getXMLHttpRequest();
  getmodule.open("GET",url,false);
  getmodule.send(null);
  try {
    var data=getmodule.responseText;
    if (document.getElementById('sug_'+update_id)) document.getElementById('sug_'+update_id).innerHTML=data;
  }
  catch (ex) {}
}
function ajaxfilelookup(basedir,search,update_id) {
  var url="/cars/ajax/lookup.php?basedir="+Base64.encode(basedir)+"&search="+search+"&update_id="+update_id;
  var getmodule = new getXMLHttpRequest();
  getmodule.open("GET",url,false);
  getmodule.send(null);
  try {
    var data=getmodule.responseText;
    if (document.getElementById('sug_'+update_id)) document.getElementById('sug_'+update_id).innerHTML=data;
  }
  catch (ex) {}
}
function ajaxselect(selection,search,update_id) {
  // - selection separated by double vertical slashes -
  var url="/cars/ajax/select.php?selection="+selection+"&search="+search+"&update_id="+update_id;
  var getmodule = new getXMLHttpRequest();
  getmodule.open("GET",url,false);
  getmodule.send(null);
  try {
    var data=getmodule.responseText;
    if (document.getElementById('sug_'+update_id)) {
      document.getElementById('sug_'+update_id).innerHTML=data;
      document.getElementById('sug_'+update_id).style.display='';
    }
  }
  catch (ex) {}
}
// ------------------- standard ajax access code -----------------
//
// Define a list of Microsoft XML HTTP ProgIDs.
//
var XMLHTTPREQUEST_MS_PROGIDS = new Array(
  "Msxml2.XMLHTTP.7.0",
  "Msxml2.XMLHTTP.6.0",
  "Msxml2.XMLHTTP.5.0",
  "Msxml2.XMLHTTP.4.0",
  "MSXML2.XMLHTTP.3.0",
  "MSXML2.XMLHTTP",
  "Microsoft.XMLHTTP"
);

//
// Define ready state constants.
//
var XMLHTTPREQUEST_READY_STATE_UNINITIALIZED = 0;
var XMLHTTPREQUEST_READY_STATE_LOADING       = 1;
var XMLHTTPREQUEST_READY_STATE_LOADED        = 2;
var XMLHTTPREQUEST_READY_STATE_INTERACTIVE   = 3;
var XMLHTTPREQUEST_READY_STATE_COMPLETED     = 4;

//
// Returns XMLHttpRequest object.
//
function getXMLHttpRequest()
{
  var httpRequest = null;

  // Create the appropriate HttpRequest object for the browser.
  if (window.XMLHttpRequest != null)
    httpRequest = new window.XMLHttpRequest();
  else if (window.ActiveXObject != null)
  {
    // Must be IE, find the right ActiveXObject.
    var success = false;
    for (var i = 0;
         i < XMLHTTPREQUEST_MS_PROGIDS.length && !success;
         i++)
    {
      try
      {
        httpRequest = new ActiveXObject(XMLHTTPREQUEST_MS_PROGIDS[i]);
        success = true;
      }
      catch (ex)
      {}
    }
  }

  // Display an error if we couldn't create one.
  if (httpRequest == null)
    alert("Error in HttpRequest():\n\n"
      + "Cannot create an XMLHttpRequest object.");

  // Return it.
  return httpRequest;
}

// end of old functions

function da_analytics() {
  var cookieEnabled = are_cookies_enabled();

  var cky_referrer = get_cookie(sitename+"_referrer");

  if (cky_referrer == "" || (cky_referrer != referrer && referrer != 'No Referrer')) {
    var session_state = 'new';
    document.cookie=sitename+"_referrer="+referrer;
  } else {
    var session_state = 'existing';
    referrer = cky_referrer;
  }

  document.cookie="perrys_referrer="+referrer

  $.ajax({
    type: "POST",
    url: "/cars/ajax/da-analytics.php",
    data: "session_state="+session_state+"&referrer="+referrer+"&cookies="+cookieEnabled
  });
}

function are_cookies_enabled() {
  var cookieEnabled = (navigator.cookieEnabled) ? 'true' : 'false';

  if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled)
  { 
    document.cookie="testcookie";
    cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? 'true' : 'false';
  }
  return (cookieEnabled);
}

function get_cookie(Name) {
  var search = Name + "="
  var returnvalue = "";
  if (document.cookie.length > 0) {
    offset = document.cookie.indexOf(search)
    // if cookie exists
    if (offset != -1) { 
      offset += search.length
      // set index of beginning of value
      end = document.cookie.indexOf(";", offset);
      // set index of end of cookie value
      if (end == -1) end = document.cookie.length;
      returnvalue=unescape(document.cookie.substring(offset, end))
    }
  }
  return returnvalue;
}

/*==============================================================================

Parameters:    toCheck - postcodeto be checked.

This function checks the value of the parameter for a valid postcode format. The
space between the inward part and the outward part is optional, although is
inserted if not there as it is part of the official postcode.

If the postcode is found to be in a valid format, the function returns the
postcode properly formatted (in capitals with the outward code and the inward
code separated by a space. If the postcode is deemed to be incorrect a value of
false is returned.

Example call:

  if (checkPostCode (myPostCode)) {
    alert ("Postcode has a valid format")
  }
  else {alert ("Postcode has invalid format")};

------------------------------------------------------------------------------*/

function checkPostCode (pCodeId, mandatory_yn) {

  toCheck = pCodeId.value;
  if (mandatory_yn == 'N' && (toCheck == '' || toCheck == 'Your Town/Postcode')) {
    return true;
  } 
  else {

    // Permitted letters depend upon their position in the postcode.
    var alpha1 = "[abcdefghijklmnoprstuwyz]";                       // Character 1
    var alpha2 = "[abcdefghklmnopqrstuvwxy]";                       // Character 2
    var alpha3 = "[abcdefghjkpmnrstuvwxy]";                         // Character 3
    var alpha4 = "[abehmnprvwxy]";                                  // Character 4
    var alpha5 = "[abdefghjlnpqrstuwxyz]";                          // Character 5

    // Array holds the regular expressions for the valid postcodes
    var pcexp = new Array ();

    // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
    pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

    // Expression for postcodes: ANA NAA
    pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

    // Expression for postcodes: AANA  NAA
    pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "{1}" + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

    // Exception for the special postcode GIR 0AA
    pcexp.push (/^(GIR)(\s*)(0AA)$/i);

    // Standard BFPO numbers
    pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);

    // c/o BFPO numbers
    pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);

    // Overseas Territories
    pcexp.push (/^([A-Z]{4})(\s*)(1ZZ)$/i);

    // Load up the string to check
    var postCode = toCheck;

    // Assume we're not going to find a valid postcode
    var valid = false;

    // Check the string against the types of post codes
    for ( var i=0; i<pcexp.length; i++) {
      if (pcexp[i].test(postCode)) {

        // The post code is valid - split the post code into component parts
        pcexp[i].exec(postCode);

        // Copy it back into the original string, converting it to uppercase and
        // inserting a space between the inward and outward codes
        postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();

        // If it is a BFPO c/o type postcode, tidy up the "c/o" part
        postCode = postCode.replace (/C\/O\s*/,"c/o ");

        // Load new postcode back into the form element
        valid = true;

        // Remember that we have found that the code is valid and break from loop
        break;
      }
    }

    // Return with either the reformatted valid postcode or the original invalid postcode
    if (valid) {
      pCodeId.value = postCode;
      return true;
    } 
    else {
      // alert('Please enter a valid postcode');
      // $('#postcode_F').addClass('error');
      return false;
    }
  }
}


