var clockDiv = null;

function updateClock() {
    if (clockDiv === null) {
        clockDiv = document.getElementById("header-clock");
    }

    if (clockDiv) {
        var d = new Date();
        var h = d.getHours();
        var m = d.getMinutes();

        clockDiv.innerHTML = h + (m < 10 ? ":0" : ":") + m; // set hour:minute

        clockDiv.style.display = "block"; // make visible when javascript is present

        setTimeout(updateClock, 5000);
    }
    else {
        setTimeout(updateClock, 250);
    }
}

updateClock();

String.prototype.startsWith = function (str) { return (this.match("^" + str) == str); };

function updateLanguage(language) {
  language = language.substring(0, 2);

  $.get(window.Path + "/Cultures/Translation." + language + ".xml?rv=" + window.Version, function (xmlDoc) {
    var dict = [];
    var translations = xmlDoc.getElementsByTagName("trans");
    for (var t = 0; t < translations.length; t++) {
      var k = translations[t].attributes.getNamedItem("key").value;
      var v = translations[t].textContent || translations[t].text;

      dict[k] = v;
    }

    var els = document.getElementsByTagName("p");
    for (var p = 0; p < els.length; p++) {
      if (els[p].className == "Translation") {
        els[p].innerHTML = dict[els[p].attributes.getNamedItem("key").value];
      }
    }
  });
}

function initializeInterface() {
  // initialize all labeled textboxes
  $(".labeled_textbox").click(function () {
    $(this).children("input")[0].focus();
  });
  // initialize delayed text changed
  $(".labeled_textbox").data('timeout', null).keyup(function () {
    clearTimeout($(this).data('timeout'));

    $(this).data('timeout', setTimeout("document.getElementById('" + this.id + "').delayedTextChanged()", /*500*/0));
  });

  // IN IE (does not work atm)
  /*if (isIE()) {
    // wrap each default_button with an inline-block span to remove the corner-radius
    $(".default_button").wrap(function () {
      return '<span style="border-radius: 4px; overflow: hidden; display: inline-block;" />';
    });
  }*/
}


/* LOADING ANIMATION */
function LoadingAnimation() { }

LoadingAnimation.Show = function (id) {
  var container = $(id);
  if (container === null) {
    return;
  }

  var p = container.offset();
  var la = $('<div id="loading_animation_' + container.attr('id') + '" style="left: ' + p.left + 'px; width: ' + container.width() + 'px; top: ' + (p.top + (container.height() / 2)) + 'px;" class="loading_animation"><div></div><div></div><div></div><div></div></div>');

  $('body').append(la);
};

LoadingAnimation.Hide = function (id) {
  var container = $(id);
  if (container === null) {
    return;
  }

  id = '#loading_animation_' + container.attr('id');
  $(id).remove();
};

/* LABELED TEXTBOX */
function LabeledTextbox(id) {
  this.id = id;
}

LabeledTextbox.prototype.SetValue = function (val) {
  document.getElementById(this.id).children[1].value = val;
};

LabeledTextbox.prototype.GetValue = function () {
  return document.getElementById(this.id).children[1].value;
};

function PagingListbox(id, templateId, url) {
  this.id = id;
  this.url = url;
  this.templateId = templateId;
  this.parameters = [];

  this.offset = 0;
  this.maxResults = 5;
  this.maxOffset = -1;

  this.delayedRefresh = null;

  this.lastRequest = null;

  var thisObj = this;

  $(this.id + " .paging_listbox_prev").click(function () { thisObj.offset = Math.max(0, (thisObj.offset - thisObj.maxResults)); thisObj.DelayedRefresh(); });
  $(this.id + " .paging_listbox_next").click(function () { thisObj.offset = Math.min(thisObj.maxOffset, (thisObj.offset + thisObj.maxResults)); thisObj.DelayedRefresh(); });
}

PagingListbox.prototype.setValue = function (key, value) {
  this.parameters[key] = value;
};

PagingListbox.prototype.getUrl = function () {
  var target = this.url;

  target = target + "&offset=" + this.offset;
  target = target + "&maxResults=" + this.maxResults;

  for (var key in this.parameters) {
    if (this.parameters.hasOwnProperty(key)) {
      if (this.parameters[key] === "") {
        continue;
      }

      target = target + "&" + key + "=" + encodeURI(this.parameters[key]);
    }
  }

  return target;
};

PagingListbox.prototype.Reset = function () {
  this.parameters = [];
};

PagingListbox.prototype.ShowLoadingAnimation = function (show) {
  var anim = $(this.id + " .loading_animation");

  if (show) {
    anim.show();
  }
  else {
    anim.hide();
  }
};

PagingListbox.prototype.EnablePrevButton = function (enable) {
  var btn = $(this.id + " .paging_listbox_prev");

  if (enable) {
    btn.removeClass("default_button_disabled");
  }
  else {
    btn.addClass("default_button_disabled");
  }
};

PagingListbox.prototype.EnableNextButton = function (enable) {
  var btn = $(this.id + " .paging_listbox_next");

  if (enable) {
    btn.removeClass("default_button_disabled");
  }
  else {
    btn.addClass("default_button_disabled");
  }
};

PagingListbox.prototype.ShowItems = function (offset, maxOffset, visibleCount) {
  $(this.id + " .paging_listbox_items").css('display', 'inline-block');
  $(this.id + " .paging_listbox_no_items").css('display', 'none');
};

PagingListbox.prototype.ShowNoItems = function () {
  this.EnablePrevButton(false);
  this.EnableNextButton(false);

  $(this.id + " .paging_listbox_items").css('display', 'none');
  $(this.id + " .paging_listbox_no_items").css('display', 'inline-block');
};

PagingListbox.prototype.SetPagingLabel = function (label) {
  var lbl = $(this.id + " .paging_listbox_paging_label");
  lbl[0].innerHTML = label;
};

PagingListbox.prototype.ResetPaging = function () {
  this.maxOffset = -1;
  this.offset = 0;
  this.SetPagingLabel("");
};

PagingListbox.prototype.Refresh = function () {
  var thisObj = this;

  LoadingAnimation.Show(thisObj.id);

  var url = this.getUrl();

  if (this.lastRequest !== null) {
    this.lastRequest.abort();
  }

  this.lastRequest = $.get(url, function (data) {
    LoadingAnimation.Hide(thisObj.id);

    var ul = $(thisObj.id + " ul");

    // remove current items
    ul.empty();

    var p = null;
    try {
      p = $.parseJSON(data);
    }
    catch (err) { }

    if (p && p.items && p.items.length && p.items.length > 0) {
      var items = p.items.length;
      var offset = p.paging.offset;
      var maxOffset = p.paging.maxOffset;
      thisObj.maxOffset = maxOffset;

      // for IE: hide img when no image uri is available, else we get an ugly missing image icon
      var itm;
      for (itm in p.items) {
        if (p.items.hasOwnProperty(itm)) {
          if (p.items[itm].uri === undefined || p.items[itm].uri === '') {
            p.items[itm].img_visibility = 'visibility: hidden;';
          }
        }
      }

      thisObj.ShowItems(offset, maxOffset, items);

      if (offset > 0) {
        thisObj.EnablePrevButton(true);
      }
      else {
        thisObj.EnablePrevButton(false);
      }

      if (offset + items <= maxOffset) {
        thisObj.EnableNextButton(true);
      }
      else {
        thisObj.EnableNextButton(false);
      }

      $(thisObj.templateId).tmpl(p.items).appendTo(ul);

      // set paging position
      thisObj.SetPagingLabel("" + (Math.round(offset / thisObj.maxResults) + 1) + " / " + (Math.round(maxOffset / thisObj.maxResults) + 1));
    }
    else {
      thisObj.ShowNoItems();
      thisObj.SetPagingLabel("");
    }
  });
};

PagingListbox.prototype.DelayedRefresh = function () {
  if (this.delayedRefresh !== null) {
    clearTimeout(this.delayedRefresh);
  }

  //http://klevo.sk/javascript/javascripts-settimeout-and-how-to-use-it-with-your-methods/
  var thisObj = this;
  this.delayedRefresh = setTimeout(function () { thisObj.Refresh(); }, 350);
};

PagingListbox.prototype.HasValues = function () {
  for (var key in this.parameters) {
    if (this.parameters.hasOwnProperty(key)) {
      if (this.parameters[key] !== "") {
        return true;
      }
    }
  }
  return false;
};

/* SCROLLBOX */
function Scrollbox(id, templateId, url) {
  this.id = id;
  this.url = url;
  this.templateId = templateId;

  this.lastRequest = null;

  //  $(this.id + " .scrollbox_items").wrapInner(function () {
  //    return $('<div class="scrollbar"><div class="track"><div class="thumb"><div class="end"></div></div></div><div class="viewport"><div class="overview"><ul></ul></div></div></div></div>');
  //  });
  //  $(this.id + " .scrollbox_items").tinyscrollbar();
}

Scrollbox.prototype.ItemPressed = function (index, item) { };

Scrollbox.prototype.Refresh = function () {
  var thisObj = this;

  LoadingAnimation.Show(thisObj.id);

  if (this.lastRequest !== null) {
    this.lastRequest.abort();
  }

  this.lastRequest = $.get(this.url, function (data) {
    LoadingAnimation.Hide(thisObj.id);

    var ul = $(thisObj.id + " ul");

    // remove current items
    ul.empty();

    var p = null;
    try {
      p = $.parseJSON(data);
    }
    catch (err) { }

    if (p && p.items && p.items.length && p.items.length > 0) {
      var items = p.items.length;

      // for IE: hide img when no image uri is available, else we get an ugly missing image icon
      var itm;
      for (itm in p.items) {
        if (p.items.hasOwnProperty(itm)) {
          if (p.items[itm].uri === undefined || p.items[itm].uri === '') {
            p.items[itm].img_visibility = 'visibility: hidden;';
          }
        }
      }

      $(thisObj.templateId)
      .tmpl(p.items)
      .appendTo(ul)
      .click(function () {
        var tmplitem = $.tmplItem(this);
        thisObj.ItemPressed(tmplitem.key - 1, tmplitem.data);
      });

      $(thisObj.id + " .scrollbox_items").css('display', '');
      $(thisObj.id + " .scrollbox_no_items").css('display', 'none');

      $(thisObj.id).scrollbars();
    }
    else {
      $(thisObj.id + " .scrollbox_items").css('display', 'none');
      $(thisObj.id + " .scrollbox_no_items").css('display', 'inline-block');
    }
  });
};

