/*
 * $Id: utilities.js 4007 2011-12-13 14:22:58Z j.thomae $
 * (c) 2010 Tallence GmbH
 */

var DEBUG = true;

var spd = spd || {};
spd.dialog = spd.dialog || {};

/**
 * Debugs a message to a console, e.g. firebug.
 *
 * @param msg message to debug
 */
function debug(msg) {
  if (DEBUG && window.console && typeof(console.log) == 'Function') {
    window.console.log(msg);
  }
}

/**
 * Cuts text to a given length and adds a configurable ellipsis.
 *
 * @param text text to cut
 * @param length maximum text length
 * @param ellipsis ellipsis to append, by default '...'
 */
function cutText(text, length, ellipsis) {
  if (ellipsis === undefined) {
    ellipsis = '...';
  }
  if (text.length > length) {
    return text.substring(0, length - ellipsis.length) + ellipsis;
  } else {
    return text;
  }
}

/**
 * Formats the date portion of a given date.
 *
 * @param date date to format
 * @param longFormat if <code>true</code> the month will be rendered as its textual name instead of its number (optional)
 */
function formatDate(date, longFormat) {
  var day = date.getDate();
  var month = date.getMonth() + 1;
  var year = date.getFullYear();

  if (day < 10) {
    day = '0' + day;
  }

  if (longFormat === true) {
    switch (month) {
      case 1: month = 'Januar'; break;
      case 2: month = 'Februar'; break;
      case 3: month = 'M\u00E4rz'; break;
      case 4: month = 'April'; break;
      case 5: month = 'Mai'; break;
      case 6: month = 'Juni'; break;
      case 7: month = 'Juli'; break;
      case 8: month = 'August'; break;
      case 9: month = 'September'; break;
      case 10: month = 'Oktober'; break;
      case 11: month = 'November'; break;
      case 12: month = 'Dezember'; break;
    }

    month = ' ' + month + ' ';
  } else {
    if (month < 10) {
      month = '0' + month;
    }
    month = month + '.';
  }

  return day + '.' + month + year;
}

/**
 * Formats the time portion of a given date.
 *
 * @param date the date to format
 * @param longFormat if <code>true</code> the seconds will be rendered as well (optional)
 */
function formatTime(date, longFormat) {
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var seconds = date.getSeconds();

  if (hours < 10) {
    hours = '0' + hours;
  }
  if (minutes < 10) {
    minutes = '0' + minutes;
  }
  if (seconds < 10) {
    seconds = '0' + seconds;
  }

  if (longFormat === true) {
    return hours + ':' + minutes + ':' + seconds;
  } else {
    return hours + ':' + minutes;
  }
}

var lightbox = {
  open : function(url, width, height, data) {
    // early out
    if (url === undefined || url == '') {
      return;
    }
    // move to top, so we can actually see the lightbox
    $('html').animate({scrollTop:0}, 700);
    // compute style
    var style = 'display:none;';
    if (width !== undefined) { style += 'width:' + width + 'px;'}
    if (height !== undefined) { style += 'height:' + height + 'px;'}

    $('body').prepend('<div id="lightbox" style="' + style + '"><div class="lightbox-content">&nbsp;</div></div><div id="lightbox-dimmer" style="display: none;">&nbsp;</div>');
    $('#lightbox-dimmer').fadeTo(500, 0.5);
    //$('#lightbox-dimmer').click(function() {
    //  lightbox.close();
    //});
    $('#lightbox').fadeIn(500, function() {
      //$(this).find('.btn-close-lightbox').focus();
    });
    $('#lightbox .lightbox-content').prepend('<div class="loading"></div>');
    if (data != undefined && data != null) {
      $.ajax({
        type: 'POST',
        url: url,
        data: data,
        dataType: 'html',
        success: function(html) {
          $('#lightbox .lightbox-content .loading').fadeOut(200, function() {
            lightbox.html(html);
          });
        }
      });
    } else {
      $.ajax({
        url: url,
        success: function(html) {
          $('#lightbox .lightbox-content .loading').fadeOut(200, function() {
            lightbox.html(html);
          });
        }
      });
    }
    return false;
  },
  ajax : function(url, width, height) {
    $.ajax({
      url: url,
      success : function(html) {
          lightbox.html(html);
      }
    });
  },
  html : function(html, width, height) {
    // resize lightbox
    if (width !== undefined) { $('#lightbox').css({ width : width }); }
    if (height !== undefined) { $('#lightbox').css({ height : height });}

    // update markup
    var container = $('#lightbox .lightbox-content');
    container.html(html);

    // look and feel
    container.find('input[type="checkbox"]').custCheckBox();
    container.find('input[type="radio"]').custCheckBox();
    container.find('label').each(function(index, element) {
      var attr = element.getAttribute('for');
      if (!attr) {
        return;
      }
      var target = document.getElementById(attr);
      if (!target) {
        return;
      }
      attr = target.getAttribute('type');
      if (attr != 'radio' && attr != 'checkbox') {
        return;
      }
      element.targetInput = target;
      element.targetElement = target.previousSibling;
      $(element).bind('click', function() {
        switch (this.targetInput.getAttribute('type')) {
          case 'checkbox' :
            if (this.targetInput.checked) {
              this.targetElement.className = this.targetElement.className.replace("on", "off");
            }
            else {
              this.targetElement.className = this.targetElement.className.replace("off", "on");
            }
            return;
          case 'radio' :
            var name = this.targetInput.getAttribute('name');
            var input = Array.prototype.slice.call(document.getElementsByTagName('input'), 0);
            for (var item = input.shift(); item; item = input.shift()) {
              if (item.getAttribute('name') != name) {
                continue;
              }
              var target = item.previousSibling;
              if (item == this.targetInput) {
                target.className = target.className.replace("off", "on");
                continue;
              }
              target.className = target.className.replace("on", "off");
            }
        }
      });
    });

    $('select#salutation').msDropDown();
    $('select#birthday_day').msDropDown();
    $('select#birthday_month').msDropDown();
    $('select#birthday_year').msDropDown();
    $('select#state').msDropDown();

    $('#state-select .select-input').width('284px');
    $('#state-select .select-options').width('314px');

    $('input#title').jSuggest({
      default_text : "",
      terms : ['Dr.','Prof.','Prof. Dr.','Dipl. Ing.'],
      limit : 10000
    });

    // attention: keep order!
    $('input#username').focus();
    $('input#email').focus();
    $('input#firstname').focus();
    $('input#memberid').focus();

    // scroll to top
    $(window).scrollTop(0);

    // ajaxify forms
    container.find('form').not('.noajax').ajaxForm({
      success : function(html) {
        lightbox.html(html);
      }
    });
  },
  close : function() {
    $('#lightbox-dimmer, #lightbox').fadeOut(500, function() { $(this).remove(); });
  }
};

/**
 * confirm dialog in a lightbox.
 * call open() to create such a dialog.
 * param callback is the function that will be called when either "close", "ok" or "cancel" is clicked.
 *   - if "close" or "cancel" is clicked, false will be passed to the callback function,
 *   - if "ok" is clicked, true will be passed back
 */
spd.dialog.lightboxConfirm = {
  callback: {},
  defaultTexts: {
    close: 'Schließen',
    ok: 'Okay',
    cancel: 'Abbrechen',
    title: 'Bestätigen'
  },
  open: function(callback, texts, width, height) {

    if (texts.body === undefined) {
      return;
    }
    if (typeof callback !== "function") {
      return;
    }

    this.callback = callback;
    var txt = $.extend(spd.dialog.lightboxConfirm.defaultTexts, texts);

    // compute style
    var style = 'display:none;';
    if (width !== undefined) { style += 'width:' + width + 'px;'}
    if (height !== undefined) { style += 'height:' + height + 'px;'}

    var bodyText = createLightboxBodyText(txt);
    $('body').prepend('<div id="lightbox" style="' + style + '"><div class="lightbox-content">' + bodyText + '</div></div><div id="lightbox-dimmer" style="display: none;">&nbsp;</div>');

    $('#lightbox-dimmer').fadeTo(500, 0.5);

    $('#lightbox').fadeIn(500, function() {
      //$(this).find('.btn-close-lightbox').focus();
    });

    /*$('#lightbox-dimmer').click(function() {
      $('#lightbox-dimmer, #lightbox').fadeOut(500, function() { $(this).remove(); });
    });*/

    // scroll to top
    $(window).scrollTop(0);

  },
  close: function(result) {
    $('#lightbox-dimmer, #lightbox').fadeOut(500, function() { $(this).remove(); });
    this.callback(result);
    return false;
  }
};

function createLightboxBodyText(txt){
  if(txt.boxHead != undefined) {
    var bodyText = '<div class="content-head"><h2>' + txt.title + '</h2><p class="overview"><a href="#" onclick="spd.dialog.lightboxConfirm.close(false);" class="btn-close-lightbox">' + txt.close + '</a></p></div>';
    bodyText += '<div class="box-head"><h4>' + txt.boxHead + '</h4></div>';
    bodyText += '<div class="box-content"><div class="grey_box"><form action="#" method="post" onsubmit="return false;"><fieldset>' + txt.body + '<br /><br />';
    bodyText += '<p class="clearfix"><input type="submit" value="' + txt.cancel + '" class="submit fancy right" title="' + txt.ok + '"  onclick="return spd.dialog.lightboxConfirm.close(false);"/><input type="submit" value="' + txt.ok + '" class="submit fancy right abstand_rechts_8" title="' + txt.ok + '" onclick="return spd.dialog.lightboxConfirm.close(true);" /></p>';
    bodyText += '</fieldset></form></div></div></div>';  return bodyText;
  } else {
    var bodyText = '<div class="content-head"><h2>' + txt.title + '</h2><p class="overview"><a href="#" onclick="spd.dialog.lightboxConfirm.close(false);" class="btn-close-lightbox">' + txt.close + '</a></p></div>';
    bodyText += '<div class="light-box">';
    bodyText += '<div class="box-content"><form action="#" method="post" onsubmit="return false;"><fieldset>' + txt.body;
    bodyText += '<p class="submit"><input type="submit" value="' + txt.ok + '" class="submit fancy left" title="' + txt.ok + '" onclick="return spd.dialog.lightboxConfirm.close(true);" /><input type="submit" value="' + txt.cancel + '" class="submit fancy right" title="' + txt.ok + '"  onclick="return spd.dialog.lightboxConfirm.close(false);"/></p>';
    bodyText += "</fieldset></form></div></div>";return bodyText;
  }
}

