// from common.js: Define Message object



// Message
//

var Message = {};

Message.Determine_Origin = function (param_window) {
  'use strict';

  var result, start_prefix_minimum, start_index, end_index;

  if (param_window.location.protocol === 'file:') {
    result = '*';
  } else {
    // Ensure start index starts after protocol and host info
    //
    start_prefix_minimum = param_window.location.protocol + '//' + param_window.location.host;
    start_index = start_prefix_minimum.length;
    end_index = param_window.location.href.indexOf(param_window.location.pathname, start_index);
    result = param_window.location.href.substring(0, end_index);
  }

  return result;
};

Message.Listen = function (param_window, param_function) {
  'use strict';

  var origin, middleware;

  // Use appropriate browser method
  //
  if ((param_window.postMessage !== undefined) && (param_window.JSON !== undefined)) {
    // Wrap function to ensure security
    //
    origin = Message.Determine_Origin(param_window);
    middleware = function (param_event) {
      var accept, event, key;

      // Ensure origin matches
      //
      accept = (param_event.origin === origin);
      if (!accept) {
        if (param_window.location.protocol === 'file:') {
          accept = (param_event.origin.indexOf('file:') === 0);
          if (!accept) {
            accept = (param_event.origin === 'null');
          }
        }
      }

      // Invoke function if message acceptable
      //
      if (accept) {
        // Copy existing event
        //
        event = {};
        for (key in param_event) {
          if (param_event[key] !== undefined) {
            event[key] = param_event[key];
          }
        }

        // Expand JSON data
        //
        try {
          // event.data = param_window.JSON.parse(param_event.data); // error: will not work
          event.data = param_event.data; // error: will not work
          param_function(event);
        } catch (ignore) {
          // Apparently, this message wasn't meant for us
          //
        }
      }
    };

    if (param_window.addEventListener !== undefined) {
      // Via postMessage
      //
      param_window.addEventListener('message', middleware, false);
    } else if (param_window.attachEvent !== undefined) {
      // Via postMessage
      //
      param_window.attachEvent('onmessage', middleware, false);
    }
  } else {
    // Direct send
    //
    if (!param_window.POSTMESSAGE_message) {
      param_window.POSTMESSAGE_message = param_function;
    }
  }
};

Message.Post = function (param_to_window, param_data, param_from_window) {
  'use strict';

  var data, origin, event;

  // Use appropriate browser method
  //
  if ((param_from_window.postMessage !== undefined) && (param_from_window.JSON !== undefined)) {
    // Via postMessage
    //
    data = param_from_window.JSON.stringify(param_data);
    origin = Message.Determine_Origin(param_from_window);
    param_to_window.postMessage(data, origin);
  } else {
    // Direct send
    //
    if (param_to_window.POSTMESSAGE_message) {
      event = { 'origin': origin, 'source': param_from_window, 'data': param_data };
      param_from_window.setTimeout(function () {
        param_to_window.POSTMESSAGE_message(event);
      });
    }
  }
};


// from connect.js



// SQ: defines Connect_Window
var LandingPage_Window = window;
LandingPage_Window.name = 'lp_main';

var Connect = {
  loading: false,
  first_page_loaded: false,
  page_cargo: {}
};

Connect.LoadPage = function (param_to_window) { // error: Added argument
  var data;

  data = {
    'action': 'page_load'
  };

  Message.Post(param_to_window, data, LandingPage_Window); // error: Changed 'Connect.page_iframe.contentWindow' to 'param_to_window'
};


// Load Version and language from json SQNobit 2021-08-02
(()=>{
    // debugger;
    
  var loadVersions = function(url){

    if(document.getElementById("nobitVersionSelectorStyles") === null){
      $selectBoxStyles = document.createElement("style");
      $selectBoxStyles.setAttribute("id", "nobitVersionSelectorStyles")
      document.getElementsByTagName("head")[0].appendChild($selectBoxStyles);

      $selectBoxStyles.innerHTML = `
          #versionLanguageSelector{
              border: 0;
              margin: 0 20px;
              }
          #nobitVersionLabel{
            font-size: 13px;
            margin: 0 20px;
          }
        `;

    }

    $versionListParent = document.getElementById("version-lang"); // error: Added "id" on the html element

    //var $selectBox = $("<select></select>");
    fetch(url).then( (data) =>{
      if(data.ok) {
        data.json().then((vData) => {
          // The first part (labels) of the loaded JSON file contains localized labels for stuff like "version" or the languages themself
          let labels = vData.labels;
          // The second part (data) contains an array of objects with a version number, a languag token and a url later used as href, example: {"v": "4.11", "l": "de", "href": "Administrator/co-about_this_guide.html#"}
          let versions = vData.data;
          let currentLanguage = document.querySelector("html").getAttribute("lang");

          let currentVersion = null;
          var releaseMeta = document.querySelector("head meta[name='version']"); // error: Changed selector from "head meta[name='Release']" to "head meta[name='version']"
          if(releaseMeta){
            currentVersion = releaseMeta.getAttribute("content");
          }



          // If we have no or just one version we quit. We don't have
          // to generate a selectbox for one option.
          if((!Array.isArray(versions)) || (versions.length < 2)) return;

          // If we have different version objects, we sort them
          // according to their ascending version string.
          //versions = versions.sort((a, b) => {return b.v.localeCompare(a.v);})

          //split a version string into array, converts each part of the version to a number and compares it numerically. 
          versions = versions.sort((a, b) => b.v.split('.').map(Number).reduce((acc, val, i) => acc || val - a.v.split('.')[i], 0));

          // Let's start our "StringBuilder" array with the start tag of our new selectbox
          // let $options = [`<select id="version-dropdown-select" class="dlt-single-select" data-placeholder="Select Capabilities">`]; // modified: Changed the id from 'versionLanguageSelector' and added other attributes
          let $options = [`<select onchange="window.location = this.value;" id="version-dropdown-select" class="dlt-single-select" data-placeholder="Select Versions">`];

          for (let version in versions) {
            // We build our strings for an option according to the
            // language of document it shows so Japanese documents get
            // a japanese version label etc.
            let local_labels = labels[versions[version].l] ?? labels["en_US"];
	    let linkTarget = '/' + versions[version].href + 'index.html';
            // If we find the current document in out selectbox, we
              // have our currently selected option.
            let isCurrent =  versions[version].v == currentVersion && versions[version].l == currentLanguage;
              $options.push(`<option ${isCurrent ? "selected='selected'": ""} value="${isCurrent ? "" : linkTarget}">${local_labels.version} ${versions[version].v} (${local_labels.lang_self})</option> `);
          }

          $options.push("</select>");

          $versionListParent.innerHTML = $options.join("");


          var changeVersionLanguage = function(event){
            // If something else other than our selectbox is changed, we don't bother
            if(event.target != document.getElementById('versionLanguageSelector')){
              return;
            }
            //Get the href from the value of the selected option an set out location to it.
            var selectedOption = event.target.options[event.target.selectedIndex];
            if(selectedOption && selectedOption.getAttribute("value") && selectedOption.getAttribute("value").length > 1){
              document.location = selectedOption.getAttribute("value");
            }
          }

          if (document.addEventListener !== undefined) {
            document.addEventListener('change', changeVersionLanguage);
          } else if (window.attachEvent !== undefined) {
            document.attachEvent('change', changeVersionLanguage);
          }

        })

      }else{

      }
    }).catch(()=>{

    })
  }

  var getVersionsUrl = function(location){
    let hash = location.hash;
    let pathname = location.origin + location.pathname;
    versions_url = pathname.split('/').slice(0,-3).join('/') + '/releases/versions.json';

    hash = hash.replace("#page/", "")
    let parts = hash.split("#");
    let path = parts.shift();
    let package = path.split("/").shift();
    // return `/public/sag/2021Y/${package}/versions.json`;
    // console.log(`${pathname}${package}/versions.json`); // error: will not generate the right path to versions.json
      // return `${pathname}${package}/versions.json`;
      // use current directory or Asset/json?
      // return `versions.json`; // error: will not return the right path to versions.json
    return(versions_url)
  }

    // orig SQ
    /*
    Message.Listen(Connect_Window, (data)=>{
    if(data.data.action === "parcel_load"){
      console.log(data.currentTarget.location);
      let versionsUrl = getVersionsUrl(data.currentTarget.location);
      loadVersions(versionsUrl);
    }
  }
    */
    
  Connect.LoadPage(LandingPage_Window); // error: Added explicit call for firefox

  Message.Listen(LandingPage_Window, (data)=>{
    // error: Added flag to prevent infinite load
    if(!Message.loaded){
      console.log(data.currentTarget.location);
      let versionsUrl = getVersionsUrl(data.currentTarget.location);
      loadVersions(versionsUrl);
      Message.loaded = true;
    }
  });

})();
