// Create Base64 Object
Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9+/=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/rn/g,"n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}

function SBMSPage(custom) {

  //this.vars = vars;
  //this.cf = customFunc;
  fk = Object.keys(custom);
  for(var i = 0; i < fk.length; i++) {
    this[fk[i]] = custom[fk[i]];
  }
  
  var initFunc = this.init;
  
  $(document).ready([this.showLoading, function() {
	  if($("#menu").length) {
		  $("#menu").addClass("navbar navbar-inverse");
		  $("#menu").load("inclMenu.html", function() {
			  var page = location.pathname.substring(location.pathname.lastIndexOf("/") + 1).replace(".html","");
			  $('#menu li[data-page="' + page + '"]').addClass("active"); 
			  if(SBMSPage["noAuth"]) {
				  $("#login").hide();
			  }
			  SBMSPage.prototype.i18nInit(); 
			  SBMSPage.prototype.savePassInit(); 
			  initFunc();
	  });
	  } else {
		  SBMSPage.prototype.i18nInit(); 
		  SBMSPage.prototype.savePassInit(); 
		  initFunc();
	  }
  	}]);
}

  SBMSPage.prototype.trees = {};
  SBMSPage.prototype.mapURL = "https://kompas.muni.cz/auth/";
  SBMSPage.prototype.sbmsURL = "/sbms/v1/";
  
  SBMSPage.prototype.setAuth = function(xhr) {
    xhr.setRequestHeader('authorization', "Basic " + Base64.encode($("#user").val() + ":" + $("#pass").val()));
  };

  SBMSPage.prototype.toggleButtonSending = function(id) {
    $("#" + id).html($.t("Sending..."));
    $("#" + id).removeClass("label-success");
    $("#" + id).removeClass("label-danger");
    $("#" + id).addClass("label-info");
    $(".sendButton").attr("disabled", "disabled");
  };
  
  SBMSPage.prototype.toggleButtonSuccess = function(id) {
    $("#" + id).html($.t("Completed"));
    $("#" + id).removeClass("label-info");
    $("#" + id).addClass("label-success");
  };
  
  SBMSPage.prototype.toggleButtonError = function(id, error) {
     //$(resultsDivId).html(status + ":" + error);
     $("#" + id).html($.t("Error: ") + $.t(error));
     $("#" + id).removeClass("label-info");
     $("#" + id).addClass("label-danger");
  };
  
  SBMSPage.prototype.toggleButtonComplete = function(id, status) {
    //$("#status").html("Completed with " + status);
    $(".sendButton").removeAttr("disabled");
  };

  SBMSPage.prototype.loadList = function(type, func, params) {
      this.loadList(type, func, params, null);
  };

  SBMSPage.prototype.loadList = function(type, func, params, member) {
    var query= this.sbmsURL + "types/" + type;
    if(member != null && member != "") {
      query+="/" + member;
    }
    var members = {};
    var name;
    $.ajax({
          type: 'GET',
          cache: true,
          url: query,
          success: function(result) { 
               if(func.constructor == Array) {
                $.each(func, function(i, f) {
                  f(result.members, params);
                });
              } else { 
               func(result.members, params);
              }
                   
          }
    });
    return members;
  };
  
  SBMSPage.prototype.getField = function(id) {
     return id.substring(7).replace(/_/g,".");
  };
  
  SBMSPage.prototype.getId = function(field) {
     return "params_" + field.replace(/\./g,"_"); 
  };
  
  
  // parent, type, name
  SBMSPage.prototype.createList = function(data, params) {
    //var  parent = params[0];
    var type = params[1];
    var name = params[2];
    for(i = 0; i < data.length; i++) {
      parent = params[0]; //+ "Col" + Math.floor(i / (Math.floor(data.length / 2)));
      //var width= (columns) ? 6 : 6;
      $(parent).append('<div class="' + type + ' col-lg-6 col-md-12"><label><input id="' + name + i.toString() + '" name="' + name + '" type="' + type + '" value="' + data[i] +  '">' 
      + $.t(data[i]) +  '</label></div>');
    }    
  };
  
  SBMSPage.prototype.fieldCategories = null;
  
  // parent, columns, openTreeAction, closeTreeAction, openMapAction, closeMapAction
  SBMSPage.prototype.createParams = function(data, params) {
      //var  parent = params[0];
      var columns = params[1];
      var ota = params[2];
      var cta = params[3];
      var oma = params[4];
      var cma = params[5];
      var mapFrame = params[6];
      var treeSelect = params[7];
      $.ajax({
          type: 'GET',
          cache: true,
          url: SBMSPage.prototype.sbmsURL + "types/field.source"
      }).done( function(fieldsList) {
    	  // saving to cache
    	  SBMSPage.prototype.fieldCategories = fieldsList;
      for(i = 0; i < data.length; i++) {
        var parent = params[0]; //(columns) ? params[0] + "Col" + Math.floor((i / (Math.floor(data.length / 2) + 1))) : params[0];
        var width= (columns) ? 3 : 6;
        var id = SBMSPage.prototype.getId(data[i]);
        var app = '<label class="col-lg-' + width + ' col-md-6 control-label" for="' + id + '">' + $.t(data[i]) + '</label> <div class="col-lg-' + width + ' col-md-6">';
        
        type = fieldsList[data[i]];
        switch(type) {
          // map select
          case "bim":
            app += '<div class="input-group"><input type="text" class="form-control field" id="' + id + '" />'
             + '<span class="input-group-btn"><button class="btn btn-default mapButton" data-input="' + id + '" type="button"><span class="glyphicon glyphicon-map-marker"></span></button></span></div>';
          break;
          // tree menus
          case "sbms-tree":
            app+= '<div class="input-group"><input type="text" class="form-control field" id="' + id + '" />'
             + '<span class="input-group-btn"><button class="btn btn-default treeButton" data-input="' + id + '" type="button"><span class="glyphicon glyphicon-option-horizontal"></span></button></span></div>';
          break;
          // lists
          case "sbms-enum":
            app+= '<select id="' + id + '" class="form-control selectpickerfield" data-live-search="true"></select>'
          break;
          // free text
          default:
        
        app+= '<div class="input-group"><input type="text" class="form-control field freeform" data-text-processor="u" id="' + id + '" /><div class="input-group-btn"><button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">'
        +'<span class="glyphicon glyphicon-menu-up" id="glyph' + id + '"></span></button>'
        + '<ul class="dropdown-menu dropdown-menu-right">'
        + '<li><a href="#" class="textProcessor" data-input-id="' + id + '" data-text-processor="u"><span class="glyphicon glyphicon-menu-up"></span> Uppercase</a></li>'
        + '<li><a href="#" class="textProcessor" data-input-id="' + id + '" data-text-processor="l"><span class="glyphicon glyphicon-menu-down"></span> Lowercase</a></li>'
        + '<li><a href="#" class="textProcessor" data-input-id="' + id + '" data-text-processor="d"><span class="glyphicon glyphicon-menu-left"></span> Do not change</a></li>'
        + '</ul>'
        + '</div></div>';
        }
        app += '</div>';
        $(parent).append(app);
      }     
      
      // adding actions to text processor buttons
      $("a.textProcessor").click(function() {
        $("#" + $(this).attr("data-input-id")).attr("data-text-processor", $(this).attr("data-text-processor"));
        $("#glyph" + $(this).attr("data-input-id")).removeClass().addClass($(this).find("span").attr("class"));
        $("#" + $(this).attr("data-input-id")).change();
      });
      
      // adding text processor actions to the input
      $("input.freeform", "#params").change(function() {
        switch($(this).attr("data-text-processor")) {
          case "u":
             $(this).val($(this).val().toUpperCase());
             break;
          case "l":
            $(this).val($(this).val().toLowerCase());
            break;
        }    
      });
      
      // filling lists
      $("select", "#params").each(function(key, selectEl) {
          SBMSPage.prototype.loadList(SBMSPage.prototype.getField(selectEl.id) /*.replace("influenced.", "")*/, function(data, params) {
            var select = $("#" + params[0]);
            select.selectpicker();
            var html = '<option value=""></option>';
            for(i = 0; i < data.length; i++) {
              html += '<option value="' + data[i] + '">' + data[i] + '</option>'; 
            }
            
            select.html(html).selectpicker('refresh');
            
          }, [selectEl.id]);
        });
      
        
      $(".mapButton", "#params").each(function(key, buttonEl) {
        $(buttonEl).click(function() {
          var inputSelector = "#" + $(this).attr("data-input");
          
          if($(inputSelector).val().trim() != "") {
            $("#" + mapFrame).attr("src", SBMSPage.prototype.mapURL + "?code=" + $(inputSelector).val().trim()); 
          } else {
            $("#" + mapFrame).attr("src", SBMSPage.prototype.mapURL); 
          }
          $(inputSelector).select();
          $(inputSelector).focus();
          oma();
        });
      });
      
      $(".treeButton", "#params").each(function(key, buttonEl) {
        var id = $(buttonEl).attr("data-input");
        var sid = "#" + id;
        var field = SBMSPage.prototype.getField(id);
        // load the first level
        SBMSPage.prototype.loadList(field, function(data, params) {
          var treeName = params[0];
          SBMSPage.prototype.trees[treeName] = { type: field, index: "0", selectId: sid };
          SBMSPage.prototype.populateNode(SBMSPage.prototype.trees[treeName], data);
        }, [sid]);
        
        $(buttonEl).click(function() {
          SBMSPage.prototype.loadTree(sid, cta, treeSelect);
          ota();
        });
      });
      
      });
  };

  SBMSPage.prototype.loadTree = function(sid, closeTreeAction, treeSelect) {
    $('#' + treeSelect).treeview({
            data: SBMSPage.prototype.trees[sid].nodes,
            onNodeSelected: function(event, node) {
              $(sid).val(node.text);
              closeTreeAction();
            },
            onNodeExpanded: function(event, node) {
              SBMSPage.prototype.loadList(node.type, function(data, params) {
                  var sid = params[0];
                  var indeces = node.index.split(":");
                  
                  // find node
                  var tn = SBMSPage.prototype.trees[sid];
                  for(i = 1; i < indeces.length; i++) {
                    tn = tn.nodes[indeces[i]];
                    tn.state.expanded = true;  
                  }
                  SBMSPage.prototype.populateNode(tn, data);
                  SBMSPage.prototype.loadTree(tn.selectId, closeTreeAction, treeSelect);
              }, [node.selectId], node.member );  
            }
          });
  
  };

  SBMSPage.prototype.populateNode = function(node, data) {
     node.nodes = [];
     for(i =0; i < data.length; i++) {
      node.nodes[i] = { text : data[i], type : node.type, member : data[i], selectId : node.selectId, index: node.index + ":" + i, state: {expanded: false }, nodes: [ { text : "Loading..." } ] }; 
    }
  };

  SBMSPage.prototype.getPropertyValue = function(dp, field) {
    return eval("(dp." + field + " == null) ? '' : dp." + field);
  };
  
  SBMSPage.prototype.getPropertyValueCell = function(dp, field) {
    var propVal = this.getPropertyValue(dp, field); 
    //var tools = "";
    /* 
    if(propVal != '') {
    	// result of the ajax call should be cached
    	$.ajax({
            type: 'GET',
            cache: true,
            url: SBMSPage.prototype.sbmsURL + "types/field.source"
        }).done( function(fieldsList) {
        	if(fieldsList[field] == "bim") {
        		$('td[data-prop-cell="' + field + '"]').append(' <button type="button" class="btn btn-default btn-xs mapButton" data-field="' + encodeURIComponent(field) + '" data-field-value="' + encodeURIComponent(propVal) + '"><span class="glyphicon glyphicon-map-marker" aria-hidden="true"></span></button>');
        	}
        });
    }
    */
    
    /*
    if(this.getFieldDisplayCategory(field) == "map" && propVal != '') {
        tools = ' <button type="button" class="btn btn-default btn-xs mapButton" data-field="' + encodeURIComponent(field) + '" data-field-value="' + encodeURIComponent(propVal) + '"><span class="glyphicon glyphicon-map-marker" aria-hidden="true"></span></button>';
    }
     */  
    return '<td class="propCell" data-field-value="' + propVal + '" data-field="' + field + '">' + $.t(propVal) + '</td>';
  };
  
  SBMSPage.prototype.enrichPropertyValueCells = function(parent, callback) {
	  if(SBMSPage.prototype.fieldCategories == null) {
		  $.ajax({
			  type: 'GET',
			  cache: true,
			  url: SBMSPage.prototype.sbmsURL + "types/field.source"
		  }).done( function(fieldsList) {      	
      		this.fieldCategories = fieldsList;
      		SBMSPage.prototype.enrichPVC(parent, fieldsList, callback); 	
      });
	  } else {
		  SBMSPage.prototype.enrichPVC(parent, this.fieldCategories, callback); 	
	  }
  }
  
  SBMSPage.prototype.enrichPVC = function(parent, fl, callback) {
	  $(parent + ' td.propCell').each(function() {
			var field = $(this).attr("data-field");
			var propVal = $(this).attr("data-field-value");
			if(propVal.trim() != "") {
				if(fl[field] == "bim") {
					$(this).append(' <button type="button" class="btn btn-default btn-xs mapButton" data-field="' + encodeURIComponent(field) + '" data-field-value="' + encodeURIComponent(propVal) + '"><span class="glyphicon glyphicon-map-marker" aria-hidden="true"></span></button>');
				}
			}
		});
	  callback();
  };
  
  SBMSPage.prototype.setDpField = function(dp, field, val) {
  var fname = field.split(".");
  if(val != "" && fname[0] != "") {
    // traverse through objects in field name and create corresponding Javascript hashes
    var i = 0;
    var f = fname[i];
    var o = dp;
    while(i< fname.length - 1) {
      if(o[f] == null) o[f] = {};
      o = o[f];
      f = fname[++i];
    }
    o[f] = val;
  }
  return dp;
};

// https://css-tricks.com/snippets/javascript/get-url-variables/
SBMSPage.prototype.getQueryVariable = function(variable)
{
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
};

SBMSPage.prototype.switchPanel = function(navClass, divClass, activeNav, activeDiv) {
  $("."+ divClass).hide();
  $("." + navClass).removeClass("active");
  $(activeNav).addClass("active");
  $("#" + activeDiv).show();
};

SBMSPage.prototype.switchTab = function(navClass, activeNav) {
	  $("." + navClass).removeClass("active");
	  activeNav.addClass("active");
	};

SBMSPage.prototype.langPanelSetup = function(lang) {
  $("#langIndicator").html($("a.langChange[data-lang='" + lang + "']").attr("data-lang-indicator-abbrev"));
  
  $("a.langChange").click(function() {
    $("#langIndicator").html($(this).attr("data-lang-indicator-abbrev"));
    // cookie for further use
    Cookies.set("sbms-i18n", $(this).attr("data-lang"));
    location.reload();
    // immediate translation - not working completely
    //SBMSPage.prototype.i18nInit();
  });
}

SBMSPage.prototype.i18nInit = function() {

var lang = (Cookies.get("sbms-i18n") != null) ? Cookies.get("sbms-i18n") : navigator.language.split("-")[0];

i18next.init({
  resources: translation,
  debug: false,
  lng: lang,
  nsSeparator: false,
  keySeparator: false,
  fallbackLng: false,
  }, function (err, t) {
  jqueryI18next.init(i18next, $);
  
  if($.fn.selectpicker != null) {
  $.fn.selectpicker.defaults = {
		    noneSelectedText: $.t('Nothing selected'),
		    noneResultsText: $.t('No results match') + ' {0}',
		    /*
		    countSelectedText: 'Označeno {0} z {1}',
		    maxOptionsText: ['Limit překročen ({n} {var} max)', 'Limit skupiny překročen ({n} {var} max)', ['položek', 'položka']], */
		    multipleSeparator: ', '
  };
  }
  $('html').localize();
  
  
  
  SBMSPage.prototype.langPanelSetup(lang);
});
};

SBMSPage.prototype.showLoading = function() {
	$("body").append('<div id="loading" class="text-center"><h3><span class="glyphicon glyphicon-hourglass" aria-hidden="true"></span></h3></div>');
	$("#loading").dialog({
		dialogClass: "no-close",
		modal: true,
		title: "Loading..."
	});
	
	$(document).ajaxStop(function() {$("#loading").dialog("close");})
}
SBMSPage.prototype.savePassInit = function() {
	$("#login").submit(function() {
		this.reset();
	});
};



  
