//***************************************************************************************
function CommercialQuickSearch(bsDdlIndex)
{ 
    //first check that the user has at least selected a manufacturer
    if(bsDdlIndex == 0) 
    {
        alert('Please select a Bodystyle.');
    }
    else
    {    
        window.location.href = '/Commercial/UsedCommercialLocator.aspx?bsId=' + bsDdlIndex;
    }
}
function ValidateQuickSearch(searchType, mnDdlIndex, rnIdIndex)
{ 
    //first check that the user has at least selected a manufacturer
    if ((mnDdlIndex == 0) && (rnIdIndex == 0))
    {
		alert('Please select a manufacturer/model.');
	}
    else if(mnDdlIndex == 0) 
    {
        alert('Please select a manufacturer.');
    }
    else if(rnIdIndex == 0) 
    {
        alert('Please select a model.');
    }    
    else
    {
        //now we need to check what kind of search they are performing, vans or cars
        if(searchType == 1) {
            //document.qsForm.action = '/UsedCars/UsedCarSearch.aspx';
            //window.location.href = '/UsedCars/UsedCarSearch.aspx?pc=&st=' + searchType + '&mnid=' + mnDdlIndex + '&rnid=' + rnIdIndex;
            window.location.href = '/UsedCars/UsedCarLocator.aspx?mnid=' + mnDdlIndex + '&rnid=' + rnIdIndex;
        }
        else {
            //document.qsForm.action = '/Commercial/UsedCommercialSearch.aspx';
            //window.location.href = '/Commercial/UsedCommercialSearch.aspx?pc=&st=' + searchType + '&mnid=' + mnDdlIndex + '&rnid=' + rnIdIndex;
            window.location.href = '/Commercial/UsedCommercialLocator.aspx?mnid=' + mnDdlIndex + '&rnid=' + rnIdIndex;
        }        
    }
}
//***************************************************************************************

//***************************************************************************************
//function used to handle the selected index change event of the manufacturer quicksearch dropdown
function SelectManufacturer(id)
{
    var qs = GetQsArray();
    var KEY = 0;
    var VALUE = 1;
    var frnId = document.getElementById(id).options[document.getElementById(id).selectedIndex].value;
    
    //build the redirect url
    var url = window.location.pathname  + "?";
    
    //loop through our qs and rebuild it.
    for(i = 0; i < qs.length; i++)
    {
        url += qs[i][KEY] + "=";
        url += (qs[i][KEY] == "frn")? frnId : qs[i][VALUE]
        url += (i < (qs.length - 1))? "&" : "";
    }
    //check if we have a franchise if not append it.
    if(url.indexOf('frn=') == -1)
    {
        url += (qs.length > 0)? "&" : "";
        url += "frn=" + frnId;
    }
    window.location.href = url;
}
//***************************************************************************************

//***************************************************************************************
function GetQsArray()
{
    var qsParm = new Array();
    var query = window.location.search.substring(1);
    var parms = query.split('&');
    for (var i=0; i<parms.length; i++)
    {
        var pos = parms[i].indexOf('=');
        if (pos > 0)
        {
            var key = parms[i].substring(0,pos);
            var val = parms[i].substring(pos+1);
            qsParm[i] = new Array(key,val);
        }
    }
    return qsParm;
}
//*************************************************************************************** 


//function used to refresh the page ap[pending the required searchtype variable to the qs
function SearchTypeSwitch(val) {
    url = window.location.href;
    
    //first check to see if this is gonna be the only param
    if(url.indexOf('?') > -1) {
      var base = url.substring(0,url.indexOf('?'));
      var args = '';
      
      var query = window.location.search.substring(1);
      var vars = query.split("&");
      for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if ((pair[0] != 'st') && (pair[0] != 'frn') && (pair[0] != '')) {
          args = args + '&' + pair[0] + "=" + pair[1];
        }
      }       

      if(args.length > 1) {  
        args = '?' + args.substring(1) + '&st=' + val;
      }
      else {
        args = '?st=' + val;
      }
    
      window.location.href = base + args;
    }
    else {
       window.location.href = url + '?st=' + val;
    }
}

//***************************************************************************************
 //functions used to power the comparer
function Compare_Click() {
    //get all of the input tags, and being to build the args
    var e=document.getElementsByTagName('input');
    var args = '?ShowComparer=true&BookmarkIds=';

    //cycle the inputs and find the checkboxes, if they're checked append the carid to the args var
    for(var i=0;i<e.length;i++){
        if(e[i].type == 'checkbox') {
            if(e[i].checked) {
                args += e[i].title + ",";
            }
        }
    }

    //now check that the user has selected at least one car, if not give them an error, if so goto the comparer
    if(args == '?ShowComparer=true&BookmarkIds=') 
        alert('You Must Select At Least One Vehicle To Compare');
    else {
        var ids = args.split(',');
        if(ids.length > 4) {
            alert('You Can Only Compare Up To 3 Vehicles At Once');
        }
        else
            window.location.href = '/UsedCars/UsedCarSearch.aspx' + args;          
    }
}
//***************************************************************************************





function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
}

/****************************************************************************************/
/*  Finance Examples functions															*/	
/****************************************************************************************/
function ValidateFinanceEnquiriesRequest() {
	//validate that the user has entered a valid deposit amount
	var deposit = document.getElementById("ctl03_ctl00_txtFinanceDeposit").value;
	var term = document.getElementById("ctl03_ctl00_ddlTerm").value;
	var depositInValid = !ValidateDeposit(deposit);
	var termInValid = (term == '-1');	
	if(depositInValid) {
		document.getElementById('spnFinanceDepositError').style.display = "block";
	}
	else {
		document.getElementById('spnFinanceDepositError').style.display = "none";
	}
	if(termInValid) {
		document.getElementById('spnFinanceTermError').style.display = "block";
	}
	else {
		document.getElementById('spnFinanceTermError').style.display = "none";
	}
	
	if(depositInValid || termInValid) {
		return false;
	}
	else {
		return ValidateDepositLimit(deposit);
	}
}

//function used to validate that the deposit isn't more than the value of the vehicle
function ValidateDepositLimit(deposit) {
	//get the vars needed to validate the deposit upper limit
	var vehiclePriceInput = document.getElementById("hdnVehiclePrice");
	var vehiclePriceError = document.getElementById("spnFinanceDepositHigh");
	
	//if the deposit is greater or equal to 80% of the price of the vehicle then it is valid
	if(parseFloat(deposit) >= (parseFloat(vehiclePriceInput.value) * 0.8)) {
		vehiclePriceError.style.display = "block";
		return false;
	}
	else {
		vehiclePriceError.style.display = "none";
		return true;
	}
}

//function used to check if a value is numeric
function ValidateDeposit(sText)
{
   if(!sText || sText == '' || sText.length > 6)
	return false;

   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
}

/****************************************************************************************/
/*  Service Assure functions															*/	
/****************************************************************************************/

//function used to handle the select change event of the range ddl
function RangeDropDownChange() {
	var rangeSelect = document.getElementById('serviceAssureRange').getElementsByTagName('select')[0];
	var yearSelect = document.getElementById('serviceAssureYears').getElementsByTagName('select')[0];
	if(rangeSelect.value == '-1') {
		//the range has been deselected so we needto clear down the items in the year select and re-add in the default
		yearSelect.options.length = 0;
		var opt = document.createElement("option");
        yearSelect.options.add(opt);        // Assign text and value to Option object
        opt.text = "Please select the required range above...";
        opt.value = "-1";
        yearSelect.disabled = true;
	}
	else {
		//the user has changed the range selection so we need to change the form action to remove the yr
		//param and change the value of the rng param
		var form = document.getElementById('frmServiceAssure');
		var formAction;
		
		//we need to handle the action differently if there is already a QS present
		if(window.location.href.indexOf('?') > -1) {
			//we need to keep the existing params but change/add the rng param as required
			var urlParts = window.location.href.split('?'); 
			formAction = urlParts[0] + "?" + RemoveQSParam(urlParts[1], "rng") + "&rng=" + rangeSelect.value;
		}
		else {
			formAction = window.location.href + "?rng=" + rangeSelect.value;
		}	
		
		//assign the updated form action to the form and submit it
		form.action = formAction;
		form.submit();
	}
}

//function used to validate the users selection and forward them to the correct page
function ServiceAssureSubmit() {
	//first validate that the user selected both a range an the number of years required
	var rangeSelect = document.getElementById('serviceAssureRange').getElementsByTagName('select')[0];
	var yearSelect = document.getElementById('serviceAssureYears').getElementsByTagName('select')[0];
	var rangeValid = (rangeSelect.value != -1)
	var yearValid = (yearSelect.value != -1);
	
	//hide or show the error message as required
	if(!rangeValid) {
		document.getElementById('serviceAssureRangeError').style.display = "block";
	}
	else {
		document.getElementById('serviceAssureRangeError').style.display = "none";
	}
	if(!yearValid) {
		document.getElementById('serviceAssureYearError').style.display = "block";

	}
	else {
		document.getElementById('serviceAssureYearError').style.display = "none";
	}

	//if both are valid permit the redirect, otherwise stop it
	if(!rangeValid || !yearValid)
		return false;
	else {
		//rewrite the form action to include the selected params, we need to include any existing
		//params, but replace the rng and yr params with the newely selected ones.
		var form = document.getElementById('frmServiceAssure');
		var formAction;
		 
		if(window.location.href.indexOf('?') > -1) {
			//we need to check if we're adding in the params or altering them
			var urlParts = window.location.href.split('?'); 
			if(window.location.href.indexOf('rng=') > -1)
				formAction = UpdateQSParam(urlParts[1], 'rng', rangeSelect.value);
			else
				formAction = urlParts[1] + '&rng=' + rangeSelect.value
				
			if(window.location.href.indexOf('yr=') > -1)
				formAction = UpdateQSParam(formAction, 'yr', yearSelect.value);
			else
				formAction = formAction + '&yr=' + yearSelect.value;
				
			//add the url back on
			formAction = urlParts[0] + '?' + formAction;
		}
		else {
			formAction  = window.location.href + '?rng=' + rangeSelect.value + '&yr=' + yearSelect.value;
		}
		
		//we cant do a normal form submission becuase the entire vehicle form is contained within a form for some reason. So we just need to do a redirect
		window.location.href = formAction;
		 
		//form.action = formAction;				
		//return true;
	}
}

//function used to change a querystring param
function UpdateQSParam(qs, param, value) {
	var retval = '';
	var params = qs.split("&");
	for(i=0;i<params.length;i++) {
		var parts = params[i].split("=");
		if(parts[0] == param) {
			retval = retval + "&" + parts[0] + "=" + value;
		}
		else {
			retval = retval + "&" + parts[0] + "=" + parts[1];
		}
	}
	
	//return the modified qs without the leading '&'
	return retval.substring(1);
}

//function used to remove a param from the string passed in
function RemoveQSParam(qs, param) {
	var retval = '';
	var params = qs.split("&");
	for(i=0;i<params.length;i++) {
		var parts = params[i].split("=");
		if(parts[0] != param) {
			retval = retval + "&" + parts[0] + "=" + parts[1];
		}
	}
	
	//return the modified qs without the leading '&'
	return retval.substring(1);
}