var g_token;

function create_xmlhttp() {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return xmlhttp;
}

function send_xmlhttp(xmlhttp, url, async) {

    // add unique string to avoid caching of xmlhttp
    if (url.indexOf("?") == -1) {
        url += "?NoCache=" + Math.random();
    } else {
        url += "&NoCache=" + Math.random();
    }
    
    // send
    xmlhttp.open("GET", url, async);
    xmlhttp.send("");
}

function download(url, async) {
    var xmlhttp = create_xmlhttp();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            xmlhttp = null;
        }
    }
    send_xmlhttp(xmlhttp, url, async);
}

function download_refresh(url) {
    download(url, false);
    setTimeout("reload()", 500);
}

function reload() {
    location.reload(true);
}

function download_jump_playing_now(url) {
    var xmlhttp = create_xmlhttp();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            window.location.href = "playingnow.html";
            xmlhttp = null;
        }
    }
    send_xmlhttp(xmlhttp, url, true);
}

function download_update_display(url) {
    var xmlhttp = create_xmlhttp();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            download_display_playing_information();
            xmlhttp = null;
        }
    }
    send_xmlhttp(xmlhttp, url, true);
}

function download_display_html(url, id) {
    var xmlhttp = create_xmlhttp();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            document.getElementById(id).innerHTML = xmlhttp.responseText;
            xmlhttp = null;
        }
    }
    send_xmlhttp(xmlhttp, url, true);
}

function download_display_image(url, id) {
    var xmlhttp = create_xmlhttp();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            document.getElementById(id).src = xmlhttp.responseText;
            xmlhttp = null;
        }
    }
    send_xmlhttp(xmlhttp, url, true);
}

function download_display_playing_information() {
    var xmlhttp = create_xmlhttp();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {

            // load response  
            var xml = xmlhttp.responseXML;
            var root = xml.getElementsByTagName("Response");

            // see if response is valid
            if ((root != null) && (root.length == 1) && (xml.documentElement.getAttribute("Status") == "OK")) {

                // get all items
                var items = xml.getElementsByTagName("Item");
                if (items != null) {

                    // loop items
                    for (var i = 0; i < items.length; i++) {

                        // parse values
                        var name = items[i].getAttribute("Name");
                        var value = items[i].childNodes[0].nodeValue;

                        // get corresponding element
                        var element = document.getElementById("PlaybackInfo." + name);
                        if (element != null) {

                            // update element
                            if ((element.src != null) && (element.src != "")) {
                                if (element.src != value)
                                    element.src = value; // image
                            }
                            else {
                                if (element.innerHTML != value)
                                    element.innerHTML = value; // text
                            }
                        }
                    }
                }

                xmlhttp = null;
            }
        }
    }
    send_xmlhttp(xmlhttp, "MCWS/v1/Playback/Info?Zone=-1&Token=" + g_token, true);
}

function init_playingnow(token) {

    // store token
    g_token = token;    
    
    // update information once now
    download_display_playing_information();

    // update again every little bit
    setInterval("download_display_playing_information()", 5000);
}

function loadDoc(id, url) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById(id).innerHTML = xhttp.responseText;
    }
  };
 xhttp.open("GET", url, true);
    xhttp.send();
}

function loadDocForm(id, url, form) {
  var form = document.getElementById(form);
  var data = serialize(form);
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    console.log(xhttp.responseText);
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        var xml = xhttp.responseXML;
        var responseElement = xml.getElementsByTagName("Response")[0];
        var info = responseElement.getAttribute("Information");
      document.getElementById(id).innerHTML = info;
    }
  };
 xhttp.open("GET", url + "?" + data, true);
    xhttp.send(data);
}

function loadDocForm_newWindow(url, form) {
  var form = document.getElementById(form);
  var data = serialize(form);
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    console.log(xhttp.responseText);
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        var xml = xhttp.responseXML;
        var responseElement = xml.getElementsByTagName("Response")[0];
        var info = responseElement.getAttribute("Information");
        var win = window.open(url, "_blank", "width=700,height=900");
        win.document.write("<PRE>" + info + "</PRE>");
    }
  };
 xhttp.open("GET", url + "?" + data, true);
    xhttp.send(data);
}

function loadDoc_newWindow(url) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      var results = xhttp.responseText;
      var win = window.open(url, "_blank", "width=700,height=900");
      win.document.write("<PRE>" + results + "</PRE>");
    }
  };
 xhttp.open("GET", url, true);
    xhttp.send();
}

function serialize (form) {
    if (!form || form.nodeName !== "FORM") {
            return;
    }
    var i, j, q = [];
    for (i = form.elements.length - 1; i >= 0; i = i - 1) {
        if (form.elements[i].name === "") {
                continue;
        }
        switch (form.elements[i].nodeName) {
        case 'INPUT':
            switch (form.elements[i].type) {
            case 'text':
            case 'email':
            case 'number':
            case 'hidden':
            case 'password':
            case 'button':
            case 'reset':
            case 'submit':
                    q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                    break;
            case 'checkbox':
            case 'radio':
                    if (form.elements[i].checked) {
                            q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                    }                                               
                    break;
            }
            break;
            case 'file':
            break; 
        case 'TEXTAREA':
                q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                break;
        case 'SELECT':
            switch (form.elements[i].type) {
            case 'select-one':
                    q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                    break;
            case 'select-multiple':
                    for (j = form.elements[i].options.length - 1; j >= 0; j = j - 1) {
                            if (form.elements[i].options[j].selected) {
                                    q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].options[j].value));
                            }
                    }
                    break;
            }
            break;
        case 'BUTTON':
            switch (form.elements[i].type) {
            case 'reset':
            case 'submit':
            case 'button':
                    q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                    break;
            }
            break;
        }
    }
    return q.join("&");
}

function clearInput(formId) {
    $("#" + formId)[0].reset();
}

function enable(targetId) {
    document.getElementById(targetId).disabled = false;
}

function disableAndResetDropdown(targetId) {
    document.getElementById(targetId).selectedIndex = 0;
    document.getElementById(targetId).disabled = true;
}

function disableAndClear(targetId) {
    document.getElementById(targetId).value = "";
    document.getElementById(targetId).disabled = true;
}

function createWiredDNSFields(name, globaldnsdropdown, dnsfieldsid) {
    if(name=="False") {
        document.getElementById(globaldnsdropdown).selectedIndex = 0;
        document.getElementById(globaldnsdropdown).disabled = true;
        document.getElementById(dnsfieldsid).innerHTML='';
    }
    else if(name=="True") {
        document.getElementById(globaldnsdropdown).disabled = false;
        document.getElementById(dnsfieldsid).innerHTML='<fieldset class="form-group"><label for="wiredsearchdomain">Search Domain</label><input class="form-control" type="text" id="wiredsearchdomain" name="WiredSearchDomain" placeholder="None"></fieldset><fieldset class="form-group"><label for="wireddnsdomain">DNS Domain</label><input class="form-control" type="text" id="wireddnsdomain" name="WiredDNSDomain" placeholder="None"></fieldset><fieldset class="form-group"><label for="wireddns1">DNS 1</label><input class="form-control" type="text" id="wireddns1" name="WiredDNS1" placeholder="None"></fieldset><fieldset class="form-group"><label for="wireddns2">DNS 2</label><input class="form-control" type="text" id="wireddns2" name="WiredDNS2" placeholder="None"></fieldset><fieldset class="form-group"><label for="wireddns3">DNS 3</label><input class="form-control" type="text" id="wireddns3" name="WiredDNS3" placeholder="None"></fieldset>'
    }
}

function createWirelessDNSFields(name, globaldnsdropdown, dnsfieldsid) {
    if(name=="False") {
        document.getElementById(globaldnsdropdown).selectedIndex = 0;
        document.getElementById(globaldnsdropdown).disabled = true;
        document.getElementById(dnsfieldsid).innerHTML='';
    }
    else if(name=="True") {
        document.getElementById(globaldnsdropdown).disabled = false;
        document.getElementById(dnsfieldsid).innerHTML='<fieldset class="form-group"><label for="wirelesssearchdomain">Search Domain</label><input class="form-control" type="text" id="wirelesssearchdomain" name="WirelessSearchDomain" placeholder="None"></fieldset><fieldset class="form-group"><label for="wirelessdnsdomain">DNS Domain</label><input class="form-control" type="text" id="wirelessdnsdomain" name="WirelessDNSDomain" placeholder="None"></fieldset><fieldset class="form-group"><label for="wirelessdns1">DNS 1</label><input class="form-control" type="text" id="wirelessdns1" name="WirelessDNS1" placeholder="None"></fieldset><fieldset class="form-group"><label for="wirelessdns2">DNS 2</label><input class="form-control" type="text" id="wirelessdns2" name="WirelessDNS2" placeholder="None"></fieldset><fieldset class="form-group"><label for="wirelessdns3">DNS 3</label><input class="form-control" type="text" id="wirelessdns3" name="WirelessDNS3" placeholder="None"></fieldset>'
    }
}

function createSecurityFields(name){
    if(name=="wpa" || name =="wep-hex" || name=="wep-shared")document.getElementById('securityfields').innerHTML='Key: <input type="password" class="form-control" name="SecurityField1" />';
    else if(name=="wpa-peap" || name =="wpa2-peap")document.getElementById('securityfields').innerHTML='Identity: <input type="text" class="form-control" name="SecurityField1" /><br>Domain: <input type="text" class="form-control" name="SecurityField2" /><br>Password: <input type="password" class="form-control" name="SecurityField3" />';
    else if(name=="wpa-psk")document.getElementById('securityfields').innerHTML='Passphrase: <input type="password" class="form-control" name="SecurityField1" />';
    else if(name=="wep-passphrase")document.getElementById('securityfields').innerHTML='Passphrase: <input type="password" class="form-control" name="SecurityField1" />';
    else if(name=="wpa2-leap" || name=="leap")document.getElementById('securityfields').innerHTML='Username: <input type="text" class="form-control" name="SecurityField1" /><br>Password: <input type="password" class="form-control" name="SecurityField2" />';
    else if(name=="peap" || name=="psu")document.getElementById('securityfields').innerHTML='Identity: <input type="text" class="form-control" name="SecurityField1" /><br>Password: <input type="password" class="form-control" name="SecurityField2" />';
    else if(name=="ttls")document.getElementById('securityfields').innerHTML='Identity: <input type="text" class="form-control" name="SecurityField1" /><br>Password: <input type="password" class="form-control" name="SecurityField2" /><br>Auth: <input type="text" class="form-control" name="SecurityField3" />';
    else if(name=="eap")document.getElementById('securityfields').innerHTML='Username: <input type="text" class="form-control" name="SecurityField1" /><br>Password: <input type="password" class="form-control" name="SecurityField2" /><br>PAC File: <input type="text" class="form-control" name="SecurityField3" />';
    else if(name=="peap-tkip")document.getElementById('securityfields').innerHTML='Identity: <input type="text" class="form-control" name="SecurityField1" /><br>Password: <input type="password" class="form-control" name="SecurityField2" /><br>CA Cert: <input type="text" class="form-control" name="SecurityField3" />';
    else if(name=="eap-tls")document.getElementById('securityfields').innerHTML='Identity: <input type="text" class="form-control" name="SecurityField1" /><br>Private Key: <input type="text" class="form-control" name="SecurityField2" /><br>Private Key Password: <input type="password" class="form-control" name="SecurityField3" /><br>Client Cert: <input type="text" class="form-control" name="SecurityField4" /><br>CA Cert: <input type="text" class="form-control" name="SecurityField5" />';
    else document.getElementById('securityfields').innerHTML='';
}

function showWirelessNetworks() {
    loadDoc_newWindow('MCWS/v1/Settings/ShowWirelessNetworks');
    document.getElementById('networknamedivid').innerHTML='<fieldset><label for="cellnumberid">Enter the cell number of the network you want to connect to from the list of networks and press enter.</label><div class="col-lg-3"><input type="number" class="form-control" id="cellnumberid" name="CellNumber" maxlength="3" onchange="javascript:loadDocIdValue(\'networkname\', \'MCWS/v1/Settings/GetNetworkName\', \'cellnumberid\')"></div></fieldset>';
}

function loadDocIdValue(idoutput, url, idinput) {
  var cellinput = document.getElementById(idinput).value;
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        var xml = xhttp.responseXML;
        var responseElement = xml.getElementsByTagName("Response")[0];
        var info = responseElement.getAttribute("Information");
        document.getElementById(idoutput).value = info;
    }
  };
 xhttp.open("GET", url + "?CellNumber=" + cellinput, true);
    xhttp.send(cellinput);
}

function loadDocValue(id, url) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        var xml = xhttp.responseXML;
        var responseElement = xml.getElementsByTagName("Response")[0];
        var info = responseElement.getAttribute("Information");
        document.getElementById(id).value = info;
    }
  };
 xhttp.open("GET", url, true);
    xhttp.send();
}

function loadDocText(id, url) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        var xml = xhttp.responseXML;
        var responseElement = xml.getElementsByTagName("Response")[0];
        var info = responseElement.getAttribute("Information");
        document.getElementById(id).innerHTML = info;
    }
  };
 xhttp.open("GET", url, true);
    xhttp.send();
}

function createNetworkInput(name, networkfieldid) {
    if(name=="1") {
        document.getElementById(networkfieldid).innerHTML='<fieldset class="form-group"><label for="wirednetworkinput">Wired Network Profile Name</label><input class="form-control" type="text" id="wirednetworkinput" name="NetworkInput"></fieldset>'
    }
    else if(name=="2") {
        document.getElementById(networkfieldid).innerHTML='<fieldset class="form-group"><label for="wirelessnetworkinput">Wireless Network Address (without [])</label><input class="form-control" type="text" id="wirelessnetworkinput" name="NetworkInput"></fieldset>'
    }
}

function addEmailOption(checkbox) {
    if (checkbox.checked) {
        document.getElementById('emailfield').innerHTML='Email: <input type="text" class="form-control" id="enteremail" name="Email"><br>';
    }
    else {
        document.getElementById('emailfield').innerHTML='';
    }
}

function checkEmailFormat(checkbox) {
    var email_regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
    if(checkbox.checked && !email_regex.test($("#enteremail").val())) {
        alert("Invalid e-mail address format");
    }
    else {
        loadDocForm('licensefooter', 'MCWS/v1/Settings/ReenterLicenseKey', 'reenterlicense');
    }
}
