function CLogger() {
 //this.log("CLogger initialized."); 
}

CLogger.prototype.log = function(text) {
 //alert(text);
}


jQuery
  .extend( {
   createButton : function(parent, label, icon, tooltip, options) {
    var button = jQuery('<button'
      + (tooltip ? ' title="' + tooltip + '"' : '') + '>'
      + (icon ? '<img src="' + icon + '" />' : '')
      + (label || '') + '</button>');

    if (options['class'])
     button.addClass(options['class']);

    if (options['style'])
     button.css(options['style']);

    if (options['click'])
     button.click(options['click']);

    if (options['mouseover'])
     button.mouseover(options['mouseover']);

    if (options['mouseout'])
     button.mouseout(options['mouseout']);

    if (options['name'])
     button.attr('name', options['name']);

    if (options['type'])
     button.attr('type', options['type']);

    if (options['value'])
     button.attr('value', options['value']);

    return button.appendTo(parent);
   },

   createImageButton : function(parent, icon, tooltip, options) {
    var button = jQuery('<img src="' + icon + '"'
      + (tooltip ? ' title="' + tooltip + '"' : '') + ' />');

    if (options['class'])
     button.addClass(options['class']);

    if (options['style'])
     button.css(options['style']);

    if (options['click'])
     button.click(options['click']);

    if (options['mouseover'])
     button.mouseover(options['mouseover']);

    if (options['mouseout'])
     button.mouseout(options['mouseout']);

    return button.appendTo(parent);
   },

   //dims the screen
   dimScreen : function(speed, opacity, callback) {
    if (jQuery('#__dimScreen').size() > 0)
     return;

    if (typeof speed == 'function') {
     callback = speed;
     speed = null;
    }

    if (typeof opacity == 'function') {
     callback = opacity;
     opacity = null;
    }

    if (speed < 1) {
     var placeholder = opacity;
     opacity = speed;
     speed = placeholder;
    }

    if (opacity >= 1) {
     var placeholder = speed;
     speed = opacity;
     opacity = placeholder;
    }
    var lpad = 0;
    if ($(window).width() > $(document.body).width()) {
     lpad = ($(window).width() - $(document.body).width()) / 2 + 1;
    }

    speed = (speed > 0) ? speed : 500;
    opacity = (opacity > 0) ? opacity : 0.5;

    jQuery.addWindowResizeListener( function() {
     var x = jQuery('#__dimScreen');
     var lpad = 0;
     var w = $(window).width();
     if ($(window).width() > $(document.body).width()) {
      lpad = (jQuery(window).width() - jQuery(document.body)
        .width()) / 2 + 1;
     }
     if (w < $(document.body).width()) {
      w = $(document.body).width() + 1;
     }
     x.css( {
      height : $(document).height() + 'px',
      left : -lpad + 'px',
      width : (w + 2) + 'px'
     });
    });

    return jQuery('<div></div>').attr( {
     id : '__dimScreen',
     fade_opacity : opacity,
     speed : speed
    }).css( {
     background : '#000',
     height : $(document).height() + 'px',
     left : -lpad + 'px',
     opacity : 0,
     position : 'absolute',
     top : '0px',
     width : ($(document).width() + 2) + 'px',
     zIndex : 9999
    }).appendTo(document.body).fadeTo(speed, opacity, callback);
   },

   //stops current dimming of the screen
   dimScreenStop : function(callback) {
    var x = jQuery('#__dimScreen');    
    var opacity = x.attr('fade_opacity');
    var speed = x.attr('speed');
    x.hide(speed, function() {
     x.remove();
     //$(this).remove();     
     if (typeof callback == 'function') callback();
    });
   },

   //adds callback function for window.resize event
   addWindowResizeListener : function(callback) {
    _wresize_listener[_wresize_listener.length] = callback;
   },

   //adds callback function for window.scroll event
   addWindowScrollListener : function(callback) {
    _wscroll_listener[_wscroll_listener.length] = callback;
   },

   openModalWindow : function(options) {
    var wnd = jQuery('<div></div>');
    wnd.title = null;
    wnd.content = null;
    wnd.wndCtrl = [];
    wnd.dlgCtrl = [];
    var yoffset = 0;
    var options = $.extend( {
     showTooltip : true,
     content : '',
     contentURL : null,
     iframe : false,
     width : 480,
     height : 320,
     resizable : true,
     id : '__modWnd_' + jQuery.data(wnd)
    }, options);

    jQuery.dimScreen();

    if ((options.width == undefined) || options.width <= 0)
     options.width = 400;
    if ((options.height == undefined) || options.height <= 0)
     options.height = 280;
    options.height += 20;

    if ((options.content == undefined))
     options.content = "";

    wnd.attr( {
     id : options.id
    }).css( {
     background : '#FFF',
     height : options.height + 'px',
     width : options.width + 'px',
     position : 'absolute',
     overflow : 'visible',
     zIndex : 10000
    }).addClass('__modWnd');
    wnd.appendTo(document.body);
    jQuery.centerOnView(wnd);

    wnd.close = function() {
     if (options.onClose)
      options.onClose();
     jQuery.closeModalWindow('#' + options.id);
    };

    var dlgForm = null;

    if (options.form) {
     dlgForm = jQuery(
       '<form action="'
         + options.form.action
         + '" method="'
         + (options.form.method || 'post')
         + '"'
         + (options.form.enctype ? +'" enctype="'
           + options.form.enctype + '"' : '')
         + '></form>').appendTo(wnd);
    }

    var layout = dlgForm || wnd;

    if (options.title || options.wndCtrl) {
     if ((options.title == undefined))
      options.title = "";

     var titleBar = jQuery('<div class=\"move_handle\"></div>')
       .css( {
        height : '20px',
        width : '100%',
        left : '-2px',
        top : '-23px',
        position : 'absolute',
        verticalAlign : 'middle'
       }).addClass('modWnd_head').appendTo(layout);

     wnd.title = jQuery('<span></span>').attr( {
      id : '__modWndTitle_' + options.id,
      unselectable : 'on',
      style : '-moz-user-select:none;'
     }).css( {
      width : '100%',
      padding : '2px 4px'
     }).appendTo(titleBar).html(options.title);

     var dlgControlBar = jQuery('<span></span>').css( {
      float : 'right'
     }).appendTo(titleBar);

     for ( var btn in options.wndCtrl) {
      wnd.wndCtrl
        .push(jQuery
          .createImageButton(
            dlgControlBar,
            options.wndCtrl[btn].icon,
            null,
            {
             'class' : 'modWnd_icon',
             'style' : {
              top : '1px',
              right : (1 + btn * 22) + 'px'
             },
             'click' : options.wndCtrl[btn].click == "CLOSE" ? wnd.close
               : options.wndCtrl[btn].click
            }));
     }
     yoffset += 22;
    }
    if (options.dlgCtrl)
     yoffset += 22;

    if (options.iframe) {
     wnd.content = jQuery('<iframe></iframe>').attr( {
      id : '__modWndContent_' + options.id
     }).css( {
      position : 'absolute',
      overflow : 'auto',
      left : '0px',
      top : '0px',
      height : '100%',
      width : '100%',
      border : 'none'
     }).addClass('modWnd_content').appendTo(layout);
     var d = wnd.content.get(0);

     if (d.contentWindow.document) {
      d = d.contentWindow.document;
      if (options.contentURL) {
       d.location.href = options.contentURL;
      } else {
       d.open('text/html', 'append');
       d.charset = "iso-8859-1";
       d.write(options.content);
       d.close();
      }
     } else
      alert('An unexpected error occured!');
    } else {
     wnd.content = jQuery('<div></div>').attr( {
      id : '__modWndContent_' + options.id
     }).css( {
      overflow : 'auto',
      verticalAlign : 'top',
      position : 'absolute',
      left : '0px',
      top : '0px',
      height : '100%',
      width : '100%'
     }).addClass('modWnd_content').appendTo(layout).html(
       options.content);
    }

    if (options.dlgCtrl) {
     var controlBar = jQuery('<div></div>').css( {
      height : '20px',
      width : '100%',
      position : 'absolute',
      left : '-2px',
      top : '100%',
      verticalAlign : 'middle'
     }).addClass('modWnd_foot').appendTo(layout);

     for ( var btn in options.dlgCtrl) {
      wnd.dlgCtrl
        .push(jQuery
          .createButton(
            controlBar,
            options.dlgCtrl[btn].label,
            options.dlgCtrl[btn].icon,
            options.dlgCtrl[btn].tooltip,
            {
             'class' : 'modWnd_icon',
             //            'style': { right: (btn*22)+'px'},
             'click' : (options.dlgCtrl[btn].click == "CLOSE" ? wnd.close
               : options.dlgCtrl[btn].click),
             'name' : options.dlgCtrl[btn].name,
             'type' : options.dlgCtrl[btn].type,
             'value' : options.dlgCtrl[btn].value
            }));
     }
     jQuery('<div></div>').addClass('resize_handle').appendTo(
       controlBar);
    }

    if (options.showTooltip && wnd.addFormHelp)
     wnd.addFormHelp();

    if(options.resizable) {
      wnd
      .bind('dragstart', function(event) {
       if (!$(event.target).is('.move_handle'))
        return false;
       $(this).addClass('active');
      })
      .bind(
        'drag',
        function(event) {
         var wdif = ($(window).width() - jQuery(
           document.body).width()) / 2;
         wdif = (wdif < 0) ? 0 : wdif;
         $(this).css( {
          top : event.offsetY,
          left : (event.offsetX - wdif)
         });
        })
      .bind('dragend', function(event) {
       $(this).removeClass('active');
       $.centerOnView(this);
      })
      .resizable(
        {
         handler : '.resize_handle',
         min : {
          width : Math.min(options.minWidth,
            options.width) - 5,
          height : Math.min(options.minHeight,
            options.height) - 45
         },
         max : {
          width : options.maxWidth ? options.maxWidth - 5
            : $(window).width(),
          height : options.maxHeight ? options.maxHeight - 45
            : $(window).height()
         },
         onResize : function(e) {
          e.data.resizeData.target
            .addClass('moving');
         },
         onStop : function(e) {
          e.data.resizeData.target
            .removeClass('moving'); // $.centerOnView(this);
         }
        })
        ;
   	}

    _modalWndNum++;
    return wnd;
   },

   closeModalWindow : function(qry) {
    var wnd = undefined;
    if (qry == undefined)
     wnd = jQuery(this);
    else
     wnd = jQuery(qry);

    wnd.remove();
    _modalWndNum--;
    if (_modalWndNum <= 0) {
     jQuery.dimScreenStop();
    }
   },

   getScrollXY : function() {
    var scrOfX = 0, scrOfY = 0;
    if (typeof (window.pageYOffset) == 'number') {
     //Netscape compliant
     scrOfY = window.pageYOffset;
     scrOfX = window.pageXOffset;
    } else if (document.body
      && (document.body.scrollLeft || document.body.scrollTop)) {
     //DOM compliant
     scrOfY = document.body.scrollTop;
     scrOfX = document.body.scrollLeft;
    } else if (document.documentElement
      && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
     //IE6 standards compliant mode
     scrOfY = document.documentElement.scrollTop;
     scrOfX = document.documentElement.scrollLeft;
    }
    return [ scrOfX, scrOfY ];
   },

   centerOnView : function(obj) {
    var x = undefined;
    if (obj == undefined)
     x = jQuery(this);
    else
     x = jQuery(obj);

    var scrl = jQuery.getScrollXY();
    var lpad = ($(window).width() / 2) - (x.width() / 2);
    var tpad = ($(window).height() / 2) - (x.height() / 2);

    if (lpad > 0)
     lpad += scrl[0];
    else
     lpad = scrl[0];
    var ldif = (jQuery(document).width() - (x.width() + lpad));
    if ((ldif < 0))
     lpad += ldif;

    if (tpad > 0)
     tpad += scrl[1];
    else
     tpad = scrl[1];
    var tdif = (jQuery(document).height() - (x.height() + tpad));
    if ((tdif < 0))
     tpad += tdif;

    var wdif = ($(window).width() - jQuery(document.body).width()) / 2;
    wdif = (wdif < 0) ? 0 : wdif;

    if (tpad < 0)
     tpad = 0;
    if (lpad < 0)
     lpad = 0;
    x.css( {
     top : tpad + 'px',
     left : (lpad - wdif) + 'px'
    });
   }

  });

( function($) {
 $.fn.extend( {
  setUserID : function(id) {
   var _wnd = this;
   return _wnd.each( function() {
    if (jQuery(this).hasClass('__modWnd')) {
     jQuery(this).attr( {
      id : id
     }).children(".modWnd_head").children(".modWnd_close")
       .click( function() {
        jQuery.closeModalWindow('#' + id);
       })
    }
   });
  },
  content: function(html) {
	  
	  var _wnd = jQuery(this);
	  var ret_content = undefined;
	  _wnd.each( function() {
		if (jQuery(this).hasClass('__modWnd')) {
			if(html == undefined) {
				jQuery(this).children(".modWnd_content").each(function() {
					if(jQuery(this).get(0).nodeName == "DIV") {
						ret_content = jQuery(this).html();
					} else {
						ret_content = jQuery(this).html();					
					}
				});
			} else {
				jQuery(this).children(".modWnd_content").each(function() {
					//console.log(jQuery(this).get(0).nodeName);
					if(jQuery(this).get(0).nodeName == "DIV") {
						jQuery(this).html(html);
					} else
					if(jQuery(this).get(0).nodeName == "IFRAME") {
						var d = jQuery(this).get(0);
						if (d.contentWindow.document) {
					    	d = d.contentWindow.document;					    	
				       		d.open('text/html', 'append');
				       		d.charset = "iso-8859-1";
				       		d.write(html);
				       		d.close();					      	
					     } else
					     	alert('An unexpected error occured!');	
					}
				});				
			}
		}
	  });
	  if(html == undefined) {
		return ret_content;  
	  } else {
		  return _wnd;
	  }
	  
  },
  controls: function(options, safe_ctrl) {
  	var _wnd = jQuery(this);
	_wnd.each( function() {
		if (jQuery(this).hasClass('__modWnd')) {
			var _wnd_id = jQuery(this).attr("id");			
			jQuery(this).children(".modWnd_foot").each(function() {
				if(options == undefined) {
					//console.log("undef");
					return $(this).children("button");
				} else {
					if(safe_ctrl == undefined) {
						$(this).children("button").remove();
					} else {						
						$(this).children("button").appendTo(jQuery(safe_ctrl));
					}
					//console.log("def");
					if(options instanceof jQuery) {
						options.children("button").appendTo($(this));	
					} else {
						for ( var btn in options) {
					      jQuery.createButton(
					    		$(this),
					            options[btn].label,
					            options[btn].icon,
					            options[btn].tooltip,
					            {
					             'class' : 'modWnd_icon',
					             'click' : (options[btn].click == "CLOSE" ? jQuery.closeModalWindow("#"+_wnd_id) : options[btn].click),
					             'name' : options[btn].name,
					             'type' : options[btn].type,
					             'value' : options[btn].value
					            });
					    
						}
					} 					
					return jQuery(this);
				}
			});
		}
	});
  }
 });
})(jQuery);

/*  */
var _modalWndNum = 0;
var _wresize_listener = new Array();
var _wscroll_listener = new Array();

jQuery(window).resize( function() {
 for (i = 0; i < _wresize_listener.length; i++) {
  _wresize_listener[i]();
 }
}).scroll( function() {
 for (i = 0; i < _wscroll_listener.length; i++) {
  _wscroll_listener[i]();
 }
});

jQuery.addWindowScrollListener( function(e) {
 jQuery('.__modWnd').each( function() {
  jQuery.centerOnView(this);
 });
});

jQuery.addWindowResizeListener( function() {
 jQuery('.__modWnd').each( function() {
  jQuery.centerOnView(this);
 });
});

/*
 * var MAX_DUMP_DEPTH = 10;
 * 
 * function dumpObj(obj, name, indent, depth) {
 * 
 * if (depth > MAX_DUMP_DEPTH) {
 * 
 * return indent + name + ": <Maximum Depth Reached>\n"; }
 * 
 * if (typeof obj == "object") {
 * 
 * var child = null;
 * 
 * var output = indent + name + "\n";
 * 
 * indent += "\t";
 * 
 * for (var item in obj) {
 * 
 * try {
 * 
 * child = obj[item]; } catch (e) {
 * 
 * child = "<Unable to Evaluate>"; }
 * 
 * if (typeof child == "object") {
 * 
 * //output += dumpObj(child, item, indent, depth + 1); } else {
 * 
 * output += indent + item + ": " + child + "\n"; } }
 * 
 * return output; } else {
 * 
 * return obj; } }
 */
( function($) {
 $.openEditWindow = function(settings, extraSettings) {
  var options = {
   title : 'Bearbeiten',
   source : null,
   hiddenfield : null,
   minTextLength : 0,
   onUpdate : null,
   updatePost : null,
   updateMsg : 'Der Text wurde erfolgreich gespeichert. Gegebenenfalls werden jetzt noch Daten aktualisiert.',
   table : '',
   field : '',
   id : ''
  };
  $.extend(options, settings, extraSettings);

  var dataType = "xml";

  var textfield = $("<textarea class=\"editor\" style=\"width:100%;height:100%;\">Load data...</textarea>");
  var editor = null;

  var wnd = $.openModalWindow(
  {
    content : textfield,
    width : 640,
    height : 320,
    minWidth : 320,
    minHeight : 240,
    maxWidth : 1024,
    maxHeight : 768,
    title : options.title,
    id : "Edit_Wnd",
    //wndCtrl:[{tooltip:"Schließen", icon:"../gfx/bubble/icons/bubble_close.png", click:"CLOSE"}],
    dlgCtrl : [
    {
      label : "Abbrechen",
      click : "CLOSE"
    },
    {
      label : "Speichern",
      click : function()
      {
        var tmpLength;
        if (options.minTextLength > 0
           && editor.getHTML().length < options.minTextLength)
          alert("Der Text muß mindestens "
            + options.minTextLength
            + " Zeichen groß sein. ");
        else
        {         
         for (i in wnd.dlgCtrl)
          wnd.dlgCtrl[i].attr("disabled", "true");
         for (i in wnd.wndCtrl)
          wnd.wndCtrl[i].attr("disabled", "true");
          
          var bbcode= editor.getBBCode()//.replace(/(\r\n|\n\r|\r)/, '\n')
          .replace(/[\n]{3,}/, '\n\n');
          console.log(bbcode);
          if (options.source)
           options.source.html(editor.getHTML());
          if (options.hiddenfield)
          {
             options.hiddenfield.val(bbcode);
             wnd.close();
             return true;
          }
          else if (options.table && options.field && options.id)
          {
           $.post(
               "ajax/fodb.php",
               {
                METHOD : 'UPDATE',
                TABLE : options.table,
                FIELD : options.field,
                ID : options.id,
                VALUE : bbcode
               },
               function(msg) {
                $
                  .ajaxResponse(
                    msg,
                    {
                     dataType : dataType,
                     onParam : function(
                       param) {
                      if (param.name == "success") {
                       if (param.value == "1") {
                        wnd.content
                          .html("<center>"
                            + options.updateMsg
                            + "</center><center><img src=\"gfx/load_pic/ajax-loader_bar.gif\"></center>");
                        if (options.onUpdate) {
                         options
                           .onUpdate();
                         wnd
                           .close();
                         return true;
                        } else if (options.updatePost) {
                        	wnd.close();	
                         	$.post(options.updatePost, null, function() {return true;});
                        }
                       }
                       else
                       {
                        alert("Die Änderung war nicht erfolgreich!");
                        wnd.close();
                        return false;
                       }
                      }
                     }
                    });
               });
          }
         }
        }
       } ]
    });
    
    var markupSet= user.id==83548? adminMarkupSet: bbcodeRTEditorSet;

  if (options.hiddenfield) {
   textfield.val(options.hiddenfield.val());
   editor = $.markup(textfield, {
    menuContainer : textfield.parent(),
    markupSet : markupSet,
    updateInterval : 100
   });
  } else if (options.table && options.field && options.id) {
   $.ajax( {
    type : "POST",
    url : "ajax/fodb.php",
    dataType : dataType,
    data : {
     DATATYPE : dataType,
     METHOD : 'SELECT',
     TABLE : options.table,
     FIELD : options.field,
     ID : options.id
    },
    success : function(msg) {
     $.ajaxResponse(msg, {
      dataType : dataType,
      onParam : function(param) {
       if (param.name == options.field) {
        textfield.val(param.value);
        editor = $.markup(textfield, {
         menuContainer : textfield.parent(),
         markupSet : markupSet,
         updateInterval : 100
        });
       }
       return true;
      }
     });
    }
   });
  } else {
   alert("Bad parameters. No hidden field given and no table select information given.");
   return false;
  }
 };
})(jQuery);

( function($) {
 $.progressDialog = function(settings, extraSettings) {
  var options = {
   title : 'Fortschritt',
   source : null,
   hiddenfield : null,
   minTextLength : 0,
   onUpdate : null,
   updatePost : null,
   updateMsg : 'Der Text wurde erfolgreich gespeichert. Gegebenenfalls werden jetzt noch Daten aktualisiert.',
   table : '',
   field : '',
   id : ''
  };
  $.extend(options, settings, extraSettings);

  var dataType = "xml";
  var content = $("<div></div>");
  var message = $(
    "<p style=\"text-align:center;font-size:12px;-moz-user-select: none;\" unselectable=\"on\"></p>")
    .appendTo(content);
  var timer = $(
    "<p style=\"text-align:center;font-size:10px;-moz-user-select: none;\" unselectable=\"on\"></p>")
    .appendTo(content);
  var progressbar = $(
    "<div style=\"position: relative; width:100%;height:15px;background-color:white;border:1px groove orange;-moz-user-select: none;\" unselectable=\"on\"><div id=\"progress_bar\" style=\"position: absolute;width:0%;height:15px;background-color:orange;\"></div><span id=\"progress_text\" style=\"position: absolute; width:100%; color:black; font-size:11px; text-align:center;\">0 %</span></div>")
    .appendTo(content);

  var consoleSwitcher = $(
    "<button style=\"position: relative; right:0px;\">&raquo;</button>")
    .appendTo(
      $("<p align=\"right:\" style=\"margin: 0px;\"></p>")
        .appendTo(content));
  var console = $(
    "<textarea id=\"console\" style=\"width:100%;height:100%;background-color:black;color:white;\" readonly=\"readonly\" rows=\"10\"></textarea>")
    .appendTo(content);
  consoleSwitcher.click( function() {
   if ($(this).text() == String.fromCharCode(187))// "&raquo;"
    {
     $(this).html("&laquo;");
     console.show();
    } else {
     $(this).html("&raquo;");
     console.hide();
    }
   });
  console.hide();
  var editor = null;
  var minID = 0;
  var maxID = 0;
  var incID = 50;

  var percentageInc;
  var i = 0;
  var id = minID;
  var begin = null;

  $.ajax( {
   type : "POST",
   url : "ajax/db.php",
   dataType : dataType,
   data : {
    DATATYPE : dataType,
    METHOD : 'SELECT',
    TABLE : options.data,
    FIELDS : 'MIN(id) AS min_id, MAX(id) AS max_id'
   },
   success : function(msg) {
    $.ajaxResponse(msg, {
     dataType : dataType,
     onParam : function(param) {
      if (param.name == 'results') {
       minID = parseInt($(param.value).find("min_id")
         .text());
       maxID = parseInt($(param.value).find("max_id")
         .text());
       message.text("Aktualisieren von " + (maxID - minID)
         + " Datensätzen.");

       begin = new Date();
       percentageInc = incID * 100.0 / (maxID - minID);
       i = 0;
       id = minID;
      }
      return true;
     },
     onError : function(e) {
      alert(e.message);
      return true;
     }
    });
   }
  });

  var progress = function() {
   var lastID = Math.min(maxID, id + incID - 1);
   message.text("Aktualisieren von " + id + " bis " + lastID
     + " (bis " + maxID + ")");

   $.ajax( {
    type : "POST",
    url : "ajax/wordbook/clear.php",
    dataType : dataType,
    data : {
     DATATYPE : dataType,
     MIN : id,
     MAX : lastID
    },
    success : function(msg) {
     $.ajaxResponse(msg, {
      dataType : dataType,
      /*
      onParam: function(param)
      {
        if (param.name=='results')
        {
          minID= $(param.value).find("min_id").text();
          maxID= $(param.value).find("max_id").text();
          message.text("Aktualisieren von "+minID+" bis "+maxID);

         var percentage= (i+1)*percentageInc;
          progressbar.find("#progress_text").text(sprintf("%6.2f", percentage)+" %");
          progressbar.find("#progress_bar").width(sprintf("%d", percentage)+"%");   
            
        }
        return true;
      }, */
      onError : function(e) {
       console.text(console.text() + "Error: [" + e.code
         + "] " + e.message + "\n");
       alert(e.message);
       return true;
      },

      onLog : function(msg) {
       console.text(console.text() + "Notice: " + msg
         + "\n");
       return true;
      }
     });

     id += incID;
     i++;
     var percentage = sprintf("%6.2f", i * percentageInc);
     progressbar.find("#progress_text").text(percentage + " %");
     progressbar.find("#progress_bar").width(percentage + "%");

     var now = new Date();
     var time = now.getTime() - begin.getTime();
     var timeSum = time * 100.0 / percentage;
     var seconds = floor((timeSum - time) / 1000);
     if (seconds < 120)
      timer.text("Verbleibende Zeit: " + seconds
        + " Sekunden");
     else {
      var minutes = floor(seconds / 60);
      if (minutes < 120)
       timer.text("Verbleibende Zeit: "
         + (minutes < 2 ? " 1 Minute und "
           : floor(minutes) + " Minuten und ")
         + (seconds == 1 ? "1 Sekunde" : seconds
           % 60 + " Sekunden"));
      else
       timer.text("Verbleibende Zeit: "
         + floor(minutes / 60)
         + " Stunden und "
         + (minutes == 1 ? "1 Minute" : minutes % 60
           + " Minuten"));
     }

     if (id <= maxID) {
      return progress();
     }
     return false;
    }
   });
  };

  var wnd = $.openModalWindow( {
   content : content,
   width : 480,
   height : 320,
   minWidth : 320,
   minHeight : 240,
   maxWidth : 1024,
   maxHeight : 768,
   title : options.title,
   id : "Progress_Dlg",
   //wndCtrl:[{tooltip:"Schließen", icon:"../gfx/bubble/icons/bubble_close.png", click:"CLOSE"}],
   dlgCtrl : [ {
    label : "Abbrechen",
    click : "CLOSE"
   }, {
    label : "Starten",
    click : function() {
     return progress();
    }
   } ]
  });
 };
})(jQuery);

( function($) {
 $.ajaxResponse = function(data, settings, extraSettings) {
  var options = {
   abortOnError : true,
   dataType : 'xml'
  };
  $.extend(options, settings, extraSettings);

  var response = {
   log : [],
   param : {},
   error : []
  };

  var handleError = function(error) {
   response.error.push(error);
   if (options.onError)
    return options.onError(error);
   else if (options.abortOnError)
    return false;
  };

  var handleLog = function(log) {
   response.log.push(log);
   return true;
  };

  var handleParam = function(param) {
   response.param[param.name] = param;
   if (options.onParam)
    return options.onParam(param);
   return true;
  };

  if (options.dataType == 'json') {
   $.each(data.error, function(i, item) {
    return handleError(item);
   });
   $.each(data.log, function(i, item) {
    return handleLog(item);
   });
   $.each(data.param, function(i, item) {
    return handleParam(item);
   });
  }

  else if (options.dataType == 'xml') {
   $(data).find("response").each( function() {
    $(this).find("error").each( function() {
     return handleError( {
      code : $(this).attr("code"),
      message : $(this).innerXML()
     });
    });
    $(this).find("log").each( function() {
     return handleLog($(this).innerXML());
    });
    $(this).find("param").each( function() {
     return handleParam( {
      name : $(this).attr("name").toLowerCase(),
      value : $(this).innerXML()
     });
    });
    return true;
   });
  }

  else {
   alert("Unexpected data type. Use XML or JSON. ");
  }
  if (response.log.length && options.onLog)
   options.onLog(response.log);
  return response;
 };
 /*
  * $.fn.getLog= function() { return $(this).data("log"); };
  * 
  * $.fn.getParam= function() { return $(this).data("param"); };
  * 
  * $.fn.getError= function() { return $(this).data("log"); };
  */

 var getInnerNodes = function(node, opt) {
  var text = "";
  // var opt = {
  // comment : false
  // };
  // $.extend(opt, options);
  //console.log(node.nodeName+" "+node.nodeType);
  //console.log("Comment: "+(options.comment===true?"true":"false"));
  if (node.nodeType == 1) { //Element
   text += "<" + node.nodeName;
   a = node.attributes;
   for (i = 0; i < a.length; i++) {
    text += getInnerNodes(a[i]);
   }

   var y = node.childNodes;
   var len = y.length;
   if (len > 0) {
    text += ">";
    for ( var i = 0; i < len; i++) {
     text += getInnerNodes(y[i]);
    }
    text += "</" + node.nodeName + ">";
   } else {
    text += " />";
   }
  } else if (node.nodeType == 2) { //Attributknoten
   text += " " + node.nodeName + "=\"" + node.nodeValue + "\"";
  } else if (node.nodeType == 3) { //Textknoten
   text += node.nodeValue;
  } else if (node.nodeType == 4) { //CDATAknoten
   if (trim(node.nodeValue) != "")
    text += node.nodeValue;
  } else if (node.nodeType == 8 && opt.comment == true) { //Comment
   if (trim(node.nodeValue) != "")
    text += node.nodeValue;
  }
  return text;
 }

 $.fn.innerXML = function(opt) {
  var options = {
   comment : false
  };
  $.extend(options, opt);
  //console.log("Comment: "+(options.comment===true?"true":"false"));
  var y = $(this).get(0).childNodes;
  var text = "";
  for ( var i = 0; i < y.length; i++) {
   text += getInnerNodes(y[i], options);
  }
  return text;
 };
})(jQuery);

( function($) {

 $.fn.contextMenu = function(settings) {
  var options = {
   id : null,
   menuStyle : {
    listStyle : 'none',
    padding : '1px',
    margin : '0px',
    backgroundColor : '#fff',
    border : '1px solid #999',
    width : '100px'
   },
   itemStyle : {
    margin : '0px',
    color : '#000',
    display : 'block',
    cursor : 'default',
    padding : '3px',
    border : '1px solid #fff',
    backgroundColor : 'transparent'
   },
   itemHoverStyle : {
    border : '1px solid #0a246a',
    backgroundColor : '#b6bdd2'
   },
   eventPosX : 'pageX',
   eventPosY : 'pageY',
   shadow : true,
   contextAllowed : null,
   showMenu : null,
   menu : null
  };

  $.extend(options, settings);

  var shadow = null;
  if (options.shadow) {
   shadow = $('<div></div>').css( {
    backgroundColor : '#000',
    position : 'absolute',
    opacity : 0.2,
    zIndex : 499
   }).appendTo('body').hide();
  }
  /*
  hash = hash || [];
  hash.push(mObj);
   */

  // Create singleton menu
  var context = $('<div class="context"></div>').hide().css( {
   backgroundColor : 'white',
   position : 'absolute',
   zIndex : '500'
  }).appendTo('body').bind('click', function(e) {
   e.stopPropagation();
  });
  var menu= createMenu(context, options.menu).appendTo(context);

  $(this).bind('contextmenu', function(e)
  {
    if (!options.contextAllowed || options.contextAllowed(e))
    {
      menu.find('li').each(function(i)
      {
        if (options.menu[i].isEnabled())
          $(this).removeClass('disabled');
        else
          $(this).addClass('disabled');
      });
      var wdif = ($(window).width() - jQuery(document.body).width()) / 2;
      wdif = (wdif < 0) ? 0 : wdif;
      context.css({'left' : (e[options.eventPosX] - wdif) + 'px','top' : (e[options.eventPosY]) + 'px'}).show();
      if (options.shadow)
        shadow.css({width: (context.width() + 1) + 'px',height : (context.height() + 1) + 'px',left : (e[options.eventPosX] + 5 - wdif) + 'px',top : (e[options.eventPosY] + 5) + 'px'}).show();
        $(document).one('click', function()
        {
          context.hide();
          if (options.shadow)
            shadow.hide();
        });
       }
       return false;
      });
  return this;
 };

 function createMenu(context, menuStruct)
 {
  var menu = $('<menu></menu>'), i = 0;
  $('li:hover > menu', menu).css('display', 'block');

  var defaultButtonStructure = {
   isEnabled : function() {
    return true;
   },
   onClick : function() {
    return true;
   }
  };

  $(menuStruct).each(function()
  {
       var item, title, j, key, style, id, icon, label, struct = this;

       title = ' title="' + ((this.key) ? (this.tooltip || '')
         + ' [Ctrl+' + this.key + ']'
         : (this.tooltip || '')) + '"';
       key = (this.key) ? ' accesskey="' + this.key + '"'
         : '';
       style = this.style ? ' style="' + this.style + '"'
         : '';
       id = this.id ? ' id="' + this.id + '"' : '';
       icon = this.icon ? '<img src="' + this.icon + '" />'
         : '';
       label = this.label || this.tooltip || '';

       if (this.type == "separator") {
        console.log(this.separator);
        item = $('<li class="separator">' + (this.separator || '') + '</li>');
       } else if (this.type == "button") {
        i++;
        console.log(this.label);
        item = $('<li'
          + (this.className ? ' class="' + this.className + '"'
            : '') + id
          + key + title + style + '>' + icon
          + label + '</li>');
        $.extend(item, defaultButtonStructure, this);

        item.bind("contextmenu", function() { // prevent contextmenu on mac and allow ctrl+click
           return false;
          }).click( function(e) {
         e.preventDefault();
         if (!$(this).hasClass('disabled'))
         {
          if (struct.onClick && struct.onClick(e)) $(document).click();
         }
         return false;
        });
       } else if (this.type == "menu") {
        i++;
        console.log(this.label);
        item = $('<li'
          + (this.className ? ' class="' + this.className + '"'
            : '') + '><a href=""' + id
          + key + title + style + '>' + icon
          + label + '</a></li>');
        $.extend(item, defaultButtonStructure, this);

        item.bind("contextmenu", function() { // prevent contextmenu on mac and allow ctrl+click
           return false;
          }).hover( function() {
         $('> menu', this).show();
         // $(document).one('click', function(){
          // $('menu menu',
          // main_component).hide();
          // }); // close dropmenu if click
          // outside
         }, function() {
          $('> menu', this).hide();
         });
        if (this.menu) {
         $(item).addClass('dropmenu').append(
           createMenu(this.menu));
        }
       }
       item.appendTo(menu);
       return true;
      });
  // item.find('img').css({verticalAlign:'middle',paddingRight:'2px'});
  return menu;
 }

})(jQuery);

$( function() {
 $('div.contextMenu').hide();
});

( function($) {


 $.fn.inROI = function(p1, p2)
 {
   with($(this))
   {
     var x= offset().left, y= offset().top, w= width(), h= height();
     return !(x<p1.x && x<p2.x && x+w<p1.x && x+w<p2.x
     || x>p1.x && x>p2.x && x+w>p1.x && x+w>p2.x
     || y<p1.y && y<p2.y && y+h<p1.y && y+h<p2.y
     || y>p1.y && y>p2.y && y+h>p1.y && y+h>p2.y);
   }
 };

 $.fn.contains = function(p)
 {
   with($(this))
   {
     var x= offset().left, y= offset().top, w= width(), h= height();
     return x<=p.x && x+w>=p.x && y<=p.y && y+h>=p.y;
   }
 };

 $.fn.getSelection = function()
 {
  return $(this).find(".selected");
 };

})(jQuery);



( function($) {

 $.showPDF= function(settings) 
{
  var options = {
    textarea: null,
    bbcode: ''
  };
  $.extend(options, settings);
  
  var bbcode = options.textarea? options.textarea.val(): options.bbcode;
  var dataType= "xml";
  var dstFile= "tmp/test.pdf";
  
   $.ajax( {
    type : "POST",
    url : "ajax/create_pdf.php",
    dataType : dataType,
    data : {
     DATATYPE : dataType,
     BBCODE : bbcode,
     DESTINATION : dstFile
    },
    success : function(msg)
    {
     $.ajaxResponse(msg,
     {
       dataType : dataType,
       onParam: function(param)
       {
         console.log("Param: " + param.name + " = " + param.value);
         return true;
       },
       onError : function(e)
       {
         console.log("Error: [" + e.code + "] " + e.message + "\n");
         return true;
       },

       onLog : function(msg)
       {
         console.log("Notice: " + msg + "\n");
         return true;
       }
     });
     
  
  $.openModalWindow(
  {
    iframe: true,
    contentURL: dstFile, 
    width:640, 
    height:480, 
    minWidth:320, 
    minHeight:240, 
    maxWidth:1024, 
    maxHeight:768, 
    title: "PDF Vorschau", 
    id: "Preview_Wnd", 
    //wndCtrl:[{tooltip:"Schließen", icon:"../gfx/bubble/icons/bubble_close.png", click:"CLOSE"}],
    dlgCtrl:[{label:"Schließen", click:"CLOSE"}]
   });
   
     return false;
    }
   });
}

})(jQuery);


if (console == undefined) {
 var console = new CLogger();
}
