/*

    This code is copyright Fuel-Economy.co.uk 2006-2008.  Do not use
    it without consent.
     
    Some code featured here based on code found at:
    http://www.xmlhttprequest.org/ which is obviously their 
    copyright.

    Version History
    ===============
    22/06/06    Matt    Initial version - "classes" for data storage, 
                        functions related to Ajax.
    23/06/06    Matt    Function to toggle show/hide loading divs
    27/06/06    Matt    Modifications to allow "dynamic" band meter etc.
    28/07/07    Matt    Added a "G" case to the band meter...how did I miss this?!
			      		New function to make manufacturer names not all capitals.
	22/03/08	Matt	Firefox 3 wont accept a "top" value with a ; at the end
	 					anymore (e.g. "top: 10px;").
	 					Added a whitelist for the Prettified names - Bwm -> BMW etc.
*/

function ToggleShow(ElementID) {
	var ele = document.getElementById(ElementID);
	if (ele.style.display == 'none') {
		ele.style.display = 'inline';
	} else {
		ele.style.display = 'none';
	}
}

// Whitelist of non-Prettify names.
var Whitelist = "BMW TVR LTI"
function PrettifyName(Name) {
		
	if (Whitelist.indexOf(Name) >= 0) { return Name };
	
	var orig = Name;
	orig = orig.toLowerCase();
	var a = Name.substr(0,1);
	var b = orig.substring(1);
	return a + b;
	
}

var ManufacturerForm;
function ManufacturerCallback(xmlDoc) {
    try {
        var Root = xmlDoc.documentElement;
        var Manufacturers = xmlChildNodes(Root,"manufacturer");
        var ManufacturerFormDropDown = ManufacturerForm.Manufacturer;
        var FirstID = -1;
        ManufacturerFormDropDown.options.length=0;
        for (var i = 0; i < Manufacturers.length; ++i) {
            var Details = xmlAttributes(Manufacturers[i]);
            ManufacturerFormDropDown.options[ManufacturerFormDropDown.options.length] = new Option(PrettifyName(Details['name']),Details['manufacturerid']);
            if (FirstID < 0) {
                FirstID = Details['manufacturerid'];
            }
        }
        
        LoadModels(FirstID);
    } catch (Error) {
        alert("There was an error in ManufacturerCallback:\n" + Error.description);
    }
}

var ModelForm;
function ModelCallback(xmlDoc) {
    try {
        var Root = xmlDoc.documentElement;
        var Models = xmlChildNodes(Root,"model");
        var ModelFormDropDown = ModelForm.Model;
        var FirstID = -1;
        ModelFormDropDown.options.length=0;
        for (var i = 0; i < Models.length; ++i) {
            var Details = xmlAttributes(Models[i]);
            ModelFormDropDown.options[ModelFormDropDown.options.length] = new Option(Details['name'],Details['modelid']);
            if (FirstID < 0) {
                FirstID = Details['modelid'];
            }
        }
        LoadTrims(FirstID);
        ToggleShow("modelLoading");
    } catch (Error) {
        alert("There was an error in ModelCallback:\n" + Error);
    }
}

var TrimForm;
function TrimCallback(xmlDoc) {
    try {
        var Root = xmlDoc.documentElement;
        var Trims = xmlChildNodes(Root,"trim");
        var TrimFormDropDown = TrimForm.Trim;
        var FirstID = -1;
        TrimFormDropDown.options.length=0;
        for (var i = 0; i < Trims.length; ++i) {
            var Details = xmlAttributes(Trims[i]);
            TrimFormDropDown.options[TrimFormDropDown.options.length] = new Option(Details['name'],Details['vehicleid']);
            if (FirstID < 0) {
                FirstID = Details['vehicleid'];
            }
        }
        DisplayInfo(FirstID);
        ToggleShow("trimLoading");        
    } catch (Error) {
        alert("There was an error in TrimCallback:\n" + Error);
    }
}

var Urban;
var Extra;
var Combined;
var DetailsDiv;
function VehicleCallback(xmlDoc) {
    try {
        var Root = xmlDoc.documentElement;
        var Trims = xmlChildNodes(Root,"data");
        var TrimFormDropDown = TrimForm.Trim;
        for (var i = 0; i < Trims.length; ++i) {
            var Details = xmlAttributes(Trims[i]);
            DispalyInfo(Details['VEDBand'], Details['VEDPrice'], Details["CO2"], Details['MetricUrban'],Details['MetricExtraurban'],Details['MetricCombined'],Details['ImperialUrban'],Details['ImperialExtraurban'],Details['ImperialCombined']);
            Pointer = document.getElementById("pointer");
            var Band = Details['VEDBand'];
            PointerLabel = document.getElementById("pointerlabel");
            PointerLabel.innerHTML = Details['VEDBand'] + "&nbsp;&nbsp;&nbsp;&nbsp;" + parseInt(Details["CO2"]) + "g/KM";
            switch (Band) {
                case "A":
                    Move(-150);
                    break;
                case "B":
                    Move(-123);
                    break;
                case "C":
                    Move(-99);
                    break;
                case "D":
                    Move(-75);
                    break;
                case "E":
                    Move(-51);
                    break;
                case "F":
                    Move(-27);                  
                    break;
				case "G":
					Move(-3);
					break;
            }
            
        }
    } catch (Error) {
        alert("There was an error loading details: " + Error.description);
    }
}

function DispalyInfo(Band, Cost, CO2, MUrban, MExtra, MCombined,IUrban, IExtra, ICombined) {
    try {
        Urban.innerHTML = "Urban: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>" + IUrban + "</strong>MPG";
        Extra.innerHTML = "Extra Urban: &nbsp;&nbsp;<strong>" + IExtra + "</strong>MPG";
        Combined.innerHTML = "Combined: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>" + ICombined + "</strong>MPG";
    } catch (Error) {
        alert("There was an error in DisplayInfo: " + Error.description);
    }
    DetailsDiv.innerHTML = "Road Tax:<br/><span style=\"font-size: 220%; font-weight: bold;\">&pound;" + Cost + "</span><br/>Band " + Band + " (" + CO2 + "g/km)";    
}

var TempMove;
var FinalMove;
function Move(Pixels) {
    try {
        TempMove = GetTop(Pointer.style.top)
        FinalMove = Pixels;
        if (FinalMove == GetTop(Pointer.style.top)) {
            return;
        }   
        MoveIt();    
    } catch (Error) {
        alert("Error Move():\n" + Error.description);
    }
}

// This is STILL a bit nasty looking - refactor again at some point.
function MoveIt() {
    if (TempMove != FinalMove) {
        if (FinalMove < GetTop(Pointer.style.top)) {
            TempMove--;
            SetTop(TempMove);
            setTimeout('MoveIt()',10);        
        } else if (FinalMove > GetTop(Pointer.style.top)) {
            TempMove++;
            SetTop(TempMove);
            setTimeout('MoveIt()',10);   
        }
    } 
}

function SetTop(Value) {
    if (IsFirefox() > 0) {
        Pointer.style.top = Value + "px";
    } else {
        Pointer.style.top = Value;
    } 
}

function GetTop(Value) {
    var number = Value.substring(0,Value.length - 2)
    return parseInt(number);
}

function IsFirefox() {
    return navigator.userAgent.indexOf("Firefox");
}

// Ajax support functions beyond this point
// ========================================================================

var iRemoteProcedure=0;
var tRemoteProcedures={};
function RemoteProcedure(sUrl,fnOnLoad,fnOnPatience){
	this.req=null;
	this.fnOnLoad=null;
	this.id=++iRemoteProcedure;
	tRemoteProcedures[this.id]=this;
	this.timer=null;
	this.call(sUrl,fnOnLoad,fnOnPatience);
}
RemoteProcedure.prototype.call=function(url,fnOnLoad,fnOnPatience){
	this.fnOnLoad=fnOnLoad;
	this.fnOnPatience=fnOnPatience;
	this.timer=window.setTimeout('tRemoteProcedures['+this.id+'].showPatience()',500);
	var sRand=(url.indexOf('?')==-1?'?':'&')+'Rand='+Math.random();
	if (window.XMLHttpRequest){
		this.req=new XMLHttpRequest();
		this.req.onreadystatechange=new Function('tRemoteProcedures['+this.id+'].processReqChange()');
		this.req.open("GET",url+sRand,true);
		this.req.send(null);
	} else if (window.ActiveXObject){
		this.req=new ActiveXObject("Microsoft.XMLHTTP");
		if (this.req){
			this.req.onreadystatechange=new Function('tRemoteProcedures['+this.id+'].processReqChange()');
			this.req.open("GET",url+sRand,true);
			this.req.send();
		}
	}
}
RemoteProcedure.prototype.showPatience=function(){
	this.clearTimeout();
	if(this.fnOnPatience)
		this.fnOnPatience();
}
RemoteProcedure.prototype.clearTimeout=function(){
	if (this.timer!=null){
		window.clearTimeout(this.timer);
		this.timer=null;
	}
}
RemoteProcedure.prototype.processReqChange=function(){
	if (this.req.readyState==4){ // 4 means "loaded"
		this.clearTimeout();
		if (this.req.status==200){ // 200 means "OK"
			if(this.fnOnLoad)
				this.fnOnLoad(this.req.responseXML);
		}
		else
			alert("Error " + this.req.status + "\n" + this.req.statusText + "\n\n" + this.req.responseText.replace(/\r\n/g,''));
	}
}
function xmlChildNodes(oParent,sChildName){
	var tNodes=[];
	var e=oParent.firstChild;
	while(e!=null){
		if(e.nodeName==sChildName)
			tNodes.push(e);
		e=e.nextSibling;
	}
	return tNodes;
}
function xmlAttributes(oNode){
	var tAttributes={};
	for (var i=0; i<oNode.attributes.length; ++i)
		tAttributes[oNode.attributes.item(i).name]=oNode.attributes.item(i).value;
	return tAttributes;
}
