/*
  Common JS functions for vinfox AG web pages.
  (c) 2011 vinfox AG, CH-8008 Zürich
  $Id: common.js 423 2011-10-11 08:44:00Z knecht $
*/

/**
   Set the heights of the layout elements according to the height of the
   viewport.
*/
function setLayoutHeight() {
  var content = $('div.content'),
    left = $('div.left-margin'),
    h = $(window).height(),
    y = content.offset().top,
    ch = y + content.outerHeight(true);
  if (ch > h) h = ch;
  var mh = y + left.outerHeight(true);
  var footer = $('div.footer', left);
  var mh2 = footer ? mh + footer.outerHeight(true) + 30 : mh;
  if (mh2 > h) h = mh2;
  $('img.border').attr('height', h);
  h -= mh - left.height();
  left[0].style.height = h + 'px';
}

/**
   Setup the menu links and the current ids.
*/
function setupMenu() {
  $('ul.menu a').button();
}

/**
   Standard initialization function. Requires vinfox AG standard page layout,
   as defined in common.css.
*/
function setupCurrent() {
  var location = window.location;
  var host = location.hostname;
  $('span.links > a').each(function(i) {
      if ($(this).attr('href').indexOf(host) >= 0)
        $(this).addClass("current");
    });
  var language = location.pathname;
  language = language.substring(language.lastIndexOf('.') + 1);
  $('span.languages a:contains("' + language + '")').addClass("current");
  var path = location.pathname;
  if (path.indexOf("/") == 0) path = path.substring(1);
  if (path.length == 0) path = "index.";
  var slashPath = "/" + path;
  $('ul.menu a').each(function(i) {
      var href = $(this).attr('href');
      if (href.indexOf(path) == 0 || href.indexOf(slashPath) >= 0 ||
          path.indexOf(href) >= 0)
        $(this).addClass("current");
    });
}

/**
   Set the "op" field to a value.
*/
function setOp(value) {
  return $('input#op').attr('value', value).length != 0;
}

/**
   Set an input field to a value.
*/
function setFieldValue(name, value) {
  return $('input#' + name).attr('value', value).length != 0;
}

/**
   Set a radio button field to a value.
*/
function setRadioValue(name, value) {
  var elt;
  for (var i = 0; (elt = $('input#' + name + i)).length != 0; i++) {
    if (elt.attr('value') == value) elt.attr('checked', 'checked');
    else elt.removeAttr('checked');
    elt.button('refresh');
  }
}

/**
   Standard initialization function. Requires vinfox AG standard page layout,
   as defined in common.css.
*/
function commonInit() {
  $(document).ready(function() {
      $('button').button();
      $('a.button').button();
      $('input.button').button();
      $('#tabs').tabs({
          cookie: { path: window.location.pathname, expires: 1 }
        });
      $('div.buttonset').buttonset();
      $('input.focus').focus();
      $('textarea.focus').focus();
      $('div.accordion').accordion();
      setupMenu();
      setupCurrent();
      setLayoutHeight();
  }); 
}

/**
   Set the query graphic in its div.
   @param text the text to show.
   @param at the progress position (-1 for not found, 0 to max otherwise)
   @param max the maximum progress position, undefined for default.
*/
function setQueryProgress(text, at, max) {
  if (!max) max = 10;
  var div = $('div.count');
  if (at > max) at = max;
  var w = div.width() - 20,
    w1 = at < 0 ? 0 : Math.round(w * at / max);
  var s =
    '<img src="countimages/' +
    (at < 0 ? 'notfound' : 'found') +
    '_L.png" style="width: 10px;" />' +
    '<img src="countimages/' +
    (at < 0 ? 'notfound' : 'found') +
    '_C.png" style="width: ' + (w - w1) + 'px;" />' +
    '<img src="countimages/' +
    (at < 0 ? 'notfound' : 'background') +
    '_C.png" style="width: ' + w1 + 'px;" />' +
    '<img src="countimages/' +
    (at < 0 ? 'notfound' : (at == 0 ? 'found' : 'background')) +
    '_R.png" style="width: 10px;" />';
  div.html(s + '<span>' + text + '</span>');
}

var showAjaxErrors = false;

function setAjaxWaiting(enabled) {
  $('#ajaxwait').html(enabled ? '<img src="images/ajaxwait.gif" />' : '');
}

var ajaxError = function(xhr, textStatus, errorThrown) {
  setAjaxWaiting(false);
  if (showAjaxErrors) {
    alert(errorThrown);
  }
};

/**
   Run the query count from a form.
*/
function countQuery(field) {
  var form = field;
  while (field && field.tagName != 'FORM') {
    field = field.parentNode;
  }
  if (field) {
    field = $(field);
    var url = field.attr('action'), hash = '';
    var i = url.indexOf('#');
    if (i >= 0) { hash = url.substring(i); url = url.substring(0, i); }
    url = url + '?op=count&' + field.serialize() + hash;
    $.ajax({
        type: 'get',
        url: url,
        dataType: 'text',
        success: function(html, textStatus) {
          var f = html.split('\n');
          if (f.length >= 2)
            setQueryProgress(f[0], parseFloat(f[1]),
                             f.length > 2 ? parseFloat(f[2]) : null)
        },
        error: ajaxError
      });
  }
  return true;
}

function performConfirmed(elt) {
  if (elt.href) window.location = elt.href;
  else {
    while (elt && elt.tagName != 'FORM') {
      elt = elt.parentNode;
    }
    if (elt) elt.submit();
  }
}

/**
   Open a confirm dialog.
*/
function confirmDialog(elt, question, ok, cancel, confirmedAction) {
  var div = $('div#confirm');
  if (div.length == 0) return confirm(question);
  div[0].style.visibility = 'visible';
  div.text(question);
  div.dialog({
      autoOpen: false,
      width: 320,
      modal: true,
      resizable: false,
      buttons: [
        {
          text: ok,
          click: function() {
            $(this).dialog('close');
            if (confirmedAction) confirmedAction(elt);
            performConfirmed(elt);
          }
        },
        {
          text: cancel,
          click: function() {
            $(this).dialog('close');
          }
        }
      ]
    });
  div.dialog('open');
  return false;
}

/**
   Add a farbtastic colorpicker.
*/
jQuery.fn.colorpicker = function() {
  $(this).each(function(i) {
      var input = $(this);
      var div = $('<div class="colorpicker" id="' + this.id + '"></div>').
      insertAfter(input);
      input.click(function(e) {
          if (input.attr('value').length == 0)
            input.attr('value', '#ffffff');
          div.farbtastic(input);
        });
    });
}

function getValuePickerValues(input) {
  var res = new Array();
  $('div#' + input.id + '_values span').each(function(i) {
      res[i] = $(this).text();
    });
  return res;
}

/**
   Add a value picker.
*/
jQuery.fn.valuepicker = function() {
  $(this).each(function(i) {
      var values = getValuePickerValues(this);
      $(this).autocomplete({
          source: function(request, response) {
            response(values);
          },
          minLength: 0
        })
      .focus(function() {
          $(this).autocomplete('search', '');
        });
    });
}

