/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-12-20 08:43:48 -0600 (Thu, 20 Dec 2007) $
 * $Rev: 4257 $
 *
 * Version: 1.2
 *
 * Requires: jQuery 1.2+
 */
(function($){$.dimensions={version:'1.2'};$.each(['Height','Width'],function(i,name){$.fn['inner'+name]=function(){if(!this[0])return;var torl=name=='Height'?'Top':'Left',borr=name=='Height'?'Bottom':'Right';return this.is(':visible')?this[0]['client'+name]:num(this,name.toLowerCase())+num(this,'padding'+torl)+num(this,'padding'+borr);};$.fn['outer'+name]=function(options){if(!this[0])return;var torl=name=='Height'?'Top':'Left',borr=name=='Height'?'Bottom':'Right';options=$.extend({margin:false},options||{});var val=this.is(':visible')?this[0]['offset'+name]:num(this,name.toLowerCase())+num(this,'border'+torl+'Width')+num(this,'border'+borr+'Width')+num(this,'padding'+torl)+num(this,'padding'+borr);return val+(options.margin?(num(this,'margin'+torl)+num(this,'margin'+borr)):0);};});$.each(['Left','Top'],function(i,name){$.fn['scroll'+name]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(name=='Left'?val:$(window)['scrollLeft'](),name=='Top'?val:$(window)['scrollTop']()):this['scroll'+name]=val;}):this[0]==window||this[0]==document?self[(name=='Left'?'pageXOffset':'pageYOffset')]||$.boxModel&&document.documentElement['scroll'+name]||document.body['scroll'+name]:this[0]['scroll'+name];};});$.fn.extend({position:function(){var left=0,top=0,elem=this[0],offset,parentOffset,offsetParent,results;if(elem){offsetParent=this.offsetParent();offset=this.offset();parentOffset=offsetParent.offset();offset.top-=num(elem,'marginTop');offset.left-=num(elem,'marginLeft');parentOffset.top+=num(offsetParent,'borderTopWidth');parentOffset.left+=num(offsetParent,'borderLeftWidth');results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};}return results;},offsetParent:function(){var offsetParent=this[0].offsetParent;while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&$.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return $(offsetParent);}});function num(el,prop){return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;};})(jQuery);/*
 * jquery.okNotify.js
 *
 * Copyright (c) 2009 Asher Van Brunt | http://www.okbreathe.com
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 * Date: 08/13/2009
 *
 * @projectDescription Create a Growl-like notifications simply
 * @author Asher Van Brunt
 * @mailto asher@okbreathe.com
 * @version 1.0
 *
 * @id jQuery.noticeAdd
 * @param {Object} Hash of settings, none are required.
 * @return {jQuery} Returns the notice.
 * @id jQuery.noticeRemove
 * @param {Object or Selector} 
 * @return {jQuery} Nothing
 *
 */

(function($) {
  function addContainer(opts){
    var $container = $("."+opts.containerClass+"."+opts.position),
    styles = {
      'top-left'     : { left: 0, top:0    },
      'top-right'    : { right:0, top:0    },
      'bottom-right' : { right:0, bottom:0 },
      'bottom-left'  : { left: 0, bottom:0 },
      'center'       : { top: 0,  width: "50%", left: "25%"},
      'top-center'   : { top: 0,  width: "50%", left: "25%"}
    };
    if ($container.length === 0 ) {
      $container = $('<div></div>')
        .addClass(opts.containerClass)
        .addClass(opts.position)
        .css($.extend({position:opts.fixed ? 'fixed' : 'absolute',padding:'10px',zIndex:9999},styles[opts.position]))
        .appendTo('body');
    }

    if (opts.position == 'center') {
      $container.center(true);
    }

    return $container;
  }

  function uniqueId() {
    return "notice_" + parseInt(new Date().getTime()+Math.random(), 10);
  }

  // Center the element within the screen
  $.fn.center = function (absolute) {
    return this.each(function () {
      var self = $(this);
      self.css({
        position:	absolute ? 'absolute' : 'fixed', 
        left:		'50%', 
        top:		'50%', 
        zIndex:	'99'
      }).css({
        marginLeft:	'-' + (self.outerWidth() / 2) + 'px', 
        marginTop:	'-' + (self.outerHeight() / 2) + 'px'
      });

      if (absolute) {
        self.css({
          marginTop:	parseInt(self.css('marginTop'), 10) + $(window).scrollTop(), 
          marginLeft:	parseInt(self.css('marginLeft'), 10) + $(window).scrollLeft()
        });
      }
    });
  };

  $.extend({      
      noticeAdd: function(opts) {  
        opts = typeof(opts) == "string" ? {text:opts} : opts;
        opts = $.extend(true, {
          inEffect:         {            // passed to $.fn.animate(), any parameters that it accepts are valid         
            opacity: 'show'           
          },
          inEffectDuration: 600,         // in effect duration in miliseconds
          duration:         3000,        // time before the item disappears
          text:             '',          // content of the notification
          title:            '',          // title of the notification
          stay:             false,       // should the notice item stay or not? (if false it will fade after duration milliseconds)
          type:             'notice',    // could also be error, success etc.
          position:         'top-right', // top-center, top-left, top-right, bottom-left, bottom-right, center
          containerClass :  'ui-notification-container', // class that wraps the container
          template:         'standard',  // Extend the $.noticeAdd.templates object to add additional templates
          fixed:            false        // Whether to use absolute or fixed positioning. (Note: IE6 doesn't support position fixed)  
        }, opts);

        var $container,
            $notice  = $($.noticeAdd.templates[opts.template]),
            text     = $.trim(opts.text);

        $notice.attr('id', uniqueId());

        $.noticeAdd.notices = $.noticeAdd.notices.add($notice);

        $container = addContainer(opts);

        // Append the title 
        $('.ui-notification-title', $notice).append(opts.title);
        // Append the text, wrap it in a <p> if it doesn't look like markup
        $('.ui-notification-content', $notice).append(text[0] == "<" ? text : '<p>'+text+'</p>');

        // Append the notice
        $notice
          .hide()
          .addClass(opts.type)
          .appendTo($container)
          .animate(opts.inEffect, opts.inEffectDuration);

        $('.ui-notification-close', $notice).click(function(e) { 
            e.preventDefault();
            $.noticeRemove($notice);
         });

        if (!opts.stay) {
          setTimeout(function() {
              $.noticeRemove($notice);
            },
            opts.duration);
        }
        return $notice;
      },

      noticeRemove: function(obj) {
        if (obj) {
          obj = typeof(obj) == "string" ? $(obj) : obj;
          obj.animate({ opacity: '0' }, 600, function() {
            obj.animate({ height: '0px' }, 300, function() {
              $.noticeAdd.notices.splice($.noticeAdd.notices.index(obj),1); 
              obj.parent().children().length <= 0 ? obj.parent().remove() : obj.remove();
            });
          });
        } else {
          $.noticeAdd.notices.fadeOut(function(){ 
            $(this).parent().remove();
            $.noticeAdd.notices = $([]);
          });
        }
      }
    }); // $.extend

    // Extend the templates to add more
    $.noticeAdd.templates = {
      standard: "<div class='ui-notification'><div class='ow'><div class='iw'><div class='ui-notification-titlebar'><span class='ui-notification-title'></span><a class='ui-notification-close' href='#'>x</a></div> <div class='ui-notification-content'> </div></div></div></div>"
    };

    // List of active notices
    // Start by storing an empty jQuery object
    $.noticeAdd.notices = $([]);

})(jQuery);
/* Well, this file is _far_ too large, but i failed to make it modular. */

jQuery(document).ready(function() {

    jQuery.ajaxSetup({
      error: function(rq,errstr,ex) {
	var st='';
	try {
	  st=rq.statusText;
	} catch(e) { };
          $("#generic_busywait").hide();
	  if (st && rq.responseText)
	    alert('Ein Fehler ist aufgetreten (1): '+st+": "+rq.responseText);
	  else if (rq.responseText)
	    alert('Ein Fehler ist aufgetreten (2): '+rq.responseText);
	  else if (st) {
	    if (st!='OK')
	      alert('Ein Fehler ist aufgetreten (3): '+st);
	  }
	  else
	    alert('Ein Fehler ist aufgetreten (4): '+errstr);
	}
    });
});
jslog=function(s) {
    s=new Date().valueOf()+" "+s;
    if (window.console)
	console.log(s);
    jQuery("<div>"+s+"</div>").appendTo("#timingdebughelp");
};

my_overlay_ajaxcall=function(url,data,title, lv) {
    if (typeof(lv)=='undefined')
      lv=1000;
    var sel='#generic_overlay_'+lv;
    $(sel).remove(); // just in case
    var fullerstring="<a class='generic_overlay_fuller' href='#'>&#x25A1;</a>";
    if (typeof(data['fullsize'])!='undefined' && data['fullsize']>0) {
      fullerstring='';
    }
    var x=jQuery('<div></div>').attr({
      id: 'generic_overlay_'+lv,
      level: lv
    }).addClass('generic_overlay').css('display','none')
    .html("<div class='generic_overlay_head'>"
	   +"<a class='generic_overlay_closer' href='#'>X</a>"
	   +fullerstring
	   +"<h1 class='generic_overlay_title'>"+title+"</h1>"
	   +"</div>"
	   +"<div class='generic_overlay_main'></div>\n"
    );
    x.appendTo(document.body);
    if (fullerstring=='')
      $(sel).css({left: '0%', right: '0%', top: '0%', bottom: '0%', margin:0, border:0});
    $("#generic_busywait").show();
    $.ajax({
      url: url,
      data: data,
      dataType: 'html',
      success: function(data,sta) {
        $(sel).css("position","absolute");
	$(sel).css({top: '10%', left: '10%', bottom:'0', right:'10%'});
	$(sel).height("80%");
        $("#generic_busywait").hide();
	$(sel + ' .generic_overlay_main').html(data);
	$(sel + ' .generic_overlay_closer').click(function() {
	  $.dimScreenStop(function() {
	    $(sel).hide();
	    $(sel).remove();
	    return false;
	  },parseInt($(sel).attr('level'))-1);
	});
	if ($.browser.msie) {
	  if ($.browser.version.substr(0,3)=='6.0') {
	    $(sel).width("80%");
	    $(sel).css('overflow','auto');
	    $(sel).css('pading',"0 1em");
	  }
	}
	$(sel + ' .generic_overlay_fuller').click(function() {
	  var l=$(sel).css('left');
	  l=parseInt(l);
	  if (l==0) {
	    $(sel).css({left: '10%', right: '10%', top: '10%', bottom: '10%'});
	    if ($.browser.msie) {
	      if ($.browser.version.substr(0,3)=='6.0') {
		$(sel).height("80%");
		$(sel).width("80%");
	      }
	      if ($.browser.version.substr(0,3)=='7.0') {
		$(sel).height("80%");
	      }
	    }
	    $(this).html("&#x25A1;");
	  } else {
	    $(sel).css({left: '0', right: '0', top: '0', bottom: '0'});
	    if ($.browser.msie) {
	      if ($.browser.version.substr(0,3)=='6.0') {
	        $(sel).height($(window).height()-25);
	        $(sel).width($(window).width()-25);
	      }
	      if ($.browser.version.substr(0,3)=='7.0') {
	        $(sel).height($(window).height()-25);
	      }
	    }
	    $(this).html("&#x25A3;");
	  }
	});
        
	var workaround=function() {
	  var h;
	  var t;
	  h=$(sel + ' .generic_overlay_main h1');
          t=h.html();
          if (t=='') {
	    h=$(sel + ' .generic_overlay_main h2');
            t=h.html();
          }
          if (t>'') {
            h.hide();
            $(sel + ' .generic_overlay_title').html(t);
          }
	  $(sel).show();
	};
	$.dimScreen(200,0.500,workaround,parseInt($(sel).attr('level'))-1);
      }
    });  
};

my_kwpreview=function(u,v) {
    data={
      action: 'make-kwpreview',
      text: v
    };
    my_overlay_ajaxcall(u,data,'');
};
my_kwguess_bbcode=function(u,v,w) {
    data={
      action: 'kw_guess_bbcode',
      text: v,
      keywords: w
    };
    my_overlay_ajaxcall(u,data,'');
};

my_ajax_op_with_confirm=function(opkey,text) {
    var data={
      opkey:opkey
    };
    var ch=confirm(text);
    if (ch) {	
      d=$("#generic_directory").html();
      my_overlay_ajaxcall(d+'ajax.php?action=op',data,'',1000);
    }
};
my_ajax=function(url,lv) {
    my_overlay_ajaxcall(url,{},'title',lv);
};
my_ajax_base=function(url,title, lv) {
    my_overlay_ajaxcall(url, {},title,lv);
};
my_ajax_edit_object=function(oid,text) {
    var data={
      object_id:oid
    };
    var ch=confirm(text);
    if (ch) {	
      d=$("#generic_directory").html();
      my_overlay_ajaxcall(d+'ajax.php?action=object_edit',data,'',250);
    }
};

imagetrail_setup=function(id,bigsrc,bigw,bigh) {
    var thing;
    var xOffset = 10;
    var yOffset = 30;
    var did=0;
    var fix=function(e)
    {
	var t=jQuery("div#imgtrail");
	var dh=jQuery(document).height();
	var wh=jQuery(window).height();
	var st=jQuery(window).scrollTop();
	var th=t.outerHeight();
	var my=e.pageY;
	my+=yOffset;

	var dw=jQuery(document).width();
	var ww=jQuery(window).width();
	var sl=jQuery(window).scrollLeft();
	var tw=t.outerWidth();
	var mx=e.pageX;
	mx+=xOffset;
	var fixed=0; // avoid fixing x and y: that could move the mouse over the trailer, therefore triggering mouseout.   
	if (my+th>st+wh) {
	  my=st+wh-th;
	  fixed=1;
	}
	if (mx+tw>sl+ww && !fixed) {
	  mx=sl+ww-tw;
	} else if (mx+tw>sl+ww) {
	  mx=e.pageX-xOffset-tw;
        }
	t.css("top",my+"px");
	t.css("left",mx+"px");
    };

    thing=jQuery("#"+id);
    thing.hover(
      function(e){

	this.t=this.title;
	this.title = "";
	var c = (this.t != "") ? "<br/>" + this.t : "";
	add="";
	if (bigw)
	  add=add+" width='"+bigw+"' height='"+bigh+"'";
	jQuery("body").append("<div id='imgtrail'><img src='"+ bigsrc +"' alt='Image preview' "+add+" />"+ c +"</div>");   
	jQuery('div#imgtrail')
		.css("display","none")
		.css("position","absolute")
		.css("top","0px")
		.css("z-index","1000")
		.css("left","0px")
		.css("border","1px solid #888")
		.css("text-align","center")
		.css("background","#333")
		.css("color","#fff")
		.css("padding","5px")
		.fadeIn("fast");
	fix(e);
      },
      function(e){
	this.title = this.t;
	jQuery("div#imgtrail").remove();
      }
    );
    thing.mousemove(function(e){
      fix(e);
    });
};
  autocomplete_format_item=function(r,p,n,t) {
    return t;
    var r = $.trim(t);
    r = r.split("##");
    return r[0];
  };
  autocomplete_format_result=function(r,p,n) {
    return p;
    var r = $.trim(p);
    r = r.split("##");
    return r[1];
  };


/*************************************************************************
  taken from quirksmode.org
 *************************************************************************/

var bugRiddenCrashPronePieceOfJunk = (
    navigator.userAgent.indexOf('MSIE 5') != -1
  &&
    navigator.userAgent.indexOf('Mac') != -1
);

var W3CDOM = (!bugRiddenCrashPronePieceOfJunk && 
    document.getElementsByTagName && document.createElement);
var IE = document.all?true:false;

function getObjNN4(obj,name)
{
  var x = obj.layers;
  var foundLayer;
  for (var i=0;i<x.length;i++)
  {
    if (x[i].id == name)
      foundLayer = x[i];
    else if (x[i].layers.length)
      var tmp = getObjNN4(x[i],name);
    if (tmp) foundLayer = tmp;
  }
  return foundLayer;
}


function get_object_by_id(name)
{
  if (document.getElementById) {
    return document.getElementById(name);
  } else if (document.all) {
    return document.all[name];
  } else if (document.layers) {
    return getObjNN4(document,name);
  }
}

function get_object_style_by_id(name)
{
  if (document.getElementById) {
    return document.getElementById(name).style;
  } else if (document.all) {
    return document.all[name].style;
  } else if (document.layers) {
    return getObjNN4(document,name);
  }
}

function movecommentthing(id)
{
  var thing, style;
  old=get_object_by_id('com_bit');
  oldp=old.parentNode;
  val=oldp.removeChild(old);

  thing=get_object_by_id('com_'+id);
//#  thing.innerHTML=val.innerHTML;
  thing.appendChild(val);

// reactive disabled "comment this" links
  a=document.getElementsByTagName("a");
  for (i=0;i<a.length;i++) {
    l=a[i].attributes.length;
    for (j=0;j<l;j++) {
      x=a[i].attributes[j];
//      val.innerHTML=val.innerHTML+'<div>'+i+","+j+": "+x.nodeValue+" "+x.nodeName+'</div>';
      // com_a_118008 id
      if (x.nodeName=='id') {
        if (x.nodeValue.substr(0,6)=='com_a_') {
          a[i].style.display='inline';
        }
      }
    }
  }
  x=get_object_by_id("com_a_"+id);
  if (x)
    x.style.display='none';

  // make sure the reference object is selected correctly.
  if (1) {
    var cb=$('#com_bit');
    $('#com_bit_refselect option').attr('selected','');
    $('#com_bit_refselect option[value='+id+']').attr('selected','selected');
  }
}

var ajax;
function fix_XMLHttpRequest() {
  if( !window.XMLHttpRequest )
    XMLHttpRequest = function() {
      try{ return new ActiveXObject("MSXML3.XMLHTTP") }catch(e){}
      try{ return new ActiveXObject("MSXML2.XMLHTTP.3.0") }catch(e){}
      try{ return new ActiveXObject("Msxml2.XMLHTTP") }catch(e){}
      try{ return new ActiveXObject("Microsoft.XMLHTTP") }catch(e){}
      throw new Error("Could not find an XMLHttpRequest alternative.")
    };
}
function ajaxcall(dir,q,callback)
{
  if (!XMLHttpRequest)
    fix_XMLHttpRequest();
  if (!ajax)
    ajax = new XMLHttpRequest();

  ajax.open("POST",dir+"ajax.php",true);
  ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  ajax.setRequestHeader("Content-length", q.length);
  ajax.setRequestHeader("Connection", "close");
  ajax.onreadystatechange=callback;
  ajax.send(q);
}
function ajax_preview_close()
{
  div=get_object_by_id("generic_preview_background");
  if (div) div.style.display='none';
  div=get_object_by_id("generic_preview");
  if (div) div.style.display='none';
}
function ajax_preview_callback()
{
  if (ajax.readyState==4 && ajax.status>199) {
    div=get_object_by_id("generic_preview_background");
    div.style.display='block';
    div=get_object_by_id("generic_preview");
    div.innerHTML="<div style=\"float:right; border:1px solid;\"><a href=\"javascript:ajax_preview_close()\">Schliessen</a></div><p><b>Vorschau</b></p><div id=\"generic_preview_main\">"+ajax.responseText+"</div>";
    div.style.display='block';
    // alert("callback state="+ajax.readystate+" status="+ajax.status+" returninfo="+returninfo);
  }
}
function ajax_preview(dir,contentvar)
{
  q="action=make-preview"+"&text="+contentvar;
  ajaxcall(dir,q, ajax_preview_callback);
}
function ajax_kwpreview(dir,contentvar)
{
  q="action=make-kwpreview"+"&text="+contentvar;
  ajaxcall(dir,q, ajax_preview_callback);
}
function ajax_postcard_preview(dir,formname)
{
  oid=document.forms[formname].object_id.value;
  q="action=make-postcardpreview&object_id="+oid;
  q=q+"&bg_color="+encodeURIComponent(document.forms[formname].form_bg_color.value)
  q=q+"&font_color="+encodeURIComponent(document.forms[formname].form_font_color.value)
  q=q+"&border_color="+encodeURIComponent(document.forms[formname].form_border_color.value)
  q=q+"&font_face="+encodeURIComponent(document.forms[formname].form_font_face.value)
  q=q+"&sender_email="+encodeURIComponent(document.forms[formname].form_sender_email.value)
  q=q+"&recipient_name="+encodeURIComponent(document.forms[formname].form_recipient_name.value)
  q=q+"&recipient_email="+encodeURIComponent(document.forms[formname].form_recipient_email.value)
  q=q+"&headline="+encodeURIComponent(document.forms[formname].form_headline.value)
  q=q+"&layout="+encodeURIComponent(document.forms[formname].form_layout.value)
  q=q+"&message="+encodeURIComponent(document.forms[formname].form_message.value)

  ajaxcall(dir,q, ajax_preview_callback);
}
function ajax_get_callback()
{
  if (ajax.readyState==4 && ajax.status>199) {
    div=get_object_by_id("generic_preview_background");
    div.style.display='block';
    div=get_object_by_id("generic_preview");
    div.innerHTML="<div style=\"float:right; border:1px solid;\"><a href=\"javascript:ajax_preview_close()\">Schliessen</a></div><div id=\"generic_preview_main\">"+ajax.responseText+"</div>";
    div.style.display='block';
    // alert("callback state="+ajax.readystate+" status="+ajax.status+" returninfo="+returninfo);
  }
}
function ajax_get_to_preview_area(q)
{
  if (!XMLHttpRequest)
    fix_XMLHttpRequest();
  if (!ajax)
    ajax = new XMLHttpRequest();

  ajax.open("GET",q,true);
  ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//  ajax.setRequestHeader("Content-length", q.length);
  ajax.setRequestHeader("Connection", "close");
  ajax.onreadystatechange=ajax_get_callback;
  ajax.send(q);
}



/***************************************************************************
 * Find object positions
 ***************************************************************************/

function get_object_x(obj,relative) {
  if (typeof(obj)!="object") return false;
  var x=obj.offsetLeft;
  if (obj.offsetParent && !relative)
    x+=get_object_x(obj.offsetParent,relative);
  return x;
}

function get_object_y(obj,relative) {
  if (typeof(obj)!="object") return false;
  var y=obj.offsetTop;
  if (obj.offsetParent && !relative)
    y+=get_object_y(obj.offsetParent,relative);
  return y;
}

function get_scroll_x_offset()
{
  if (self.pageXOffset)
    return self.pageXOffset;
  if (document.documentElement && document.documentElement.scrollLeft) 
    return document.documentElement.scrollLeft;
  if (document.body)
    return document.body.scrollLeft;
  return 0;
}
function get_scroll_y_offset()
{
  if (IE) { // grab the x-y pos.s if browser is IE
    if (document.documentElement && document.documentElement.scrollTop) {
      return document.documentElement.scrollTop;
    } else {
      return document.body.scrollTop;
    }
  }
  return 0;
  if (window.pageYOffset)
    return window.pageYOffset;
  if (self.pageYOffset)
    return self.pageYOffset;
  return 0;
}

/***************************************************************************
 * Show mouse position relative to object "oname"
 ***************************************************************************/

//if (!IE) document.captureEvents(Event.MOUSEMOVE);

var mouseposmode = new Object();
mouseposmode.watch="";
mouseposmode.show="";
mouseposmode.flag=0;
mouseposmode.off=function () {
    document.onmousemove = "";
    this.show.innerHTML="Mausposition einblenden";
}
mouseposmode.startstop= function (watchid,showid) {
  this.flag=!this.flag;
  this.watch=get_object_by_id(watchid);
  this.show=get_object_by_id(showid);
  if (!this.flag) {
    this.off();
  } else {
    magnifier.off();
    document.onmousemove = this.doit;
  }
  return true;
}

mouseposmode.doit=function (e) {
  if (IE) { // grab the x-y pos.s if browser is IE
    if (document.documentElement && document.documentElement.scrollTop) {
      mx=event.clientX + document.documentElement.scrollLeft;
      my=event.clientY + document.documentElement.scrollTop;
    } else {
      mx = event.clientX + document.body.scrollLeft;
      my = event.clientY + document.body.scrollTop;
    }
  } else {  // grab the x-y pos.s if browser is NS
    mx = e.pageX;
    my = e.pageY;
  }

  ix=get_object_x(mouseposmode.watch,0);
  iw=mouseposmode.watch.width;
  iy=get_object_y(mouseposmode.watch,0);
  ih=mouseposmode.watch.height;

  if (mx<ix || my<iy) {
    mouseposmode.show.innerHTML=" [Maus au&szlig;erhalb] ";
    return true;
  }
  rx=mx-ix;
  ry=my-iy;
  if (rx>iw || ry>ih) {
    mouseposmode.show.innerHTML=" [Maus au&szlig;erhalb] ";
    return true;
  }

  mouseposmode.show.innerHTML=" [Position "+rx+","+ry+"] ";
  return true;
}

/* quirksmode.org, renamed and with generic_directory support */
function cookie_set(name,value,days,path)
{
  var expires;
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    expires = "; expires="+date.toGMTString();
  }
  var expires = "";
  if (typeof(path)=='undefined') {
      path=$("#generic_directory").html();
      if (typeof(path)=='undefined' || path=='')
	path='/';
  }
  document.cookie = name+"="+value+expires+"; path="+path;
}

function cookie_get(name)
{
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function cookie_delete(name) { cookie_set(name,"",-1); }

function rgb2color(r,g,b)
{
   var s = "0123456789ABCDEF";
   var o = '#';
   o+=s.substr( (r>>4)&15,1);
   o+=s.substr( r&15,1);
   o+=s.substr( (g>>4)&15,1);
   o+=s.substr( g&15,1);
   o+=s.substr( (b>>4)&15,1);
   o+=s.substr( b&15,1);
   return o;
}
function make_color(
	num, 
	     frequency1, frequency2, frequency3,
	     phase1, phase2, phase3,
	     center, width)
  {
    if (frequency1 == undefined) frequency1 = 2.4;
    if (frequency2 == undefined) frequency2 = 2.4;
    if (frequency3 == undefined) frequency3 = 2.4;
    if (phase1 == undefined) phase1 = 0;
    if (phase2 == undefined) phase2 = 2;
    if (phase3 == undefined) phase3 = 4;
    if (center == undefined)   center = 128;
    if (width == undefined)    width = 127;

    var red = Math.sin(num*frequency1 + phase1) * width + center;
    var grn = Math.sin(num*frequency2 + phase2) * width + center;
    var blu = Math.sin(num*frequency3 + phase3) * width + center;
    return rgb2color(red,grn,blu);
}


var baselib = new Object();

baselib.init=function() {
  x=get_object_by_id('maginfo');
  if (x) {
    y=get_object_style_by_id('maginfo');
    y.visibility="visible";
    x.innerHTML=" [Lupe ist aus] ";
  }
  x=get_object_by_id('mouseinfo');
  if (x) {
    y=get_object_style_by_id('mouseinfo');
    y.visibility="visible";
    x.innerHTML=" [Positionsanzeige ist aus] ";
  }
}
/*
Simple Image Trail script- By JavaScriptKit.com
Visit http://www.javascriptkit.com for this script and more
This notice must stay intact
*/
/* cleaned up and adapted to nforum: Uwe Ohse */


//image x,y offsets from cursor position in pixels. Enter 0,0 for no offset
var offsetfrommouse=[15,15];
//duration in seconds image should remain visible. 0 for always.
var displayduration=0;
// maximum image size.
var currentimageheight = 400;
// 
var overlaywidth=436;
var overlayheight=486;

if (document.getElementById || document.all){
  document.write('<div id="overlayimage" ');
  document.write('style="font-size: 0.75em; position: absolute; display:none;');
  document.write(' visibility: hidden; left: 0px; top: 0px; width: 0px;');
  document.write(' margin:0; padding:0; height: 0px; z-index: 200;">');
  document.write('</div>');

}

function gettrailobj(){
  if (document.getElementById)
    return document.getElementById("overlayimage").style
  else if (document.all)
    return document.all.overlayimage.style
}

function gettrailobjnostyle(){
  if (document.getElementById)
    return document.getElementById("overlayimage")
  else if (document.all)
    return document.all.overlayimage
}
function winheight() {
  if (self.innerHeight) {
    return window.innerHeight;
  } 
  else if (document.documentElement && document.documentElement.clientHeight)
  {
    // IE 6 Strict
    return document.documentElement.clientHeight;
  } 
  else {
    // IE, other versions
    return document.body.clientHeight;
  }
  return 600;
}
function winwidth() {
  if (self.innerHeight) {
    return window.innerWidth;
  } 
  else if (document.documentElement && document.documentElement.clientHeight)
  {
    // IE 6 Strict
    return document.documentElement.clientWidth;
  } 
  else {
    // IE, other versions
    return document.body.clientWidth;
  }
  return 800;
}

function showtrail(imagesrc,title,w,h){
  // make sure there is place enough for the overlay on the screen, so that
  // it does not grab the mouse.
/*
  ww=winwidth();
  wh=winheight();
  if (w+36 > ww/2) w=ww/2-36;
  if (h+100 > wh/2) h=wh/2-100;
*/
  if (h> 0){
    currentimageheight = h;
  }
  if (w> 0){
    currentimagewidth = w;
  }
  overlaywidth=currentimagewidth+16;
  overlayheight=currentimageheight+50;
  gettrailobj().width = overlaywidth+"px";
  gettrailobj().height = overlayheight+"px";

  document.onmousemove=followmouse;
  title=title.replace(/&/g,'&amp;');
  title=title.replace(/</g,'&lt;');
  title=title.replace(/>/g,'&gt;');

  newHTML = '<div style="padding: 5px; border: 1px solid #888;" class="row1">';
  newHTML = newHTML + '<h2 id="TTT">' + title + '</h2>';

  newHTML = newHTML + '<div align="center" style="padding: 8px 2px 2px 2px;"><img style="height:'+h+'px; width:'+w+'px;" src="' + imagesrc + '" border="0"></div>';
  newHTML = newHTML + '<span id="FFF">Vom Browser herunterskaliert auf '+w+'x'+h+' - das Original ist oft besser</span>';

  newHTML = newHTML + '</div>';

  gettrailobjnostyle().innerHTML = newHTML;

  gettrailobj().visibility="visible";
  gettrailobj().display="block";
  gettrailobj().height=h+50+"px";
  gettrailobj().width=w+16+"px";
}


function hidetrail(){
  gettrailobj().visibility="hidden"
  gettrailobj().display="none";
  document.onmousemove=""
  gettrailobj().left="-500px"
}

function my_get_scroll_x_offset()
{
  if (self.pageXOffset)
    return self.pageXOffset;
  if (document.documentElement && document.documentElement.scrollLeft)
    return document.documentElement.scrollLeft;
  if (document.body)
    return document.body.scrollLeft;
  return 0;
}
function my_get_scroll_y_offset()
{
  if (self.pageYOffset)
    return self.pageYOffset;
  if (document.documentElement && document.documentElement.scrollTop)
    return document.documentElement.scrollTop;
  if (document.body)
    return document.body.scrollTop;
  return 0;
}


function followmouse(e){
  var xcoord=offsetfrommouse[0]
  var ycoord=offsetfrommouse[1]

  if (!e) {
    e=window.event;
  }

  ww=winwidth();
  wh=winheight();

  if (IE) { // grab the x-y pos.s if browser is IE
    mx = event.clientX + document.body.scrollLeft;
    my = event.clientY + document.body.scrollTop;
    mx+=my_get_scroll_x_offset();
    my+=my_get_scroll_y_offset();
  } else {  // grab the x-y pos.s if browser is NS
    mx = e.pageX;
    my = e.pageY;
  }
//debug="       Mouse("+mx+","+my+") ";
//debug=debug+ "Scroll("+my_get_scroll_x_offset()+","+my_get_scroll_y_offset()+") ";
//debug=debug+ "Win("+ww+","+wh+") Off("+xcoord+","+ycoord+")";
  mx-=my_get_scroll_x_offset();
  my-=my_get_scroll_y_offset();

  // The different logic for x/y jumps 
  ly=my+offsetfrommouse[1];
  if (ly+overlayheight>wh)
    ly=wh-offsetfrommouse[1]-overlayheight;

  lx=mx+offsetfrommouse[0];
  if (lx+overlaywidth>ww)
    lx=mx-offsetfrommouse[0]-overlaywidth;
  lx+=my_get_scroll_x_offset();
  ly+=my_get_scroll_y_offset();

//debug=debug+ " Final("+lx+","+ly+")";
//  document.getElementById("TTT").innerHTML="<b>"+debug+"</b>";
//  document.getElementById("FFF").innerHTML="<b>"+debug+"</b>";


  gettrailobj().left=lx+"px";
  gettrailobj().top=ly+"px";
}
/**
modal_content => sm_content
modal_overlay => sm_olay
modal_close => sm_close
modal_title => sm_title
fn.modal* => fn.smart_modal*
modal_count => sm_count
**/
(function($) {
	//base function to call and setup everything
	$.fn.smart_modal=function(options){
		return this.each(function(){			
			if(this._sm) return; //if already a modal return
			if(typeof(options) != "undefined")	var params = $.extend({}, $.fn.smart_modal.defaults, options); //if some options are passed in merge them
			else var params = $.fn.smart_modal.defaults;
			if(typeof(sm_count) == "undefined") sm_count=0; //set the counter to 0
			sm_count++;
			this._sm=sm_count; //set what modal number this is
			H[sm_count] = {config:params,target_sm:this}; //add to hash var
			$(this).smart_modal_add_show(this); //add show & hide triggers
		});
	};
	$.fn.smart_modal_add_show=function(ele){ return $.smart_modal.show(ele); };
	//extra function so show & hide can be called
	$.fn.smart_modal_show=function(){
		return this.each(function(){
			$.smart_modal.open(this);
		});		
	};
	$.fn.smart_modal_hide=function(){
		return this.each(function(){
			$.smart_modal.hide(this, true);
		});		
	};
	//the default config vars
	$.fn.smart_modal.defaults = {show:false, hide:false, modal_styles:{display:"block", zIndex:1001}, resize:true, hide_on_overlay_click:true };
	//the over riden stuff
	$.smart_modal = {
		hash:{}, //the hash used to store all the configs & targets
		show:function(ele){
			var pos = ele._sm, h = H[pos];
			jQ(h.target_sm).click(function(){
				$.smart_modal.open(ele);
				return false;
			});
			return false;
		},
		
		hide:function(ele, force){
			var pos = ele._sm, h = H[pos];			
			if(h.config.hide_on_overlay_click) var idstr = "#sm_olay, .sm_close";
			else var idstr = ".sm_close";
			if(force) $.smart_modal.remove(ele);
			jQ(idstr).click(function(){
       	$.smart_modal.remove(ele);
				return false;
      });
		},
		remove:function(ele){
			var pos = ele._sm, h = H[pos];
			jQ("#sm_content").remove();
			jQ("#sm_olay").remove();							
			if(h.config.hide)	h.config.hide();
		},
		open:function(ele){
			var pos = ele._sm;
			var h = H[pos];			
			$.smart_modal.insert_overlay();
			$.smart_modal.insert_content_container();
			var smcontent = $.smart_modal.get_content($(h.target_sm));
			jQ("#sm_content").html(smcontent);			
			if(h.config.modal_styles) jQ("#sm_content").css(h.config.modal_styles);
			if(h.config.resize) $.smart_modal.resize_container();
      $.smart_modal.for_ie(jQ("#sm_olay"));	
			if(h.config.show) h.config.show();
			$.smart_modal.hide(ele); //add hiding
		},
		resize_container: function(){
			var max_width = 0, max_height=0;
			jQ('#sm_content *').load(function(){				
				jQ('#sm_content *').each(function(){					
					var tw = jQ(this).outerWidth(), th = jQ(this).outerHeight();
					if(tw > max_width) max_width = tw;
					max_height += th;
				});
				if(max_width >0 && max_height>0) jQ('#sm_content').css('width', (max_width+jQ('#sm_content .sm_close:first').outerWidth())+'px').css('height', (max_height)+'px').css('margin-left', '-'+(max_width/2)+'px');
				var off=jQ('#sm_content').offset();
				if (off.left<0)
				    jQ('#sm_content').css('margin-left', '-'+(max_width/2+off.left-50)+'px')
			});
			
		},
		insert_overlay:function(){
			if(!jQ('#sm_olay').length) jQ("body").append('<div id="sm_olay"></div>');
      jQ("#sm_olay").css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':1000,opacity:50/100});
		},
		insert_content_container:function(){
			if(!jQ('#sm_content').length) jQ("body").append('<div id="sm_content"></div>');
		},
		get_content:function(trig){
			c = "<div class='sm_close'><p>x</p></div>";
			if(trig.attr("rel")){ //if rel exists
				div_id = jQ('#'+trig.attr('rel'));
				div_class = jQ('.'+trig.attr('rel'));	
				if(div_id.length){ c += div_id.html(); }
				else if(div_class.length){ c += div_class.html();	}
			}else if(trig.attr('href')){ 
				// if it has a href but no rel then insert the href as image src
			        // or load content, if it doesn't look like an image.
				if(trig.attr('href').match(/.(gif|png|jpg|jpeg|bmp|tif)$/i)) {
                                       if(trig.attr('title')) {
                                               c +="<h3 class='sm_title'>"+trig.attr('title')
                                                 +"</h3><img src='"+trig.attr('href')+"' alt='"+trig.attr('title')+"' />";
                                       } else{
                                               c += "<img src='"+trig.attr('href')+"' alt='modal' />";
                                       }
				} else {
                                     $(".busywait-image").show(); // if something like that is here at all.
                                     $.ajax({
                                         url: trig.attr('href'),
                                         dataType: 'html',
                                         async: false,
                                         success: function(data,sta) {
                                           if (trig.attr('class'))
                                             jQ("#sm_content").addClass(trig.attr('class'));
                                           c += "<div id='sm_loaded_content'>"+data+"</div>";
                                         }
                                     });
                                     $(".busywait-image").hide();
                               }
			}else{ c = c + trig.html(); }
			return c;
		},
		for_ie:function(o){
			if(ie6&&$('html,body').css({height:'100%',width:'100%'})&&o){
				$('html,body').css({height:'100%',width:'100%'});
        i=$('<iframe src="javascript:false;document.write(\'\');" class="overlay"></iframe>').css({opacity:0});
        o.html('<p style="width:100%;height:100%"/>').prepend(i);
        o = o.css({position:'absolute'})[0];
			}
		}
	};
	var H=$.smart_modal.hash,	jQ = jQuery;
			ie6=$.browser.msie&&($.browser.version == "6.0");
})(jQuery);
// ----------------------------------------------------------------------------
// markItUp! Universal MarkUp Engine, JQuery plugin
// v 1.1.5
// Dual licensed under the MIT and GPL licenses.
// ----------------------------------------------------------------------------
// Copyright (C) 2007-2008 Jay Salvat
// http://markitup.jaysalvat.com/
// ----------------------------------------------------------------------------
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ----------------------------------------------------------------------------
(function($) {
	$.fn.markItUp = function(settings, extraSettings) {
		var options, ctrlKey, shiftKey, altKey;
		ctrlKey = shiftKey = altKey = false;

		options = {	id:						'',
					nameSpace:				'',
					root:					'',
					previewInWindow:		'', // 'width=800, height=600, resizable=yes, scrollbars=yes'
					previewAutoRefresh:		true,
					previewPosition:		'after',
					previewTemplatePath:	'~/templates/preview.html',
					previewParserPath:		'',
					previewParserVar:		'data',
					resizeHandle:			true,
					beforeInsert:			'',
					afterInsert:			'',
					onEnter:				{},
					onShiftEnter:			{},
					onCtrlEnter:			{},
					onTab:					{},
					markupSet:			[	{ /* set */ } ]
				};
		$.extend(options, settings, extraSettings);

		// compute markItUp! path
		if (!options.root) {
			$('script').each(function(a, tag) {
				miuScript = $(tag).get(0).src.match(/(.*)jquery\.markitup(\.pack)?\.js$/);
				if (miuScript !== null) {
					options.root = miuScript[1];
				}
			});
		}

		return this.each(function() {
			var $$, textarea, levels, scrollPosition, caretPosition, caretOffset,
				clicked, hash, header, footer, previewWindow, template, iFrame, abort;
			$$ = $(this);
			textarea = this;
			levels = [];
			abort = false;
			scrollPosition = caretPosition = 0;
			caretOffset = -1;

			options.previewParserPath = localize(options.previewParserPath);
			options.previewTemplatePath = localize(options.previewTemplatePath);

			// apply the computed path to ~/
			function localize(data, inText) {
				if (inText) {
					return 	data.replace(/("|')~\//g, "$1"+options.root);
				}
				return 	data.replace(/^~\//, options.root);
			}

			// init and build editor
			function init() {
				id = ''; nameSpace = '';
				if (options.id) {
					id = 'id="'+options.id+'"';
				} else if ($$.attr("id")) {
					id = 'id="markItUp'+($$.attr("id").substr(0, 1).toUpperCase())+($$.attr("id").substr(1))+'"';

				}
				if (options.nameSpace) {
					nameSpace = 'class="'+options.nameSpace+'"';
				}
				$$.wrap('<div '+nameSpace+'></div>');
				$$.wrap('<div '+id+' class="markItUp"></div>');
				$$.wrap('<div class="markItUpContainer"></div>');
				$$.addClass("markItUpEditor");

				// add the header before the textarea
				header = $('<div class="markItUpHeader"></div>').insertBefore($$);
				$(dropMenus(options.markupSet)).appendTo(header);

				// add the footer after the textarea
				footer = $('<div class="markItUpFooter"></div>').insertAfter($$);

				// add the resize handle after textarea
				if (options.resizeHandle === true && $.browser.safari !== true) {
					resizeHandle = $('<div class="markItUpResizeHandle"></div>')
						.insertAfter($$)
						.bind("mousedown", function(e) {
							var h = $$.height(), y = e.clientY, mouseMove, mouseUp;
							mouseMove = function(e) {
								$$.css("height", Math.max(20, e.clientY+h-y)+"px");
								return false;
							};
							mouseUp = function(e) {
								$("html").unbind("mousemove", mouseMove).unbind("mouseup", mouseUp);
								return false;
							};
							$("html").bind("mousemove", mouseMove).bind("mouseup", mouseUp);
					});
					footer.append(resizeHandle);
				}

				// listen key events
				$$.keydown(keyPressed).keyup(keyPressed);
				
				// bind an event to catch external calls
				$$.bind("insertion", function(e, settings) {
					if (settings.target !== false) {
						get();
					}
					if (textarea === $.markItUp.focused) {
						markup(settings);
					}
				});

				// remember the last focus
				$$.focus(function() {
					$.markItUp.focused = this;
				});
			}

			// recursively build header with dropMenus from markupset
			function dropMenus(markupSet) {
				var ul = $('<ul></ul>'), i = 0;
				$('li:hover > ul', ul).css('display', 'block');
				$.each(markupSet, function() {
					var button = this, t = '', title, li, j;
					title = (button.key) ? (button.name||'')+' [Ctrl+'+button.key+']' : (button.name||'');
					key   = (button.key) ? 'accesskey="'+button.key+'"' : '';
					if (button.separator) {
						li = $('<li class="markItUpSeparator">'+(button.separator||'')+'</li>').appendTo(ul);
					} else {
						i++;
						for (j = levels.length -1; j >= 0; j--) {
							t += levels[j]+"-";
						}
						li = $('<li class="markItUpButton markItUpButton'+t+(i)+' '+(button.className||'')+'"><a href="" '+key+' title="'+title+'">'+(button.name||'')+'</a></li>')
						.bind("contextmenu", function() { // prevent contextmenu on mac and allow ctrl+click
							return false;
						}).click(function() {
							return false;
						}).mouseup(function() {
							if (button.call) {
								eval(button.call)();
							}
							markup(button);
							return false;
						}).hover(function() {
								$('> ul', this).show();
								$(document).one('click', function() { // close dropmenu if click outside
										$('ul ul', header).hide();
									}
								);
							}, function() {
								$('> ul', this).hide();
							}
						).appendTo(ul);
						if (button.dropMenu) {
							levels.push(i);
							$(li).addClass('markItUpDropMenu').append(dropMenus(button.dropMenu));
						}
					}
				}); 
				levels.pop();
				return ul;
			}

			// markItUp! markups
			function magicMarkups(string) {
				if (string) {
					string = string.toString();
					string = string.replace(/\(\!\(([\s\S]*?)\)\!\)/g,
						function(x, a) {
							var b = a.split('|!|');
							if (altKey === true) {
								return (b[1] !== undefined) ? b[1] : b[0];
							} else {
								return (b[1] === undefined) ? "" : b[0];
							}
						}
					);
					// [![prompt]!], [![prompt:!:value]!]
					string = string.replace(/\[\!\[([\s\S]*?)\]\!\]/g,
						function(x, a) {
							var b = a.split(':!:');
							if (abort === true) {
								return false;
							}
							value = prompt(b[0], (b[1]) ? b[1] : '');
							if (value === null) {
								abort = true;
							}
							return value;
						}
					);
					return string;
				}
				return "";
			}

			// prepare action
			function prepare(action) {
				if ($.isFunction(action)) {
					action = action(hash);
				}
				return magicMarkups(action);
			}

			// build block to insert
			function build(string) {
				openWith 	= prepare(clicked.openWith);
				placeHolder = prepare(clicked.placeHolder);
				replaceWith = prepare(clicked.replaceWith);
				closeWith 	= prepare(clicked.closeWith);
				if (replaceWith !== "") {
					block = openWith + replaceWith + closeWith;
				} else if (selection === '' && placeHolder !== '') {
					block = openWith + placeHolder + closeWith;
				} else {
					block = openWith + (string||selection) + closeWith;
				}
				return {	block:block, 
							openWith:openWith, 
							replaceWith:replaceWith, 
							placeHolder:placeHolder,
							closeWith:closeWith
					};
			}

			// define markup to insert
			function markup(button) {
				var len, j, n, i;
				hash = clicked = button;
				get();

				$.extend(hash, {	line:"", 
						 			root:options.root,
									textarea:textarea, 
									selection:(selection||''), 
									caretPosition:caretPosition,
									ctrlKey:ctrlKey, 
									shiftKey:shiftKey, 
									altKey:altKey
								}
							);
				// callbacks before insertion
				prepare(options.beforeInsert);
				prepare(clicked.beforeInsert);
				if (ctrlKey === true && shiftKey === true) {
					prepare(clicked.beforeMultiInsert);
				}			
				$.extend(hash, { line:1 });
				
				if (ctrlKey === true && shiftKey === true) {
					lines = selection.split(/\r?\n/);
					for (j = 0, n = lines.length, i = 0; i < n; i++) {
						if ($.trim(lines[i]) !== '') {
							$.extend(hash, { line:++j, selection:lines[i] } );
							lines[i] = build(lines[i]).block;
						} else {
							lines[i] = "";
						}
					}
					string = { block:lines.join('\n')};
					start = caretPosition;
					len = string.block.length + (($.browser.opera) ? n : 0);
				} else if (ctrlKey === true) {
					string = build(selection);
					start = caretPosition + string.openWith.length;
					len = string.block.length - string.openWith.length - string.closeWith.length;
					len -= fixIeBug(string.block);
				} else if (shiftKey === true) {
					string = build(selection);
					start = caretPosition;
					len = string.block.length;
					len -= fixIeBug(string.block);
				} else {
					string = build(selection);
					start = caretPosition + string.block.length ;
					len = 0;
					start -= fixIeBug(string.block);
				}
				if ((selection === '' && string.replaceWith === '')) {
					caretOffset += fixOperaBug(string.block);
					
					start = caretPosition + string.openWith.length;
					len = string.block.length - string.openWith.length - string.closeWith.length;

					caretOffset = $$.val().substring(caretPosition,  $$.val().length).length;
					caretOffset -= fixOperaBug($$.val().substring(0, caretPosition));
				}
				$.extend(hash, { caretPosition:caretPosition, scrollPosition:scrollPosition } );

				if (string.block !== selection && abort === false) {
					insert(string.block);
					set(start, len);
				} else {
					caretOffset = -1;
				}
				get();

				$.extend(hash, { line:'', selection:selection });

				// callbacks after insertion
				if (ctrlKey === true && shiftKey === true) {
					prepare(clicked.afterMultiInsert);
				}
				prepare(clicked.afterInsert);
				prepare(options.afterInsert);

				// refresh preview if opened
				if (previewWindow && options.previewAutoRefresh) {
					refreshPreview(); 
				}
																									
				// reinit keyevent
				shiftKey = altKey = ctrlKey = abort = false;
			}

			// Substract linefeed in Opera
			function fixOperaBug(string) {
				if ($.browser.opera) {
					return string.length - string.replace(/\n*/g, '').length;
				}
				return 0;
			}
			// Substract linefeed in IE
			function fixIeBug(string) {
				if ($.browser.msie) {
					return string.length - string.replace(/\r*/g, '').length;
				}
				return 0;
			}
				
			// add markup
			function insert(block) {	
				if (document.selection) {
					var newSelection = document.selection.createRange();
					newSelection.text = block;
				} else {
					$$.val($$.val().substring(0, caretPosition)	+ block + $$.val().substring(caretPosition + selection.length, $$.val().length));
				}
			}

			// set a selection
			function set(start, len) {
				if (textarea.createTextRange){
					// quick fix to make it work on Opera 9.5
					if ($.browser.opera && $.browser.version >= 9.5 && len == 0) {
						return false;
					}
					range = textarea.createTextRange();
					range.collapse(true);
					range.moveStart('character', start); 
					range.moveEnd('character', len); 
					range.select();
				} else if (textarea.setSelectionRange ){
					textarea.setSelectionRange(start, start + len);
				}
				textarea.scrollTop = scrollPosition;
				textarea.focus();
			}

			// get the selection
			function get() {
				textarea.focus();

				scrollPosition = textarea.scrollTop;
				if (document.selection) {
					selection = document.selection.createRange().text;
					if ($.browser.msie) { // ie
						var range = document.selection.createRange(), rangeCopy = range.duplicate();
						rangeCopy.moveToElementText(textarea);
						caretPosition = -1;
						while(rangeCopy.inRange(range)) { // fix most of the ie bugs with linefeeds...
							rangeCopy.moveStart('character');
							caretPosition ++;
						}
					} else { // opera
						caretPosition = textarea.selectionStart;
					}
				} else { // gecko
					caretPosition = textarea.selectionStart;
					selection = $$.val().substring(caretPosition, textarea.selectionEnd);
				} 
				return selection;
			}

			// open preview window
			function preview() {
				if (!previewWindow || previewWindow.closed) {
					if (options.previewInWindow) {
						previewWindow = window.open('', 'preview', options.previewInWindow);
					} else {
						iFrame = $('<iframe class="markItUpPreviewFrame"></iframe>');
						if (options.previewPosition == 'after') {
							iFrame.insertAfter(footer);
						} else {
							iFrame.insertBefore(header);
						}	
						previewWindow = iFrame[iFrame.length-1].contentWindow || frame[iFrame.length-1];
					}
				} else if (altKey === true) {
					if (iFrame) {
						iFrame.remove();
					}
					previewWindow.close();
					previewWindow = iFrame = false;
				}
				if (!options.previewAutoRefresh) {
					refreshPreview(); 
				}
			}

			// refresh Preview window
			function refreshPreview() {
				if (previewWindow.document) {			
					try {
						sp = previewWindow.document.documentElement.scrollTop
					} catch(e) {
						sp = 0;
					}					
					previewWindow.document.open();
					previewWindow.document.write(renderPreview());
					previewWindow.document.close();
					previewWindow.document.documentElement.scrollTop = sp;
				}
				if (options.previewInWindow) {
					previewWindow.focus();
				}
			}

			function renderPreview() {				
				if (options.previewParserPath !== '') {
					$.ajax( {
						type: 'POST',
						async: false,
						url: options.previewParserPath,
						data: options.previewParserVar+'='+encodeURIComponent($$.val()),
						success: function(data) {
							phtml = localize(data, 1); 
						}
					} );
				} else {
					if (!template) {
						$.ajax( {
							async: false,
							url: options.previewTemplatePath,
							success: function(data) {
								template = localize(data, 1); 
							}
						} );
					}
					phtml = template.replace(/<!-- content -->/g, $$.val());
				}
				return phtml;
			}
			
			// set keys pressed
			function keyPressed(e) { 
				shiftKey = e.shiftKey;
				altKey = e.altKey;
				ctrlKey = (!(e.altKey && e.ctrlKey)) ? e.ctrlKey : false;

				if (e.type === 'keydown') {
					if (ctrlKey === true) {
						li = $("a[accesskey="+String.fromCharCode(e.keyCode)+"]", header).parent('li');
						if (li.length !== 0) {
							ctrlKey = false;
							li.triggerHandler('mouseup');
							return false;
						}
					}
					if (e.keyCode === 13 || e.keyCode === 10) { // Enter key
						if (ctrlKey === true) {  // Enter + Ctrl
							ctrlKey = false;
							markup(options.onCtrlEnter);
							return options.onCtrlEnter.keepDefault;
						} else if (shiftKey === true) { // Enter + Shift
							shiftKey = false;
							markup(options.onShiftEnter);
							return options.onShiftEnter.keepDefault;
						} else { // only Enter
							markup(options.onEnter);
							return options.onEnter.keepDefault;
						}
					}
					if (e.keyCode === 9) { // Tab key
						if (shiftKey == true || ctrlKey == true || altKey == true) { // Thx Dr Floob.
							return false; 
						}
						if (caretOffset !== -1) {
							get();
							caretOffset = $$.val().length - caretOffset;
							set(caretOffset, 0);
							caretOffset = -1;
							return false;
						} else {
							markup(options.onTab);
							return options.onTab.keepDefault;
						}
					}
				}
			}

			init();
		});
	};

	$.fn.markItUpRemove = function() {
		return this.each(function() {
				$$ = $(this).unbind().removeClass('markItUpEditor');
				$$.parent('div').parent('div.markItUp').parent('div').replaceWith($$);
			}
		);
	};

	$.markItUp = function(settings) {
		var options = { target:false };
		$.extend(options, settings);
		if (options.target) {
			return $(options.target).each(function() {
				$(this).focus();
				$(this).trigger('insertion', [options]);
			});
		} else {
			$('textarea').trigger('insertion', [options]);
		}
	};
})(jQuery);
// ----------------------------------------------------------------------------
// markItUp!
// ----------------------------------------------------------------------------
// Copyright (C) 2008 Jay Salvat
// http://markitup.jaysalvat.com/
// ----------------------------------------------------------------------------
// BBCode tags example
// http://en.wikipedia.org/wiki/Bbcode
// ----------------------------------------------------------------------------
// Feel free to add more tags
// ----------------------------------------------------------------------------
mySettings = {
	previewParserPath:	'ajax.php?action=make-preview', // path to your BBCode parser
	previewParserVar:	'text', // path to your BBCode parser
	resizeHandle:	true,
	markupSet: [
		{name:'B',markUp:'<b>B</b>', key:'B', openWith:'[b]', closeWith:'[/b]',
                  replaceWith:function(markitup) { 
                    var x=markitup.selection;
                    return markitup.selection.replace(/\[(.*?)\]/g, "")
                  }
                  },
		{name:'I', markUp:'<i>I</i>', key:'I', openWith:'[i]', closeWith:'[/i]'},
		{name:'S', markUp:'<strike>S</strike>', key:'s', openWith:'[s]', closeWith:'[/s]'},
		{name:'U', markUp:'<u>U</U>', key:'U', openWith:'[u]', closeWith:'[/u]'},
                {name:'Bunt', markUp:'<span style="background-color:#888"><span style="color:yellow">B</span><span style="color:red">u</span><span style="color:green">n</span><span style="color:blue">t</span></span>', openWith:'[color=[![Color]!]]', closeWith:'[/color]', className:'colors', dropMenu: [
                    {name:'Yellow', openWith:'[color=yellow]', closeWith:'[/color]', className:"colorbutton col1-1" },
                    {name:'Orange', openWith:'[color=orange]', closeWith:'[/color]', className:"colorbutton col1-2" },
                    {name:'Red', openWith:'[color=red]', closeWith:'[/color]', className:"colorbutton col1-3" },
                    {name:'Blue', openWith:'[color=blue]', closeWith:'[/color]', className:"colorbutton col2-1" },
                    {name:'Purple', openWith:'[color=purple]', closeWith:'[/color]', className:"colorbutton col2-2" },
                    {name:'Green', openWith:'[color=green]', closeWith:'[/color]', className:"colorbutton col2-3" },
                    {name:'White', openWith:'[color=white]', closeWith:'[/color]', className:"colorbutton col3-1" },
                    {name:'Gray', openWith:'[color=gray]', closeWith:'[/color]', className:"colorbutton col3-2" },
                    {name:'Black', openWith:'[color=black]', closeWith:'[/color]', className:"colorbutton col3-3" }
                ]},

		{name:'H2', openWith:'[h2]', closeWith:'[/h2]'},
		{name:'H3', openWith:'[h3]', closeWith:'[/h3]'},
		{name:'H4', openWith:'[h4]', closeWith:'[/h4]'},
		{name:'OL', openWith:'[ol]\n', closeWith:'\n[/ol]'}, 
		{name:'UL', openWith:'[ul]\n', closeWith:'\n[/ul]'},
		{name:'*', openWith:'[*] '},
		{name:'www', key:'L', openWith:'[url=[![Url]!]]', closeWith:'[/url]', placeHolder:'Your text to link here...'},
		{name:'img', key:'P', replaceWith:'[img][![Url]!][/img]'},
		{name:'Q', openWith:'[quote]', closeWith:'[/quote]'},
		{name:'BQ', openWith:'[blockquote]', closeWith:'[/blockquote]'},
		{name:'pre', openWith:'[pre]', closeWith:'[/pre]'},
		{name:'[]',markUp:'<strike>[]</strike>', title:'a[...]b => ab', className:"clean", replaceWith:function(markitup) { return markitup.selection.replace(/\[(.*?)\]/g, "") } }

	]
};

