// ads.js for functions related to the ads module

// fill model: based on make, populate a model dropdown

function populateModel(baseurl, el, makeid, busyid, firstempty, available, modelid)
{
    el.options.length = 0;
    var ajaxurl = baseurl + '/resources/scripts/ajax.php?action=get_models&id=' + makeid + '&available=' + available;
    if (busyid) busy(busyid,true);
    // Create Ajax Request
    var a = new ajax (ajaxurl, {onComplete: function(){updateModel(busyid,el,this.transport.responseText, firstempty, modelid);}});
}

function updateModel(busyid,el,what,firstempty, modelid)
{
    var models = what.split('#$#');
    if (firstempty)
    {
        el.options[el.options.length] = new Option('Geen voorkeur','');
    }
    if (models.length > 1)
    {
        el.disabled = false;
        for(i = 0; i < models.length; ++i)
        {
            model = models[i].split('|||');
            if (model[1] > 0)
            {
                el.options[el.options.length] = new Option(model[0],model[1]);
		if (modelid && model[1] == modelid)
			el.options[el.options.length-1].selected = true;
            }
        }
    }
    else
    {
        el.options[0] = new Option('Selecteer een merk','');
        el.disabled = true;
    }
    if (typeof initModel == 'function')
	initModel();
    if (busyid) busy(busyid,false);
}

function set_max(minlist, maxlist)
{
    if (maxlist.selectedIndex < minlist.selectedIndex)
    {
        maxlist.options[minlist.selectedIndex].selected = true;
    }

}

function set_min(minlist, maxlist)
{
    if (maxlist.selectedIndex < minlist.selectedIndex)
    {
        minlist.options[maxlist.options.selectedIndex].selected = true;
    }

}

function changeMainImg(im)
{
  if($('mainimg'))
  {
    $('mainimg').src = im;
  }
}

function toggle_block(id)
{
    if (document.getElementById(id))
    {
        obj = document.getElementById(id);
        obj.style.display = obj.style.display == 'block' ? 'none' : 'block';
    }
}

function fix_money(obj)
{
  var val = obj.value;
  //replace anything that ain't a number or .,
  val = val.replace(/[^0-9\.,]/g,"");
  
  if(val.match(/,[0-9]{3}$/g))
  {
    if(parseInt(val)>0) //don't replace numbers as 0,002
    {
      val = val.replace(/[,]/g,"");
    }
  }
  else if(val.match(/,[0-9]{2}$/g) || val.match(/\.[0-9]{3}$/g))
  {
    if(parseInt(val)>0) //don't replace numbers as 0,002
    {
      val = val.replace(/[\.]/g,"");
    }
  }
  
  obj.value = val;
}

function fix_moneyfields(step)
{
  if(step=='contract' || step=='all')
  {
    els = document.forms['ad'].elements;
    fix_money(els['monthlyfee']);
    fix_money(els['car_value']);
    fix_money(els['km_price']);
  }
  return true;
}
