// ajax
// used to hide any elements - without having to wait for content to load
if (document.getElementById) {
    document.writeln('<' + 'link rel="stylesheet" href="/ll/css/2.0/hide.css" type="text/css"' + ' />');
}

/* global variables */

var elementSuffix = "Data.htm"; // added to end of 'formId' = url of data page for ajax

/* end - global variables */

function getHTTPObject() {
    var xhr = false;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try {
            xhr = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            try {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                xhr = false;
            }
        }
    }
    return xhr;
}

function setGenericDatePicker(theFormId, theIndexType) {
    if (!document.getElementById) return false;
    if (!document.getElementById(theFormId)) return false;
    document.getElementById(theFormId).onchange = function() {
        unLoadingDataAlert("loadingInfo");
        var data = ""; // reset 'data' to empty string
        for (var i = 0; i < this.elements.length; i++) {
            data += this.elements[i].name;
            data += "=";
            data += encodeURI(this.elements[i].value);
            data += "&";
        }
        //var action = theFormId + elementSuffix;
        return !sendData(data, theFormId, theIndexType);
    }
    return true;
}

function buildLoadingImageElement() {
    var imageElement = document.createElement("img");
    imageElement.setAttribute("src", "/ll/images/loading.gif");
    imageElement.setAttribute("alt", "loading...");
    imageElement.setAttribute("title", "data is loading, please wait...");
    return imageElement;
}

function loadingDataAlert(element, elementToBeInserted) {
    document.getElementById(element).appendChild(elementToBeInserted);
}

function loadingPanelDataAlert(element) {
    document.getElementById(element).style.cssText = "background: url(/ll/images/loadingSmall.gif) no-repeat 255px 2px;";
}

function unLoadingPanelDataAlert(element) {
    document.getElementById(element).style.backgroundImage = "none";
}

function errorLoadingDataAlert(element) {
    var errorSpan = document.createElement("span");
    errorSpan.setAttribute("id", "redErrorText");
    var alertText = document.createTextNode("Server not responding. Please try again later.");
    errorSpan.appendChild(alertText);
    document.getElementById(element).appendChild(errorSpan);
}

function errorLoadingPanelDataAlert(element) {
    document.getElementById(element).style.cssText = "background: url(/ll/images/loadingErrorSmall.gif) no-repeat 255px 2px;";
}

function unLoadingDataAlert(element) {
    document.getElementById(element).innerHTML = ""; // clear the image from 'element'
}

function prepareForm(theFormId, theIndexType) {
    if (!document.getElementById) return;
    if (!document.getElementById(theFormId)) return;
    setGenericDatePicker(theFormId, theIndexType); // enable datePicker functionality
    //change the action attribute to enable the ajax version
    var action = theFormId + elementSuffix;
    document.getElementById(theFormId).setAttribute("action", action);
    document.getElementById(theFormId).onsubmit = function() {
        unLoadingDataAlert("loadingInfo");
        var data = "";
        for (var i = 0; i < this.elements.length; i++) {
            data += this.elements[i].name;
            data += "=";
            data += encodeURI(this.elements[i].value);
            data += "&";
        }
        return !sendData(data, theFormId, theIndexType);
    }
}

function sendData(data, theFormId, theIndexType) {
    var request = getHTTPObject();
    if (request) {
        loadingDataAlert("loadingInfo", buildLoadingImageElement());
        // set a timeout - if no response abort request after 20 seconds
        var timer = setTimeout(function() {
            request.abort();
            unLoadingDataAlert("loadingInfo");
            errorLoadingDataAlert("loadingInfo");
        }, 20000);
        request.onreadystatechange = function() {
            parseResponse(request, theFormId, timer, theIndexType);
        };
        var filePath = "/ll/" + theIndexType + "data/indices/" + theFormId + elementSuffix;
        request.open("POST", filePath, true);
        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        request.send(data);
        data = "";
        return true;
    } else {
        return false;
    }
}

function parseResponse(request, theForm, theTimer, theIndexType) {
    if (request.readyState == 4) {
        if (request.status == 200 || request.status == 304) {
            var container = document.getElementById("container");
            container.innerHTML = request.responseText;
            clearTimeout(theTimer);
            unLoadingDataAlert("loadingInfo");
            prepareForm(theForm, theIndexType);
        }
    }
}

/* this function runs 'on load' and displays the initial data in the right hand panel */
function prepareFirstItemDataForDisplay() {
    var panelNum = 1;
    //check to see if there is company info to display, if not then places, vessels, people is this order ...
    var url;
    if (document.getElementById("tabsCompanies") || document.getElementById("tabsVessels") ||
        document.getElementById("tabsPlaces") || document.getElementById("tabsPeople")) {
        if (typeof $("#tabsCompanies #cComboOption1").attr("href") != 'undefined') {
            url = $("#tabsCompanies #cComboOption1").attr("href");
            $("#tabsCompanies").css("display", "block");
            sendLinkData(url, panelNum, "cO", "companyLink", false);
        } else if (typeof $("#tabsPlaces #pComboOption1").attr("href") != 'undefined') {
            url = $("#tabsPlaces #pComboOption1").attr("href");
            $("#tabsPlaces").css("display", "block");
            $("#tab2").addClass("selected");
            sendLinkData(url, panelNum, "pO", "placeLink", false);
        } else if (typeof $("#tabsVessels #vComboOption1").attr("href") != 'undefined') {
            url = $("#tabsVessels #vComboOption1").attr("href");
            $("#tabsVessels").css("display", "block");
            $("#tab3").addClass("selected");
            sendLinkData(url, panelNum, "vO", "vesselLink", false);
        } else if (typeof $("#tabsPeople #peComboOption1").attr("href") != 'undefined') {
            url = $("#tabsPeople #peComboOption1").attr("href");
            $("#tabsPeople").css("display", "block");
            $("#tab4").addClass("selected");
            sendLinkData(url, panelNum, "peO", "peopleLink", false);
        }
    }
}

function prepareDataPanelLinks(panelType, panelId, linkType) {
    if (!document.getElementById) return false;
    if (!document.getElementById(panelId)) return false;
    var dataLinks = document.getElementsByClassName(linkType);
    // loop through the links...
    for (var i = 0; i < dataLinks.length; i++) {
        dataLinks[i].onclick = function() {
            unLoadingPanelDataAlert(this.getElementsByTagName("span")[0].id); // clear any error messages
            var panelNum = this.id.match(/\d/g).join("");
            var url = this.getAttribute("href");
            return !sendLinkData(url, panelNum, panelType, linkType, false);
        }
    }
    return true;
}

function sendLinkData(url, panelNum, panelType, linkType, clickSource) {
    var request = getHTTPObject();
    if (request) {
        loadingPanelDataAlert(panelType + panelNum);
        var timer = setTimeout(function() {
            request.abort();
            unLoadingPanelDataAlert(panelType + panelNum);
            errorLoadingPanelDataAlert(panelType + panelNum);
        }, 20000);
        request.onreadystatechange = function() {
            parseResponseDataLinks(request, panelNum, panelType, linkType, clickSource, timer);
        };
        request.open("GET", url, true);
        request.send(null);
        return true;
    } else {
        return false;
    }
}

function parseResponseDataLinks(request, panelNum, panelType, linkType, clickSource, theTimer) {
    if (request.readyState == 4) {
        if (request.status == 200 || request.status == 304) {
            var targetDiv = document.getElementById(panelType + "Contents" + panelNum);
            //alert(panelType + "Contents" + panelNum);
            var ieClearFloats = "<div class='clearFloats'><!-- clear floats --></div>"; // todo rdc - remove horrible ie hack when alternative decided...
            targetDiv.innerHTML = request.responseText + ieClearFloats;
            //need to get the javascript on the page and run it to display the chart...
            var theResponse = request.responseText;
            var theScriptTag = '<script id="jsChart" type="text/javascript">';
            if (theResponse.indexOf(theScriptTag) >= 0) {
                var s = theResponse.split(theScriptTag);
                eval(s[1].substring(0, s[1].indexOf("</script>"))); // use eval to execute the text as js
            }
            clearTimeout(theTimer);
            unLoadingPanelDataAlert(panelType + panelNum);
            // slide the panels...
            togglePanels($("#" + panelType + panelNum), panelNum, panelType, $("a." + linkType).length, clickSource);
        }
    }
}

