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();
            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,
        cov:true,
        dim:true,
        id:'__modWnd_'+jQuery.data(wnd)
      }, options); 


      if((options.dim == true) )
    	  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);
      
      if(options.cov==true)
    	  jQuery.centerOnView(wnd);
      else
      { 
          if((options.top == undefined) || options.top <= 0)
              options.top = 100;
          if((options.left == undefined) || options.left <= 0)
              options.left = 100;
    	  wnd.css({
    		  top:options.top,
    		  left:options.left   		  
    	  });
      }
      
      
      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();
      
      wnd.bind('dragstart',
        function(event)
        {
          if (!$(event.target).is('.move_handle')) return false; 
          $(this).addClass('active');
        });
        
        wnd.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) });
        });
        
        wnd.bind('dragend', function(event) 
        { 
          $(this).removeClass('active'); $.centerOnView(this); 
        });
        
        if(wnd.resizable) {
	        wnd.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); 
	          }
	        });
        }

        if(options.cov==true)
        {
	        jQuery.addWindowScrollListener(function(e) {
	            jQuery.centerOnView(wnd);
	          
	        });
	                
	        jQuery.addWindowResizeListener(function() {
	            jQuery.centerOnView(wnd);
	        });
        }
        
        //console.log('_modalWndNum:'+$._modalWndNum);

        $._modalWndNum++; 

        //console.log('_modalWndNum:'+$._modalWndNum);
      return wnd;
      
    },
    
    closeModalWindow: function(qry) {
      var wnd = undefined;
      if(qry == undefined) wnd = jQuery(this);
      else wnd = jQuery(qry);

      //console.log('_modalWndNum:'+_modalWndNum);
      wnd.remove();
      //console.log('wnd.remove():'+_modalWndNum);
      $._modalWndNum--;
      //console.log('_modalWndNum:'+_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); 
              })
          }
        });
      }     
  }); 
})(jQuery);



/*  */
jQuery.extend({_modalWndNum: 0});
//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]();
  }
});



/*
       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,
      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: 480, 
      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+" enthalten. ");
          else
          {
            if (options.source) options.source.html(editor.getHTML());
            if (options.hiddenfield) options.hiddenfield.val(editor.getBBCode());
            else if (options.table && options.field && options.id)
              $.ajax(
              { type: "POST", url: "ajax/fodb.php", data: {METHOD: 'UPDATE', TABLE: options.table, FIELD: options.field, ID: options.id, VALUE: editor.getBBCode()}, 
                success: function(msg)
                {
                  if (options.onUpdate)
                  {
                    $.ajaxResponse(msg, 
                    {
                      dataType: dataType, 
                      onParam: function(param)
                      {
                        if (param.name=="success" && param.value=="1")
                        {
                          options.onUpdate();
                        }
                        return true;
                      }
                    });
                  }
                }
              });
            wnd.close();
          }
        }
      }]
    });
    
    
    if (options.hiddenfield)
    {
      textfield.val(options.hiddenfield.val());
      editor= $.markup(textfield, {menuContainer: textfield.parent(), markupSet: bbcodeRTEditorSet, 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: bbcodeRTEditorSet, updateInterval: 100});
              }
              return true;
            }
          });
        }
      });
    }
    else
    {
      alert("Bad parameters. No hidden field given and no table select information given.");
      return false;
    }
  };
})(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 (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 = "";
		//alert(node.nodeName+" "+node.nodeType);
		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);
	  var y = $(this).get(0).childNodes;
	  var text = "";	  
	  for (var i=0;i<y.length;i++) {
		  text += getInnerNodes(y[i], options);	
	  }
	  return text;
  };
})(jQuery);

