/** @file baugui-defaults.js
 *  @brief basic gui functionality
 *  @version $Id: bau.gui.js,v 1.119 2009-05-11 23:12:53 bauglir Exp $
 *  @author Bronislav Klucka, Bronislav.Klucka@bauglir.com,
 *          Copyright &copy; 2009+ Bronislav Klucka
 *
 * This script is licenced under BSD licence: http://licence.bauglir.com/bsd.php
 *
 *
 */

jQuery.fx.off = Bauglir.Browser.Msie6;

Bauglir.GUI = {};
Bauglir.GUI.libVersion = '000.900';

Bauglir.GUI.buttonSelector = "button, input[type='submit'], input[type='reset'], input[type='image']";
Bauglir.GUI.buttonSelectorNoImg = "button, input[type='submit'], input[type='reset']";
Bauglir.GUI.buttonSelectorOnly = "input[type='submit'], input[type='reset']";

Bauglir.GUI.ribbonSetHeightTimeOut = 1000;

/*********************************/
/******** GENERAL ****************/
/*********************************/

/**
 * display element at the bottom of other element
 * @param jQuery|string element element to display
 * @param jQuery|string destination element to position showing to
 */
Bauglir.GUI.DisplayBottom = function(element, destination)
{
  if(typeof element == 'string') element = $(element);
  if(typeof destination == 'string') destination = $(destination);
  element.show();

  var top = destination.positionTop();
  var left = destination.positionLeft();

  top += destination.outerHeight();
  element.css("top", top + "px");
  element.css("left", left + "px");
}

/**
 * create visual highlight effect
 * @param jQuery|string element jQuery or selector to highlight
 */
Bauglir.GUI.HighLight = function(element)
{
  if (!jQuery.fx.off)
  {
    if(typeof element == 'string') element = $(element);
    element.stop(true, true);
    element.effect('highlight', {color: '#ffbfe8'}, 1000);
  }
}

/**
 * general function to hide all floating object that should be hidden if event occures
 * e.g. click on body should hide context menu
 * @param Event event event object 
 */
Bauglir.GUI.HideFloating = function(event)
{

  //$('#todoViewTextPanel').html('hide' + new Date());
  
  if (event == null)
  {
    
    Bauglir.GUI.ContextMenu.HideAll();
    $('.baugui-calendar-year-list').hide();
    $('.baugui-calendar-month-list').hide();
    $('.baugui-calendar-floatable').hide();
    $('.baugui-dropdownlist-items').hide();
    $('.baugui-treeview-floating-box').remove();
    //$('#todoViewTextPanel').html(' <br />none <br />');
  }
  else
  {
    /*$(event.target).parents('ul').map(function(){
      $('#todoViewTextPanel').html(" <br />" + $('#todoViewTextPanel').html() + this.id + " - " + this.className);
    })*/
    if (!Bauglir.GUI.baugui_contextMenuIsItem(event.target)) $(".baugui-contextMenu").hide();
    if (!$(event.target).parents('.baugui-calendar-year-list').length) $('.baugui-calendar-year-list').hide();
    if (!$(event.target).parents('.baugui-calendar-month-list').length) $('.baugui-calendar-month-list').hide();
    if (!$(event.target).parents('.baugui-calendar-floatable').length) $('.baugui-calendar-floatable').hide();
    if (!$(event.target).parents('.baugui-dropdownlist-items').length) $('.baugui-dropdownlist-items').hide();
    if (!$(event.target).closest('.baugui-treeview-floating-box').length) $('.baugui-treeview-floating-box').remove();
  }
  //throw new Exception();
}

/**
* generate random HTML id
* @return string
*/
Bauglir.GUI.RandomId = function()
{
  var d = new Date();
  var id = Math.round(Math.random() * 1000000) + d.getMilliseconds();

  return String.RandomChar() + id;
}

Bauglir.GUI.Style = '';

/**
 * set button disabled/enabled
 *
 * @param jQuery|string element jQuery object representing element or it's id
 * @param bool disabled whether element should be disabled or enabled
 */
Bauglir.GUI.SetDisabled = function(element, disabled)
{
  if(typeof element == 'string') element = $(element);
  if (disabled == null) disabled = !element.eq(0).hasClass('baugui-disabled');
  if (disabled)
  {
    element.attr('disabled', true);
    element.addClass('baugui-disabled');
  }
  else
  {
    element.removeAttr("disabled");
    element.removeClass('baugui-disabled');
  }
}


Bauglir.GUI.CSSRoot = null;

/**
 * function to change style sheet
 * @param string name enum(basic, blue, luna, obsidian, olive, silver,whidbey)
 */
Bauglir.GUI.ChangeSheets = function(name)
{
  name = name.toLowerCase();
  if(document.styleSheets)
  {
    var lunaIndex = -1;
    var c = document.styleSheets.length;
    for(var i = 0; i < c; i++)
    {
      if(document.styleSheets[i].href == null) continue;
      if (document.styleSheets[i].href.indexOf("/css/bau.gui.default.css") != -1) continue;
      if (document.styleSheets[i].href.indexOf("/css/bau.gui.default_msie.css") != -1) continue;
      if (document.styleSheets[i].href.indexOf("/css/bau.gui.luna.css") != -1)
      {
        var p = document.styleSheets[i].href.split("bau.gui.luna.css");
        Bauglir.GUI.CSSRoot = p.join('');
        lunaIndex = i;
      }
      if (document.styleSheets[i].href.indexOf("/css/bau.gui." + name + ".css") != -1)
      {
        lunaIndex = -1;
        Bauglir.GUI.Style = name;
        document.styleSheets[i].disabled = false;
      }
      else if (document.styleSheets[i].href.indexOf("/css/bau.gui.") != -1) document.styleSheets[i].disabled = true;
    }
    if (lunaIndex != -1) document.styleSheets[lunaIndex].disabled = false;
  }
}

/**
 * wrapper around jQuery.hide(speed, callback)
 */
Bauglir.GUI.Hide = function (jObject, speed, callback)
{
  /* * /
  var pos = jObject.position();
  
  var x = pos.left + Math.round((jObject.get(0).offsetWidth) / 2);  
  var y = pos.top + Math.round((jObject.get(0).offsetHeight) / 2);
  jObject.data('originaHeight', jObject.get(0).offsetHeight);
  jObject.data('originaWidth', jObject.get(0).offsetWidth);
  alert(jObject.data('originaHeight'));
  jObject.animate({width: "0px", height: '0px', opacity: '0', top: y + "px", left: x + "px"}, speed, callback);
  /* */
  jObject.hide(speed, callback);
}


/*************************************/
/*********** WAIT BOX ****************/
/*************************************/
Bauglir.GUI.Wait = {};

/**
 * create "wait box"
 * wait box is represented by DIV element stretched across whole element with wait animation
 * @param mixed parent element where to create waitbox on
 * @param float transparencyRatio ratio of opacity
 * @param mixed backgroundColor backgraoud color
 */
Bauglir.GUI.Wait.Create = function(parent, transparencyRatio, backgroundColor)
{
  if (backgroundColor == null) backgroundColor = "#FFFFFF";
  if (transparencyRatio == null) transparencyRatio = "0.7";


  $(parent).map(function(){
    if (!$(this).find('.baugui-wait').length)
    {
      var html = "<div class='baugui-waitBox'>&nbsp;</div>";
      if (($(this).css('position') != 'relative') && ($(this).css('position') != 'absolute'))
        $(this).css('position', 'relative');
      $(this).append(html);
      $(this).find('.baugui-waitBox').css('opacity', transparencyRatio);
      $(this).find('.baugui-waitBox').css('backgroundColor', backgroundColor);
    }
  });
}

/**
 * remove "wait box"
 * @param mixed parent element where to remove waitbox from
*/
Bauglir.GUI.Wait.Remove = function(parent)
{
  $(parent).map(function(){$(this).find('.baugui-waitBox').remove()});
}

/*********************************/
/****** DROP DOWN LIST ***********/
/*********************************/

Bauglir.GUI.DropDownList = {};

/**
 * select value
 * @param string inputId input
 * @param data data to select
 */
Bauglir.GUI.DropDownList.SelectData = function(inputId, data)
{
/*
    if ($(this).find('.baugui-dropdowndata').length)
      element.data("baugui-dropdowndata", $(this).find('.baugui-dropdowndata').text())
    else
      element.data("baugui-dropdowndata", element.val());

 */
  var element = $("#" + inputId);
  var list = element.data('baugui-list');
  if (list != null)
  {
    var selectedLi = null;
    list.find('li .baugui-dropdowndata').each(function(){
      if ($(this).text() == data) selectedLi = $(this).closest('li');
      return $(this).text() != data;
    });
    if (selectedLi == null)
    {
      list.find('li').each(function(){
        if ($(this).text() == data) selectedLi = $(this);
        return $(this).text() != data;
      });
    }
    if (selectedLi) selectedLi.triggerHandler('click');
  }
}

/**
 * create dropdown list
 * @param string inputId input to display dropdown on focus
 * @param string listId list of items (UL)
 * @param function callback function to be called after selection (jQuery input, jQuery li)
 * @param int defaultIndex selected drop down item
 */
Bauglir.GUI.DropDownList.Create = function(inputId, listId, callback, defaultIndex)
{
  if(defaultIndex == null) defaultIndex = 0;
  var element = $("#" + inputId);
  var list = $("#" + listId);
  element.data('baugui-list', list);
  list.appendTo(element.parent());
  element.wrap("<div class='baugui-dropdownlist-wrap'></div>");
  var wrapper = element.parent();
  element.wrap("<div class='baugui-dropdownlist-wrapinner'></div>");
  element.addClass('baugui-dropdownlist');
  element.attr('readonly', true);


  list.disableSelection();


  list.addClass('baugui-dropdownlist-items').addClass('baugui-box-dark');//.addClass('baugui-mainBackground');
  wrapper.prepend("<button class='baugui-dropdownlist-button'></button>");
  var height = element.outerHeight();
  if (Bauglir.Browser.Msie) height = element.innerHeight();
  wrapper.find('.baugui-dropdownlist-button').css('height', height + "px");
  wrapper.find('.baugui-dropdownlist-button').css('lineHeight', height + "px");
  wrapper.find('.baugui-dropdownlist-button').append("<img src='" + Bauglir.GUI.CSSRoot + "/images/downarrow_10.gif' alt='' />");

  var displayFunction = function(){
    if (element.attr('disabled')) return;
    var top = wrapper.positionTop();
    var left = wrapper.positionLeft();
    top += element.outerHeight();
    if (Bauglir.Browser.Msie) list.css('width', wrapper.outerWidth() + "px");
    else list.css('min-width', wrapper.outerWidth() + "px");
    list.css("top", top + "px");
    list.css("left", left + "px");
    list.css("zIndex", "1000");
    list.show();
    var maxLi = 0;
    list.find('li').map(function(){
      maxLi = Math.max(maxLi, $(this).outerHeight(true));
    });
    list.find('li').css('height', maxLi + "px");
  };

  list.find('li').hover(
    function(){
      $(this).addClass('baugui-darkBackground');
    },
    function(){
      $(this).removeClass('baugui-darkBackground');
    }
  );


  list.find('li').click(function(){
    var cl = $(this).clone(false);
    cl.find(".baugui-dropdowndata").replaceWith("");
    var text = cl.text().trim();
    element.val(text);
    if ($(this).find('.baugui-dropdowndata').length)
      element.data("baugui-dropdowndata", $(this).find('.baugui-dropdowndata').text())
    else
      element.data("baugui-dropdowndata", element.val());
    list.hide();
    if (callback != null) callback(element, $(this));
  });
  list.find('li').eq(defaultIndex).triggerHandler('click');

  Bauglir.GUI.baugui_buttonMainFuncts(wrapper);

  wrapper.find('.baugui-dropdownlist-button').click(function(){displayFunction(); return false;});
  element.focus(displayFunction);
}

/*********************************/
/********** NUMERIC **************/
/*********************************/

Bauglir.GUI.Numeric = {};

/**
 * create functionality for numeric input
 *
 * if either minValue or maxValue is not passed
 *
 * @param string inputId id of input
 * @param int numericType type of number (float or integer), enum(Number.Integer = 1, Number.Float = 2)
 * @param number minValue minimal value
 * @param number maxValue maximal value
 * @param string append string to append
 */
Bauglir.GUI.Numeric.Create = function(inputId, numericType, minValue, maxValue, append)
{
  var element = $("#" + inputId);
  element.css("text-align", 'right');
  element.css("padding-right", '2px');
  if (!numericType) numericType = Number.Integer;
  if (minValue) element.val(minValue);
  else element.val('0');
  element.data('baugui-number', element.val());

  var funct = (function(e)
  {
    var restore = false;
    try
    {
      var value = element.val().trim();

      if (append)
      {
        var vals = value.split(append)
        if (vals.length == 2)
          if (!vals[1])
            value = vals[0].trim();
      }

      if (value == '0'); //preserve as converting default value
      else if (value == '0 ' + append); //preserve as converting default value
      else if (value == '') value = '0';
      else
      {

        if (e.type != 'blur')
        {
          if (new Array('.', ',').contains(value.substring(value.length - 1))) return;
          if (value == '-') return;
        }

        
        if (numericType == Number.Integer) value = Bauglir.Int(value, 0);
        else if (numericType == Number.Float) value = Bauglir.Float(value, 0);
        if (value == 0) restore = true;
        else
        {
          
          if (minValue != null)
            if (value < minValue) value = minValue;
          if (maxValue != null)
            if (value > maxValue) value = maxValue;
          
        }
      }
      element.val(value);
    }
    catch(e) {restore = true;}

    if (restore)
    {
      element.val(element.data('baugui-number'));
      Bauglir.GUI.HighLight(element);
    }
    //
    element.data('baugui-number', element.val());
    if (append == null) append = '';
    if (e.type == 'blur' && append != '') element.val(element.val() + " " + append);
  });

  if (Bauglir.Browser.Opera) element.changed(funct);
  else if (Bauglir.Browser.Firefox) element.changed(funct);
  //else if (Bauglir.Browser.Msie) element.changed(funct);
  else element.changedNoKey(funct);

  element.triggerHandler('blur');
}


/*********************************/
/************ TIME ***************/
/*********************************/

Bauglir.GUI.Time = {};

/**
 * function sets date for input
 * @param string inputId
 * @param Date date JS date object
 * @param string format string to format date output
 */
Bauglir.GUI.Time.SetInputDateTime = function(inputId, date)
{
  var element = $("#" + inputId);
  if (date != null) element.val(date.TimeShort());
  else element.val("00:00");
  element.data('baugui-time', element.val());

}


/**
 * create functionality for time input
 *
 * @param string inputId id of input
 */
Bauglir.GUI.Time.Create = function(inputId)
{
  var element = $("#" + inputId);
  element.val("00:00");
  element.data('baugui-time', element.val());
  element.blur(function(){
    var restore = false;
    try
    {
      var reg = /(\d{1,2}):(\d{2})/;
      var parts = element.val().match(reg);
      if (parts.length == 3)
      {
        var hours = Bauglir.Int(parts[1], -1);
        var minutes = Bauglir.Int(parts[2], -1);
        if ((hours >= 0) && (hours < 24) && (minutes >= 0) && (minutes < 60))
        {
          var time = hours.Pad(2, '0', String.PadLeft) + ":" + minutes.Pad(2, '0', String.PadLeft);
          element.val(time);
        } else restore = true;
      }
      else restore = true;
    }
    catch(e) {restore = true;}

    if (restore)
    {
      element.val(element.data('baugui-time'));
      Bauglir.GUI.HighLight(element);
    }
    element.data('baugui-time', element.val());
  })

}

//time-input

/*********************************/
/*********** /TIME ***************/
/*********************************/



/*********************************/
/******** CALENDAR ***************/
/*********************************/

Bauglir.GUI.Calendar = {};


/**
 * list of function triggered if date is selected
 */
Bauglir.GUI.Calendar.RegisteredOnClickFunctions = new Array();

/**
 * register callback function to be triggered if date is selected
 * @param string calendarId id on calendar
 * @param function callback function(calendarjObject, datetime)
 */
Bauglir.GUI.Calendar.RegisterOnClick = function(calendarId, callback)
{
  Bauglir.GUI.Calendar.RegisteredOnClickFunctions[calendarId] = callback;
}

/**
 * function sets date for input
 * @param string inputId
 * @param Date date JS date object
 * @param string format string to format date output
 */
Bauglir.GUI.Calendar.SetInputDateTime = function(inputId, date, format)
{
  
  if (date != null)
  {
    if (!format)
      format = $("#" + inputId).data("baugui-dateformat")
    if (!format)
      format = 'Y-m-d';
    date = new Date(date);
    $("#" + inputId).val(date.Format(format));
    $("#" + inputId).data("baugui-date", date.Date());
    $("#" + inputId).data("baugui-jsdate", new Date(date));
  }
  else
  {
    $("#" + inputId).val('');
    $("#" + inputId).data("baugui-date", null);
    $("#" + inputId).data("baugui-jsdate", null);
  }
}

/**
 * function creates hidden (floating) calendar for input
 * appears if input is focused
 * @param string inputId
 * @param string language
 * @param function callback calback function triggered on date selection
 * @param string format string to format date output
 */
Bauglir.GUI.Calendar.CreateForInput = function(inputId, language, callback, format)
{
  if (!language) language = 'en';
  if (!format) format = 'Y-m-d';
  var element = $('<div></div>');
  element.css("position", "absolute");
  element.css("zIndex", "1000");
  element.css("top", "0px");
  element.css("left", "0px");
  element.appendTo($("#" + inputId).parent());
  element.id(Bauglir.GUI.RandomId());
  Bauglir.GUI.Calendar.Create(element.id(), language);
  element.css("display", "none");
  element.addClass('baugui-calendar-floatable');
  $("#" + inputId).data("baugui-dateformat", format);

  Bauglir.GUI.Calendar.RegisterOnClick(element.id(), function(calendar, datetime){
    element.hide();
    var d = new Date(datetime);
    $("#" + inputId).val(d.Format($("#" + inputId).data("baugui-dateformat")));
    $("#" + inputId).data("baugui-date", d.Date());
    $("#" + inputId).data("baugui-jsdate", d);
    if (callback) callback(calendar, new Date(d));
  });
  
  $("#" + inputId).data("baugui-jsdate", null);
  $("#" + inputId).data("baugui-date", null);

  var displayFunction = function(){
    if ($(this).attr('disabled')) return;
    element.show();

    var top = $(this).positionTop();
    var left = $(this).positionLeft();

    top += $(this).outerHeight();
    element.css("top", top + "px");
    element.css("left", left + "px");
  };
  
  $("#" + inputId).focus(displayFunction);
  
  $("#" + inputId).mouseup(displayFunction);


  $("#" + inputId).keyup(function(e){
    switch(e.keyCode)
    {
      case 38: //up arrow
      case 40: //down arrow
      case 37: //left arrow
      case 39: //right arrow
         $("#" + inputId).triggerHandler('focus');
         e.preventDefault();
         e.stopPropagation();
         return false;
      break;
      default:
        try { $("#" + inputId).val($("#" + inputId).data("baugui-jsdate").Format($("#" + inputId).data("baugui-dateformat"))); }
        catch (e) {$("#" + inputId).data("baugui-jsdate", null); $("#" + inputId).val('');}
    }
  });

  $("#" + inputId).keydown(function(e){
    switch(e.keyCode)
    {
       case 38: //up arrow
       case 40: //down arrow
       case 37: //left arrow
       case 39: //right arrow
         $("#" + inputId).triggerHandler('focus');
    }
    e.preventDefault();
    e.stopPropagation();
    return false;
  });
}

/**
 * create calendar
 * @param string calendarId id of DIV to create calendar from
 * @param string language calendar language
 */
Bauglir.GUI.Calendar.Create = function(calendarId, language)
{
  if (!language) language = 'en';
  var element = $('#' + calendarId);
  element.addClass('baugui-box');
  element.addClass('baugui-calendar');
  element.append('<div class="baugui-calendar-header"></div>');
  element.find(".baugui-calendar-header").addClass('baugui-box-bottom').addClass('baugui-darkBackground');
  var date = new Date();
  var month = Bauglir.Calendar.Months[language][date.MonthOfYear()];
  
  element.find(".baugui-calendar-header").append("<button class='baugui-calendar-next'><img src='" + Bauglir.GUI.CSSRoot + "/images/rightarrow_16.gif' alt='' /></button>");
  element.find(".baugui-calendar-header").append("<button class='baugui-calendar-today'><img src='" + Bauglir.GUI.CSSRoot + "/images/calendar_today_16.gif' alt='' /></button>");
  element.find(".baugui-calendar-header").append("<button class='baugui-calendar-previous'><img src='" + Bauglir.GUI.CSSRoot + "/images/leftarrow_16.gif' alt='' /></button>");
  element.find(".baugui-calendar-header").append("<button class='baugui-calendar-month'>" + month + "</button>");
  element.find(".baugui-calendar-header").append("<button class='baugui-calendar-year'>" + date.getFullYear() + "</button>");


  element.append("<table><tr></tr></table>")
  for (var i = 1; i < 8; ++i)
    element.find('tr').append('<th>' + Bauglir.Calendar.Days[language][i] + '</th>');
  for (var i = 0; i < 6; ++i)
    element.find('table').append('<tr><td>sd</td><td></td><td></td><td></td><td></td><td></td><td></td></tr>');

  element.data("baugui-date", new Date());
  element.data("baugui-currentdate", new Date());
  element.data("baugui-language", language);
  Bauglir.GUI.Calendar.baugui_createDays(element);

  Bauglir.GUI.baugui_buttonMainFuncts(element);
  
  element.find('.baugui-calendar-previous').click(function(){
    $('.baugui-calendar-month-list').hide();
    $('.baugui-calendar-year-list').hide();
    var d = new Date(element.data("baugui-date"));
    d.setDate(1);
    d.setMonth(d.getMonth() - 1);
    element.find('.baugui-calendar-month').text(Bauglir.Calendar.Months[element.data("baugui-language")][d.MonthOfYear()]);
    element.find('.baugui-calendar-year').text(d.getFullYear());
    element.data("baugui-date", new Date(d));
    
    Bauglir.GUI.Calendar.baugui_createDays(element);
  })
  element.find('.baugui-calendar-next').click(function(){
    $('.baugui-calendar-month-list').hide();
    $('.baugui-calendar-year-list').hide();
    var d = new Date(element.data("baugui-date"));
    d.setDate(1);
    d.setMonth(d.getMonth() + 1);
    element.find('.baugui-calendar-month').text(Bauglir.Calendar.Months[element.data("baugui-language")][d.MonthOfYear()]);
    element.find('.baugui-calendar-year').text(d.getFullYear());
    element.data("baugui-date", new Date(d));
    Bauglir.GUI.Calendar.baugui_createDays(element);
  })
  element.find('.baugui-calendar-today').click(function(e){
    $('.baugui-calendar-month-list').hide();
    $('.baugui-calendar-year-list').hide();
    var d = new Date();
    element.find('.baugui-calendar-month').text(Bauglir.Calendar.Months[element.data("baugui-language")][d.MonthOfYear()]);
    element.find('.baugui-calendar-year').text(d.getFullYear());
    element.data("baugui-date", new Date(d));
    element.data("baugui-currentdate", new Date(d));
    Bauglir.GUI.Calendar.baugui_createDays(element);
    if (Bauglir.GUI.Calendar.RegisteredOnClickFunctions[element.id()])
    {
      Bauglir.GUI.Calendar.RegisteredOnClickFunctions[element.id()](element, new Date(d));
      e.stopPropagation();
      return false;
    }
  });

  var html = '';
  for (var i = 1; i <= 12; ++i) html += "<p>" + Bauglir.Calendar.Months[language][i] + "</p>";
  element.append("<div class='baugui-calendar-month-list baugui-mainBackground baugui-box-dark'>" + html + "</div>");
  element.find('.baugui-calendar-month-list p').map(function(index){
    $(this).data('baugui-month' , index);
  })

  element.append("<div class='baugui-calendar-year-list baugui-mainBackground baugui-box-dark'>" + html + "</div>");

  element.find('.baugui-calendar-month-list p').hover(
    function(){
      $(this).addClass('baugui-darkBackground');
    },
    function(){
      $(this).removeClass('baugui-darkBackground');
    }
  );

  element.find('.baugui-calendar-month-list p').click(function(e){
    element.find('.baugui-calendar-month-list').hide();
    element.data("baugui-date").setMonth($(this).data('baugui-month'));
    element.find('.baugui-calendar-month').text(Bauglir.Calendar.Months[element.data("baugui-language")][element.data("baugui-date").MonthOfYear()]);
    Bauglir.GUI.Calendar.baugui_createDays(element);
    e.stopPropagation();
    return false;

  })

  element.find('.baugui-calendar-month').click(function(e){
    $('.baugui-calendar-month-list').hide();
    $('.baugui-calendar-year-list').hide();
    element.find('.baugui-calendar-month-list').show();
    var top = $(this).positionTop();
    var left = $(this).positionLeft();
    top += 5 + $(this).outerHeight();
    left += 5;
    element.find('.baugui-calendar-month-list').css("top", top + "px");
    element.find('.baugui-calendar-month-list').css("left", left + "px");
    
    e.stopPropagation();
    return false;

  });

  element.find('.baugui-calendar-year').click(function(e){
    $('.baugui-calendar-month-list').hide();
    $('.baugui-calendar-year-list').hide();

    element.find('.baugui-calendar-year-list').empty();
    var d = new Date(element.data('baugui-date'));
    var html = '';
    for (var i = d.getFullYear() - 2; i <= d.getFullYear() + 2; ++i) html += "<p>" + i + "</p>";
    element.find('.baugui-calendar-year-list').append(html);

    element.find('.baugui-calendar-year-list p').hover(
      function(){
        $(this).addClass('baugui-darkBackground');
      },
      function(){
        $(this).removeClass('baugui-darkBackground');
      }
    );

    element.find('.baugui-calendar-year-list p').map(function(index){
      $(this).data('baugui-year' , $(this).text());
    })


    element.find('.baugui-calendar-year-list p').click(function(e){
      element.find('.baugui-calendar-year-list').hide();
      element.data("baugui-date").setFullYear($(this).data('baugui-year'));
      element.find('.baugui-calendar-year').text($(this).data('baugui-year'));
      Bauglir.GUI.Calendar.baugui_createDays(element);
      e.stopPropagation();
      return false;
    })
    var top = $(this).positionTop();
    var left = $(this).positionLeft();
    top += 5 + $(this).outerHeight();
    left += 5;

    element.find('.baugui-calendar-year-list').css("top", top + "px");
    element.find('.baugui-calendar-year-list').css("left", left + "px");
    element.find('.baugui-calendar-year-list').show();
    e.stopPropagation();
    return false;


  });

  element.find('td').hover(
    function(){
      $(this).addClass('baugui-darkBackground');
    },
    function(){
      $(this).removeClass('baugui-darkBackground');
    }
  );
    
  element.find('td').click(function(e){
    $('.baugui-calendar-month-list').hide();
    $('.baugui-calendar-year-list').hide();
    var d = new Date($(this).data('baugui-date'));
    element.data("baugui-currentdate", new Date(d))
    element.data("baugui-date", new Date(d));
    element.find('.baugui-calendar-year').text(d.getFullYear());
    element.find('.baugui-calendar-month').text(Bauglir.Calendar.Months[element.data("baugui-language")][d.MonthOfYear()]);
    Bauglir.GUI.Calendar.baugui_createDays(element);

    if (Bauglir.GUI.Calendar.RegisteredOnClickFunctions[element.id()])
    {
      Bauglir.GUI.Calendar.RegisteredOnClickFunctions[element.id()](element, new Date(d));
      e.stopPropagation();
      return false;
    }
    e.stopPropagation();
    return false;


  });
  element.disableSelection();

}


Bauglir.GUI.Calendar.baugui_createDays = function (element)
{
  var allTds = element.find('td');

  allTds.removeClass('baugui-selected');

  var date = new Date(element.data("baugui-date"));
  var prevMonth = new Date(date);
  var first = new Date(date);
  first.setDate(1);
  prevMonth.setDate(1);
  prevMonth.setMonth(prevMonth.getMonth() - 1);
  
  var prevMonthLast = prevMonth.DaysInAMonth();
  var dateLast = date.DaysInAMonth();
  var dow = first.DayOfWeek();
  var tdIndex = 0;
  var i, j, d, dt;
  var td = null;
  for (i = prevMonthLast - dow + 2; i < prevMonthLast + 1; ++i)
  {
    td = allTds.eq(tdIndex++);
    td.text(i).css('color' ,'silver');
    d = new Date(prevMonth);
    d.setDate(i);
    td.data('baugui-date', d);
  }
  for (i = 1; i <= dateLast; ++i)
  {
    td = allTds.eq(tdIndex++);
    d = new Date(date);
    d.setDate(i);
    td.data('baugui-date', d);
    td.text(i).css('color' ,'black');
    if (
      (d.getFullYear() == element.data("baugui-currentdate").getFullYear()) &&
      (d.getMonth() == element.data("baugui-currentdate").getMonth()) &&
      (d.getDate() == element.data("baugui-currentdate").getDate())
    )
    {
      
      td.addClass('baugui-selected');
    }
  }
  var last = tdIndex;
  date.setDate(1);
  for (i = tdIndex, j = element.find('td').length; i < j; i++)
  {
    td = allTds.eq(tdIndex++);
    d = new Date(date);
    dt = i - last + 1;
    d.setMonth(date.getMonth() + 1, dt);
    td.data('baugui-date', d);
    td.text(dt).css('color' ,'silver');

  }

}

/*********************************/
/******** /CALENDAR **************/
/*********************************/


/*************************************/
/******** TAB CONTROL ****************/
/*************************************/
Bauglir.GUI.TabControl = {};
/**
 * tabControl after change
 *
 * @param jQuery tab tabControl
 * @param jQuery fromTab previously selected tab
 * @param jQuery toTab newly selected tab
 */
Bauglir.GUI.TabControl.OnChange = null;
/**
 * tabControl before change
 *
 * @param jQuery tab tabControl
 * @param jQuery fromTab previously selected tab
 * @param jQuery toTab newly selected tab
 * @return bool true if changing shoul proceed, false if there should be no change
 */
Bauglir.GUI.TabControl.OnChanging = null;

/**
 * create tab control from element
 *
 * @param jQuery|string element jQuery object representing UL element or it's id
 */
Bauglir.GUI.TabControl.Create = function(element)
{
  if(typeof element == 'string') element = $(element);
  if (element.hasClass('baugui-tabControl')) return;
  if (element.addClass('baugui-tabControl'));
  element.find("li").click(Bauglir.GUI.baugui_tabControlClick);
  element.find("li").hover(function(){Bauglir.GUI.baugui_TabMsieHoverOn(this);}, function(){Bauglir.GUI.baugui_TabMsieHoverOut(this);});
  element.map(function(){ Bauglir.GUI.baugui_TabControlAddId(this); });
  element.find("li").map(function(){ Bauglir.GUI.baugui_TabAddId(this); });
  element.disableSelection();
}

/********************************/
/******** RIBBON ****************/
/********************************/
Bauglir.GUI.Ribbon = {};
Bauglir.GUI.Ribbon.OnButtonClick = null;


/**
 * resize ribbon
 *
 * @param jQuery|string element jQuery object representing DIV element or it's id
 */
Bauglir.GUI.Ribbon.Resize = function(element)
{
  if(typeof element == 'string') element = $(element);
  setTimeout(function(){element.map(function(){Bauglir.GUI.baugui_RibbonSetHeight(this); });}, Bauglir.GUI.ribbonSetHeightTimeOut);
}

/**
 * create ribbon menu from element
 *
 * @param jQuery|string element jQuery object representing DIV element or it's id
 */
Bauglir.GUI.Ribbon.Create = function(element)
{
  if(typeof element == 'string') element = $(element);
  if (element.hasClass('baugui-ribbonMenu')) return;
  if (element.addClass('baugui-ribbonMenu'));
  element.children("div").map(function(){
    if (!$(this).hasClass('baugui-ribbonToolBar')) $(this).addClass('baugui-ribbonToolBar');
  })


  element.map(function(){ Bauglir.GUI.baugui_RibbonAddId(this);});

  element.find(Bauglir.GUI.buttonSelector).click(function () {Bauglir.GUI.baugui_RibbonButtonClick(this);});

  element.find(".baugui-ribbonToolBar").hover(function () {Bauglir.GUI.baugui_HoverOn(this, 'baugui-ribbonToolBar');}, function () {Bauglir.GUI.baugui_HoverOut(this, 'baugui-ribbonToolBar');});
  
  element.append("<br /><div class='clearBoth'>&nbsp;</div>");
  setTimeout(function(){element.map(function(){Bauglir.GUI.baugui_RibbonSetHeight(this); });}, Bauglir.GUI.ribbonSetHeightTimeOut);
}

/**********************************/
/******** SPLITTER ****************/
/**********************************/
Bauglir.GUI.Splitter = {};
/**
 * aftre splitting
 *
 * @param jQuery splitter Splitter
 */
Bauglir.GUI.Splitter.OnSplit = null;

/*
 * list of callback functions triggered if splitter is moved, array keys are splitters ids
 */
Bauglir.GUI.Splitter.RegisteredOnSplitFunctions = new Array();

/*
 * register callback functions triggered if splitter is moved
 * @param string splitterId id of splitter
 * @param function callback
 */
Bauglir.GUI.Splitter.RegisterOnSplit = function(splitterId, callback)
{
  Bauglir.GUI.Splitter.RegisteredOnSplitFunctions[splitterId] = callback;
}

/********************************/
/******** BUTTON ****************/
/********************************/
Bauglir.GUI.Button = {};

/**
 * create dropdown button disabled/enabled
 *
 * @param jQuery|string element jQuery object representing element or it's id
 * @param bool disabled whether element should be disabled or enabled
 */
Bauglir.GUI.Button.CreateDropDown = function(element)
{
  if(typeof element == 'string') element = $(element);
  Bauglir.GUI.baugui_addSpanIntoElement(element, 'baugui-container');
}


/********************************/
/******** CONTEXT MENU **********/
/********************************/

Bauglir.GUI.ContextMenu = {}

/*
 * list of callback functions triggered if menu item is clicked, array keys are items ids
 */
Bauglir.GUI.ContextMenu.RegisteredOnClickFunctions = new Array();
/*
 * list of callback functions triggered if menu item is shown, array keys are menus ids
 */
Bauglir.GUI.ContextMenu.RegisteredOnShowFunctions = new Array();

/*
 * register callback functions triggered if menu item is clicked
 * @param string menuId id of menu item
 * @param function callback
 */
Bauglir.GUI.ContextMenu.RegisterOnClick = function(menuId, callback)
{
  Bauglir.GUI.ContextMenu.RegisteredOnClickFunctions[menuId] = callback;
}

/**
 * register callback function triggered before menu is displayed
 * @param string menuId menu id
 * @param function callback callback function ( function (jQuery menu, jQuery target))
 */
Bauglir.GUI.ContextMenu.RegisterOnShow = function(menuId, callback)
{
  Bauglir.GUI.ContextMenu.RegisteredOnShowFunctions[menuId] = callback;
}

/**
 * target of context menu
 */
Bauglir.GUI.ContextMenu.Target = null;

/**
 * hide context menu
 */
Bauglir.GUI.ContextMenu.HideAll = function()
{
  $('.baugui-contextMenu').hide();
}

/**
 * create context menu from list
 * @param jQuery|string element jQuery object representing element or it's id
 */
Bauglir.GUI.ContextMenu.Create = function(element)
{
  if(typeof element == 'string') element = $(element);

  element.addClass("baugui-contextMenu");
  element.data('hovering', false);
  element.hover(function(){$(this).data('hovering', true)}, function(){$(this).data('hovering', false)});

  element.find('li').map(function(){Bauglir.GUI.baugui_addSpanIntoElement(this, 'baugui-container');});
  element.find('li').map(function () {Bauglir.GUI.baugui_contextMenuSetSubmenu(this)});

  element.find('li').map(function(){
    $(this).append("<span class='baugui-block'></span>");
  });

  element.find('li').hover(function () {Bauglir.GUI.baugui_HoverOn(this);}, function () {Bauglir.GUI.baugui_HoverOut(this);});

}


/**
 * unbind context menu from object
 * @param jQuery|string object(s) to bind menu to
 * @param string action enum(right, left, hover) type of action triggering context menu display
 */
Bauglir.GUI.ContextMenu.UnBind = function(object, action)
{
  if (action == null) action = 'right';
  if(typeof object == 'string') object = $(object);
  $(object).removeData('contextMenu');
  $(object).removeData('contextMenu-' + action);
}

/**
 * bind context menu to object
 * @param string menu id of menu to bind
 * @param jQuery|string object(s) to bind menu to
 * @param string action enum(right, left, hover) type of action triggering context menu display
 * @param string position enum(auto, right, bottom) position of context menu when displayed
 */
Bauglir.GUI.ContextMenu.Bind = function(menu, object, action, position)
{
  jQuery.fx.off = Bauglir.Browser.Msie6;
  if(typeof menu != 'string') throw ('Bauglir.GUI.ContextMenu.Bind -> menu must be id.');
  else menu = $(menu);
  if(typeof object == 'string') object = $(object);
  $(menu).find("li").unbind("mouseup", Bauglir.GUI.baugui_contextMenuClick);
  $(menu).disableSelection();

  $(object).data('contextMenu', menu);
  if ($(object).data('contextMenu-' + action)) return;
  $(object).data('contextMenu-' + action, 1);
  if (action == null) action = 'right';
  if (position == null) position = 'auto';
  var left = 0;
  var top = 0;

  if (action == 'right')
  {

    if(
      (Bauglir.Browser.Application == 'Firefox') ||
      (Bauglir.Browser.Application == 'Chrome') ||
      (Bauglir.Browser.Application == 'Safari') ||
      (Bauglir.Browser.Application == 'MSIE')
    )
    {
      $(object).bind("contextmenu",function(e)
      {
        if (!$(object).data('contextMenu')) return;
        var menu1 =  $(object).data('contextMenu');
        {
          if (position == 'auto')
          {
            left = e.pageX;
            top = e.pageY;
          }
          else if (position == 'bottom')
          {
            left = $(object).absLeft();
            top = $(object).absTop() + $(object).outerHeight();
          }
          else if (position == 'right')
          {
            left = $(object).absLeft() + $(object).outerWidth();
            top = $(object).absTop();
          }
          left -= $(menu1).parent().absLeft();
          top -= $(menu1).parent().absTop();
          Bauglir.GUI.baugui_contextMenuDisplay(menu1, this, left, top);
          //e.stopPropagation();
          return false;
        }
      });
    }
    else if(Bauglir.Browser.Application == 'Opera')
    {
      $(object).mousedown(function(e)
      {
        if (!$(object).data('contextMenu')) return;
        var menu2 =  $(object).data('contextMenu');
        if (e.button == 0 && e.altKey)
        {
          if (position == 'auto')
          {
            left = e.pageX;
            top = e.pageY;
          }
          else if (position == 'bottom')
          {
            left = $(object).absLeft();
            top = $(object).absTop() + $(object).outerHeight();
          }
          else if (position == 'right')
          {
            left = $(object).absLeft() + $(object).outerWidth();
            top = $(object).absTop();
          }
          left -= $(menu2).parent().absLeft();
          top -= $(menu2).parent().absTop();
          Bauglir.GUI.baugui_contextMenuDisplay(menu2, this, left, top);
          return false;
        }
      });
    }
    else
    {
      $(object).mousedown(function(e)
      {
        if (!$(object).data('contextMenu')) return;
        var menu3 =  $(object).data('contextMenu');
        if (e.button == 2)
        {
          if (position == 'auto')
          {
            left = e.pageX;
            top = e.pageY;
          }
          else if (position == 'bottom')
          {
            left = $(object).absLeft();
            top = $(object).absTop() + $(object).outerHeight();
          }
          else if (position == 'right')
          {
            left = $(object).absLeft() + $(object).outerWidth();
            top = $(object).absTop();
          }
          left -= $(menu3).parent().absLeft();
          top -= $(menu3).parent().absTop();
          Bauglir.GUI.baugui_contextMenuDisplay(menu3, this, left, top);
          return false;
        }
      });
    }
  }
  else if (action == 'left')
  {
    $(object).mousedown(function(e)
    {
      if (!$(object).data('contextMenu')) return;
      var menu4 =  $(object).data('contextMenu');
      if (e.button == 0 || (Bauglir.Browser.Msie && e.button == 1))
      {
        if (position == 'auto')
        {
          left = e.pageX;
          top = e.pageY;
        }
        else if (position == 'bottom')
        {
          left = $(object).absLeft();
          top = $(object).absTop() + $(object).outerHeight();
        }
        else if (position == 'right')
        {
          left = $(object).absLeft() + $(object).outerWidth();
          top = $(object).absTop();
        }
        left -= $(menu4).parent().absLeft();
        top -= $(menu4).parent().absTop();

        Bauglir.GUI.baugui_contextMenuDisplay(menu4, this, left, top);
        return false;
      }
    });
    
  }
  else if (action == 'hover')
  {
    $(object).hover(function(e)
    {
      if (!$(object).data('contextMenu')) return;
      var menu5 =  $(object).data('contextMenu');
         {
        if (position == 'auto')
        {
          left = e.pageX;
          top = e.pageY;
        }
        else if (position == 'bottom')
        {
          left = $(object).absLeft();
          top = $(object).absTop() + $(object).outerHeight();
        }
        else if (position == 'right')
        {
          left = $(object).absLeft() + $(object).outerWidth();
          top = $(object).absTop();
        }
        left -= $(menu5).parent().absLeft();
        top -= $(menu5).parent().absTop();
        Bauglir.GUI.baugui_contextMenuDisplay(menu5, this, left, top);
        return false;
      }
    },

    function(){return; setTimeout(function(){
      if (!$(menu).data('hovering')) $(menu).hide();
    }), 200});

  }
  
}



/**
 * function callback called if context menu item is clicked
 * @param jQuery menu context menu
 * @param jQuery item  context menu item
 */
Bauglir.GUI.ContextMenu.OnClick = null;



/****************************************/
/**************** WINDOW ****************/
/****************************************/

Bauglir.GUI.Window = {};

/**
 * z-index stack to display window in z-order
 */
Bauglir.GUI.Window.zIndexStack = 1000000;

/**
 * OK button text
 */
Bauglir.GUI.Window.OkDefaultText = 'Ok';

/**
 * CANCEL button text
 */
Bauglir.GUI.Window.CancelDefaultText = 'Cancel';

/**
 * ERROR dialog caption
 */
Bauglir.GUI.Window.ErrorDefaultText = 'Error';

/**
 * INFO dialog caption
 */
Bauglir.GUI.Window.InfoDefaultText = 'Information';

/**
 * WARNING dialog caption
 */
Bauglir.GUI.Window.WarningDefaultText = 'Warning';

/**
 * CONFIRMATION dialog caption
 */
Bauglir.GUI.Window.ConfirmDefaultText = 'Confirmation';

/**
 * INPUT dialog caption
 */
Bauglir.GUI.Window.InputDefaultText = 'Input';

/**
 * show/hide animation time (milliseconds)
 */
Bauglir.GUI.Window.AnimateTime = 300;


/**
 * function creates message box like DIV
 *
 * @param object dialogDefObject window parameters (ok:  ok button text, cancel: cancel button text, dialog: window modality,
 *   okFunction: function triggered if ok button pressed, cancelFunction: function triggered if cancel button pressed;
 *   type: type of dialog (error, info, warning, confirm), caption: caption text, defaultValue: default input value
 *   buttons are displayed only if functions are presented
 */
Bauglir.GUI.Window.Message = function(dialogDefObject)
{



  if (!dialogDefObject.type) dialogDefObject.type = 'error';

  if ($("#baugui-dialog-"+dialogDefObject.type).length) return;

  if (!dialogDefObject.text) dialogDefObject.text = '';
  if (!dialogDefObject.defaultValue) dialogDefObject.defaultValue = '';
  dialogDefObject.type = dialogDefObject.type.toLowerCase();
  var ondisplay = null;
  if (!dialogDefObject.caption)
  {
    switch(dialogDefObject.type)
    {
      case "error": dialogDefObject.caption = Bauglir.GUI.Window.ErrorDefaultText; break;
      case "info": dialogDefObject.caption = Bauglir.GUI.Window.InfoDefaultText; break;
      case "warning": dialogDefObject.caption = Bauglir.GUI.Window.WarningDefaultText; break;
      case "confirm": dialogDefObject.caption = Bauglir.GUI.Window.ConfirmDefaultText; break;
      case "input": dialogDefObject.caption = Bauglir.GUI.Window.InputDefaultText; break;

    }
  }

  switch(dialogDefObject.type)
  {
    case "input":
      dialogDefObject.text += "<br /><input type='text' value='" + dialogDefObject.defaultValue + "' id='baugui-dialog-input-text' />";
      if (dialogDefObject.cancelFunction == null) dialogDefObject.cancelFunction = function() {};
      ondisplay = function()
      {
        $('#baugui-dialog-input-text').get(0).focus();
      }
    break;
  }

  var id = "baugui-dialog-"+dialogDefObject.type;
  $("body").append(
    "<div class='baugui-window-dialog' id='" + id + "'>"+
    "<h6>" + dialogDefObject.caption + "</h6>" +
    "<div class='baugui-window-container'>" +
    "<p class='baugui-window-dialog-icon baugui-window-dialog-" + dialogDefObject.type + "'>&nbsp;</p>" +
    "<p class='baugui-window-dialog-text'>" + dialogDefObject.text + "</p>" +
    "</div>" + 
    "</div>"
  );

  var jObject = $('#'+id);

  var closeFunction1 = function(clbFunction, param){
    Bauglir.GUI.Window.baugui_hideDialogBack(jObject.closest('.baugui-window').id());
    if (Bauglir.Browser.Msie6)
    {
      Bauglir.GUI.Wait.Remove(jObject);
      jObject.closest('.baugui-window').hide();
      jObject.remove();
      if (clbFunction) clbFunction(param);
    }
    else
    {
      Bauglir.GUI.Wait.Remove(jObject);
      Bauglir.GUI.Hide(jObject.closest('.baugui-window'), Bauglir.GUI.Window.AnimateTime, function(){jObject.remove(); if (clbFunction) clbFunction(param);});
    }
  };

  var functCl = dialogDefObject.closeFunction;
  var closeFunction2 = function(){
    Bauglir.GUI.Window.baugui_hideDialogBack(jObject.closest('.baugui-window').id());
    jObject.remove();
    if (functCl)
      functCl();
  };


  var funct = dialogDefObject.okFunction;
  dialogDefObject.okFunction = function(){
    var param = null;
    if (dialogDefObject.type == 'input')
    {
      param = $('#baugui-dialog-input-text').val();
    }
    closeFunction1(funct, param);
  };

  var functC = dialogDefObject.cancelFunction;
  if (functC)
  {
    dialogDefObject.cancelFunction = function(){
      closeFunction1(functC);
    };
  }
  else if (dialogDefObject.type == 'confirm')
  {
    dialogDefObject.cancelFunction = function(){closeFunction1(null)};
  }


  dialogDefObject.closeFunction = closeFunction2;
  dialogDefObject.id = id;
  dialogDefObject.dialog = true;
  Bauglir.GUI.Window.Create(dialogDefObject);
  Bauglir.GUI.Window.Show("baugui-dialog-"+dialogDefObject.type, ondisplay);
  if (dialogDefObject.type == 'input')
  {
    $('#baugui-dialog-input-text').keydown(function(e){
      if (e.keyCode == 13) dialogDefObject.okFunction();
    });
  }
}




/**
 * function creates window like DIV
 *
 * @param object windowDefObject window parameters (id: element id, ok:  ok button text, cancel: cancel button text, dialog: window modality,
 *   okFunction: function triggered if ok button pressed, cancelFunction: function triggered if cancel button pressed, closeFunction: close callback
 *   function triggered if close button is pressed
 *   buttons are displayed only if functions are presented
 */
Bauglir.GUI.Window.Create = function (windowDefObject)
{
  
  jQuery.fx.off = Bauglir.Browser.Msie6;
  if (!windowDefObject.id)
  {
    if (windowDefObject.element)
    {
      var d = new Date();
      var id = Math.round(Math.random() * 1000000) + d.getMilliseconds();
      $(windowDefObject.element).id("baugui-window_" + id);
    }
  }
  
  if (windowDefObject.id)
  {
    var jq = $('#' + windowDefObject.id);
    if (!jq.length) return;
    if (jq.parent(0).get(0).tagName.toLowerCase() != 'body')
    {
      jq.parent(0).get(0).removeChild(jq.get(0));
      $('body').get(0).appendChild(jq.get(0));
      jq = $('#' + windowDefObject.id);
    }
    
    jq.addClass('baugui-window');
    if (jq.find('h6').find('baugui-window-closeButton').length == 0)
    {
      jq.find('h6').html("<span class='baugui-window-closeButton'>&nbsp;</span>" + "<span class='baugui-window-caption'>" + jq.find('h6').html() + "</span>");
    }


    
    if (jq.find('.baugui-window-inner').length == 0)
    {
      jq.wrapInner("<div class='baugui-window-inner'><div>");
    }

    if (jq.find('.baugui-window-fullcontent').length == 0)
    {
      jq.wrapInner("<div class='baugui-window-fullcontent'><div>");
    }

    if (jq.find('.baugui-window-info').length != 0)
    {
      jq.find('.baugui-window-info').appendTo(jq);
    }
    jq.find('.baugui-window-container').addClass('baugui-mainBackground');


    //buttons
    jq.find('.baugui-window-inner').remove('baugui-window-bottom');
    if (windowDefObject.okFunction || windowDefObject.cancelFunction)
    {
      var html = '';
      if (windowDefObject.okFunction) 
        html += "<button class='baugui-ok'><span class='baugui-ok'>" + (windowDefObject.ok ? windowDefObject.ok : Bauglir.GUI.Window.OkDefaultText)+ "</span></button>";
      if (windowDefObject.cancelFunction)
        html += "<button class='baugui-cancel'><span class='baugui-cancel'>" + (windowDefObject.cancel ? windowDefObject.cancel : Bauglir.GUI.Window.CancelDefaultText) + "</span></button>";
      jq.find('.baugui-window-inner').append("<div class='baugui-window-bottom'>"+html+"</div>");
      if (windowDefObject.okFunction)
        jq.find('.baugui-window-inner .baugui-window-bottom button.baugui-ok').click(windowDefObject.okFunction);
      if (windowDefObject.cancelFunction)
        jq.find('.baugui-window-inner .baugui-window-bottom button.baugui-cancel').click(windowDefObject.cancelFunction);
    }

    Bauglir.GUI.baugui_buttonMainFuncts(jq.find('.baugui-window-bottom'));

    jq.find('h6 span.baugui-window-closeButton').click(function(){
      Bauglir.GUI.Window.baugui_hideDialogBack($(this).closest('.baugui-window').id())
      Bauglir.GUI.Wait.Remove($(this).closest('.baugui-window'));
      if (Bauglir.Browser.Msie6)
      {
        
        $(this).closest('.baugui-window').hide();
        if (windowDefObject.closeFunction) windowDefObject.closeFunction();
      }
      else
      {
        Bauglir.GUI.Hide($(this).closest('.baugui-window'), Bauglir.GUI.Window.AnimateTime, function(){if (windowDefObject.closeFunction) windowDefObject.closeFunction();});
      }
    })
    jq.keydown(function(e){
      if (e.keyCode == 27) jq.find('h6 span.baugui-window-closeButton').trigger('click');
    });


    //jq.addClass('baugui-mainBackground');
    if (windowDefObject.dialog)
    {
      jq.addClass('baugui-window-dialog');
    }
    else jq.removeClass('baugui-window-dialog');
    jq.draggable({
      helper: 'original',
      containment: 'window',
      handle: 'h6',
      zIndex: 10000000,
      cursor: 'move',
      start: function(){$(".baugui-contextMenu").hide();}
    });
    jq.enableSelection();
    //jq.hide();
  }
  else throw ('Bauglir.GUI.Window.Create() -> element has no id.');
  
}

/**
 * close window
 * @param string windowId window id
 */
Bauglir.GUI.Window.Close = function(windowId)
{
  var jq = $('#'+windowId);
  Bauglir.GUI.Wait.Remove(jq);
  Bauglir.GUI.Window.baugui_hideDialogBack(jq.id());
  if (Bauglir.Browser.Msie6)
  {
    jq.hide();
  }
  else
  {
    Bauglir.GUI.Hide(jq, Bauglir.GUI.Window.AnimateTime, null);
  }
}

/**
 * function displayes window like DIV
 *
 * @param string windowId id of window element
 * @param function showFunction function triggered after window is displayed
 */
Bauglir.GUI.Window.Show = function(windowId, showFunction)
{
  var jObject = $('#' + windowId);
  var wh = 0;
  var ww = 0;
  if (jObject.data('originaHeight'))
  {
    wh = jObject.data('originaHeight');
    ww = jObject.data('originaWidth');
  }
  else
  {
    $('#' + windowId).show();
    wh = jObject.get(0).offsetHeight;
    ww = jObject.get(0).offsetWidth;
    $('#' + windowId).hide();
  }
  var top = (Bauglir.Browser.ViewportHeight - wh) / 2;
  var left = (Bauglir.Browser.ViewportWidth - ww) / 2;


  var width = ww;
  var height = wh;
  var x = left + Math.round((ww) / 2);
  var y = top + Math.round((wh) / 2);
  //jObject.css('opacity', '0.3');
  //jObject.animate({width: "0px", height: '0px', opacity: '0', top: y + "px", left: x + "px"}, speed, callback);


  
  $('#' + windowId).css('width', '0px');
  $('#' + windowId).css('height', '0px');
  $('#' + windowId).css('top', y + 'px');
  $('#' + windowId).css('left', x + 'px');
  $('#' + windowId).css('opacity', '0.03');

  Bauglir.GUI.Window.zIndexStack += 2;
  $('#' + windowId).css('zIndex', Bauglir.GUI.Window.zIndexStack);


/*
  if ($("#baugui-dialog-"+dialogDefObject.type).find(".baugui-window-bottom button").length)
  {
    //$("#baugui-dialog-"+dialogDefObject.type).find(".baugui-window-bottom button").get(0).focus();
    $("#baugui-dialog-"+dialogDefObject.type).find(".baugui-window-bottom").append("<input type='text' />");
    $("#baugui-dialog-"+dialogDefObject.type).find(".baugui-window-bottom input").get(0).focus();
  }

 */

  var showFunction2 = function()
  {
    $('#' + windowId).get(0).focus();
    if ($('#' + windowId).find(".baugui-window-bottom button").length)
    {
      //$('#' + windowId).find(".baugui-window-bottom button").get(0).focus();
      $('#' + windowId).find(".baugui-window-bottom button").trigger('focus')
    }
    
    if (showFunction) showFunction();
  }


  if ($('#' + windowId).hasClass('baugui-window-dialog'))
  {
    Bauglir.GUI.Window.baugui_displayDialogBack(windowId);
  }
  if (Bauglir.Browser.Msie)
  {
    $('#' + windowId).css('width', width + 'px');
    $('#' + windowId).css('height', height + 'px');
    $('#' + windowId).css('top', top + 'px');
    $('#' + windowId).css('left', left + 'px');
    $('#' + windowId).css('opacity', '1');
    $('#' + windowId).show();

    showFunction2();
  }
  else $('#' + windowId).animate({width: width + "px", height: height + 'px', opacity: '1', top: top + "px", left: left + "px"}, Bauglir.GUI.Window.AnimateTime, function(){showFunction2();});
}

Bauglir.GUI.Window.baugui_displayDialogBack = function(windowId)
{

  var newId = 'baugui-window-dialogBack' + windowId;
  $('body').append("<div class='baugui-window-dialogBack "+ newId +"'>&nbsp;</div>");
  $('body').find('.baugui-window-dialogBack').addClass('baugui-mainBackground');
  $('body').find('.' + newId).css("width", Bauglir.Browser.ViewportWidth + "px");
  $('body').find('.' + newId).css("height", Bauglir.Browser.ViewportHeight + "px");
  $('body').find('.' + newId).css("zIndex", Bauglir.GUI.Window.zIndexStack - 1);
  $('body').find('.' + newId).css("opacity", "0.5");
  $('body').find('.' + newId).click(function(){
    if (!Bauglir.Browser.Msie6)
    {
      
      Bauglir.GUI.HighLight($('#' + windowId + " .baugui-window-container"));
    }
  });
  $('body').find('.' + newId).show();
  
}

Bauglir.GUI.Window.baugui_hideDialogBack = function(windowId)
{
  $('body').find('.baugui-window-dialogBack'+windowId).remove();
}


/****************************************/
/************* LIST VIEW ****************/
/****************************************/

Bauglir.GUI.ListView = {};

/**
 * remove all data row
 * @param string listId id if list view
 */
Bauglir.GUI.ListView.Clear = function(listId)
{
  if ($("#" + listId).data("baugui-updatecount"))
  {
    $("#" + listId).data("baugui-updatestack").push({
      action: 'clear',
      data: null,
      rowdata: null,
      rowid: null
    });

  }
  else
  {
    $("#" + listId).find('tr').not(":first").remove();
  }



}

/*
Bauglir.GUI.ListView.UpdateStack = {
  id: '',
  action: '',
  data: ''
}
*/

/**
 *  preserve time/process consuming operations (e.g sorting)
 *  if function is called, no such action is done,
 *  Bauglir.GUI.ListView.EndUpdate must be called to do those actions
 *
 *  calls can be nested, nesting has no effect,
 *  Bauglir.GUI.ListView.EndUpdate must be called thse same time as
 *  BeginUpdate, only last EndUpdate triggers those operations
 *
 *  @param string listId id if list view
 */
Bauglir.GUI.ListView.BeginUpdate = function(listId)
{

  var table = $("#" + listId);
  table.data("baugui-updatecount",
    table.data("baugui-updatecount") ? table.data("baugui-updatecount") + 1 : 1
  );
  if (table.data("baugui-updatecount") == 1)
  {
    table.data("baugui-updatestack", new Array());
  }
}

/**
 * see Bauglir.GUI.ListView.BeginUpdate
 */
Bauglir.GUI.ListView.EndUpdate = function(listId)
{

  var table = $("#" + listId);
  var uc = table.data("baugui-updatecount") ? table.data("baugui-updatecount") - 1 : 0;
  uc = Math.max(uc, 0);
  table.data("baugui-updatecount", uc);
  if (uc == 0) 
  {

    var data = table.data("baugui-updatestack");
    var rdata = null;
    var rows = new Array();
    for (var i = 0, j = data.length; i < j; ++i)
    {
      rdata = data[i];
      if (rdata.action == 'clear')
      {
        Bauglir.GUI.ListView.Clear(listId);
        rows = new Array();
      }
      else if (rdata.action == 'add')
      {
        rows.push(rdata.data);
      }
    }
    var html = rows.join('');
    //alert(html);
    table.append(html);
    for (i = 0, j = data.length; i < j; ++i)
    {
      rdata = data[i];
      if (rdata.action == 'add')
      {
        table.find("#" + rdata.rowid).data("baugui-data", rdata.rowdata);
        table.find("#" + rdata.rowid).data("baugui-sortdata", rdata.rowsortdata);
      }
    }
    Bauglir.GUI.ListView.baugui_restoreevents(table);
    Bauglir.GUI.ListView.ReSort(listId);
    table.find("tr").removeClass('baugui-even').filter(':even').addClass('baugui-even');
    if (table.id())
      if (Bauglir.GUI.ListView.RegisteredOnSelectionChangeFunction[table.id()] != null)
        Bauglir.GUI.ListView.RegisteredOnSelectionChangeFunction[table.id()](table);

  }

}

/**
 * sort rows
 * @param string listId id if list view
 */
Bauglir.GUI.ListView.ReSort = function(listId)
{
  var table = $("#" + listId);
  Bauglir.GUI.ListView.Sort(listId,
    table.data("baugui-sortcolumn"),
    table.data("baugui-sortdirection")
  );
    
}



/**
 * set table height/width (add scrolls if nescesarry)
 * @param string listId id if list view
 * @param int width width
 * @param int height height
 */
Bauglir.GUI.ListView.SetSize = function(listId, width, height)
{
  var element = $("#" + listId);
  element.parent().css('height', height + "px");
  element.parent().css('width', width + "px");
  //element.parent().css('overflow' ,'hidden');
  var w = element.parent().contentWidth() + 1;
  element.css('width', w + "px");
}

/**
 * set table height (add scrolls if nescesarry)
 * @param string listId id if list view
 * @param int height height
 */
Bauglir.GUI.ListView.SetHeight = function(listId, height)
{
  var element = $("#" + listId);
  element.parent().css('height', height + "px");
}

/**
 * add row
 * @param string listId id of table
 * @param string rowId 
 * @param string[] contents list of HTML formated cell content
 * @param mixed[] sorts list of date columns shoul be sorted according to 
 * @param mixed data any data that thould be connected to row
 */

Bauglir.GUI.ListView.AddRow = function(listId, rowId, contents, sorts, data)
{
  var element = $("#" + listId);
  var row = ("<tr id='"+rowId+"'>");
  
  var html = '';
  var columns = element.find("th");
  for (var i = 0, j = columns.length - 1; i < j; ++i)
  {
    var column = columns.eq(i);
    var index = column.data('baugui-columnindex');

    var span = '';
    if (sorts != null)
      if (index < sorts.length)
        if (sorts[index] != null)
          span = '<span class="baugui-value">' + sorts[index] + '</span>';


    var className = "";
    if (column.hasClass('baugui-numeric')) className = "class='baugui-alignRight'";
    if (index < contents.length) html += "<td " + className + " ><div class='baugui-wrapper'>" + span + contents[index] + "</div></td>";
    else html += "<td" + className + " ><div class='baugui-wrapper'>" + span + "&nbsp;</div></td>";

  }
  html += "<td style='width: " + Bauglir.Browser.ScrollBarWidth + "px;'>&nbsp;</td>";
  row += html + "</tr>";
  

  


  
  if (!element.data("baugui-updatecount"))
  {
    row = $(row);
    row.data("baugui-data", data);
    row.data("baugui-sortdata", sorts);
    row.click(Bauglir.GUI.ListView.baugui_selectevent);
    element.append(row);
    element.find("tr").removeClass('baugui-even').filter(':even').addClass('baugui-even');
    Bauglir.GUI.ListView.ReSort(listId);
  }
  else
  {
    element.data("baugui-updatestack").push({
      action: 'add',
      data: row,
      rowdata: data,
      rowsortdata: sorts,
      rowid: rowId
    });
  }
  return row;
}

/**
 * create list view
 * @param string listId id of table
 */
Bauglir.GUI.ListView.Create = function(listId)
{
  var element = $("#" + listId);
  element.addClass('baugui-listview');
  element.data("baugui-updatecount", 0);
  element.find("td").map(function(){
    $(this).wrapInner("<div class='baugui-wrapper'></div>");
  });

  //fixing html
  if (!element.parent().hasClass('baugui-listviewscroll'))
  {
    element.wrap("<div class='baugui-listviewscroll'></div>");
  }
  if (!element.parent().id())
    element.parent().id(Bauglir.GUI.RandomId());
  var parentId = element.parent().id();

  element.find("tr:first-child").append("<th style='width: " + Bauglir.Browser.ScrollBarWidth + "px;'>&nbsp;</th>");
  element.find("tr").append("<td style='width: " + Bauglir.Browser.ScrollBarWidth + "px;'>&nbsp;</td>");
  element.find("tr:first-child td").remove();

  element.find("th").each(function(index){$(this).data("baugui-columnindex", index);})
  element.find("th").map(function(){$(this).prepend('<div class="baugui-columnprepend"></div>')});
  element.find("th").map(function(){$(this).append('<div class="baugui-columnheadersort"></div>')});
  element.find("th").map(function(){$(this).wrapInner('<div class="baugui-columncontent"></div>')});
  element.find("th").map(function(){$(this).wrapInner('<div class="baugui-columnheaderinner"></div>')});
  element.find("th").map(function(){$(this).wrapInner('<div class="baugui-columnheaderborder"></div>')});
  element.find("th:last-child").find('div').css('padding', '0px').css('margin', '0px')

  element.parent().scroll(function(){
    var top = this.scrollTop - 1;
    $(this).find('.baugui-columnheaderborder').css('top', top + "px");
  });
  element.parent().triggerHandler('scroll');

  element.find("th:last-child .baugui-columnheaderborder").removeClass('baugui-columnheaderborder').addClass('baugui-columnheaderborderlast');
  //element.find("tr:last-child").addClass('baugui-bottom');
  element.find("tr:even").addClass('baugui-even');
  
  element.find("th.baugui-numeric").map(function(){
    $(this).addClass('baugui-alignRight');
    var index = element.find("th").index($(this));
    element.find("td").map(function(){
      $(this).closest("tr").find("td").eq(index).addClass('baugui-alignRight');
    })
  });

  element.find("th").map(function(){if (!$(this).id()) {$(this).id(Bauglir.GUI.RandomId())}});
  element.find("th .baugui-columnheadersort").data('baugui-sort', 'desc');

  //events
  element.find("th").click(function()
  {
    var sort = '';
    if ($(this).find('.baugui-columnheadersort').data('baugui-sort') == 'desc') sort = 'asc';
    else sort = 'desc';
    Bauglir.GUI.ListView.Sort(element.id(), $(this).id(), sort);
  });

  var dragData =
  {
    helper: 'clone',
    opacity: '0.7',
    revert: 'invalid',
    zIndex: 100000
  };
  if ((Bauglir.Browser.Application == 'Opera') || (Bauglir.Browser.Msie))
  {
    dragData.appendTo = '#' + parentId;
  }
  element.find('th .baugui-columnheaderborder').draggable(dragData);
  element.find('th .baugui-columnheaderborder, th .baugui-columnheaderborderlast').droppable({
    tolerance: 'pointer',
    accept: function(dragged){
      if (element.id() == dragged.closest('table.baugui-listview').id())
      {
        if (dragged.closest('th').length)
          if ($(this).closest('th').id() != dragged.closest('th').id()) return true;
      }
      return false;
    },
    hoverClass: 'baugui-movebefore',
    drop: function(e, ui)
    {

      var source = ui.draggable.closest('th');
      var destination = $(this).closest('th');
      var header = source.closest('tr');
      var sourceIndex = header.find('th').index(source);
      var destinationIndex = header.find('th').index(destination);
      if (sourceIndex != destinationIndex)
      {

        destination.before(source);
        if (source.find('.baugui-columnheaderborderlast').length)
          source.find(".baugui-columnheaderborderlast").removeClass('baugui-columnheaderborderlast').addClass('baugui-columnheaderborder');
        if (element.find("th:last-child").find(".baugui-columnheaderborder").length)
          element.find("th:last-child").find(".baugui-columnheaderborder").removeClass('baugui-columnheaderborder').addClass("baugui-columnheaderborderlast");
        /*if (!element.find("th:last-child").hasClass("baugui-columnheaderborderlast"))
          element.find("th:last-child").addClass('baugui-columnheaderborderlast');*/

        element.find("tr").map(function(){
          if ($(this).find('td').length)
          {
            $(this).find('td').eq(destinationIndex).before($(this).find('td').eq(sourceIndex));
          }
        })
      }

    }
  });


  
  Bauglir.GUI.ListView.baugui_restoreevents(element);

  element.mousedown(function(e){
    Bauglir.GUI.HideFloating(e);
    e.stopPropagation();
    return false;
  });
  element.disableSelection();
}


/**
 * list of callback function if sort is changed
 */
Bauglir.GUI.ListView.RegisteredOnSortFunction = new Array();

/**
 * register on sort function
 * @param string listId id of table
 * @param function callback callback function
 */
Bauglir.GUI.ListView.RegisterOnSort = function(listId, callback)
{
  Bauglir.GUI.ListView.RegisteredOnSortFunction[listId] = callback;
}


/**
 * sort list
 * @param string listId id of table
 * @param string columnId column id to sort list according to
 * @param string sort direction
 */
Bauglir.GUI.ListView.Sort = function(listId, columnId, sort)
{
  var table = $("#" + listId);
  if (!columnId) columnId = table.find('th').eq(0).id();
  var column = $("#" + columnId);
  

  
  if (!sort) sort = 'asc';

  if (table.find('th').index(column) == table.find('th').length - 1) return;


  var div = column.find('.baugui-columnheadersort');
  //alert(div.closest('th').outerHtml());
  table.data("baugui-sortcolumn", columnId);
  table.data("baugui-sortdirection", sort);

  if (table.data("baugui-updatecount"))
    if (table.data("baugui-updatecount") > 0)
      return;

  var oldCursor = table.css('cursor');
  table.css('cursor', 'wait');

  table.find('.baugui-sortasc').removeClass('baugui-sortasc');
  table.find('.baugui-sortdesc').removeClass('baugui-sortdesc');
  
  table.find('.baugui-columnheadersort').data('baugui-sort', 'desc');


  div.data('baugui-sort', sort);
  var isNumeric = column.hasClass('baugui-numeric');


  div.addClass('baugui-sort' + sort);
  //alert(div.parent().html());
  var index = table.find('th').index(column);

  table.find('tr').addClass('baugui-sorting');
  table.find('tr:first-child').removeClass('baugui-sorting');

  //read data
  Bauglir.Log("Sorting Start: " + new Date());
  var text2Index = new Array();
  var text = new Array();
  table.find('tr.baugui-sorting').map(function(trIndex){
    var tr = $(this);
    var td = tr.find('td').eq(index);
    var data = td.find('span.baugui-value').length ? td.find('span.baugui-value').text().toLowerCase() : td.text().toLowerCase();
    data = isNumeric ? Bauglir.Int(data) : data;
    if (text2Index[data] == null)
    {
      text2Index[data] = new Array();
    }
    text2Index[data].push(trIndex);
    if (!text.contains(data))
      text.push(data);
  });

  if (isNumeric) text = text.sort(function(a, b) {return a - b;});
  else text = text.sort();
  var rows = table.find('tr.baugui-sorting');
  var row = null;
  var html = '';
  var data = new Array();
  var sdata = new Array();
  /* * /
  for (var i = 0, j = text.length; i < j; ++i)
  {
    index = sort == 'asc' ? i : j - i - 1;
    var indexes = text2Index[text[index]];
    for (var k = 0, l = indexes.length; k < l; ++k)
      rows.eq(indexes[k]).appendTo(table);
  }
  /* */
  /* */
  
  for (var i = 0, j = text.length; i < j; ++i)
  {
    index = sort == 'asc' ? i : j - i - 1;
    var indexes = text2Index[text[index]];
    for (var k = 0, l = indexes.length; k < l; ++k)
    {
      row = rows.eq(indexes[k]);
      html += row.outerHtml();
      data[row.id()] = row.data('baugui-data');
      sdata[row.id()] = row.data('baugui-sortdata');
    }
  }
  Bauglir.GUI.ListView.Clear(listId);
  //alert(html);
  table.append(html);
  for (var id in data)
  {
    table.find("#" + id).data("baugui-data", data[id]);
    table.find("#" + id).data("baugui-sortdata", sdata[id]);
  }
  Bauglir.GUI.ListView.baugui_restoreevents(table);
  /* */

  Bauglir.Log("Sorting Start: " + new Date());
  table.find('tr').removeClass('baugui-sorting');
  table.find("tr").removeClass('baugui-even');
  table.find("tr:even").addClass('baugui-even');
  table.css('cursor', oldCursor);

  if (Bauglir.GUI.ListView.RegisteredOnSortFunction[listId] != null)
      Bauglir.GUI.ListView.RegisteredOnSortFunction[listId](table);

}

Bauglir.GUI.ListView.baugui_restoreevents = function(element)
{
  element = $(element);

  var parentTable = element.closest('table.baugui-listview');

  parentTable.find('tr').not(":first").unbind('click', Bauglir.GUI.ListView.baugui_selectevent);
  parentTable.find('tr').not(":first").click(Bauglir.GUI.ListView.baugui_selectevent);
}

/**
 * list of callback function if selection is changed
 */
Bauglir.GUI.ListView.RegisteredOnSelectionChangeFunction = new Array();

/**
 * register on selection change function
 * @param string listId id of table
 * @param function callback callback function
 */
Bauglir.GUI.ListView.RegisterOnSelectionChange = function(listId, callback)
{
  Bauglir.GUI.ListView.RegisteredOnSelectionChangeFunction[listId] = callback;
}

Bauglir.GUI.ListView.baugui_selectevent = function(e)
{
  var element = $(this);
  var parentTable = element.closest('table.baugui-listview');
  var rows = parentTable.find('tr');
  if (!element.find('th').length)
  {

    if ((!e.ctrlKey && !e.shiftKey) || parentTable.data("baugui-lastselected") == null)
    {
      parentTable.find('tr.baugui-selected').removeClass('baugui-selected');
      element.addClass('baugui-selected');
      parentTable.data("baugui-lastselected", element);
    }
    else if (e.shiftKey && parentTable.data("baugui-lastselected") != null)
    {
      var indexElement = rows.index(element);
      var indexLastSelected = rows.index(parentTable.data("baugui-lastselected"));
      var i1 = 0, i;
      var i2 = 0;
      if (!e.ctrlKey) parentTable.find('tr.baugui-selected').removeClass('baugui-selected');
      else parentTable.data("baugui-lastselected", element);
      
      if (indexElement < indexLastSelected)
      {
        i1 = indexElement;
        i2 = indexLastSelected;
      }
      else
      {
        i1 = indexLastSelected;
        i2 = indexElement;
      }
      for (i = i1; i <= i2; ++i) rows.eq(i).addClass('baugui-selected');
    }
    else if (e.ctrlKey)
    {
      element.toggleClass('baugui-selected');
      parentTable.data("baugui-lastselected", element);
    }
    
  }
  Bauglir.GUI.HideFloating(e);
  e.stopPropagation();
  if (parentTable.id())
    if (Bauglir.GUI.ListView.RegisteredOnSelectionChangeFunction[parentTable.id()] != null)
      Bauglir.GUI.ListView.RegisteredOnSelectionChangeFunction[parentTable.id()](parentTable);
  return false;
  
}

/****************************************/
/************ /LIST VIEW ****************/
/****************************************/



/****************************************/
/************* TREE VIEW ****************/
/****************************************/

Bauglir.GUI.TreeView = {};

/*
 * list of callback functions triggered if tree view node is moved, array keys are tree view ids
 * if callback is registered than node if not moved automatically
 */
Bauglir.GUI.TreeView.RegisteredOnNodeMove = new Array();

/*
 * register callback functions triggered if tree view node is moved
 * @param string treeViewId id of tree view
 * @param function callback
 */
Bauglir.GUI.TreeView.RegisterOnNodeMove = function(treeViewId, callback)
{
  Bauglir.GUI.TreeView.RegisteredOnNodeMove[treeViewId] = callback;
}

/*
 * list of callback functions triggered if tree view node selection is changed, array keys are tree view ids
 */
Bauglir.GUI.TreeView.RegisteredOnSelectionChange = new Array();

/*
 * register callback functions triggered if tree view node selection is changed
* @param string treeViewId id of tree view
 * @param function callback
 */
Bauglir.GUI.TreeView.RegisterOnSelectionChange = function(treeViewId, callback)
{
  Bauglir.GUI.TreeView.RegisteredOnSelectionChange[treeViewId] = callback;
}

Bauglir.GUI.TreeView.baugui_mapContextMenu = function(element, contextMenuId)
{
  var menu = $('#' + contextMenuId);
  if (element.tagName() == 'li')
  {
    Bauglir.GUI.ContextMenu.UnBind(element);
    if (menu.length) Bauglir.GUI.ContextMenu.Bind('#' + contextMenuId, element);
  }
  element.find('li').map(function(){
    //Bauglir.GUI.TreeView.baugui_mapContextMenu($(this), contextMenuId);

    Bauglir.GUI.ContextMenu.UnBind($(this));
    if (menu.length) Bauglir.GUI.ContextMenu.Bind('#' + contextMenuId, $(this));
  })
}

/**
 * assign context menu to LI
 * @param string listId list id
 * @param string contextMenuId context menu id
 */
Bauglir.GUI.TreeView.ContextMenu = function(listId, contextMenuId)
{
  var element = $('#' + listId);
  element.data('baugui-contextmenu', contextMenuId);
  Bauglir.GUI.TreeView.baugui_mapContextMenu(element, contextMenuId);
}


/***
 * create floating tree view used to select node (double click triggers selection callback)
 * @param string listId list id (already created used by Bauglir.GUI.TreeView.Create)
 * @param function callback function triggered on double click
 * @param null|inte[] multiple if passed checkboxes allowing multiple selection are added and passed ids are checked
 */
Bauglir.GUI.TreeView.CloneAsSelectableFloating = function(listId, callback, multiple)
{
  var element = $("#" + listId).clone(false);
  try
  {
    element.data('baugui-preselected', multiple.join(','));
  }
  catch(e) {multiple = null;} 


  
  element.addClass('baugui-treeview-floating');
  //element.append("<span class='baugui-window-closeButton'></span>");
  element.wrap("<div class='baugui-treeview-floating-box baugui-box-dark'></div>");
  var wrapper = element.closest('.baugui-treeview-floating-box');
  wrapper.append("<p class='baugui-treeview-floating-bottom'><button>" + Bauglir.GUI.Window.OkDefaultText + "</button></p>");
  Bauglir.GUI.baugui_buttonMainFuncts(wrapper);
  
  element.find('li').map(function(){
    $(this).data('baugui-id', $(this).id());
    $(this).id(Bauglir.GUI.RandomId());
  });
  element.find('ul').show();
  var data1 = element.find('.baugui-expand');
  var data2 = element.find('.baugui-collapse');
  data1.addClass('baugui-collapse');
  data1.removeClass('baugui-expand');
  data2.addClass('baugui-collapse');
  data2.removeClass('baugui-expand');
  element.find('li .baugui-selectable').removeClass("baugui-selected");


  var okFunction = function(){
    var result = $(this).data('baugui-id');
    if (multiple)
    {
      result = new Array()
      element.find('li :checked').closest('li').map(function(){result.push($(this).data('baugui-id'))});
    }
    else
    {
      result = new Array()
      element.find('li .baugui-selected').closest('li').map(function(){result.push($(this).data('baugui-id'))});
    }

    if (callback != null) callback(result);
    wrapper.remove();
  };

  if (multiple != null)
  {
    element.find('li .baugui-selectable').wrapInner("<label></label>");
    element.find('li').not('.baugui-nocheck').find('.baugui-selectable').prepend("<input type='checkbox' />&nbsp;");
    element.find('li :checkbox').map(function(){
      var chId = "chid-" + $(this).closest('li').data('baugui-id');
      $(this).closest('.baugui-selectable').find('label').attr("for", chId);
      $(this).id(chId);
      if (multiple.contains($(this).closest('li').data('baugui-id')))
        $(this).attr("checked", true);
    });
  }
  else element.find('li').dblclick(okFunction);
  wrapper.find('.baugui-treeview-floating-bottom').click(okFunction);
  element.find('li').mousedown(Bauglir.GUI.TreeView.baugui_selectevent);
 
  element.css("margin", '0px');
  wrapper.css("margin", '0px');
  return wrapper;
}


/**
 * function creates tree view (collapsable/dragable) tree from UL list
 * @param string listId list id
 */
Bauglir.GUI.TreeView.Create = function(listId)
{
  
  var element = $("#" + listId);
  element.addClass('baugui-treeview');
  

  //ADD ID
  Bauglir.GUI.TreeView.baugui_createid(element);


  

  //ADD SELECTABLE
  element.find('li').map(function(){
    Bauglir.GUI.TreeView.baugui_createselectable(this);
    //Bauglir.Log($(this).text());
  });
  //Bauglir.Log($(element).html());

  //TEXT
  element.find('li').map(function(){

    $(this).data("baugui-text", $(this).children('div.baugui-selectable').text());
    //Bauglir.Log($(this).data('baugui-text'));
  });

  




  //ADD COLLAPSABLE
  element.find('li').map(function(){
    Bauglir.GUI.TreeView.baugui_createcolapsable(this);
  });
  

  //SORT
  element.find('li').map(function(){
    Bauglir.GUI.TreeView.baugui_sort(this);
  });

  
  Bauglir.GUI.TreeView.baugui_restoreevents(element);

  element.mousedown(function(e){
    Bauglir.GUI.HideFloating(e);
    e.stopPropagation();
    return false;
  });
  element.disableSelection();


  if (Bauglir.GUI.TreeView.RegisteredOnSelectionChange[listId])
  {
    Bauglir.GUI.TreeView.RegisteredOnSelectionChange[listId](
      Bauglir.GUI.TreeView.GetSelectedNode(listId)
    );
  }

}

/**
 * delete selected item from list
 * @param string listId tree view id
 */
Bauglir.GUI.TreeView.DeleteSelected = function(listId)
{
  var element = $("#" + listId);
  var liSelected = element.find('div.baugui-selected').closest('li');
  var liParent = liSelected.parent().closest('li');
  liSelected.remove();
  liParent.find('ul').map(function(){
    if (!$(this).find('li').length) $(this).remove();
  })
  if (!liParent.find('ul').length)
  {
    liParent.children('.baugui-expandCollapse').removeClass('baugui-expand');
    liParent.children('.baugui-expandCollapse').removeClass('baugui-collapse');
  }
  if (Bauglir.GUI.TreeView.RegisteredOnSelectionChange[listId])
  {
    Bauglir.GUI.TreeView.RegisteredOnSelectionChange[listId](null);
  }

}

/**
 * remoev selected item in list
 * @param string listId tree view id
 * @param string newName new node name
 */
Bauglir.GUI.TreeView.RenameSelected = function(listId, newName)
{
  var element = $("#" + listId);
  var liSelected = element.find('div.baugui-selected').closest('li');
  var parent = liSelected.parent().closest('li');
  if (Bauglir.GUI.TreeView.CanAddToNode(parent, newName))
  {
    liSelected.data('baugui-text', newName);
    liSelected.children('.baugui-selectable').text(newName);
    Bauglir.GUI.TreeView.baugui_sort(parent);
    return true;
  }
  return false;
}


/**
 * whether new node with particular name can be added
 * @param jQuery node
 * @param string nodeText
 * @return bool
 */
Bauglir.GUI.TreeView.CanAddToNode = function(node, nodeText)
{
  if (node.children('ul').children('li').length)
  {
    for (var i = 0, j = node.children('ul').children('li').length; i < j; ++i)
    {
      var nl = node.children('ul').children('li').eq(i);
      if (nl.id() != node.id()) //clearly redundant but whatever
      {
        if (nl.data('baugui-text').toLowerCase() == nodeText.toLowerCase()) return false;
      }
    }
  }
  return true;
}

/**
 * whether new node with particular name can be added
 * @param string listId id of list
 * @param string nodeText
 * @return bool
 */
Bauglir.GUI.TreeView.CanAddToSelected = function(listId, nodeText)
{
  var element = $("#" + listId);
  var liSelected = element.find('div.baugui-selected').closest('li');
  return Bauglir.GUI.TreeView.CanAddToNode(liSelected, nodeText);
}


Bauglir.GUI.TreeView.GetNodeParent = function(node)
{
  var parent = node.parent().closest('li');
  if (parent.length) return parent;
  else return null;
}

/**
 * return selected node object
 * @param string listId tree view id
 * @return jQuery
 */
Bauglir.GUI.TreeView.GetSelectedNode = function(listId)
{
  var element = $("#" + listId);
  var parent = element.find('div.baugui-selected').closest('li');
  if (parent.length) return parent;
  else return null;
}

/**
 * delete ad node to selected item
 * @param string listId tree view id
 * @param string nodeText text
 */
Bauglir.GUI.TreeView.AddToSelected = function(listId, nodeText)
{
  var element = $("#" + listId);

  var liSelected = element.find('div.baugui-selected').closest('li');

 if (!Bauglir.GUI.TreeView.CanAddToNode(liSelected, nodeText)) return null;
  


  if (!liSelected.find('ul').length) liSelected.append('<ul></ul>');
  liSelected.children('ul').show();
  liSelected.children('.baugui-expandCollapse').addClass('baugui-collapse');
  var newLi = $("<li><span class='baugui-expandCollapse'></span><div class='baugui-selectable'>" + nodeText + "</div></li>");
  newLi.data('baugui-text', nodeText);
  liSelected.children('ul').append(newLi);
  Bauglir.GUI.TreeView.baugui_createid(newLi);
  Bauglir.GUI.TreeView.baugui_sort(liSelected);
  Bauglir.GUI.TreeView.baugui_restoreevents(newLi);

  Bauglir.GUI.TreeView.baugui_mapContextMenu(newLi, element.data('baugui-contextmenu'));

  return {id: newLi.id(), text: nodeText, object: newLi};
}


Bauglir.GUI.TreeView.baugui_createid = function(element)
{
  element = $(element);
  element.find('ul').map(function(){
    //Bauglir.GUI.TreeView.baugui_createid(this);
  });
  element.find('li').map(function(){
    //Bauglir.GUI.TreeView.baugui_createid(this);
  });

  if (!element.id()) element.id(Bauglir.GUI.RandomId());
  element.find('ul').map(function(){
    if (!$(this).id()) $(this).id(Bauglir.GUI.RandomId());
  });
  element.find('li').map(function(){
    if (!$(this).id()) $(this).id(Bauglir.GUI.RandomId());
  });
}

////Bauglir.GUI.RandomId


Bauglir.GUI.TreeView.baugui_sort = function(element)
{
  element = $(element);
  element.children('ul').map(function(){
    Bauglir.GUI.TreeView.baugui_sort(this);
  });

  element.children('li').addClass('baugui-sorting');

  while(element.find('.baugui-sorting').length)
  {
    try
    {
      var liToAdd = element.find('.baugui-sorting').eq(0);
      for (var i = 0, j = element.children('li').length; i < j; i++)
      {
        var liProc = element.children('li').eq(i);
        if (liProc.hasClass('baugui-sorting'))
        {
          if (liToAdd.data('baugui-text').toLowerCase() > liProc.data('baugui-text').toLowerCase())
          {
            liToAdd = liProc;
          }
        }
      }
      liToAdd.removeClass('baugui-sorting');
      element.append(liToAdd);
    } catch(e) {}
  }
  element.find('.baugui-sorting').removeClass('sorting');
}


Bauglir.GUI.TreeView.baugui_createselectable = function(element)
{
  element = $(element);
  /*
  element.find('li').map(function(){
    Bauglir.GUI.TreeView.baugui_createselectable(this);
  });
  var html = $(element).html();
  
  if (html.indexOf('<ul') > -1) var parts = html.split("<ul");
  else var parts = html.split("<UL");
  if (parts.length)
  {
    parts[0] = parts[0].trim();
    parts[0] = "<div class='baugui-selectable'>" + parts[0] + "</div>";
  }
  
  $(element).html(parts.join("<ul"));
  */
  var ul = $(element).children('ul').remove();
  var txt = $(element).text().trim();
  $(element).text('');
  //$(element).wrapInner("<div class='baugui-selectable'></div>");
  $(element).append("<div class='baugui-selectable'>" + txt + "</div>");
  $(element).append(ul);

  //Bauglir.Log($(element).html());
  //Bauglir.Log($(element).closest('.baugui-treeview').html());
}

Bauglir.GUI.TreeView.baugui_createcolapsable = function(element)
{

  element = $(element);
  //element.find('li').map(function(){Bauglir.GUI.TreeView.baugui_createcolapsable(this)});

  element.find('ul').map(function(){
    if (!$(this).find('li').length) $(this).remove();
  });
  element.find("span.baugui-expandCollapse").remove();
  element.prepend("<span class='baugui-expandCollapse'></span>");
  element.map(function(){
    if ($(this).children('ul').length)
    {
      if ($(this).children('ul').hidden()) $(this).children('.baugui-expandCollapse').addClass('baugui-expand');
      else $(this).children('.baugui-expandCollapse').addClass('baugui-collapse');
    }
  });

}


Bauglir.GUI.TreeView.RegisteredOnDropAcceptFunctions = new Array();

Bauglir.GUI.TreeView.RegisterOnDropAccept = function(treeViewId, callback)
{
  Bauglir.GUI.TreeView.RegisteredOnDropAcceptFunctions[treeViewId] = callback;
}

Bauglir.GUI.TreeView.RegisteredOnDropFunctions = new Array();

Bauglir.GUI.TreeView.RegisterOnDrop = function(treeViewId, callback)
{
  Bauglir.GUI.TreeView.RegisteredOnDropFunctions[treeViewId] = callback;
}

Bauglir.GUI.TreeView.baugui_restoreevents = function(element)
{
  element = $(element);

  var parentTree = element.closest('ul.baugui-treeview');

  parentTree.find('li').unbind('mousedown', Bauglir.GUI.TreeView.baugui_selectevent);
  parentTree.find('li').mousedown(Bauglir.GUI.TreeView.baugui_selectevent);

  parentTree.find('li').unbind('dblclick', Bauglir.GUI.TreeView.baugui_dblclickevent);
  parentTree.find('li').dblclick(Bauglir.GUI.TreeView.baugui_dblclickevent);
  
  parentTree.find('span.baugui-expandCollapse').unbind('click', Bauglir.GUI.TreeView.baugui_collapseevent);
  parentTree.find('span.baugui-expandCollapse').click(Bauglir.GUI.TreeView.baugui_collapseevent);

  // baugui-nodrop
  parentTree.find('li').not('.baugui-nodrag').draggable({helper: 'clone', opacity: '0.5', revert: 'invalid', zIndex: 100000  });
  parentTree.find('li').find('.baugui-selectable').droppable({
    tolerance: 'pointer',
    accept: function(dragged)
    {
      var result = parentTree.id() == dragged.closest('ul.baugui-treeview').id();
      result = result && !$(this).closest('li').hasClass('baugui-nodrop');
      if (!result && !$(this).closest('li').hasClass('baugui-nodrop'))
      {
        if (parentTree.id())
          if (Bauglir.GUI.TreeView.RegisteredOnDropAcceptFunctions[parentTree.id()])
            result = Bauglir.GUI.TreeView.RegisteredOnDropAcceptFunctions[parentTree.id()](parentTree, dragged, $(this).closest('li'));
      }
      return result;
    },
    hoverClass: 'baugui-hoverselected',
    drop: function(e, ui)
    {
      var source = ui.draggable;
      var destination = $(this).closest('li');
      if (source.closest('ul.baugui-treeview').id() == destination.closest('ul.baugui-treeview').id())
      {
        if (Bauglir.GUI.TreeView.RegisteredOnNodeMove[parentTree.id()] && Bauglir.GUI.TreeView.CanMove(source.id(), destination.id()))
        {
          setTimeout(function(){
            Bauglir.GUI.TreeView.RegisteredOnNodeMove[parentTree.id()](source, destination);
          }, 1);
        }
        else setTimeout(function(){Bauglir.GUI.TreeView.Move(source.id(), destination.id());}, 1);
      }
      else
      {
        if (parentTree.id())
          if (Bauglir.GUI.TreeView.RegisteredOnDropFunctions[parentTree.id()])
            Bauglir.GUI.TreeView.RegisteredOnDropFunctions[parentTree.id()](parentTree, source, destination);

      }
    }
  });
}





/**
 * whether node can be moved
 * @param string sourceId id of node to move
 * @param string destinationId id of new parent node
 * @return bool
 */

Bauglir.GUI.TreeView.CanMove = function(sourceId, destinationId)
{
  var source = $('#' + sourceId);
  var sourceParent = source.parent().closest('li');
  var destination = $('#' + destinationId);
  return ((destination.id() != sourceParent.id()) && Bauglir.GUI.TreeView.CanAddToNode(destination, source.data('baugui-text')));
}

/**
 * move node
 * @param string sourceId id of node to move
 * @param string destinationId id of new parent node
 */
Bauglir.GUI.TreeView.Move = function(sourceId, destinationId)
{
  /*
  var source = ui.draggable;
  var sourceParent = source.parent().closest('li');
  var destination = $(this).closest('li');
  */
  //alert(sourceId + "\n\n" + destinationId);
  var source = $('#' + sourceId);
  var sourceParent = source.parent().closest('li');
  var destination = $('#' + destinationId);
  //if ((destination.id() != sourceParent.id()) && Bauglir.GUI.TreeView.CanAddToNode(destination, source.data('baugui-text')))
  if (Bauglir.GUI.TreeView.CanMove(sourceId, destinationId))
  {
    //alert(source.data('baugui-text') + "\n\n" + destination.data('baugui-text'));
    if (!destination.children('ul').length) destination.append("<ul></ul>");
    source.appendTo(destination.children('ul'));


    if ($(destination).children('ul').hidden()) $(this).children('span.baugui-expandCollapse').addClass('baugui-expand');
    else $(destination).children('span.baugui-expandCollapse').addClass('baugui-collapse');

    //setTimeout(function(){
      Bauglir.GUI.TreeView.baugui_sort(destination.children('ul'), false);
      sourceParent.find('ul').map(function(){
        if (!$(this).find('li').length) $(this).remove();
      });
      if (!sourceParent.find('ul').length)
      {
        sourceParent.children('span.baugui-expandCollapse').removeClass('baugui-collapse');
        sourceParent.children('span.baugui-expandCollapse').removeClass('baugui-expand');
      }
    //}, 1);
    
    if (Bauglir.Browser.Msie)
    {
      setTimeout(function(){
        var oldd = sourceParent.css('display');
        sourceParent.css('display', 'none');
        sourceParent.css('display', oldd);
        //sourceParent.css('background', 'red');
      }, 10);
    }
    return true;
  }
  return false;
}

/**
 * select node
 * @param string nodeId node to select
 */
Bauglir.GUI.TreeView.SetSelected = function(nodeId)
{
  var node = $('#' + nodeId);
  if (node.length)
  {
    if (!node.children('div.baugui-selectable').hasClass('baugui-selected'))
    {
      node.closest('ul.baugui-treeview').find('div.baugui-selectable').removeClass('baugui-selected');
      node.children('div.baugui-selectable').addClass('baugui-selected');
      if (Bauglir.GUI.TreeView.RegisteredOnSelectionChange[node.closest('ul.baugui-treeview').id()])
      {
        Bauglir.GUI.TreeView.RegisteredOnSelectionChange[node.closest('ul.baugui-treeview').id()](node);
      }

    }
  }
}

Bauglir.GUI.TreeView.baugui_selectevent = function(e)
{
  Bauglir.GUI.TreeView.SetSelected($(this).id());
  Bauglir.GUI.HideFloating(e);
  e.stopPropagation();
  return false;
}


Bauglir.GUI.TreeView.baugui_dblclickevent = function(e)
{
  if ($(this).children('ul').length)
  {
    $(this).children('ul').toggle();
    $(this).children("span.baugui-expandCollapse").removeClass('baugui-expand');
    $(this).children("span.baugui-expandCollapse").removeClass('baugui-collapse');
    if ($(this).children('ul').hidden()) $(this).children("span.baugui-expandCollapse").addClass('baugui-expand');
    else $(this).children("span.baugui-expandCollapse").addClass('baugui-collapse');
  }
  e.stopPropagation();
}

Bauglir.GUI.TreeView.baugui_collapseevent = function(e)
{
  if ($(this).parent('li').children('ul').length)
  {
    $(this).parent('li').children('ul').toggle();
    $(this).removeClass('baugui-expand');
    $(this).removeClass('baugui-collapse');
    if ($(this).parent('li').children('ul').hidden()) $(this).addClass('baugui-expand');
    else $(this).addClass('baugui-collapse');
  }
}


/****************************************/
/******** DOCUMENT READY ****************/
/****************************************/

$(document).ready(function () {

  /*********** STYLE ***************/

  var bi = $("body").css('backgroundImage');
  if (bi)
  {
    //url("http://tools.bauglir.dev/css/luna")
    //
    var parts = bi.split('/');
    if (parts.length)
    {
      var res = parts[parts.length - 1];//
      res = res.replace(/[^a-z]/g,"");
      Bauglir.GUI.Style = res;
    }
  }

  Bauglir.GUI.ChangeSheets('luna');

  /*********** /STYLE ***************/

  /********* GENRAL ************/
  Bauglir.GUI.SetDisabled("*[disabled='disabled']", true);

  /********* GENRAL ************/


  /********* Context menu **********/
  $(".baugui-contextMenu").map(function(){Bauglir.GUI.ContextMenu.Create($(this))});
  /********* /Context menu **********/
  
  /*********** SPLITTER ***************/
  $(".baugui-VSplitter, .baugui-HSplitter").html("<div></div>");
  $(".baugui-VSplitter").draggable({
      helper: 'original',
      containment: 'parent',
      axis: 'x',
      zIndex: 100,
      //
      stop: function(){Bauglir.GUI.baugui_splitterOnSplit($(this));}
  });
  $(".baugui-HSplitter").draggable({
      helper: 'original',
      containment: 'parent',
      axis: 'y',
      zIndex: 100,
      stop: function(){Bauglir.GUI.baugui_splitterOnSplit($(this));}
  });
  $(".baugui-VSplitter").map(function(){
    if (!$(this).id().trim())
    {
      var d = new Date();
      var id = Math.round(Math.random() * 1000000) + d.getMilliseconds();
      $(this).id("baugui-VSplitter_" + id);
    }
  });
  $(".baugui-HSplitter").map(function(){
    if (!$(this).id().trim())
    {
      var d = new Date();
      var id = Math.round(Math.random() * 1000000) + d.getMilliseconds();
      $(this).id("baugui-HSplitter_" + id);
    }
  });
  $(".baugui-VSplitter, .baugui-HSplitter").parent().map(function(){
    switch($(this).css("position").toLowerCase())
    {
      case "absolute":
      case "relative":
      break;
      default: $(this).css("position", 'relative');
    }
  });

  $(".baugui-HSplitter, .baugui-VSplitter").data("moving", false);

  $(".baugui-HSplitter").hover(
    function(){
      Bauglir.GUI.baugui_HoverOn(this, 'baugui-HSplitter');
    },
    function(){
      if (!$(this).data("moving")) Bauglir.GUI.baugui_HoverOut(this, 'baugui-HSplitter'); //$(this).removeClass('hover');
    }
  );

  $(".baugui-VSplitter").hover(
    function(){
      Bauglir.GUI.baugui_HoverOn(this, 'baugui-VSplitter');
    },
    function(){
      if (!$(this).data("moving")) Bauglir.GUI.baugui_HoverOut(this, 'baugui-VSplitter'); //$(this).removeClass('hover');
    }
  );



  $(".baugui-HSplitter, .baugui-VSplitter").mousedown(function(){
    $(this).data("moving", true);
  });
  

  /*********** /SPLITTER ***************/



  /*********** TABS ***************/
  $(".baugui-tabControl li").click(Bauglir.GUI.baugui_tabControlClick);
  $(".baugui-tabControl li").hover(function(){Bauglir.GUI.baugui_TabMsieHoverOn(this);}, function(){Bauglir.GUI.baugui_TabMsieHoverOut(this);});
  $(".baugui-tabControl").map(function(){ Bauglir.GUI.baugui_TabControlAddId(this); });
  $(".baugui-tabControl li").map(function(){ Bauglir.GUI.baugui_TabAddId(this); });
  $(".baugui-tabControl").disableSelection();





  /*********** /TABS ***************/

  /*********** BUTTONS ***************/
  Bauglir.GUI.baugui_buttonMainFuncts();

  /*********** /BUTTONS ***************/


  /*********** RIBBON ***************/
  $(".baugui-ribbonMenu").map(function(){ Bauglir.GUI.baugui_RibbonAddId(this);});
  $(".baugui-ribbonMenu").find(Bauglir.GUI.buttonSelector).click(function () {Bauglir.GUI.baugui_RibbonButtonClick(this);});
  $(".baugui-ribbonToolBar").hover(function () {Bauglir.GUI.baugui_HoverOn(this, 'baugui-ribbonToolBar');}, function () {Bauglir.GUI.baugui_HoverOut(this, 'baugui-ribbonToolBar');});
  $(".baugui-ribbonMenu").append("<br /><div class='clearBoth'>&nbsp;</div>");

  //$(".baugui-ribbonToolBar p.flat

  setTimeout(function(){$(".baugui-ribbonMenu").map(function(){Bauglir.GUI.baugui_RibbonSetHeight(this); });}, Bauglir.GUI.ribbonSetHeightTimeOut);
  
  /*********** /RIBBON ***************/

  $('body').mouseup(function(){
    $(".baugui-HSplitter, .baugui-VSplitter").data("moving", false);
    $(".baugui-HSplitter, .baugui-VSplitter").removeClass("hover");
    $(Bauglir.GUI.buttonSelector).removeClass('baugui-click');
    
  });
  
  $('body').mousedown(function(e){
    //$('#todoViewTextPanel').html(e.target.className);
    Bauglir.GUI.HideFloating(e);
    /*
    if (!Bauglir.GUI.baugui_contextMenuIsItem(e.target))
      $(".baugui-contextMenu").hide();
    if (e.target.parents('.baugui-calendar-year-list').length)
    $('.baugui-calendar-year-list').hide();
    $('.baugui-calendar-month-list').hide();
    */

  });

  $('body').keyup(function(e){
    /*
    if (!Bauglir.GUI.baugui_contextMenuIsItem(e.target))
      $(".baugui-contextMenu").hide();
    $('.baugui-calendar-year-list').hide();
    $('.baugui-calendar-month-list').hide();
    */
   Bauglir.GUI.HideFloating(e);

  });

  


});



/*************************************/
/************** HELPERS **************/
/*************************************/

Bauglir.GUI.baugui_buttonId = function(element)
{
  if (!$(element).id().trim())
  {
    var d = new Date();
    var id = Math.round(Math.random() * 1000000) + d.getMilliseconds();
    $(element).id("baugui-button_" + id);
  }
}

Bauglir.GUI.baugui_RibbonAddId = function(element)
{
  if (!$(element).id().trim())
  {
    var d = new Date();
    var id = Math.round(Math.random() * 1000000) + d.getMilliseconds();
    $(element).id("baugui-ribbonMenu_" + id);
  }
}

Bauglir.GUI.baugui_RibbonButtonClick = function(element)
{
  if (Bauglir.GUI.Ribbon.OnButtonClick != null)
  {
    var btn = $(element);
    var rt = $(element).closest(".baugui-ribbonToolBar").eq(0);
    var rb = $(element).closest(".baugui-ribbonMenu");
    Bauglir.GUI.Ribbon.OnButtonClick(rb, $(element));
  }
}

Bauglir.GUI.baugui_HoverOn = function(element, mainClass)
{
  if(!mainClass) mainClass = '';
  if (!$(element).hasClass('baugui-disabled'))
  {
    if (mainClass) $(element).addClass(mainClass + 'hover');
    else $(element).addClass('baugui-hover');
  }
}

Bauglir.GUI.baugui_HoverOut = function(element, mainClass)
{
  if(!mainClass) mainClass = '';
  if (!$(element).hasClass('baugui-disabled'))
  {
    if (mainClass) $(element).removeClass(mainClass + 'hover');
    else $(element).removeClass('baugui-hover');
  }
}

Bauglir.GUI.baugui_RibbonSetHeight = function (element)
{
  Bauglir.GUI.baugui_RibbonSetHeightEx(element);
  setTimeout(function(){$(element).map(function(){Bauglir.GUI.baugui_RibbonSetHeightEx(this); });}, 5000);
}

Bauglir.GUI.baugui_RibbonSetHeightEx = function (element)
{
  var id = $(element).id();
  var maxRibbonHeight = 0;
  var oldDisplay = $(element).eq(0).css('display');
  $(element).css('display', 'block');
  $("#" + id + " .baugui-ribbonToolBar div").map(function(){
    if (this.className == '')
    {
      maxRibbonHeight = Math.max(maxRibbonHeight, this.offsetHeight);
    }
  });
  $("#" + id + " .baugui-ribbonToolBar div").map(function(){
    if (this.className == '')
      $(this).css('height', maxRibbonHeight + "px");
  });
  $(element).css('display', oldDisplay);
}

Bauglir.GUI.baugui_TabMsieHoverOn = function (element)
{
  if (!$(element).hasClass('baugui-active'))
    $(element).addClass('baugui-hover');
  
}

Bauglir.GUI.baugui_TabMsieHoverOut = function (element)
{
  if (!$(element).hasClass('baugui-active'))
    $(element).removeClass('baugui-hover');
}


Bauglir.GUI.baugui_TabControlAddId = function(element)
{
  if (!$(element).id().trim())
  {
    var d = new Date();
    var id = Math.round(Math.random() * 1000000) + d.getMilliseconds();
    $(element).id("baugui-tabControl_" + id);
  }
}

Bauglir.GUI.baugui_TabAddId = function(element)
{
  if (!$(element).id().trim())
  {
    var d = new Date();
    var id = Math.round(Math.random() * 1000000) + d.getMilliseconds();
    $(element).id("baugui-tabControlTab_" + id);
  }
  Bauglir.GUI.baugui_addSpanIntoElement(element, 'baugui-container');
}


Bauglir.GUI.baugui_addSpanIntoElement = function(element, spanClass)
{
  //alert(Bauglir.GUI.baugui_addSpanIntoElement.caller);
  if (!$(element).contents().length) return;
  if(!$(element).contents().eq(0).get(0).tagName)
  {
    var h = $(element).html();
    $(element).html("<span>" + h + "</span>");
  }
  
  if ($(element).contents().eq(0).get(0).tagName.toLowerCase() != 'span')
  {
    var h = $(element).html();
    $(element).html("<span>" + h + "</span>");
  }
  
  $(element).find('span').eq(0).addClass(spanClass);
  
}

Bauglir.GUI.baugui_addPIntoElement = function(element, spanClass)
{

  if(!$(element).contents().eq(0).get(0).tagName)
  {
    var h = $(element).html();
    $(element).html("<p>" + h + "</p>");
  }

  if ($(element).contents().eq(0).get(0).tagName.toLowerCase() != 'p')
  {
    var h = $(element).html();
    $(element).html("<p>" + h + "</p>");
  }

  $(element).find('p').eq(0).addClass(spanClass);

}



/**
 * click on tabControl
 */
Bauglir.GUI.baugui_tabControlClick = function(e)
{
  $(".baugui-contextMenu").hide();
  var targetLi = $(e.target);
  while(targetLi.get(0).tagName.toLowerCase() != 'li') targetLi = targetLi.closest('li');
  var targetUl = targetLi.parent();
  oldLi = targetUl.find("li.baugui-active").eq(0);

  

  if (oldLi.id() != targetLi.id() )
  {
    if (Bauglir.GUI.TabControl.OnChanging != null)
      if (!Bauglir.GUI.TabControl.OnChanging(targetUl, oldLi, targetLi))
        return;
    targetUl.find("li.baugui-active").removeClass('baugui-hover');
    targetUl.find("li.baugui-active").removeClass('baugui-active');
    targetLi.addClass('baugui-active');
    targetLi.removeClass('baugui-hover');
    if (Bauglir.GUI.TabControl.OnChange != null) Bauglir.GUI.TabControl.OnChange(targetUl, oldLi, targetLi)
  }
}


Bauglir.GUI.baugui_contextMenuClick = function(e)
{
  $(".baugui-contextMenu").hide();
  $(".baugui-contextMenu").find("li").unbind("mouseup", Bauglir.GUI.baugui_contextMenuClick);

  var li = e.target;
  while($(li).parents().length)
  {
    if (li.tagName.toLowerCase() == 'li') break;
    li = li.parentNode;
  }
  var liTarget = li;
  
  if ($(liTarget).hasClass('baugui-checkable'))
  {
    $(liTarget).toggleClass('baugui-checked');
  }


  var ul = null;
  while($(li).parents().length)
  {
    li = li.parentNode;
    if (li.tagName.toLowerCase() == 'ul' && $(li).hasClass('baugui-contextMenu')) ul = li;
  }

  if (!$(liTarget).hasClass('baugui-disabled'))
  {
    if ($(liTarget).id())
    {
      
      if (Bauglir.GUI.ContextMenu.RegisteredOnClickFunctions[$(liTarget).id()])
      {
        Bauglir.GUI.ContextMenu.RegisteredOnClickFunctions[$(liTarget).id()](Bauglir.GUI.ContextMenu.Target);
        return;
      }
    }
    if (Bauglir.GUI.ContextMenu.OnClick != null) Bauglir.GUI.ContextMenu.OnClick($(ul), $(liTarget));
  }

  //Bauglir.GUI.ContextMenu.RegisteredOnClickFunctions
  
}

Bauglir.GUI.baugui_contextMenuIsItem = function(element)
{
  while($(element).parents().length)
  {
    element = element.parentNode;
    if (element.tagName.toLowerCase() == 'ul' && $(element).hasClass('baugui-contextMenu')) return true;
  }
  return false
}

Bauglir.GUI.baugui_contextMenuTestHide = function(e)
{
  if (!Bauglir.GUI.baugui_contextMenuIsItem(e.target)) $('baugui-contextMenu').hide();
}


Bauglir.GUI.baugui_contextMenuDisplay = function(menu, element, left, top, dontSetTarget)
{
  left += 1;
  top += 1;
  if (dontSetTarget == null || dontSetTarget == false) Bauglir.GUI.ContextMenu.Target = $(element);
  $(menu).hide();
  $(menu).css("left", left + "px");
  $(menu).css("top", top + "px");
  if ($(menu).id())
  if (Bauglir.GUI.ContextMenu.RegisteredOnShowFunctions[$(menu).id()])
    Bauglir.GUI.ContextMenu.RegisteredOnShowFunctions[$(menu).id()]($(menu), $(element));
  $(menu).fadeIn(250);
  if (dontSetTarget == null || dontSetTarget == false)
  {
    $(menu).find("li").bind("mouseup", Bauglir.GUI.baugui_contextMenuClick);
  }
}

Bauglir.GUI.baugui_contextMenuSetSubmenu = function(element)
{
  if ($(element).hasClass('baugui-disabled')) return;
  if ($(element).find('ul').length) 
  {
    $(element).find('ul').addClass('baugui-contextMenu');
    $(element).children('.baugui-container').addClass('baugui-submenu');

    $(element).hover(
      function(){
        var left = $(this).absLeft() + $(this).outerWidth();
        var top = $(this).absTop();
        left -= $(this).absLeft();
        top -= $(this).absTop();
        if (Bauglir.Browser.Msie) left -= 30;
        Bauglir.GUI.baugui_contextMenuDisplay($(element).find('ul').eq(0), this, left, top, true);
      },
      null
    );
    $(element).find('li').map(function(){Bauglir.GUI.baugui_addSpanIntoElement(this, 'baugui-container');});
    $(element).find('li').map(function () {Bauglir.GUI.baugui_contextMenuSetSubmenu(this)});
  }
  else $(element).mouseover(function(){$(element).parent().find('ul').hide()});

}

Bauglir.GUI.baugui_buttonGroupFunctionality = function(element)
{
  var parent = element.parentNode;
  while($(parent).parents().length)
  {
    if ($(parent).hasClass('baugui-buttonGroup') || $(parent).hasClass('baugui-buttonGroupFull'))
    {
      $(parent).find(Bauglir.GUI.buttonSelector).removeClass('baugui-down');
    }
    parent = parent.parentNode;
  }

}

Bauglir.GUI.baugui_splitterOnSplit = function(element)
{
  if ($(element).id())
  {
    if (Bauglir.GUI.Splitter.RegisteredOnSplitFunctions[$(element).id()])
    {
      Bauglir.GUI.Splitter.RegisteredOnSplitFunctions[$(element).id()]($(element));
      return;
    }
  }
  if (Bauglir.GUI.Splitter.OnSplit != null) Bauglir.GUI.Splitter.OnSplit($(element))
}

/*********************************************
 *******************************************/
Bauglir.GUI.baugui_buttonMainFuncts = function(jqueryObject)
{
  if (jqueryObject == null) jqueryObject = $("body");
  $(jqueryObject).find(".baugui-buttonGroupFull").find(Bauglir.GUI.buttonSelector).addClass("baugui-buttonDown");

  $(jqueryObject).find(Bauglir.GUI.buttonSelectorOnly).addClass('baugui-button');
  $(jqueryObject).find(Bauglir.GUI.buttonSelectorNoImg).hover(
    function () {Bauglir.GUI.baugui_HoverOn(this);}, function () {Bauglir.GUI.baugui_HoverOut(this);}
  );

  $(jqueryObject).find(Bauglir.GUI.buttonSelector).mousedown(
    function () {
        $(this).addClass('baugui-click');
    }
  );

  $(jqueryObject).find(Bauglir.GUI.buttonSelector).filter(".baugui-buttonDown").click(
    function () {
        Bauglir.GUI.baugui_buttonGroupFunctionality(this);
        $(this).toggleClass('baugui-down');
    }
  );

  $(jqueryObject).find(Bauglir.GUI.buttonSelector).filter(":disabled").map(
    function () {
        $(this).addClass('baugui-disabled');
    }
  );

  $(jqueryObject).find(Bauglir.GUI.buttonSelector).map(function(){Bauglir.GUI.baugui_buttonId(this);});

  $(jqueryObject).find(".baugui-ribbonToolBar p.baugui-group, .baugui-ribbonToolBar p span.baugui-containerGroup").find(Bauglir.GUI.buttonSelector).map(function(){
    $(this).addClass('baugui-ingroup');
  });
  $(jqueryObject).find(".baugui-ribbonToolBar p.baugui-group, .baugui-ribbonToolBar p span.baugui-containerGroup").find(Bauglir.GUI.buttonSelector).filter(":last-child").map(function(){
    $(this).removeClass('baugui-ingroup');
  });


  $(jqueryObject).find(".baugui-buttonDropDown").map(function(){Bauglir.GUI.Button.CreateDropDown(this);});
}
/*******************************************
 ******************************************/




/***************************************************/



if (Bauglir.libVersion < Bauglir.GUI.libVersion)
  {throw ('Reguires Bauglir Core version ' + Bauglir.libVersion + '.');}

/** TESTING jQuery **/
try
{
  jQuery('body');
}
catch (e)
{
  {throw ('Reguires jQuery version 1.3.1.');}
}

