﻿var hrdl_debug = '';

function ParseXML(text) {
    try {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(text);
        return xmlDoc;
    }
    catch (e) {
        try {
            parser = new DOMParser();
            xmlDoc = parser.parseFromString(text, "text/xml");
            return xmlDoc;
        }
        catch (e) { alert("Your browser cannot handle this script."); }
    }
    return null;
}

function FormatXMLDateTime(str) {
    var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
        "(T([0-9*]{2}):([0-9*]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
        "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
    var d = str.match(new RegExp(regexp));
    return d[1] + '-' + d[3] + '-' + d[5] + '  ' + d[7] + ':' + d[8];
}

function FormatNumber(nStr) {
    x = nStr.split('.');
    x1 = x[0];
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1;
}


function scriptTransport() {
}

//
//------------------------------ initialize, open and send ------------------------------------------------------
//

scriptTransport.prototype.initialize = function() {
    this.readyState = 0;
}

scriptTransport.prototype.open = function(method, url, asynchronous) {
    if (method != 'GET')
    alert('Method should be set to GET when using cross site ajax');
    this.readyState = 1;
    /* little hack to get around the late assignment of onreadystatechange */
    this.respondToReadyState(1);
    this.onreadystatechange();
    this.url = url;
    this.userAgent = navigator.userAgent.toLowerCase();
    this.setBrowser();
}

scriptTransport.prototype.send = function(body) {
    this.readyState = 2;
    this.onreadystatechange();
    this.getScriptXS(this.url);
}

//
//------------------------------ actually do the request: setBrowser, prepareGetScriptXS, callback, getScriptXS ----------
//

scriptTransport.prototype.setBrowser = function(body) {
    scriptTransport.prototype.browser = {
        version: (this.userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1],
        safari: /webkit/.test(this.userAgent),
        opera: /opera/.test(this.userAgent),
        msie: /msie/.test(this.userAgent) && !/opera/.test(this.userAgent),
        mozilla: /mozilla/.test(this.userAgent) && !/(compatible|webkit)/.test(this.userAgent),
        konqueror: this.userAgent.match(/konqueror/i)
        };
}

scriptTransport.prototype.callback = function() {
    this.status = 200;
    try {
        hrdl_debug += this.suffix + '->';
        xmldoc = ParseXML(eval('HrdlogResponse' + this.suffix + '()'));
        hrdl_debug += xmldoc.text + '<br>';
        try {
            this.node.removeNode(true);
        } catch (e) {
            try {
                this.node.parentNode.removeChild(this.node);
            } catch (e) { }
        }
        clearInterval(this.checkTimer);
        this.responseXML = xmldoc;
        this.readyState = 4;
    }
    catch (e) { }
    this.onreadystatechange();
}

scriptTransport.prototype.getScriptXS = function() {

    if (typeof scriptTransport.counter == 'undefined')
        scriptTransport.counter = 0;
    this.suffix = scriptTransport.counter.toString();
    scriptTransport.counter++;

    /* determine arguments */
    var arg = {
        'url': null
    }
    arg.url = arguments[0] + '&suffix=' + this.suffix;
    hrdl_debug += '==>' + arg.url + '<br>';

    /* generate <script> node */
    this.node = document.createElement('SCRIPT');
    this.node.type = 'text/javascript';
    this.node.src = arg.url;

    /* FF and Opera properly support onload. MSIE has its own implementation. Safari and Konqueror need some polling */

    var instance = this;

    this.timepassed = 0;
    this.checkTimer = setInterval(function() {
        instance.callback();
        instance.timepassed = instance.timepassed++;
        if (instance.timepassed > 100)
            clearInterval(instance.checkTimer);
    }, 100);

    // MSIE
    if (this.browser.msie) {
        this.node.onreadystatechange = function() {
            if (this.readyState == "complete" || this.readyState == "loaded")
                instance.callback();
        }
        // FIREFOX

    } else if (this.browser.mozilla) {
        this.node.onload = function() { instance.callback(); };
    }


    /* inject <script> node into <head> of document */
    this.readyState = 3;
    this.onreadystatechange();
    var head = document.getElementsByTagName('HEAD')[0];
    head.appendChild(this.node);
    //alert(head.innerHTML);

}

//
//------------------------------ Don't complain when these are called: setRequestHeader and onreadystatechange ----------
//

scriptTransport.prototype.setRequestHeader = function() {
}
scriptTransport.prototype.onreadystatechange = function() {
}
scriptTransport.prototype.respondToReadyState = function() {
}

function BaseXMLHttpRequest() {
    var http_request = false;

    if (window.XMLHttpRequest) {
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType)
            http_request.overrideMimeType('text/xml');
    } else if (window.ActiveXObject) {
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) { }
        }
    }
    return http_request;
}

function Async() {
    this._xmlhttp = new scriptTransport();
}

function Async_req(url, obj) {
    var instance = this;

    this._xmlhttp.open('GET', url, true);
    this._xmlhttp.onreadystatechange = function() {
        switch (instance._xmlhttp.readyState) {
            case 1:
                instance.loading();
                break;
            case 2:
                instance.loaded();
                break;
            case 3:
                instance.interactive();
                break;
            case 4:
                instance.complete(instance._xmlhttp.status, instance._xmlhttp.statusText, instance._xmlhttp.responseText, instance._xmlhttp.responseXML, obj);
                break;
        }
    }
    this._xmlhttp.send(null);
}

function Async_loading() {
}
function Async_loaded() {
}       
function Async_interactive() {
}
function Async_complete(status, statusText, responseText, responseXML, obj) {
}

Async.prototype.loading = Async_loading;
Async.prototype.loaded = Async_loaded;
Async.prototype.interactive = Async_interactive;
Async.prototype.complete = Async_complete;
Async.prototype.req = Async_req;

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(elt) {
        var len = this.length;
        for (idx = 0; idx < len; idx++) {
            if (idx in this & this[idx] === elt)
                return idx;
        }
        return -1;
    }
}

function HrdLog(qrz) {
    this._qrz = qrz;
    this._showBandSlots = false;
    this._showLinks = true;
    this._txtSelectQrz = '';
    this._txtQsoImage = '';
    this._txtLastQso = '';
    this._txtLinks = '';
    this._txtLoadCallsign = '';
    this._txtReqCallsign = '';
    this._txtOnAir = '';
    this._numQSO = 10;
    this._txtBanner = '<p align="center"><a href="http://www.hrdlog.net" target="_blank">Web Logbook (HRDLOG.net) by IW1QLH</a></p>';
    this._errMsg = '';
    this._host = (location.hostname == 'localhost') ? '' : 'http://xml.hrdlog.net/';
    this._allfields = true;
    this._container = 'hrdlog';
    this._lastLoadOnAir = new Date(2000, 1, 1);
    this.BackgroundColor = '#F6F4EB';
    this.RowColor = '#FFFFFF';
    this.AlternatingRowColor = '#F6F4EB';
    this._managedQrz = new Array();
    this._userData = null;
    this.Update();
}

HrdLog.prototype.LoadLastQso = function(numQSO) {
    if (numQSO)
        this._numQSO = numQSO;
    else
        this._numQSO = 10;
    if (this._userData == null)
        this.LoadUserData();
    var async = new Async();
    async.complete = function(status, statusText, responseText, responseXML, obj) {
        if (status == 200) {
            txt = '<table class="hrdl_table">';
            txt += '<tr><th colspan="7">My last ' + obj._numQSO.toString() + ' QSO</th></tr>';
            if (obj._allfields)
                txt += '<tr><th>CALL</th><th>DX</th><th>TIME</th><th>BAND</th><th>MODE</th><th>RSTr</th><th>RSTs</th></tr>';

            var xmldoc = responseXML;
            var qsolist = xmldoc.getElementsByTagName('Logbooks');
            var trclass = 'odd';
            for (i = 0; ((i < qsolist.length) && (i < obj._numQSO)); i++) {
                qso = qsolist.item(i);
                txt += '<tr class="hrdl_' + trclass + '">';
                if (obj._allfields)
                    txt += '<td>' + qso.getElementsByTagName('QRZ')[0].childNodes[0].nodeValue + '</td>';
                txt += '<td>' + qso.getElementsByTagName('Station')[0].childNodes[0].nodeValue + '</td>';
                //txt += '<td>' + qso.getElementsByTagName('StartTime')[0].childNodes[0].nodeValue + '</td>';
                if (obj._allfields)
                    txt += '<td>' + FormatXMLDateTime(qso.getElementsByTagName('StartTime')[0].childNodes[0].nodeValue) + '</td>';
                txt += '<td>' + qso.getElementsByTagName('BandMHz')[0].childNodes[0].nodeValue + '</td>';
                txt += '<td>' + qso.getElementsByTagName('Mode')[0].childNodes[0].nodeValue + '</td>';
                if (obj._allfields) {
                    txt += '<td>' + qso.getElementsByTagName('ReportRecv')[0].childNodes[0].nodeValue + '</td>';
                    txt += '<td>' + qso.getElementsByTagName('ReportSent')[0].childNodes[0].nodeValue + '</td>';
                }
                txt += '</tr>';
                trclass = (trclass == 'odd') ? 'even' : 'odd';
            }
            txt += '</table><br/>';

            obj._txtLastQso = txt;
            obj.Update();

        } else {
            alert('Error\n' + statusText);
        }
    }

    async.req(this._host + 'hrdlog.aspx?qrz=' + this._qrz + '&numqso=' + this._numQSO.toString(), this);
    this._txtLastQso = 'Loading...';
}

HrdLog.prototype.SetColors = function(bgColor, rowColor, altColor) {
    this.BackgroundColor = bgColor;
    this.RowColor = rowColor;
    this.AlternatingRowColor = altColor;
}

HrdLog.prototype.SetNarrowView = function() {
    this._allfields = false;
}

HrdLog.prototype.EnableBandSlots = function() {
    this._showBandSlots = true;
}

HrdLog.prototype.DisableLinks = function() {
    this._showLinks = false;
}

HrdLog.prototype.EnableQsoMap = function(imageSize) {
    imgUrl = this._host + 'map.aspx?user=' + this._qrz;
    this._txtQsoImage = '<p align="center"><a href="' + imgUrl + '" target="_blank"><img src="' + imgUrl + '" width="' + imageSize + '" title="Click to enlarge."></a></p>';
    this.Update();
}

HrdLog.prototype.SetContainer = function(name) {
    this._container = name;
}

HrdLog.prototype.AddManaged = function(qrz) {
    if (this._managedQrz.length == 0) {
        this._managedQrz.push(this._qrz);
    }
    this._managedQrz.push(qrz);
    
    var txt = '';
    for (var i = 0; (i < this._managedQrz.length); i++) {
        txt += '<option value="' + this._managedQrz[i] + '">' + this._managedQrz[i] + '</option>';
    }
    this._txtSelectQrz = 'Select the station <select id="hrdl_qrz" onchange="ohrdlog.ChangeQrz(this);">' + txt + '</select>&nbsp;';
    
}

HrdLog.prototype.ChangeQrz = function(obj) {
    this._qrz = obj.value;
    this._txtReqCallsign = '';
    if (this._txtLastQso != '') {
        this.LoadLastQso();
    } else {
        this.Update();
    }
    var element = document.getElementById('hrdlog-oa');
    if (element != null) {
        element.innerHTML = '';
    }
}

HrdLog.prototype.LoadByCallsign = function() {
    var element = document.getElementById(this._container);
    var insideForm = false;
    while (element != null) {
        if (element.nodeName == 'FORM')
            insideForm = true;
        element = element.parentNode;
    }

    this._txtLoadCallsign = 'Enter your callsign <input type="text" name="hrdl_callsign" /><input type="button" value="Send" onclick="ohrdlog.RequestByCallsign(hrdl_callsign.value);" /><img id="hrdl_loading" src="http://www.hrdlog.net/images/indicator.gif" style="display:none" /><br/><br/>';
    if (!insideForm)
        this._txtLoadCallsign = '<form>' + this._txtLoadCallsign + '</form>';
    this.Update();

}

HrdLog.prototype.RequestByCallsign = function(callsign) {
    var element;
    var async = new Async();
    async.complete = function(status, statusText, responseText, responseXML, obj) {
        if (status == 200) {

            var xmldoc = responseXML;
            var qsolist = xmldoc.getElementsByTagName('Logbooks');
            var trclass = 'even';
            var txt = '';
            var MAX_QSO = 24;

            if (obj._showBandSlots && (qsolist.length > 0)) {
                var modes = ["CW", "PH", "RTTY", "DIG"];
                var bands = [6, 10, 12, 15, 17, 20, 30, 40, 80, 160];

                var qsobands = new Array(bands.length);
                for (i = 0; i < bands.length; i++)
                    qsobands[i] = new Array(modes.length);

                for (i = 0; i < qsolist.length; i++) {
                    qso = qsolist.item(i);
                    m = modes.indexOf(qso.getElementsByTagName('QMode')[0].childNodes[0].nodeValue);
                    b = bands.indexOf(parseInt(qso.getElementsByTagName('BandMHz')[0].childNodes[0].nodeValue));
                    qsobands[m][b] = 1;
                }

                txt += '<table class="hrdl_table">';
                txt += '<tr><td></td>';
                for (b = 0; b < bands.length; b++)
                    txt += '<td align="center">' + bands[b].toString() + '</td>';
                txt += '</tr>';
                trclass = 'odd';
                for (m = 0; m < modes.length; m++) {
                    txt += '<tr class="hrdl_' + trclass + '">';
                    txt += '<td>' + modes[m] + '</td>';
                    for (b = 0; b < bands.length; b++) {
                        txt += (qsobands[m][b] == undefined) ? '<td>&nbsp;</td>' : '<td align="center"><img src="http://www.hrdlog.net/images/check.png" width="20" height="20" /></td>';
                    }
                    txt += '</tr>';
                    trclass = (trclass == 'odd') ? 'even' : 'odd';
                }
                txt += '</table><hr/>';
            }

            trclass = 'odd';
            txt += '<table class="hrdl_table">';
            txt += '<tr><th colspan="8">Your QSOs</th></tr>';
            txt += '<tr><th>CALL</th><th>DX</th><th>TIME</th><th>BAND</th><th>MODE</th><th>RSTr</th><th>RSTs</th><th>';
            if ((obj._userData != null) && (obj._userData.oqrs_enabled == 'true'))
                txt += 'OQRS';
            txt += '</th></tr>';
            for (i = 0; i < qsolist.length; i++) {
                qso = qsolist.item(i);
                txt += '<tr class="hrdl_' + trclass + '">';
                txt += '<td>' + qso.getElementsByTagName('QRZ')[0].childNodes[0].nodeValue + '</td>';
                txt += '<td>' + qso.getElementsByTagName('Station')[0].childNodes[0].nodeValue + '</td>';
                //txt += '<td>' + qso.getElementsByTagName('StartTime')[0].childNodes[0].nodeValue + '</td>';
                txt += '<td>' + FormatXMLDateTime(qso.getElementsByTagName('StartTime')[0].childNodes[0].nodeValue) + '</td>';
                txt += '<td>' + qso.getElementsByTagName('BandMHz')[0].childNodes[0].nodeValue + '</td>';
                txt += '<td>' + qso.getElementsByTagName('Mode')[0].childNodes[0].nodeValue + '</td>';
                txt += '<td>' + qso.getElementsByTagName('ReportRecv')[0].childNodes[0].nodeValue + '</td>';
                txt += '<td>' + qso.getElementsByTagName('ReportSent')[0].childNodes[0].nodeValue + '</td>';
                txt += '<td>'
                if ((obj._userData != null) && (obj._userData.oqrs_enabled == 'true'))
                    txt += '<a href="http://www.hrdlog.net/Oqrs.aspx?user=' + obj._qrz + '" target="_blank"><img src="http://www.hrdlog.net/images/mail.jpg" title="Online QSL request"/></a>';
                txt += '</td>';
                txt += '</tr>';
                trclass = (trclass == 'odd') ? 'even' : 'odd';
            }
            txt += '<tr><td colspan="8" align="center">';
            if (qsolist.length == 0)
                txt += 'Sorry, no QSOs found.';
            else if (qsolist.length <= MAX_QSO)
                txt += qsolist.length.toString() + ' QSOs found.';
            else
                txt += 'More than ' + MAX_QSO.toString() + ' QSOs found.';

            txt += '</td></tr>';
            txt += '</table><hr/>';

            element = document.getElementById('hrdl_loading');
            if (element != null) {
                element.style.display = 'none';
            }

            obj._txtReqCallsign = txt;
            obj.Update();

        } else {
            alert('Error\n' + statusText);
        }
    }

    if (callsign != '') {
        element = document.getElementById('hrdl_loading');
        if (element != null) {
            element.style.display = '';
        }
        async.req(this._host + 'hrdlog.aspx?qrz=' + this._qrz + '&callsign=' + callsign, this);
        this._txtReqCallsign = 'Loading...';
    }
}

HrdLog.prototype.LoadOnAir = function() {
    var async = new Async();
    async.complete = function(status, statusText, responseText, responseXML, obj) {
        if (status == 200) {
            txt = '';

            var xmldoc = responseXML;
            var onairdoc = xmldoc.getElementsByTagName('OnAir');
            if (onairdoc.length == 1) {
                onair = onairdoc.item(0);
                if (onair.getElementsByTagName('oa_QRZ').length > 0) {
                    txt += '<img src="http://www.hrdlog.net/images/onair.gif" height="33" width="65" /><br/>';
                    txt += '<font size="+1">' + onair.getElementsByTagName('oa_QRZ')[0].childNodes[0].nodeValue + ' is on air</font><br/>';
                    txt += '<b>';
                    txt += FormatNumber(onair.getElementsByTagName('oa_Frequency')[0].childNodes[0].nodeValue) + '&nbsp;';
                    try {
                        txt += onair.getElementsByTagName('oa_Mode')[0].childNodes[0].nodeValue + '</b><br/>';
                        txt += onair.getElementsByTagName('oa_Radio')[0].childNodes[0].nodeValue + '<br/><br/>';
                    } catch (e) { }
                    //txt += onair.getElementsByTagName('oa_Status')[0].childNodes[0].nodeValue + '<br/>';
                }
            }

            element = document.getElementById('hrdlog-oa');
            if (element != null) {
                element.innerHTML = txt;
            }

        } else {
            alert('Error\n' + statusText);
        }
    }

    if ((new Date().getTime() - this._lastLoadOnAir.getTime()) > 14500) {
        this._lastLoadOnAir = new Date();
        async.req(this._host + 'hrdlog.aspx?onair=' + this._qrz, this);
    }
}

HrdLog.prototype.Run = function() {
    this._txtLastQso = '';
    this._txtLoadCallsign = '';
    this._txtReqCallsign = '';
    this._txtOnAir = '';
    element = document.getElementById(this._container);
    if (element != null) {
        this.LoadLastQso();
        this.LoadByCallsign();
    }
}

HrdLog.prototype.LoadUserData = function() {
    var async = new Async();
    async.complete = function(status, statusText, responseText, responseXML, obj) {
        if (status == 200) {
            var xmldoc = responseXML;
            var userlist = xmldoc.getElementsByTagName('UserData');
            if (userlist.length == 1) {
                var user = userlist.item(0);
                obj._userData = {
                    'callsign': user.getElementsByTagName('callsign')[0].childNodes[0].nodeValue,
                    'log_url': user.getElementsByTagName('log_url')[0].childNodes[0].nodeValue,
                    'mypage_url': user.getElementsByTagName('mypage_url')[0].childNodes[0].nodeValue,
                    'stats_url': user.getElementsByTagName('stats_url')[0].childNodes[0].nodeValue,
                    'oqrs_enabled': user.getElementsByTagName('oqrs_enabled')[0].childNodes[0].nodeValue,
                    'issupporter': user.getElementsByTagName('issupporter')[0].childNodes[0].nodeValue
                }
                if (obj._showLinks) {
                    var txt = '';
                    txt += '<p align="center">';
                    txt += '<a href="' + obj._userData.log_url + '" target="_blank">My logbook</a>&nbsp;&nbsp;&nbsp;';
                    txt += '<a href="' + obj._userData.mypage_url + '" target="_blank">My page</a>&nbsp;&nbsp;&nbsp;';
                    txt += '<a href="' + obj._userData.stats_url + '" target="_blank">Statistics</a>';
                    if (obj._userData.oqrs_enabled == 'true')
                        txt += '&nbsp;&nbsp;&nbsp;<a href="http://www.hrdlog.net/Oqrs.aspx?user=' + obj._qrz + '" target="_blank">QSL request</a>';
                    txt += '</p>';
                    obj._txtLinks = txt;
                }
            }
        }
    }
    async.req(this._host + 'hrdlog.aspx?userdata=' + this._qrz, this);
}


HrdLog.prototype.Update = function() {
    var element;
    element = document.getElementById(this._container);
    if (element != null) {
        if (document.styleSheets) {
            try {
                ss = null;
                for (i = 0; i < document.styleSheets.length; i++) {
                    if (document.styleSheets[i].title == "hrdlog_ss")
                        ss = document.styleSheets[i];
                }

                // IE
                if (document.createStyleSheet) {
                    if (ss == null) {
                        ss = document.createStyleSheet('');
                        ss.title = "hrdlog_ss";
                    } else {
                        while (ss.rules.length > 0)
                            ss.removeRule(0);
                    }
                    if (ss.addRule) {
                        ss.addRule('.hrdl_table', 'width: 100%;');
                        ss.addRule('.hrdl_table', 'background: ' + this.BackgroundColor + ';');
                        ss.addRule('.hrdl_table', 'font: 100% arial, verdana, trebuchet ms, helvetica;');
                        ss.addRule('tr.hrdl_odd td', 'background: ' + this.RowColor + ';');
                        ss.addRule('tr.hrdl_even td', 'background: ' + this.AlternatingRowColor + ';');
                    }
                } else {
                    if (ss == null) {
                        ss = document.createElement('style');
                        ss.type = "text/css";
                        ss.title = "hrdlog_ss";
                        document.getElementsByTagName('head')[0].appendChild(ss);

                        for (i = 0; i < document.styleSheets.length; i++) {
                            if (document.styleSheets[i].title == "hrdlog_ss")
                                ss = document.styleSheets[i];
                        }
                    } else {
                        for (i = 0; i < 5; i++)  // !!! sarebbe meglio lenght !!!
                            ss.deleteRule(0);
                    }
                    ss.insertRule('.hrdl_table {width: 100%}', 0);
                    ss.insertRule('.hrdl_table {background: ' + this.BackgroundColor + '}', 0);
                    ss.insertRule('.hrdl_table {font: 100% arial, verdana, trebuchet ms, helvetica;}', 0);
                    ss.insertRule('tr.hrdl_odd td {background: ' + this.RowColor + '}', 0);
                    ss.insertRule('tr.hrdl_even td {background: ' + this.AlternatingRowColor + '}', 0);
                }
            }

            catch (e) { this._errMsg += '<p>' + e.message + '</p>' }
        }
        element.innerHTML = this._txtSelectQrz + this._txtLoadCallsign + this._txtReqCallsign + this._txtLastQso + this._txtLinks + this._txtQsoImage + this._txtBanner + this._errMsg; // +hrdl_debug;
    }
    element = document.getElementById('hrdl_qrz');
    if (element != null) {
        for (var i = 0; i < element.options.length; i++) {
            element.options[i].selected = (element.options[i].value == this._qrz);
        }
    }

}

HrdLog.prototype.LoadElement = function(elementName) {
    var async = new Async();
    async.complete = function(status, statusText, responseText, responseXML, obj) {
        if (status == 200) {
            var xmldoc = responseXML;
            var list = xmldoc.getElementsByTagName('updateElement');
            element = document.getElementById(elementName);
            if (element != null) {
                element.innerHTML = list[0].childNodes[0].nodeValue;
            }
        }
    }
    var now = new Date();
    async.req(this._host + 'Loading.aspx?var=' + now.toString(), this);
}

        


