// load the button images
loadingImg = new Image();
loadingImg.src = "../images/loading.gif";

// global flag
var isIE = false;

// global request and XML document objects
var req;

// the cartax xml file
var url = "../cartax.xml";

// retrieve XML document (reusable generic function);
// parameter is URL string (relative or complete) to
// an .xml file whose Content-Type is a valid XML
// type, such as text/xml; XML source must be from
// same domain as HTML file
function loadCarTaxXMLDoc(process) {
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = process;
        req.open("GET", url, true);
        req.send(null);
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        isIE = true;
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = process;
            req.open("GET", url, true);
            req.send();
        }
    }
}

// handle onreadystatechange event of req object
function processItemList() {
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            buildItemList();
         } else {
            alert("There was a problem retrieving the XML data:\n" +
                req.statusText);
         }
    }
}

// handle onreadystatechange event of req object
function processModelList() {
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            buildModelList();
         } else {
            alert("There was a problem retrieving the XML data:\n" +
                req.statusText);
         }
    }
}

// handle onreadystatechange event of req object
function processPriceList() {
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            buildPriceList();
         } else {
            alert("There was a problem retrieving the XML data:\n" +
                req.statusText);
         }
    }
}

// retrieve text of an XML document element, including
// elements using namespaces
function getElementTextNS(prefix, local, parentElem, index) {
    var result = "";
    if (prefix && isIE) {
        // IE/Windows way of handling namespaces
        result = parentElem.getElementsByTagName(prefix + ":" + local)[index];
    } else {
        // the namespace versions of this method
        // (getElementsByTagNameNS()) operate
        // differently in Safari and Mozilla, but both
        // return value with just local name, provided
        // there aren't conflicts with non-namespace element
        // names
        result = parentElem.getElementsByTagName(local)[index];
    }
    if (result) {
        // get text, accounting for possible
        // whitespace (carriage return) text nodes
        if (result.childNodes.length > 1) {
            return result.childNodes[1].nodeValue;
        } else {
            if (result.firstChild) {
                return result.firstChild.nodeValue;
            } else {
                return null;
            }
        }
    } else {
        return "n/a";
    }
}

// fill with items from
// the current XML document
function buildCarTaxItemList() {
    var model = document.getElementById("model");
    var modelid = model.options[model.selectedIndex].value;
    
    var taxband = document.getElementById("taxband");
    var taxbandid = taxband.options[taxband.selectedIndex].value;
    
    var metallic = document.getElementById("metallic");
    var metallicid = metallic.options[metallic.selectedIndex].value;
    
    //alert(modelid + ", " + taxbandid + ", " + metallicid);
    
    var listdiv = document.getElementById("tax-container");
    listdiv.innerHTML = "";
    var items = req.responseXML.getElementsByTagName("Vehicle");
    // loop through <Item> elements, and add each nested
    // <title> element to Topics select element
    for (var i = 0; i < items.length; i++) {
        var id = getElementTextNS("", "Id", items[i], 0);
        if (id == modelid) {
            var div = document.createElement("div");
            
            var co2 = getElementTextNS("", "CO2Emissions", items[i], 0);
            var desc = getElementTextNS("", "Description", items[i], 0);
            var p11d;
            var atb;
            var blk;
            
            if (taxbandid == 22) {
                if (metallicid == "NM") {
                    p11d = getElementTextNS("", "NonMetallicP11DValue", items[i], 0);
                    blk = getElementTextNS("", "NonMetallic22MonthlyBLK", items[i], 0);
                    atb = getElementTextNS("", "NonMetallicAnnualTaxableBenefit", items[i], 0);
                } else {
                    p11d = getElementTextNS("", "MetallicP11DValue", items[i], 0);
                    blk = getElementTextNS("", "Metallic22MonthlyBLK", items[i], 0);
                    atb = getElementTextNS("", "MetallicAnnualTaxableBenefit", items[i], 0);
                }
            } else {
                if (metallicid == "NM") {
                    p11d = getElementTextNS("", "NonMetallicP11DValue", items[i], 0);
                    blk = getElementTextNS("", "NonMetallic40MonthlyBLK", items[i], 0);
                    atb = getElementTextNS("", "NonMetallicAnnualTaxableBenefit", items[i], 0);
                } else {
                    p11d = getElementTextNS("", "MetallicP11DValue", items[i], 0);
                    blk = getElementTextNS("", "Metallic40MonthlyBLK", items[i], 0);
                    atb = getElementTextNS("", "MetallicAnnualTaxableBenefit", items[i], 0);
                }
            }

            var text = "";
            text += "<div id=\"cartax-header\">Tax Calculator</div>";
            text += "<div id=\"cartax-content\">";
            text += "<p class=\"bold\">" + desc + "</p>";
            text += "<p>P11D Value: &pound;" + p11d + "</p>";
            text += "<p>CO2 Emissions: " + co2 + "g/km</p>";
            text += "<p>Annual Taxable Benefit: &pound;" + atb + "</p>";
            text += "<p>Monthly BLK: &pound;" + blk + "</p>";
            text += "</div>";
            text += "<div class=\"clear\">&nbsp;</div>";
            text += "<p class=\"smallprint\">The result of this company car calculation is based on a " +
                    "standard specification vehicle with no optional equipment. This calculator is intended " +
                    "as a guide only. Accordingly, we recommend that you seek proper advice regarding your " +
                    "circumstances. This calculator should not be relied on as a substitute for such advice.</p>";

            div.innerHTML = text;
            listdiv.appendChild(div);
            break;
        } else {
            continue;
        }
    }
}

function buildModelList() {
    var select = document.getElementById("model");
    while (select.length > 0) {
        select.remove(0);
    }
    var items = req.responseXML.getElementsByTagName("Vehicle");
    // loop through <Vehicle> elements, and add each nested
    // <Description> element to model select element
    for (var i = 0; i < items.length; i++) {        
        var id = getElementTextNS("", "Id", items[i], 0);
        var desc = getElementTextNS("", "Description", items[i], 0);
        
        var opt;
        opt = document.createElement("option") ;
        //opt.value = id;
        opt.setAttribute('value', id);
        // opt.text = desc;
        var txt = document.createTextNode(desc);
        opt.appendChild(txt);

        select.appendChild(opt)
    }
}

function buildPriceList() {
    var listdiv = document.getElementById("p11d-container");
    listdiv.innerHTML = "";
    var items = req.responseXML.getElementsByTagName("Vehicle");
    var text = "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" id=\"p11d-price-table\">";
    text += "<tr>";
    text += "<th rowspan=\"2\" class=\"table-header-left\">Model</th>";
    text += "<th rowspan=\"2\">CO2 Emissions (g/km)</th>";
    text += "<th colspan=\"4\">Non-Metallic</th>";
    text += "<th colspan=\"4\">Metallic</th>";
    text += "</tr>";
    text += "<tr>";
    text += "<th>Annual Tax Benefit</th>";
    text += "<th>P11D Value</th>";
    text += "<th>22% Monthly BLK</th>";
    text += "<th>40% Monthly BLK</th>";
    text += "<th>Annual Tax Benefit</th>";
    text += "<th>P11D Value</th>";
    text += "<th>22% Monthly BLK</th>";
    text += "<th>40% Monthly BLK</th>";
    text += "</tr>";
    
    var run = 1;
    var leftrowclass = "table-row-left";
    var rowclass = "table-row";
    
    for (var i = 0; i < items.length; i++) {
        var div = document.createElement("div");
        
        var desc = getElementTextNS("", "Description", items[i], 0);
        var co2 = getElementTextNS("", "CO2Emissions", items[i], 0);
        var nmp11d = getElementTextNS("", "NonMetallicP11DValue", items[i], 0);
        var nm22blk = getElementTextNS("", "NonMetallic22MonthlyBLK", items[i], 0);
        var nm40blk = getElementTextNS("", "NonMetallic40MonthlyBLK", items[i], 0);
        var nmatb = getElementTextNS("", "NonMetallicAnnualTaxableBenefit", items[i], 0);
        var mp11d = getElementTextNS("", "MetallicP11DValue", items[i], 0);
        var m22blk = getElementTextNS("", "Metallic22MonthlyBLK", items[i], 0);
        var m40blk = getElementTextNS("", "Metallic40MonthlyBLK", items[i], 0);
        var matb = getElementTextNS("", "MetallicAnnualTaxableBenefit", items[i], 0);
        
        if (run == 2) {
            run = 1;
            leftrowclass = "table-row-alt-left";
            rowclass = "table-row-alt";
        } else {
            leftrowclass = "table-row-left";
            rowclass = "table-row";
            run++;
        }
        
        text += "<tr>";
        text += "<td class=\"" + leftrowclass + "\">" + desc + "</td>";
        text += "<td class=\"" + rowclass + "\">" + co2 + "</td>";
        text += "<td class=\"" + rowclass + "\">&pound;" + nmatb + "</td>";
        text += "<td class=\"" + rowclass + "\">&pound;" + nmp11d + "</td>";
        text += "<td class=\"" + rowclass + "\">&pound;" + nm22blk + "</td>";
        text += "<td class=\"" + rowclass + "\">&pound;" + nm40blk + "</td>";
        text += "<td class=\"" + rowclass + "\">&pound;" + matb + "</td>";
        text += "<td class=\"" + rowclass + "\">&pound;" + mp11d + "</td>";
        text += "<td class=\"" + rowclass + "\">&pound;" + m22blk + "</td>";
        text += "<td class=\"" + rowclass + "\">&pound;" + m40blk + "</td>";
        text += "</tr>";
    }
    
    text += "</table>";
    listdiv.innerHTML = text;
}

function populateModels() {
    try {
        loadCarTaxXMLDoc(processModelList);
    } catch(e) {
        var msg = (typeof e == "string") ? e : ((e.message) ? e.message : "Unknown Error");
        alert("Unable to get XML data:\n" + msg);
        return;
    }
}

// loads chosen XML document
function calculateTax() {
    try {
        if (req) {
            buildCarTaxItemList();
        } else {
            loadCarTaxXMLDoc(processItemList);
            document.getElementById("tax-container").innerHTML = "<div style='height: 200px; text-align: center;'><h3 style='color: #999; margin-top: 50px;'>Loading</h3><img src='../images/loading.gif' alt='' /></div>";
        }
    } catch(e) {
        var msg = (typeof e == "string") ? e : ((e.message) ? e.message : "Unknown Error");
        alert("Unable to get XML data:\n" + msg);
        return;
    }
}

function populatePriceList() {
    try {
        loadCarTaxXMLDoc(processPriceList);
    } catch(e) {
        var msg = (typeof e == "string") ? e : ((e.message) ? e.message : "Unknown Error");
        alert("Unable to get XML data:\n" + msg);
        return;
    }
}