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

var alias = '';
function setAlias(alias)
{
  this.alias = alias;
}

var sql_where= '';
function setSqldepend(sqldepend)
{
  this.sql_where= sqldepend;
}

function dropdown_controller(module,instance,dbf,dbt,where_field,where_value,depends,clear) {
  where_value = encodeURIComponent(where_value);
  $.getJSON("/cars/ajax/getdbvalues.php?module="+module+"&instance="+instance+"&dbf="+dbf+"&dbt="+dbt+"&where_field="+where_field+"&where_value="+where_value+"&depends="+depends+"&alias="+alias+"&sql_where="+sql_where,function(data){
    if (dbf.indexOf(',') > 0) {
      var elements = dbf.split(',');
      var i = 0;
      while (i < elements.length) {
        dbf = elements[i];
        $.each(data, function(key,elem){
	  if(key == dbf) {
            var first = $("[class^="+module+"_"+instance+"] select[name="+key+"] option:first").text();
	    var current = $("[class^="+module+"_"+instance+"] select[name="+key+"] option:selected").val();
            var options = '<option value="">'+first+'</option>';
	    if (elem != '' && elem != 'null'){
      	      var vals = elem.split(',');
              var j = 0;
              while (j < vals.length) {
	        var output = vals[j].split('*');
	        var selected = '';
  	        var value = output[0];

// counter removed temporarirly
//	        var label = output[0] + ' (' + output[1] + ')';
var label = output[0];
if (value.indexOf('_') > 0) {
  var new_vl = value.replace('comma',',').split('_');
  value = new_vl[0];
  label = new_vl[1];
}
	        if (value == current && (value != '')) {
	  	  selected = ' SELECTED';
//		  label = value;	
	        }
 	        options += '<option value="'+value+'"'+selected+'>'+label+'</option>';
	        j+=1;
              }
            }
	    $("[class^="+module+"_"+instance+"] select[name="+key+"]").html(options);
          }
        });
        i += 1;
      }
    }
    else {
      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
  });

this.sql_where='';
this.alias ='';

}

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 modules_controller(module,instance,variable,value,id,clear,section){
  if (clear != '') {
    var clear = "&clear=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
  }).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


