// 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;
  var showLogin = this.noAuth;
  $(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(showLogin) {
				  $("#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/semantics/";
  SBMSPage.prototype.bmsChartsURL = "https://bms.muni.cz/Charts/";
  SBMSPage.prototype.cafmURL = "https://archibus.ics.muni.cz/archibus/schema/ab-products/custom/sbms/muni-helpdesk-manager-search-tabs.axvw";
  SBMSPage.prototype.trendDBs = ["93", "94"];
  SBMSPage.prototype.bmsURL = "https://bms.muni.cz/deltaweb/newlogin/?Referer=/deltaweb/navigator/index.asp&FrameSrc=%2Fdeltaweb%2Fnavigator%2FObject%5F{0}%2Easp%3FObjRef%3DBAC%2E{1}";
// "https://bms.muni.cz/deltaweb/newlogin/?Referer=/deltaweb/navigator/index.asp&FrameSrc=%2Fdeltaweb%2Fnavigator%2FObject%5F{0}%2Easp%3FObjRef%3DBAC%2E{1}";
// http://bms.muni.cz/deltaweb/login.asp?Referer=%2Fdeltaweb%2Fnavigator%2FObject%5FAV%2Easp%3FObjRef%3DBAC%2E11304%2EAV202 &logoffReason=1
// https://bms.muni.cz/deltaweb/newlogin/?Referer=/deltaweb/navigator/index.asp&FrameSrc=%2Fdeltaweb%2Fnavigator%2FObject%5FAV%2Easp%3FObjRef%3DBAC%2E11304%2EAV202 &logoffReason=1  
// https://bms.muni.cz/deltaweb/shibblogin/SSOLogin.aspx?Referer=/deltaweb/navigator/index.asp&FrameSrc=%2Fdeltaweb%2Fnavigator%2FObject%5FAV%2Easp%3FObjRef%3DBAC%2E11304%2EAV202%20&logoffReason=1
  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.toggleButtonFinishing = function(id) {
	  $("#"+ id).html($.t("Finishing..."));
  };
  
  SBMSPage.prototype.showLoginDialog = function(func){
	  if(!$("#scripts_loginPrompt").length) {
		  var dialog = '<div id="scripts_loginPrompt" title="' + $.t('Login') + '">';
		  dialog += '<p>' + $.t('Enter your credentials please:') + '</p>';
		  dialog += '<div class="form-horizontal">'
		  dialog += '<div class="form-group">';
		  dialog += '<label class="col-lg-6 control-label" for="scripts_loginPromptUser">' + $.t('User:') + '</label>';
		  dialog += '<div class="col-lg-6"><input type="text" class="form-control" id="scripts_loginPromptUser"></div></div>';
		  dialog += '<div class="form-group">';
		  dialog += '<label class="col-lg-6 control-label" for="scripts_loginPromptPass">' + $.t('Password:') + '</label>';
		  dialog += '<div class="col-lg-6"><input type="text" class="form-control" id="scripts_loginPromptPass"></div></div>';
		  dialog +=	'</div></div>';  
			  
		  $("body").append(dialog);
		  $("#scripts_loginPrompt").hide();
	  }
	  $("#scripts_loginPrompt").dialog({
	      resizable: false,
	      height: "auto",
	      width: 400,
	      modal: true,
	      buttons: [{
	        text: $.t("Login"),
	        click: function() {
	        	$("#user").val($("#scripts_loginPromptUser").val());
	        	$("#pass").val($("#scripts_loginPromptPass").val());
	        	$( this ).dialog( "close" );
	        	func();
	        }
	      }]
	    });  
	  
  }
  
  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 + 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 + "fields/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">';
        
        var paramVal = SBMSPage.prototype.getQueryVariable(data[i]); 
        var type = fieldsList[data[i]];
        switch(type) {
          // map select
          case "bim":
            app += '<div class="input-group"><input type="text" class="form-control field" id="' + id + '" ' 
            + ((paramVal) ? 'value="' + paramVal + '"' : '') + ' />'
             + '<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 + '" ' 
            + ((paramVal) ? 'value="' + paramVal + '"' : '') + ' />'
             + '<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 selectpicker field" data-live-search="true"'
            + ((paramVal) ? 'data-active-option="' + paramVal + '"' : 'data-active-option=""') + '></select>'
          break;
          // free text
          default:
        
        app+= '<div class="input-group"><input type="text" class="form-control field freeform" data-text-processor="u" id="' + id + '" ' 
        + ((paramVal) ? 'value="' + paramVal + '"' : '') + ' />'
        + '<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("types/" + SBMSPage.prototype.getField(selectEl.id), function(data, params) {
            var select = $("#" + params[0]);
            var attr = select.attr("data-active-option");
            select.selectpicker();
            var html = '<option value=""></option>';
            for(i = 0; i < data.length; i++) {
              html += '<option value="' + data[i] + '" ' 
              + ((attr == data[i]) ? 'selected="selected"' : '') + ' >' + 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("types/" + 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("types/" + 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); 
    
    return '<td class="propCell" data-field-value="' + propVal + '" data-field="' + field + '">' + $.t(propVal) + '</td>';
  };
  
  SBMSPage.prototype.enrichPropertyValueCells = function(parent, callbackMap, callbackTrend, callbackBMS, callbackCAFM, callbackInfluenced, callbackInfluencing, callbackGlobal) {
	  if(SBMSPage.prototype.fieldCategories == null) {
		  $.ajax({
			  type: 'GET',
			  cache: true,
			  url: SBMSPage.prototype.sbmsURL + "fields/source"
		  }).done( function(fieldsList) {      	
      		this.fieldCategories = fieldsList;
      		SBMSPage.prototype.enrichPVC(parent, fieldsList, callbackMap, callbackTrend, callbackBMS, callbackCAFM, callbackInfluenced, callbackInfluencing, callbackGlobal); 	
      });
	  } else {
		  SBMSPage.prototype.enrichPVC(parent, this.fieldCategories, callbackMap, callbackTrend, callbackBMS, callbackCAFM, callbackInfluenced, callbackInfluencing, callbackGlobal); 	
	  }
  }
  
  SBMSPage.prototype.enrichPVC = function(parent, fl, callbackMap, callbackTrend, callbackBMS, callbackCAFM, callbackInfluenced, callbackInfluencing, callbackGlobal) {
	  $(parent + ' td.propCell').each(function() {
			var field = $(this).attr("data-field");
			var propVal = $(this).attr("data-field-value");
			if(propVal.trim() != "") {
				var buttons = ' <div class="btn-group btn-group-xs" role="group">';
				var bl = buttons.length;
				//var buttonCount = 0;
				if(fl[field] == "bim") {
					// bim map
					buttons += ' <button type="button" class="btn btn-default mapButton" data-field="' + encodeURIComponent(field) + '" data-field-value="' + encodeURIComponent(propVal) + '"><span class="glyphicon glyphicon-map-marker" aria-hidden="true" title="' + $.t("button.hover.map") + '"></span></button>';
					// cafm
					// technology passport hack
					if(propVal.length > 13) {
						buttons += ' <button type="button" class="btn btn-default cafmButton" data-field="' + encodeURIComponent(field) + '" data-field-value="' + encodeURIComponent(propVal) + '"><span class="glyphicon glyphicon-wrench" aria-hidden="true" title="' + $.t("button.hover.cafm") + '"></span></button>';
					}
					// Influencing
					buttons += ' <button type="button" class="btn btn-default influencingButton" data-field="influenced.scope.bimId" data-field-value="' + encodeURIComponent(propVal) + '"><span class="glyphicon glyphicon-random" aria-hidden="true" title="' + $.t("button.hover.influence") + '"></span></button>';
				}
				if(fl[field] == "bms") {
					// BMS Present value
					buttons += ' <button type="button" class="btn btn-default bmsButton" data-field="' + encodeURIComponent(field) + '" data-field-value="' + encodeURIComponent(propVal) + '"><span class="glyphicon glyphicon-eye-open" aria-hidden="true" title="' + $.t("button.hover.bms") + '"></span></button>';

					if(propVal.indexOf(".TL") > -1) {
						// BMS Charts
						for(var i = 0; i < SBMSPage.prototype.trendDBs.length; i++) {
							if(propVal.startsWith(SBMSPage.prototype.trendDBs[i])) {
								buttons += ' <button type="button" class="btn btn-default btn-xs trendButton" data-field="' + encodeURIComponent(field) + '" data-field-value="' + encodeURIComponent(propVal) + '"><span class="glyphicon glyphicon-stats" aria-hidden="true" title="' + $.t("button.hover.charts") + '"></span></button>';
								break;
							}
						}
					} else {
						// Influenced
						buttons += ' <button type="button" class="btn btn-default btn-xs influencedButton" data-field="' + encodeURIComponent(field) + '" data-field-value="' + encodeURIComponent(propVal) + '"><span class="glyphicon glyphicon-random" aria-hidden="true" title="' + $.t("button.hover.influence") + '"></span></button>';
					}
				}
				if(buttons.length > bl) {
					$(this).append(buttons + "</div>");
				}
			}
		});
	  
	// adding actions to buttons
	    $("button.mapButton").click(function() {
	      callbackMap(SBMSPage.prototype.mapURL + "?code=" + $(this).attr("data-field-value"), this);
	    });
	    
	    $("button.trendButton").click(function() {
	        callbackTrend(SBMSPage.prototype.bmsChartsURL + "?tl=" + $(this).attr("data-field-value"), this);
	      });
	    
	    $("button.bmsButton").click(function() {
	        var propVal = $(this).attr("data-field-value");
	        callbackBMS(SBMSPage.prototype.bmsURL.replace("{0}", propVal.replace(/[0-9\.]/g,"")).replace("{1}", propVal), this);
	      });
	    
	    $("button.cafmButton").click(function() {
	    	callbackCAFM(SBMSPage.prototype.cafmURL + "?wr.eq_id=" + $(this).attr("data-field-value"), this);
	      });
	    
	    $("button.influencedButton").click(function() {
	    	callbackInfluenced("query.html?" + $(this).attr("data-field") + "=" + $(this).attr("data-field-value") + "#QueryRelationsId", this);
	      });
	    
	    $("button.influencingButton").click(function() {
	    	callbackInfluencing("query.html?" + $(this).attr("data-field") + "=" + $(this).attr("data-field-value") + "#QueryRelationsIg", this);
	    });
	    
	    callbackGlobal();
  };
  
  SBMSPage.prototype.buttonEnrichCallbackLink = function(url) {
	  location.href=url;
  };
  
  SBMSPage.prototype.buttonEnrichCallbackOpenWindow= function(url) {
	    window.open(url);  
  };
  
  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.initPanels = function() {
	if (window.location.hash != null
		&& window.location.hash != ""
		&& window.location.hash != "#") {
		var panel = window.location.hash.substring(1);
		p.loadPanelFromFile("#nav" + panel);
		
	} else {
		p.loadPanelFromFile("li.opNav.active");
	}

	$(".opNav").click(function() { p.loadPanelFromFile($(this)); } );
	
	
};

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.loadPanelFromFile = function(srcSelector) {
		var src = $(srcSelector);
		p.switchTab("opNav", src);
		$("#content").load(src.attr("data-incl-file"), function() {
			p[src.attr("data-init-func")]();
			$("#content").localize();
			
			var srcHref = src.children().first().attr("href");
			srcHref = srcHref.substring(srcHref.indexOf("#"));
			$('a[data-sbms-tab-href="yes"]').attr("href", srcHref);
		});
	};	

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() {
	var creds = (Cookies.get("sbms-login") != null) ? Cookies.get("sbms-login").split(":") : ["", ""];
	$("#user").val(creds[0]);
	$("#pass").val(creds[1]);
	$("#login").submit(function() {
		Cookies.set("sbms-login", $("#user").val() + ":" + $("#pass").val());
		this.reset();
	});
};



  
