// Logausgabe in FireBug
function LogMessage(message) {
  try {
    if (console) {
      console.log(message);
    }
  }
  catch(e) {}
}

$(function() {
  $('.sublink').click( function() {
    var alfnr = $(this).data('lfnr');
    var type = $(this).data('type');
    deflateTree(alfnr);
    top.mainframe.location.href = "https://sedi.luxtram.lu/wponline.dll/TreeLink?alfnr=" + alfnr + '&PageType=' + type;
  });  
})

function deflateTree (id) {
  if (top && top.Inhalt && top.Inhalt.deflateByID)
    top.Inhalt.deflateByID(id);
}

function changeIFrameSource(cid, url) {
  var theFrame = document.getElementById(cid);
  if (theFrame) {
    if (theFrame.contentWindow && theFrame.contentWindow.location) {
      theFrame.contentWindow.location = url;
    } else if (theFrame.src) {
      theFrame.src = url;
    } else {
      theFrame.setAttribute('src', url);
    }
  }
}
var bindHelp = function() {
  var topic = arguments[0], i;

  for (i = 1; i <arguments.length; i++) {
    var obj = document.getElementById(arguments[i]);
    if (obj) {
      if (obj.dataset) {
        obj.dataset.help = topic;
      } else {
        obj.setAttribute('data-help', topic);
      }
    }
  }
}

function hasHelp(elem) {
  return (elem.getAttribute('data-help') && elem.getAttribute('data-help') != '');
}

var escapeRegExp;

(function () {
  // siehe http://stackoverflow.com/a/6969486

  // Referring to the table here:
  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  // these characters should be escaped
  // \ ^ $ * + ? . ( ) | { } [ ]
  // These characters only have special meaning inside of brackets
  // they do not need to be escaped, but they MAY be escaped
  // without any adverse effects (to the best of my knowledge and casual testing)
  // : ! , =
  // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

  var specials = [
      // order matters for these
      "-", "[", "]",
      // order doesn't matter for any of these
      "/", "{", "}", "(", ")", "*", "+", "?", ".", "\\", "^", "$", "|"
    ],

  // I choose to escape every character with '\'
  // even though only some strictly require it when inside of []
    regex = RegExp('[' + specials.join('\\') + ']', 'g');

  escapeRegExp = function (str) {
    return str.replace(regex, "\\$&");
  };
}());

function translateWPOLanguageKeyToISO(wpoLanguage, jQueryUi) {
  if (!wpoLanguage)
    wpoLanguage = 'de';
  switch(wpoLanguage.toUpperCase()) {
    case 'GER': return 'de';
    case 'FRA': return 'fr';
    case 'ENG': return jQueryUi ? '' : 'en';
    case 'RUM': return 'ro'; 
    case 'HRV': return jQueryUi ? 'sr' : 'en'; // default - moment.js kann noch kein Kroatisch
    case 'HUN': return 'hu';
    case 'RUS': return 'ru';
    case 'ESP': return 'es';
  }
}

function throttle(fn, delay) {
    var timer = null;
    return function() {
        var context = this,
            args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function() {
            fn.apply(context, args);
        }, delay);
    };
}

function setShortTimeout() {
  return $.ajax({
    url: 'https://sedi.luxtram.lu/wponline.dll/SetShortTimeout',
    type: 'POST'
  }).promise();
};  

if (!Array.prototype.indexOf) {
  // Der IE8 (nicht im Kompatibilitätsmodus(!) hat bei Arrays kein indexOf implementiert. 
  Array.prototype.indexOf = function(value) { 
    for (var idx = 0; idx <this.length; idx++) {
      if (this[idx] == value)
        return idx;
    }
    return -1;
  }
}

// Array Remove - By John Resig (MIT Licensed) http://ejohn.org/blog/javascript-array-remove/
Array.prototype.removeByIndex = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from <0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

Array.prototype.removeByValue = function(value) {
  var idx = this.indexOf(value);

  if (idx > -1)
    this.splice(idx, 1);
};

Array.prototype.contains = function(value) {
  return this.indexOf(value) > -1;
};

var gsLongMonthNames = new Array(
  'Januar', 'Februar', 'März', 
  'April', 'Mai', 'Juni', 
  'Juli', 'August', 'September', 
  'Oktober', 'November', 'Dezember'
);

var gsLongDayNames = new Array(
  'Sonntag', 'Montag', 'Dienstag', 
  'Mittwoch', 'Donnerstag', 'Freitag', 
  'Samstag'
);

String.prototype.zf = function (l) { return '0'.string(l - this.length) + this; }
String.prototype.alert = function () { alert(this); }
String.prototype.string = function(l) { var s = '', i = 0; while (i++ <l) { s += this; } return s; }
Number.prototype.zf = function(l) { return this.toString().zf(l); }

String.prototype.fullTrim = function(splitChar) {
  var items = this.split(splitChar); 
  items.forEach(function(item, index, data) { 
    data[index] = trim(item); 
   }); 
   return items.join(splitChar + ' '); 
}
String.prototype.removeHtml = function() {
  var tmp = document.createElement("DIV");
  tmp.innerHTML = this;
  return tmp.textContent || tmp.innerText;
}

Date.prototype.convertFormatSyntax = {};
Date.prototype.convertFormatSyntax.FromPHPToDelphi = function (pattern) {
  return pattern.replace(/[dDjlFmMnyYsiGH]/gi, function () {
    switch (arguments[0]) {
      case 'd': return 'dd';
      case 'D': return 'ddd';
      case 'j': return 'd';
      case 'l': return 'dddd';
      case 'F': return 'mmmm';
      case 'm': return 'mm';
      case 'M': return 'mmm';
      case 'n': return 'm';
      case 'y': return 'yy';
      case 'Y': return 'yyyy';
      case 's': return 'ss';
      case 'i': return 'nn';
      case 'G': return 'h';
      case 'H': return 'hh';
    }
  });
};

Date.prototype.convertFormatSyntax.FromDelphiToPHP = function (pattern) {
  throw 'Not implemented!';
};

Date.prototype.formatDateTime = function (f) {
  if (!this.valueOf())
    return ' ';

  var tmp = new Array();
  f = f.replace(/(['"])(.*?)\1/gi, function ($1, $2, $3, $4) {
    var no = tmp.push(arguments[2]);
    return "x" + (no - 1);
  });
  var d = this;
  return f.replace(/(yyyy|yy|m{1,4}|d{1,4}|h{1,2}|n{1,2}|s{1,2}|(x)(\d+))/gi, function () {
    if (arguments[2] === 'x') {
      return tmp[arguments[3]];
    }
    switch (arguments[1].toLowerCase()) {
      case 'yy': // next case..
      case 'yyyy': return d.getFullYear();
      case 'mmmm': return gsLongMonthNames[d.getMonth()];
      case 'mmm': return gsLongMonthNames[d.getMonth()].substr(0, 3);
      case 'mm': return (d.getMonth() + 1).zf(2);
      case 'm': return (d.getMonth() + 1);
      case 'dddd': return gsLongDayNames[d.getDay()];
      case 'ddd': return gsLongDayNames[d.getDay()].substr(0, 3);
      case 'dd': return d.getDate().zf(2);
      case 'd': return d.getDate();
      case 'hh': return d.getHours().zf(2);
      case 'h': return d.getHours();
      case 'nn': return d.getMinutes().zf(2);
      case 'n': return d.getMinutes();
      case 'ss': return d.getSeconds().zf(2);
      case 's': return d.getSeconds();
    }
  });
}

function stripHTML(value) {
  var rg = /<(.*?)>(.*)<\/\1>/;
  var tmp = '';
  var result = value;
  
  while (result != tmp) {
    tmp = result;
    result = tmp.replace(rg, '$2');
  }
  
  return result;
}

function ExtractFileName(fileName) {
  var data = fileName.split("/");

  return data[data.length - 1];
}

function WinExtractFileName(fileName) {
  var data = fileName.split("\\");
  return data[data.length - 1];
}

function ExtractFileExtension(fileName) {
  var data = fileName.split(".");
  return "." + data[data.length - 1];
}

String.prototype.equalsStr = function(value) {
  return this == value
}
String.prototype.equalsText = function(value) {
  return this.toUpperCase() == value.toUpperCase();
}

// Funktion sprintf, arbeitet ähnlich zu Delphis Format-Befehl. 
// 2010-03-01: kopiert von http://www.webtoolkit.info/javascript-sprintf.html
sprintfWrapper = {
 
	init : function () {
 
		if (typeof arguments == "undefined") { return null; }
		if (arguments.length <1) { return null; }
		if (typeof arguments[0] != "string") { return null; }
		if (typeof RegExp == "undefined") { return null; }
 
		var string = arguments[0];
		var exp = new RegExp(/(%([%]|((\d)+\:)?(\-)?(\+|\x20)?(0)?(\d+)?(\.(\d)?)?([bcdfosxX])))/g);
		var matches = new Array();
		var strings = new Array();
		var convCount = 0;
		var stringPosStart = 0;
		var stringPosEnd = 0;
		var matchPosEnd = 0;
		var newString = '';
		var match = null;
 
		while (match = exp.exec(string)) {
			if (match[11]) { 
        if (match[4])
          convCount = parseInt(match[4]) + 1;
        else
          convCount += 1; 
      }
 
			stringPosStart = matchPosEnd;
			stringPosEnd = exp.lastIndex - match[0].length;
			strings[strings.length] = string.substring(stringPosStart, stringPosEnd);
 
			matchPosEnd = exp.lastIndex;
			matches[matches.length] = {
				match: match[0],
				left: match[5] ? true : false,
				sign: match[6] || '',
				pad: match[7] || ' ',
				min: match[8] || 0,
				precision: match[10],
				code: match[11] || '%',
				negative: parseInt(arguments[convCount]) <0 ? true : false,
				argument: String(arguments[convCount])
			};
		}
		strings[strings.length] = string.substring(matchPosEnd);
 
		if (matches.length == 0) { return string; }
		// if ((arguments.length - 1) <convCount) { return null; }
 
		var code = null;
		var match = null;
		var i = null;
 
		for (i=0; i <matches.length; i++) {
 
			if (matches[i].code == '%') { substitution = '%' }
			else if (matches[i].code == 'b') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(2));
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'c') {
				matches[i].argument = String(String.fromCharCode(parseInt(Math.abs(parseInt(matches[i].argument)))));
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'd') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'f') {
				matches[i].argument = String(Math.abs(parseFloat(matches[i].argument)).toFixed(matches[i].precision ? matches[i].precision : 6));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'o') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(8));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 's') {
				matches[i].argument = matches[i].argument.substring(0, matches[i].precision ? matches[i].precision : matches[i].argument.length)
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'x') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'X') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
				substitution = sprintfWrapper.convert(matches[i]).toUpperCase();
			}
			else {
				substitution = matches[i].match;
			}
 
			newString += strings[i];
			newString += substitution;
 
		}
		newString += strings[i];
 
		return newString;
 
	},
 
	convert : function(match, nosign){
		if (nosign) {
			match.sign = '';
		} else {
			match.sign = match.negative ? '-' : match.sign;
		}
		var l = match.min - match.argument.length + 1 - match.sign.length;
		var pad = new Array(l <0 ? 0 : l).join(match.pad);
		if (!match.left) {
			if (match.pad == "0" || nosign) {
				return match.sign + pad + match.argument;
			} else {
				return pad + match.sign + match.argument;
			}
		} else {
			if (match.pad == "0" || nosign) {
				return match.sign + match.argument + pad.replace(/0/g, ' ');
			} else {
				return match.sign + match.argument + pad;
			}
		}
	}
}
 
sprintf = sprintfWrapper.init;
format = sprintfWrapper.init;

// Bewegt das übergebene Objekt in die Mitte des übergebenen Fensters und zeigt das Objekt ggf. an.
function MoveObjectToCenter(win, obj, show) {
	var top  = (win.innerHeight / 2) - (obj.getHeight() / 2); 
	var left = (win.innerWidth / 2) - (obj.getWidth() / 2);
  
	obj.setLeft(left);
	obj.setTop(top);
	
	if (show) {
	  obj.show();
	}
}

// Prüft, ob der übergebene Dateiname eine vorzugebende Endung hat. 
function CheckFileExtension(filename, extension) {
  var pattern = new RegExp('\\' + extension + '$', 'i');
  var res = filename.search(pattern);
  return res > -1;
}

// Alle Leerzeichen am Anfang und Ende von str werden entfernt
function trim(str) {
  if(typeof(str) == "string") 
    return str.replace(/^\s+|\s+$/g, "");
	else 
    return str;
}

function compareOptionText(a,b) {
  /*
   * return >0 if a>b
   *         0 if a=b
   *        <0 if a<b
   */
  // textual comparison
  return a.text != b.text ? a.text<b.text ? -1 : 1 : 0;
  // numerical comparison
  //  return a.text - b.text;
}

function sortOptions(list) {
  var items = list.options.length;
  // create array and make copies of options in list
  var tmpArray = new Array(items);
  for ( i=0; i<items; i++ )
    tmpArray[i] = new Option(list.options[i].text,list.options[i].value);
  // sort options using given function
  tmpArray.sort(compareOptionText);
  // make copies of sorted options back to list
  for ( i=0; i<items; i++ )
    list.options[i] = new Option(tmpArray[i].text,tmpArray[i].value);
}

function removeClass(value, classToRemove) {
  if (typeof(value) === 'undefined')
    return '';
    
  var tmp = new Array();
  var rst = '';
  
  tmp = value.split(' ');
  
  for (var i in tmp) {
    if (classToRemove.toLowerCase() != tmp[i].toLowerCase()) 
      rst = rst + ' ' + tmp[i];    
  }
  return trim(rst);
}

function addClass(value, classToAdd) {
  if (typeof(value) === 'undefined') 
    return classToAdd;
    
  var tmp = new Array();
  var rst = '';
  var already = false;
  
  tmp = value.split(' ');
  
  for (var i in tmp) {
    already = already || (classToAdd.toLowerCase() == tmp[i].toLowerCase());
    rst = rst + ' ' + tmp[i];
  }
  if (!already)
    rst = rst + ' ' + classToAdd;
    
  return trim(rst);
}

function toggleVis(doc, elemID)
{
  var elem = doc.getElementById(elemID);
  if ((elem) && (elem.style))
  {
    if (elem.style.display == "none")
      elem.style.display = ""
    else
      elem.style.display = "none";
  }
}

function VisOn(doc, elemID)
{
  var elem = doc.getElementById(elemID);
  if (elem)
    elem.style.display = ""
}

function VisOff(doc, elemID)
{
  var elem = doc.getElementById(elemID);
  if (elem)
    elem.style.display = "none"
}

function selectItemByValue(elmnt, value)
{
  for(var i=0; i <elmnt.options.length; i++)
  {
    if(elmnt.options[i].value == value)
      elmnt.selectedIndex = i;
  }
}

function convertToLatinString(message)
{
  var resStr = "";
  var subStr = "";
  var i;
  for (i=0; i<message.length;)
  {
    if ((message.charAt(i) == "&") && ((i+4) <= message.length) && (message.charAt(i+1) == "#"))
    {
      subStr = message.substring (i+2,i+5);
      resStr += String.fromCharCode(subStr);
      i += 5;  
    }
    else
    {
      resStr += message.charAt(i); 
      i++;
    }
  }
  return (resStr);
}