/*jslint bitwise: true, browser: true, eqeqeq: true, immed: true, newcap: true, nomen: true, regexp: true, undef: true, white: true, indent: 4 */
/*global window*/
/*global ActiveXObject*/
/*global CartwrightUtil*/

var CartwrightPortal = {
    widgetdrag: {
        isdragged: 0,   		// Monitors if mouse is being dragged or not
        dragenabled: 0, 		// Turn mouse dragging off by setting this to 0: TODO: Try and get dragging to work!!
        startdragX: 0,
        startdragY: 0,
        initdragX: 0,
        initdragY: 0,
        /* get mouse location */

        startdrag: function(event, a) {
            if (this.dragenabled === 0) {
                return;
            }
            var d = document.getElementById(a);
            d.style.cursor = "move";
            this.isdragged = 1;
            this.startdragX = CartwrightUtil.mousePosition.getMouseX(event);
            this.startdragY = CartwrightUtil.mousePosition.getMouseY(event);
            this.initdragX = CartwrightUtil.elePosition.findPosX(d) - CartwrightUtil.elePosition.findPosX(document.getElementById('container'));
            this.initdragY = CartwrightUtil.elePosition.findPosY(d) - CartwrightUtil.elePosition.findPosY(document.getElementById('container'));
            d.style.position = "absolute";
            d.style.left = this.initdragX + "px";
            d.style.top = this.initdragY + "px";
        },
        enddrag: function(event, a) {
            this.isdragged = 0;
            document.getElementById(a).style.cursor = "auto";
        },
        processdrag: function(event, a) {
            if (this.isdragged === 1 && this.dragenabled === 1) {
                document.getElementById(a).style.left = this.initdragX + (CartwrightUtil.mousePosition.getMouseX(event) - this.startdragX) + "px";
                document.getElementById(a).style.top = this.initdragY + (CartwrightUtil.mousePosition.getMouseY(event) - this.startdragY) + "px";
            }
        }
    },


    mainwidgets: {
        moveup: function(a) {
            d1 = document.getElementById("content" + a);
            d2 = document.getElementById("content" + (a - 1));
            if (d1 && d2) {
                dp = d1.innerHTML;
                d1.innerHTML = d2.innerHTML;
                d2.innerHTML = dp;
            }
            return false;
        },
        movedown: function(a) {
            d1 = document.getElementById("content" + a);
            d2 = document.getElementById("content" + (a + 1));
            if (d1 && d2) {
                dp = d1.innerHTML;
                d1.innerHTML = d2.innerHTML;
                d2.innerHTML = dp;
            }
            return false;
        },
        hidecontent: function(a) {
            var d;
            d = document.getElementById(a);
            if (d.style.display === 'none') {
                // move offscreen and record length
                var l = d.style.left;
                d.style.left = "-5000px";  // restore off screeen, record height in f                
                d.style.height = 'auto';
                document.getElementById(a).style.display = 'block';
                var f = d.offsetHeight;
                d.style.height = "1px";
                d.style.left = l; // put back on screen
                this.grow(a, f);  // grow
            } else {
                d.style.height = d.offsetHeight + "px";
                var h = parseInt(d.style.height, 10);
                this.shrink(a, h);
            }
        },
        shrink: function(a, h) {
            var f = h;
            setTimeout(function() {
                if (h > 0) {
                    document.getElementById(a).style.height = h + 'px';
                    h = h - f / 10;
                    setTimeout(arguments.callee, 1);
                } else {
                    document.getElementById(a).style.display = 'none';
                    var ele = a.replace("content", "footer");
                    document.getElementById(ele).className = "footerdown";
                }
            }, 1);
        },
        grow: function(a, f) {
            setTimeout(function() {
                var h = parseInt(document.getElementById(a).style.height, 10);
                if (h < f) {
                    h = h + f / 10;
                    if (h > f) {
                        h = f;
                    }
                    document.getElementById(a).style.height = h + 'px';
                    setTimeout(arguments.callee, 1);
                } else {
                    var ele = a.replace("content", "footer");
                    document.getElementById(a).style.height = 'auto';
                    document.getElementById(ele).className = "footerup";
                }
            }, 1);
        }
    },
    showhiddenvehicles: function() { // Show/hide hidden vehicles on my page
        document.getElementById("vhidden").style.display = 'block';
        document.getElementById("voha").style.display = 'none';
    },
    showsearch: function() {
        if (document.forms['srch'].st.value !== "") {
            var xmlHttp;
            if (!(xmlHttp = new CartwrightUtil.Xhr())) { // Create AJAX object and check it exists
                alert("Sorry, your browser does not support this feature");
                return false; // If we couldn't create the AJAX return a message to the user
            }
            xmlHttp.onreadystatechange = function() {
                if (xmlHttp.readyState === 4) {
                    document.getElementById('srchres').innerHTML = xmlHttp.responseText;
                }
            };
            var getURL = "vehiclesearch.php?st=" + document.forms['srch'].st.value;
            document.getElementById('srchres').innerHTML = "Searching please wait";
            xmlHttp.open("GET", getURL, true);
            xmlHttp.send(null);
        }
    },
    ddtrainsearch: function() {

        var xmlHttp;
        if (!(xmlHttp = new CartwrightUtil.Xhr())) { // Create AJAX object and check it exists
            alert("Sorry, your browser does not support this feature");
            return false; // If we couldn't create the AJAX return a message to the user
        }
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState === 4) {
                document.getElementById('ddresult').innerHTML = xmlHttp.responseText;
            }
        };
        var getURL = "ddtrained2.php?search=" + document.forms['ddsearchform'].elements["ddsearch"].value;
        document.getElementById('ddresult').innerHTML = "Searching please wait";
        xmlHttp.open("GET", getURL, true);
        xmlHttp.send(null);

    },
    repopdoclst: function(ext) {
        if (!ext) {
            ext = "asp";
        }
        var d = document.getElementById("docvehiclelist");
        var xmlHttp;
        if (!(xmlHttp = new CartwrightUtil.Xhr())) { // Create AJAX object and check it exists
            alert("Sorry, your browser does not support this feature");
            return false; // If we couldn't create the AJAX return a message to the user
        }
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState === 4) {
                var docstring = '<ul class="docvehlist">' + xmlHttp.responseText + '</ul>';
                d.innerHTML = docstring;
            }
        };
        var geturl = 'docvehiclelist.' + ext + '?';
        geturl += 'st=' + document.forms['docsrchform'].st.value;
        d.innerHTML = "Retrieving your vehicles currently on hire, please wait...";
        xmlHttp.open("GET", geturl, true);
        xmlHttp.send(null);
    },
    filldiv: function(div, fleetnumber, rentalstartdate, servicecycle, ext, depot, custfleet) { /* Ajax code for updaing documents window */
        if (!ext) {
            ext = "asp";
        }
        var d = document.getElementById(div);
        var xmlHttp;
        if (!(xmlHttp = new CartwrightUtil.Xhr())) { // Create AJAX object and check it exists
            alert("Sorry, your browser does not support this feature");
            return false; // If we couldn't create the AJAX return a message to the user
        }
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState === 4) {
                var docstring = 'Currently viewing ';
                if (custfleet != "") {
                    docstring += custfleet + ' ';
                }
                docstring += fleetnumber;
                if (depot != "") {
                    docstring += ' from depot ' + depot;
                }
                docstring += '<ul class="doclist">' + xmlHttp.responseText + '</ul>';
                d.innerHTML = docstring;
            }
        };
        var geturl = 'docinc.' + ext + '?';
        geturl += 'fleetnumber=' + fleetnumber;
        geturl += '&rentalstartdate=' + rentalstartdate;
        geturl += '&servicecycle=' + servicecycle;
        geturl += '&handlerfunc=CartwrightPortal.opendocwindow';
        //prompt('',geturl)
        d.innerHTML = "Retrieving documents, please wait...";
        xmlHttp.open("GET", geturl, true);
        xmlHttp.send(null);
    },
    opendocwindow: function(doc, demo) { // Function to display document, or message when in demo mode 
        if (demo === 1) {
            document.getElementById("docview").innerHTML = '<iframe height="100%" width="100%" frameborder="0" src="pdf/sample.pdf"></iframe>';
        } else {
            var dochtml = '<iframe height="100%" width="100%" frameborder="0" src="' + doc.replace("\\", "/") + '"></iframe>'; // TODO: Don't use IFRAME?
            document.getElementById("docview").innerHTML = dochtml;
        }
    },
    changepass: function() {/* Display password dialog */
        if (document.getElementById('cp1').style.display === "none") {
            document.getElementById('cp1').style.display = 'block';
            document.getElementById('cp2').style.display = 'block';

        } else {
            document.getElementById('cp1').style.display = 'none';
            document.getElementById('cp2').style.display = 'none';
        }
    },
    showVOR: function() {/* Display password dialog */
        if (document.getElementById('vor1').style.display === "none") {
            document.getElementById('vor1').style.display = 'block';
            document.getElementById('vor2').style.display = 'block';

        } else {
            document.getElementById('vor1').style.display = 'none';
            document.getElementById('vor2').style.display = 'none';
        }
    },
    subfeedback: function(ext) {
        f = document.forms['feedback'].elements['comments'].value;
        var xmlHttp;
        if (!(xmlHttp = new CartwrightUtil.Xhr())) { // Create AJAX object and check it exists
            alert("Sorry, your browser does not support this feature");
            return false; // If we couldn't create the AJAX return a message to the user
        }
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState === 4) {
                document.getElementById("fb1").innerHTML = xmlHttp.responseText;
                document.forms["feedback"].elements["comments"].value = "";
                if (document.forms["feedback"].elements["name"]) {
                    document.forms["feedback"].elements["name"].value = "";
                    document.forms["feedback"].elements["contact"].value = "";
                }

            }
        };
        var geturl = 'subfeedback.php';
        var params = 'c=' + escape(f);
        if (document.forms["feedback"].elements["name"]) {
            params = params + "&name=" + escape(document.forms["feedback"].elements["name"].value);
            params = params + "&contact=" + escape(document.forms["feedback"].elements["contact"].value);
        }

        xmlHttp.open("POST", geturl, true);
        xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlHttp.setRequestHeader("Content-length", params.length);
        xmlHttp.setRequestHeader("Connection", "close");
        xmlHttp.send(params);
    },
    custacces: function(a, b, c) {
        var xmlHttp;
        if (!(xmlHttp = new CartwrightUtil.Xhr())) { // Create AJAX object and check it exists
            alert("Sorry, your browser does not support this feature");
            return false; // If we couldn't create the AJAX return a message to the user
        }
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState === 4) {
                document.getElementById("fb1").innerHTML = xmlHttp.responseText;
            }
        };
        var geturl = 'custaccess.php?a=' + a + '&b=' + b + '&c=' + c;
        xmlHttp.open("GET", geturl, true);
        xmlHttp.send(null);
    },
    modaccess: function(a, b, c) {
        var xmlHttp;
        if (!(xmlHttp = new CartwrightUtil.Xhr())) { // Create AJAX object and check it exists
            alert("Sorry, your browser does not support this feature");
            return false; // If we couldn't create the AJAX return a message to the user
        }
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState === 4) {
                document.getElementById("fb1").innerHTML = xmlHttp.responseText;
            }
        };
        var geturl = 'modaccess.php?a=' + a + '&b=' + b + '&c=' + c;
        xmlHttp.open("GET", geturl, true);
        xmlHttp.send(null);
    },
    checkfrm: function() {
        var f = document.forms['inp'];
        var d = f.requireddated.value;
        if (d === "" || !CartwrightUtil.isNumeric(d, 1) || d > 31 || d === 0) {
            alert("Required date - day is not valid");
            return 1;
        }
        d = f.requireddatem.value;
        if (d === "" || !CartwrightUtil.isNumeric(d, 1) || d > 12 || d === 0) {
            alert("Required date - month is not valid");
            return 1;
        }
        d = f.requireddatey.value;
        if (d !== "08" && d !== "09" && d !== "10") {
            alert("Required date - year is not valid");
            return 1;
        }
        d = f.numberoftrailers.value;
        if (d === "" || !CartwrightUtil.isNumeric(d, 1)) {
            alert("Please enter valid number of trailers");
            return 1;
        }
        d = f.height.value;
        if (!CartwrightUtil.isNumeric(d)) {
            alert("Please enter valid height in metres");
            return 1;
        }
        f.submit();
    },
    openAsdaWin: function() {
        if (window.location.hash != "") {
            this.asdawin(window.location.hash.replace("#",""));
        }
    },
    asdawin: function(id) {
        window.location.hash = id;
        document.getElementById('asdadata').innerHTML = 'Loading';
        document.getElementById('asdadatawindow').style.display = 'block';
        var xmlHttp;
        if (!(xmlHttp = new CartwrightUtil.Xhr())) { // Create AJAX object and check it exists
            alert("Sorry, your browser does not support this feature");
            return false; // If we couldn't create the AJAX return a message to the user
        }
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState === 4) {
                document.getElementById("asdadata").innerHTML = xmlHttp.responseText;
            }
        };
        var geturl = 'asdainc.php?depot=' + id;
        xmlHttp.open("GET", geturl, true);
        xmlHttp.send(null);
    },
    hideasdawin: function() {
        document.getElementById('asdadatawindow').style.display = 'none';
    },
    loadassetcostdata: function() {
        if (document.getElementById('assetcostload')) {
            var xmlHttp;
            if (!(xmlHttp = new CartwrightUtil.Xhr())) { // Create AJAX object and check it exists
                alert("Sorry, your browser does not support this feature");
                return false; // If we couldn't create the AJAX return a message to the user
            }
            xmlHttp.onreadystatechange = function() {
                if (xmlHttp.readyState === 4) {
                    document.getElementById("assetcostload").innerHTML = xmlHttp.responseText;
                }
            };
            var geturl = 'assetcostdata.php';
            xmlHttp.open("GET", geturl, true);
            xmlHttp.send(null);
        }
    },
    asdawintool: function(id) {
        document.getElementById('asdadata').innerHTML = 'Loading';
        document.getElementById('asdadatawindow').style.display = 'block';
        var xmlHttp;
        if (!(xmlHttp = new CartwrightUtil.Xhr())) { // Create AJAX object and check it exists
            alert("Sorry, your browser does not support this feature");
            return false; // If we couldn't create the AJAX return a message to the user
        }
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState === 4) {
                document.getElementById("asdadata").innerHTML = xmlHttp.responseText;
            }
        };
        var geturl = 'asdatools.php';
        xmlHttp.open("GET", geturl, true);
        xmlHttp.send(null);

    },
    asdawinrep: function(id) {
        document.getElementById('asdadata').innerHTML = 'Loading';
        document.getElementById('asdadatawindow').style.display = 'block';
        document.getElementById("asdadata").innerHTML = "Reports willl appear here, including KPI";

    },
    asdasearch: function() {
        document.getElementById('asdasearchresults').innerHTML = 'Loading';
        var xmlHttp;
        if (!(xmlHttp = new CartwrightUtil.Xhr())) { // Create AJAX object and check it exists
            alert("Sorry, your browser does not support this feature");
            return false; // If we couldn't create the AJAX return a message to the user
        }
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState === 4) {
                document.getElementById("asdasearchresults").innerHTML = xmlHttp.responseText;
            }
        };
        var geturl = 'asdasearch.php?st=' + document.forms["asdasearch"].elements["search"].value;
        xmlHttp.open("GET", geturl, true);
        xmlHttp.send(null);
    },
    offVOR: function(fleetnumber, vorid) {
        var xmlHttp;
        if (!(xmlHttp = new CartwrightUtil.Xhr())) { // Create AJAX object and check it exists
            alert("Sorry, your browser does not support this feature");
            return false; // If we couldn't create the AJAX return a message to the user
        }
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState === 4) {
                document.getElementById("vor" + fleetnumber).style.display = "none";
            }
        };
        var geturl = 'offVOR.php?fleetnumber=' + fleetnumber + '&vorid=' + vorid;
        xmlHttp.open("GET", geturl, true);
        xmlHttp.send(null);

    },
    vendorCountdown: function() {
        var xmlHttp;
        if (!(xmlHttp = new CartwrightUtil.Xhr())) { // Create AJAX object and check it exists
            alert("Sorry, your browser does not support this feature");
            return false; // If we couldn't create the AJAX return a message to the user
        }
        that = this;
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState === 4) {
                resp = xmlHttp.responseText;
                var o = eval('(' + resp + ')');
                for (var ele in o) {
                    if (ele == "padder") {

                    } else if (o[ele]["approved"]) {

                        document.getElementById("cd" + o[ele]["id"]).innerHTML = "Approved by Customer";
                    } else {
                        that.countdown(o[ele]["id"], eval(o[ele]["date"]))
                    }
                }
            }
        };
        var geturl = 'jobtimes.php';
        xmlHttp.open("GET", geturl, true);
        xmlHttp.send(null);

    },
    countdown: function(id, datefrom) {

        setInterval(function() {
            var currDate = new Date();
            var ms = datefrom - currDate + (4 * 1000 * 3600);
            ms = ms / 1000;
            hr = Math.floor(ms / 3600);
            min = Math.floor(ms / 60) - (hr * 60);
            sec = Math.floor(ms - (hr * 3600) - (min * 60));
            if (sec < 10) sec = "0" + sec;
            if (min < 10) min = "0" + min;
            if (ms > 0) {
                document.getElementById("cd" + id).innerHTML = "Time to go: " + hr + ":" + min + ":" + sec;
            } else {
                document.getElementById("cd" + id).innerHTML = "No answer in time - Approved";
            }
        }, 1000);
    },
    submitBookOut: function() {
        if (document.forms["bookout"].elements["MOT"]) {
            if (document.forms["bookout"].elements["MOT"].value == "") {
                alert("Please attach MOT document");
                return;
            }
        }
        if (document.forms["bookout"].elements["service"]) {
            if (document.forms["bookout"].elements["service"].value == "") {
                alert("Please attach service document");
                return;
            }
        }
        if (document.forms["bookout"].elements["LOLER"]) {
            if (document.forms["bookout"].elements["LOLER"].value == "") {
                alert("Please attach LOLER document");
                return;
            }
        }
        if (document.forms["bookout"].elements["weighttest"]) {
            if (document.forms["bookout"].elements["weighttest"].value == "") {
                alert("Please attach weight test document");
                return;
            }
        }
        if (document.forms["bookout"].elements["ddservice"]) {
            if (document.forms["bookout"].elements["ddservice"].value == "") {
                alert("Please attach double deck service document");
                return;
            }
        }
        document.forms["bookout"].submit();

    },
    updatevendordamage: function(t) {
        if (!CartwrightUtil.isNumeric(t.value)) {
            alert("Please enter a valid number");
            t.value = "0";
            return 0;
        }
        f = document.forms["damageform"];
        t = (parseFloat(f.elements["hours"].value) * parseFloat(f.elements["hourlyrate"].value)) + parseFloat(f.elements["partprice"].value);
        tnew = Math.round(t * 100) / 100;
        f.elements["price"].value = tnew;
        document.getElementById("totalprice").innerHTML = tnew;




    }

};

