/****************************************
 *Functions for pole capacity calculator*
 *By: Zernyu                            *
 ****************************************/

var epaTotal = 0;
var weightTotal = 0;
var epa;
var weight;
var loaded = true;
var selectFix = "";
var req;
var xmlData;
var itemTree;
var fixFound = new Array();
var tabcount = 1;

function init(){
    Event.observe($("polecontainer"), 'keypress', waitBit.bindAsEventListener(this));
}
function addElement(){
    var buttoncont	= $("buttoncont");
    var fixturecont = $("fixturecont");
    var epacont     = $("epacont");
    var weightcont  = $("weightcont");
    var amount = $("amount");
    amount.value++;
    if(amount.value > 1){
        var deladd = $("addcont" + (amount.value-1));
        if(navigator.appName == "Microsoft Internet Explorer"){
            var arVersion = navigator.appVersion.split("MSIE")
            var version = parseFloat(arVersion[1])
            if (version >= 8.0){
                deladd.setAttribute("class", "polebuttons");
            }
            else
                deladd.setAttribute("className", "polebutton");
        }else
            deladd.setAttribute("class", "polebutton");
        deladd.setAttribute("value", " ");
        deladd.onclick = function(){};
    }
    var newadd = document.createElement("input");
    var newaddid = "addcont" + $F(amount);
    newadd.setAttribute("id", newaddid);
    newadd.setAttribute("type", "button");
    newadd.setAttribute("value", "+");
    setWidth(newadd, 1);
    buttoncont.appendChild(newadd);
    newadd.onclick = function(){
        addElement();
    };
    var newdelete = document.createElement("input");
    var newdeleteid = "deletecont" + $F(amount);
    newdelete.setAttribute("id", newdeleteid);
    newdelete.setAttribute("type", "button");
    newdelete.setAttribute("value", "-");
    setWidth(newdelete, 1);
    buttoncont.appendChild(newdelete);
    newdelete.onclick = function(){
        remElement(this.getAttribute("id"));
    };
    var newfixturecont = document.createElement("input");
    var newfixturecontid = "fixturecont" + $F(amount);
    newfixturecont.setAttribute("id", newfixturecontid);
    newfixturecont.setAttribute("type", "text");
    newfixturecont.setAttribute("value", "");
    newfixturecont.setAttribute("tabIndex", tabcount);
    newfixturecont.setAttribute("class", "polefixture");
    newfixturecont.style.background = "#ffffff";
    newfixturecont.style.color = "#000000";
    setWidth(newfixturecont);
    fixturecont.appendChild(newfixturecont);
    newfixturecont.onfocus = function(){
        selectFix = this.id;
    };
    newfixturecont.onblur  = function(){
        selectFix = "";
    };
    var newepacont = document.createElement("input");
    var newepacontid = "epacont" + $F(amount);
    newepacont.setAttribute("id", newepacontid);
    newepacont.setAttribute("type", "text");
    newepacont.setAttribute("value", "");
    newepacont.setAttribute("tabIndex", tabcount);
    newepacont.setAttribute("class", "polefixture");
    newepacont.style.background = "#ffffff";
    newepacont.style.color = "#000000";
    setWidth(newepacont, 0);
    epacont.appendChild(newepacont);
    var newweightcont = document.createElement("input");
    var newweightcontid = "weightcont" + $F(amount);
    newweightcont.setAttribute("id", newweightcontid);
    newweightcont.setAttribute("type", "text");
    newweightcont.setAttribute("value", "");
    newweightcont.setAttribute("tabIndex", tabcount);
    newweightcont.setAttribute("class", "polefixture");
    newweightcont.style.background = "#ffffff";
    newweightcont.style.color = "#000000";
    setWidth(newweightcont);
    weightcont.appendChild(newweightcont);
    tabcount++;
}
function setWidth(element, set){
    switch(set){
        case 0:
            if(navigator.appName == "Microsoft Internet Explorer"){
                element.style.setAttribute("width", "80%");
                element.style.setAttribute("height", "20px");
            }
            else
                element.setAttribute("style", "width: 80%; height: 20px;");
            break;
        case 1:
            if(navigator.appName == "Microsoft Internet Explorer"){
                var arVersion = navigator.appVersion.split("MSIE")
                var version = parseFloat(arVersion[1])
                if (version >= 8.0){
                    element.setAttribute("class", "polebuttons");
                }
                else
                    element.setAttribute("className", "polebuttons");
                element.style.setAttribute("marginTop", "2px");
                element.style.setAttribute("marginLeft", "2px");
            }
            else{
                element.setAttribute("class", "polebuttons");
                element.setAttribute("style", "margin-left: 2px");
            }
            break;
        default:
            if(navigator.appName == "Microsoft Internet Explorer"){
                element.style.setAttribute("width", "100%");
                element.style.setAttribute("height", "20px");
            }
            else
                element.setAttribute("style", "width: 100%; height: 20px;");
            break;
    }
}
function remElement(deleteName){
    var amount = $("amount");
    if(amount.value > 1){
        var button = $("buttoncont");
        var fixture = $("fixturecont");
        var epa = $("epacont");
        var weight = $("weightcont");
        var eleID = deleteName.substring(10, deleteName.length);
        var addName		= "addcont"+eleID;
        var fixtureName = "fixturecont" + eleID;
        var epaName     = "epacont" + eleID;
        var weightName  = "weightcont" + eleID;
        var del	 = $(addName);
        var del0 = $(deleteName);
        var del1 = $(fixtureName);
        var del2 = $(epaName);
        var del3 = $(weightName);
        button.removeChild(del);
        button.removeChild(del0);
        fixture.removeChild(del1);
        epa.removeChild(del2);
        weight.removeChild(del3);
        amount.value--;
        fixIDs();
    }
    else{
        eraseValues(1);
        $("fixturecont1").value = "";
    }
    calculate();
}
function fixIDs(){
    var amount = $F("amount");
    if(amount > 0){
        var count = 1;
        var current = 1;
        while(count <= amount){
            var fixtureName = $("fixturecont"+current);
            if(typeof(fixtureName) != "undefined" && fixtureName != null){
                if(fixtureName.getAttribute("id") != ("fixturecont"+count)){
                    var addName = $("addcont"+current);
                    var deleteName = $("deletecont"+current);
                    var epaName = $("epacont"+current);
                    var weightName = $("weightcont"+current);
                    fixtureName.setAttribute("id", "fixturecont"+count);
                    addName.setAttribute("id", "addcont"+count);
                    deleteName.setAttribute("id", "deletecont"+count);
                    epaName.setAttribute("id", "epacont"+count);
                    weightName.setAttribute("id", "weightcont"+count);
                }
                count++;
            }
            current++;
        }
        var addbutton = $("addcont" + $F("amount"));
        if(navigator.appName == "Microsoft Internet Explorer"){
            var arVersion = navigator.appVersion.split("MSIE")
            var version = parseFloat(arVersion[1])
            if (version >= 8.0){
                addbutton.setAttribute("class", "polebuttons");
            }
            else
                addbutton.setAttribute("className", "polebuttons");
        }else
            addbutton.setAttribute("class", "polebuttons");
        addbutton.setAttribute("value", "+");
        addbutton.onclick = function(){
            addElement();
        };
    }
}
function calculate(){
    epaTotal = 0;
    weightTotal = 0;
    var len = $F("amount");
    for(var i = 1; i <= len; i++){
        if(!isNaN($F("epacont"+i)))
            if($F("epacont"+i) != "")
                epaTotal += parseFloat($F("epacont"+i));
        if(!isNaN($F("weightcont"+i)))
            if($F("weightcont"+i) != "")
                weightTotal += parseFloat($F("weightcont"+i));
    }
    if(!isNaN(epaTotal))
        $("epaTotal").innerHTML = Math.round(epaTotal*100)/100
    if(!isNaN(weightTotal))
        $("weightTotal").innerHTML = Math.round(weightTotal*100)/100;
    compare();
    findFix();
}
function calculatealt(){
    epaTotal = 0;
    weightTotal = 0;
    var len = $F("amount");
    for(var i = 1; i <= len; i++){
        if(!isNaN($F("epacont"+i)))
            if($F("epacont"+i) != "")
                epaTotal += parseFloat($F("epacont"+i));
        if(!isNaN($F("weightcont"+i)))
            if($F("weightcont"+i) != "")
                weightTotal += parseFloat($F("weightcont"+i));
    }
    if(!isNaN(epaTotal))
        $("epaTotal").innerHTML = Math.round(epaTotal*100)/100
    if(!isNaN(weightTotal))
        $("weightTotal").innerHTML = Math.round(weightTotal*100)/100;
    compare();
}
function waitBit(){
    var timeout;
    if(timeout)
        clearTimeout(timeout);
    setTimeout(calculate.bind(this), 50);
}
function changeWind(name){
    var poleID = $("windzone");
    var len = poleID.options.length;
    for(var i = 1 ; i < len; i++)
        poleID.remove(1);
    for(var wind in data[name]){
        var optn = document.createElement("OPTION");
        optn.text = wind;
        optn.value = wind;
        poleID.options.add(optn);
    }
    compare();
}
function windChanged(wind){
    if(wind != ""){
        var name = $F("pole");
        epa = data[name][wind][0];
        weight = data[name][wind][1];
        $("epaTot").innerHTML = epa;
        $("weightTot").innerHTML = weight;
    }
    else{
        $("epaTot").innerHTML = "";
        $("weightTot").innerHTML = "";
    }
    if($F("amount") == 0)
        addElement();
    compare();
}
function compare(){
    if($F("windzone") != "" && $F("amount") > 0){
        if(epaTotal <= epa)
            $("epaPass").innerHTML = "<span style='color: white'>OK</span>";
        else
            $("epaPass").innerHTML = "<span style='color: red'>OVER</span>";
        if(weightTotal <= weight)
            $("weightPass").innerHTML = "<span style='color: white'>OK</span>";
        else
            $("weightPass").innerHTML = "<span style='color: red'>OVER</span>";
    }
    else{
        $("epaPass").innerHTML = "";
        $("weightPass").innerHTML = "";
    }
}
function Tree(){
    this.fNode;
}

Tree.prototype.addNode = function(name, epa, weight){
    if(this.fNode == null){
        this.fNode = new node(name, epa, weight);
    }
    else{
        var temp = nodeCompare(name, this.fNode);
        if(name <= temp.name)
            temp.left = new node(name, epa, weight);
        else
            temp.right = new node(name, epa, weight);
    }
}
nodeCompare = function(name, node){
    if(name <= node.name)
        if(node.left != null)
            return nodeCompare(name, node.left);
    if(name > node.name)
        if(node.right != null)
            return nodeCompare(name, node.right);
    return node;
}
findFix = function(){
    if(selectFix != ""){
        var fixID = selectFix.substring(11, selectFix.length);
        var value = $F(selectFix).toUpperCase();
        var find = itemTree.treeSearch(value);
        if(find.name == value){
            inputValues(fixID, find);
            calculatealt();
        }
        else{
            if(fixFound[fixID]){
                eraseValues(fixID);
                calculatealt();
            }
        }
    }
}
inputValues = function(fixID, item){
    $("epacont"+fixID).value = item.epa;
    $("epacont"+fixID).disabled = true;
    $("weightcont"+fixID).value = item.weight;
    $("weightcont"+fixID).disabled = true;
    fixFound[fixID] = true;
}
eraseValues = function(fixID){
    $("epacont"+fixID).value = "";
    $("epacont"+fixID).disabled = false;
    $("weightcont"+fixID).value = "";
    $("weightcont"+fixID).disabled = false;
}
Tree.prototype.treeSearch = function(name){
    return nodeCompare(name, this.fNode);
}
function node(name, epa, weight){
    this.node = this;
    this.name   = name;
    this.epa    = epa;
    this.weight = weight;
    this.left = null;
    this.right = null;
}
function sendRequest(url){
    req = createXMLHTTPObject();
    req.open("GET",url,true);
    req.setRequestHeader('User-Agent','XMLHTTP/1.0');
    req.onreadystatechange = loadXML;
    if (req.readyState == 4) return;
    req.send(null);
}
function XMLHttpFactories(){
    return [
    function () {
        return new XMLHttpRequest()
        },
    function () {
        return new ActiveXObject("Msxml2.XMLHTTP")
        },
    function () {
        return new ActiveXObject("Msxml3.XMLHTTP")
        },
    function () {
        return new ActiveXObject("Microsoft.XMLHTTP")
        }
    ];
}
function createXMLHTTPObject() {
    var xmlhttp = false;
    var factories = XMLHttpFactories();
    for (var i=0;i<factories.length;i++) {
        try {
            xmlhttp = factories[i]();
        }
        catch (e) {
            continue;
        }
        break;
    }
    return xmlhttp;
}
function loadXML(){
    if (req.readyState == 4) {
        if (req.status == 200) {
            xmlData = req.responseXML;
            if(navigator.appName == "Microsoft Internet Explorer")
                $("loadingMessage").style.setAttribute("display", "none");
            else
                $("loadingMessage").setAttribute("style", "display: none");
            xmltoArray();
        }
    }
}
function xmltoArray(){
   var temp = xmlData.documentElement;
	itemTree = new Tree();
	var iName, iEPA, iWeight;
	//Random items in beginning of catalog database with invalid EPA
	for(var i = 3; i < temp.childNodes.length; i++){
		iName   = temp.childNodes[i].childNodes[0].childNodes[0].nodeValue;
		iEPA    = temp.childNodes[i].childNodes[1].childNodes[0].nodeValue;
		iWeight = temp.childNodes[i].childNodes[2].childNodes[0].nodeValue;
		itemTree.addNode(iName, iEPA, iWeight);
	}
}
