/**
	Dom Ready
	*/
Object.extend(Event, {
  _isDomReady : false,
  
  asap: function(f) {
  	this._isDomReady ?
  		f() : document.observe('dom:loaded', f);
  }
});
document.observe('dom:loaded', function() {Event._isDomReady = true;});

function isWindowLoaded() {
  return Event._isDomReady;
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

/* ---------------------------------------

  TinyMCEConfig

--------------------------------------- */
var TinyMCEConfig = { 
	css     : null,
	advanced: false,
	initdone: false,
	
	init: function() {
		if (!this.initdone) {
			tinyMCE_GZ.init({
		      themes : "advanced",
		      plugins: "inlinepopups,fullscreen,table,contextmenu",
		      languages : "en",
		      disk_cache : true
		   }, TinyMCEConfig.configure); 
		}
	},
	
	configure: function() {
		tinyMCE.init({
		  mode: "none",
		  language: "en",
		  plugins: "inlinepopups,fullscreen,table,contextmenu",
		  theme: "advanced",
		  theme_advanced_toolbar_location: "top",
		  theme_advanced_toolbar_align: "left",
		  theme_advanced_path: false,
		  theme_advanced_buttons1: TinyMCEConfig.advanced ? "justifyleft,justifycenter,justifyright,justifyfull,formatselect,bold,italic,bullist" : "justifyleft,justifycenter,justifyright,justifyfull,separator,bold,bullist,formatselect",
   		  theme_advanced_buttons2: TinyMCEConfig.advanced ? "fullscreen,code,cleanup,removeformat,outdent,indent,numlist,link,unlink" : "",
		  theme_advanced_buttons3: "",
		  theme_advanced_blockformats: 'p,h3,h4,h5,h6',
		  theme_advanced_styles : "klein=small; Grauverlauf=greytextbox; Preistabelle=pricetable",
		  table_styles: "Preistabelle=pricetable",
		  convert_newlines_to_brs : false,
		  remove_trailing_nbsp : false,
		  auto_resize : false,
		  apply_source_formatting : true,
		  relative_urls: false,
		  content_css : TinyMCEConfig.css,
		  cleanup_on_startup : true,
		  cleanup : true,
		  paste_auto_cleanup_on_paste : true,
		  verify_html : true,
		  verify_css_classes : false,
		  extended_valid_elements : "fieldset[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress"
  											+"|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title]",
		  invalid_elements : TinyMCEConfig.advanced ? "script,head,body" : "img,script,style,head,body",
		  file_browser_callback: TinyMCEConfig.advanced ? "sfMediaLibrary.fileBrowserCallBack" : null,
		  debug: false
		});
	}
}



/* ---------------------------------------

  Overlib

--------------------------------------- */

ol_padxl=5;
ol_padxr=5;
ol_padyt=5;
ol_padyb=5;
ol_width="";
ol_fgclass="overlay";
ol_bgclass="overlibBg";
ol_textfont="";

function toggleVisibility(element, visible) {
	toggle(element, visible);
}

function toggle(elementName, visible) {
    element = $(elementName);
    if (element.visible() != visible) {

    	visible ?
    		new Effect.BlindDown(element, {duration: 0.3, queue: {position:'first', scope:element.id, limit:1}}) :
    		new Effect.BlindUp(element,   {duration: 0.3, queue: {position:'first', scope:element.id, limit:1}}) ;

    	//visible ? element.show() : element.hide();
    }
}

/* ---------------------------------------

  Dynamic textarea

--------------------------------------- */

var ResizingTextArea = Class.create();

ResizingTextArea.prototype = {
    defaultRows: 1,

    initialize: function(field)
    {
        this.defaultRows = Math.max(field.rows, 1);
        this.resizeNeeded = this.resizeNeeded.bindAsEventListener(this);
        Event.observe(field, "click", this.resizeNeeded);
        Event.observe(field, "keyup", this.resizeNeeded);
    },

    resizeNeeded: function(event)
    {
        var t = Event.element(event);
        var lines = t.value.split('\n');
        var newRows = lines.length + 1;
        var oldRows = t.rows;
        for (var i = 0; i < lines.length; i++)
        {
            var line = lines[i];
            if (line.length >= t.cols) newRows += Math.floor(line.length / t.cols);
        }
        if (newRows > t.rows) t.rows = newRows;
        if (newRows < t.rows) t.rows = Math.max(this.defaultRows, newRows);
    }
}


function changePosition(position, pictureEditArea, textAreaDiv, width) {
  if (!$(position)) {
    return;
  }
  var pos = $F(position);
  if (pos == 'left') {
    $(pictureEditArea).style.left = '0px';
    $(textAreaDiv).style.left = (width/2 + 10) + 'px';
  }
  else {
    $(pictureEditArea).style.left = (width/2) + 'px';
    $(textAreaDiv).style.left = '0px';
  }
}

/* ---------------------------------------

  Widget Registry

--------------------------------------- */
Notifier = Class.create();
Notifier.prototype = {
    listener: null,

    initialize: function() {
      this.listener = new Array();
    },

    addListener: function(listen) {
      this.listener[this.listener.length] = listen;
    },

    onEvent: function(event) {
      this.listener.reverse().each(
        function (item) {
          item(event);
        }
      )
    }
};

Widget = Class.create();
Widget.prototype = {
	id: null,
	element: null,
	widget:  null,
	dragDropContainer: null,
	isMoveable: false,
	isEditable: false,
	editMode:   false,
	toolbar:    null,
	
	initialize: function(id, element) {
		this.id = id;
		this.element = $(element);
		
		this.widget = this.element.select('.widgetcontainer')[0];
		this.widget.widgetId = this.id;  
		this.isMoveable = this.widget.hasClassName('dragDropContainer');
		
		if (this.isMoveable) {
			this.draggable = new Draggable(this.widget, {
      			handle: 'movearrow',
      			constraint: 'vertical',
      			revert: true,
      			scroll: window
      		});
	      	Droppables.add(this.element, {
	    		accept:     'dragDropContainer',
	    		hoverclass: 'dropzoneHover',
	    		onDrop:		this.onDrop.bind(this)     
	    	});
    	}
    	
    	
    	this.editBind =     this.edit.bindAsEventListener(this);
   		this.moveUpBind =   this.moveUp.bindAsEventListener(this);
   		this.moveDownBind = this.moveDown.bindAsEventListener(this);
   		this.removeBind   = this.remove.bindAsEventListener(this)

   		this.element.select('.edit_button').invoke('observe', 'click', this.editBind);
   		this.element.select('.moveup'     ).invoke('observe', 'click', this.moveUpBind);
   		this.element.select('.movedown'   ).invoke('observe', 'click', this.moveDownBind);
   		this.element.select('.delete'     ).invoke('observe', 'click', this.removeBind);
    	
    	this.isEditable = this.element.select('.edit_button').length > 0;
    	if (this.isEditable) {
    		this.toolbar = this.widget.select('.newToolbar')[0];
    		
    		this.showToolbarBind = this.showToolbar.bindAsEventListener(this);
    		this.hideToolbarBind = this.hideToolbar.bindAsEventListener(this)
    	
			this.widget.observe('mouseover', this.showToolbarBind, true);
			this.widget.observe('mouseout',  this.hideToolbarBind, true); 
    	}
	},
	
	onDrop: function(draggable, droppable, event) {
		if (draggable.parentNode != droppable) {
			move(draggable.id, droppable, draggable.widgetId);
		}
	},
	
	moveUp: function() {
		moveup(this.widget.id, this.id);
	},
	
	moveDown: function() {
		movedown(this.widget.id, this.id);
	},

	_showToolbar: false,	
	showToolbar: function() {
		this._showToolbar = true;
		this.toolbar.visible() ? null : this.toolbar.show();
	},
	hideToolbar: function() {
		if (this.toolbar.visible()) {
			this._showToolbar = false;
			Prototype.Browser.IE ? 
				(function() { if(!this._showToolbar) this.toolbar.hide(); }).bind(this).defer(0.1) :
				this.toolbar.hide();
		}
	},

	edit: function() {
		if (!registry.checkEdit()) { return false; };
		this.destroy();
		new Ajax.Updater(this.widget, 
			'/page/editWidget', 
			{   parameters: {
					type: WindowRegistry2._pageType,
					id:   WindowRegistry2._pageId,
					widgetId: this.id
				},
				asynchronous:true, 
			    evalScripts:true}
		); 
	},
	
	remove: function() {
		if (!confirm('Element wirklich löschen?')) 
			return;
			
		registry.removeWidget(this.widget.id);
	
		new Ajax.Updater(this.widget, 
			'/page/deleteWidget', 
			{   parameters: {
					type: WindowRegistry2._pageType,
					id:   WindowRegistry2._pageId,
					widgetId: this.id
				},
				asynchronous:true, 
			    evalScripts:true}
		);
	},
	
	destroy: function() {
		this.element.select('.edit_button').invoke('stopObserving');
   		this.element.select('.moveup'     ).invoke('stopObserving');
   		this.element.select('.movedown'   ).invoke('stopObserving');
   		this.element.select('.delete'     ).invoke('stopObserving');
		this.widget.stopObserving('mouseover');
		this.widget.stopObserving('mouseout');
		if (this.draggable)
			this.draggable.destroy();
	}
};

var WindowRegistry2 = {
	_pageType: null,
	_pageId  : null,
	
	_widgets : null,
	
	configure: function(pageType, pageId) {
		TinyMCEConfig.init(); 
		this._pageType = pageType;
		this._pageId   = pageId;
		this._widgets  = $H();
	},
	
	add: function(widgetId, element) {
		// if (!this._widgets[widgetId]) {
			this._widgets[widgetId] = new Widget(widgetId, element);
		// }
	},
	
	moveUp: function(widgetId) {
	
	}
};

WidgetRegistry = Class.create();
WidgetRegistry.prototype = {
	singleEdit: false,
    saving: 0,
    widgets: null,
    hasErrors: false,

    initialize: function() {
      this.widgets = new Hash();
    },

	getNrOfOpenWidgets : function() {
		var c = 0;
		this.widgets.each(
			function(pair) {if (pair.value) c++;} );
		return c;
	},

	checkEdit : function() {
		if (this.singleEdit && this.getNrOfOpenWidgets() > 0) {
			Dialog.alert(
			'Es sind noch Elemente zur Bearbeitung ge&ouml;ffnet. Diese m&uuml;ssen vorher gespeichert werden.',
			{	className: 'alphacube',
				okLabel: 'Schlie&szlig;en',
				destroyOnClose: true,
				zIndex: 1000}
			);
			return false;
		}
		return true;
	},

	verifyEnd : function(url) {
		if (this.getNrOfOpenWidgets() > 0) {
			Dialog.confirm(
			'Es sind noch ungespeicherte Elemente auf der Seite. Willst du wirklich beenden?',
			{	className: 'alphacube',
				okLabel: 'Jetzt beenden',
				cancelLabel: 'Bearbeiten fortsetzen',
				onOk: function() {document.location.href = url},
				destroyOnClose: true,
				zIndex: 1000}
			);
			return false;
		}
		return true;
	},

	inputSource : function(element) {
		var value = element.value;
		var name  = 'source' + Math.random();

		Dialog.confirm(
		'<h3>Quellennachweis</h3><p>Du kannst hier einen Quellennachweis f&uuml;r das Foto angeben.</p>' +
		'Foto: <input type="text" id="'+name+'" value="'+value+'" size="50" />',
		{	className: 'alphacube',
			okLabel: 'Ok',
			cancelLabel: 'Abbrechen',
			onOk: function() { element.value = $(name).value; return true;},
			destroyOnClose: true,
			zIndex: 1000}
		);
	},

    addWidget: function(id, rawWidgetId) {
      var _this = this;

		if (this.widgets[id]) {
		_this.removeWidget(id);
		}

      this.widgets[id] = new Hash({rawWidgetId: rawWidgetId});
      this.widgets[id]['onremove'] = new Notifier();
      this.widgets[id]['oninit']   = new Notifier();
      this.widgets[id]['onsubmit'] = new Notifier();

      // widgets[id][onload]   = new Notifier();
      this.addOnSubmitListener(id,
          function(e) {
          	Event.stop(e);

			// do this before the request, becuaes after the request it might already be the new widget
	        var rawId = registry.widgets[id].get('rawWidgetId');
               if (registry.widgets[id]) {
				registry.removeWidget(id);
			}
			if (Prototype.Browser.IE) {
				// discardTree($(rawId), false);
			}

            form = Event.element(e);
            if (form.target) {
              // target was set so it is an iframe upload.
              return;
            }
            form = null;
            e = null;

	        showLoadingWindow();

				

			var params = Form.serialize($('form' + id));

			registry.hasErrors = false;

              new Ajax.Updater(rawId, '/page/saveWidget',
              {
                asynchronous:true,
                evalScripts:true,
                parameters:params,
                onComplete: function() {
                  	registry.saving--;
                   	if (registry.singleEdit && !registry.hasErrors && $$('.notice').length == 0) {
               			window.location.reload();
	               		showLoadingWindow();
    	           	}
                }
              });
        }
      );
    },

    setUpListener: function(id) {
      this.widgets[id]['onSubmitBind'] = this.widgets[id]['onsubmit'].onEvent.bindAsEventListener(this.widgets[id]['onsubmit']);
      Event.observe($('form' + id), 'submit', this.widgets[id]['onSubmitBind']);
    },

    removeWidget: function(id) {
    	if (!this.widgets[id]) {
    		return;
    	} 
      this.widgets[id]['onremove'].onEvent(id);
      Event.stopObserving($('form' + id), 'submit', this.widgets[id]['onSubmitBind']);

    this.widgets[id]['onSubmitBind'] = null;
    this.widgets[id]['onsubmit'] = null;
      this.widgets[id]['onremove'] = null;
      this.widgets[id] = null;


    },
    
    initWidget: function(id) {
    	if (!this.widgets[id]) {
    		return;
    	} 
        this.widgets[id]['oninit'].onEvent(id);
    },

    addOnLoadListener: function(id, callback) {
		this.widgets[id]['oninit'].addListener(callback);
    },

    addOnSubmitListener: function(id, callback) {
      this.widgets[id]['onsubmit'].addListener(callback);
    },

    addOnRemoveListener: function(id, callback) {
      this.widgets[id]['onremove'].addListener(callback);
    },

    saveAll: function() {
      var widgetIds = this.widgets.keys();
      this.saving = 0;
      this.hasErrors = false;
      showLoadingWindow();

      Ajax.Responders.register(registry.saveAllListener);
      widgetIds.each(function(id) {
        if($('form' + id)) {
          registry.saving++;
          setTimeout(function() {
            var form = $('form' + id);
              if (document.createEvent) {
              var evObj = document.createEvent('HTMLEvents');
              evObj.initEvent( 'submit', true, true );
              form.dispatchEvent(evObj);
            } else if( document.createEventObject ) {
              form.fireEvent('onsubmit');
            }
          }, registry.saving * 200);
        }
      });
      if (this.saving == 0) {
        this.saveAllListener.onComplete();
      }
    },

    submit: function(id) {
	    this.widgets[id]['onremove'].onEvent(id);
      var form = $('form' + id);
        if (document.createEvent) {
        var evObj = document.createEvent('HTMLEvents');
        evObj.initEvent( 'submit', true, true );
        form.dispatchEvent(evObj);
      } else if( document.createEventObject ) {
        form.fireEvent('onsubmit');
      } 
    },

    removeTextArea : function(widgetId) {
    	// due to any unknown reason, removing in ie does not work in same thread context than submitting
    	var inst = tinyMCE.getInstanceById(widgetId);
    	if (inst) inst.save();
    	
    	(function() {
    		var inst = tinyMCE.getInstanceById(widgetId);
	    	if (inst) {
	    		var editor_id = inst.editorId + '_parent';
	      		var domNode = $(editor_id);
	   			tinyMCE.execCommand('mceRemoveControl', false, widgetId);
	   			// discardTree(domNode, true);
	    	}
    	}).delay(0.1);
	}
}

   function discardTree(tree, inclusive) {
     if (Prototype.Browser.IE) {
   	   $(tree).descendants().each(function(element) {discardElement(element);});
	   if (inclusive) 
		   	discardElement(tree);
	 }
   }

  function discardElement(element) {
    if (element.parentNode) {
        element.parentNode.removeChild(element);
    }
    if (Prototype.Browser.IE) {
	    // move the element to the garbage bin
	    getGarbageBin().appendChild(element);
	    setTimeout(emptyBin, 200);
    }
  }  
   
   function emptyBin() {
  		getGarbageBin().innerHTML = '';
  		CollectGarbage();
   }
 
   function getGarbageBin() {
   	var garbageBin = $('IELeakGarbageBin');
    if (!garbageBin) {
        garbageBin = document.createElement('DIV');
        garbageBin.id = 'IELeakGarbageBin';
        garbageBin.style.display = 'none';
        document.body.appendChild(garbageBin);
    }
    return garbageBin;
   }



var registry = new WidgetRegistry();

/* move into registry and move directly in the dom without response */
function moveup(id, widgetId) {
  var myPlaceHolder = $($(id).parentNode);
  var prevSiblings = myPlaceHolder.previousSiblings();
  if (!prevSiblings || prevSiblings.length < 1 || !prevSiblings[0].hasClassName('dropzone')) {
    Dialog.alert(
      'Dieses Element kann nicht weiter verschoben werden',
      {	className: 'alphacube',
        okLabel: 'Schlie&szlig;en',
        zIndex: 1000}
    );
    return false;
  }
  var otherPlaceHolder = myPlaceHolder.previousSiblings()[0];
  move(id, otherPlaceHolder, widgetId);
}

function movedown(id, widgetId) {
  var myPlaceHolder = $($(id).parentNode);
  var nextSiblings = myPlaceHolder.nextSiblings();
  if (!nextSiblings || nextSiblings.length < 2 || !nextSiblings[1].hasClassName('dropzone')) {
    Dialog.alert(
      'Dieses Element kann nicht weiter verschoben werden',
      {	className: 'alphacube',
        okLabel: 'Schlie&szlig;en',
        zIndex: 1000}
    );
    return false;
  }
  var otherPlaceHolder = myPlaceHolder.nextSiblings()[1];
  move(id, otherPlaceHolder, widgetId);
}

function move(id, otherPlaceHolder, widgetId) {
  var myPlaceHolder = $($(id).parentNode);
  var placeHolderId = otherPlaceHolder.id;

  if ($(id.replace('widget_', 'form_'))) {
  	var params = Form.serialize($(id.replace('widget_', 'form_')), true);
  }
  else {
  	var params = {
  		type : WindowRegistry2._pageType,
	  	id   : WindowRegistry2._pageId,
	  	widgetId : widgetId,
	  	edit : 0
  	}
  }
  
  params.placeHolder = placeHolderId;

  registry.removeWidget(id.replace('widget_', '_'));

    new Ajax.Updater(otherPlaceHolder, '/page/savePosition',
      {
        asynchronous:true,
        evalScripts:true,
        parameters: params,
        insertion: Insertion.Before,
        onSuccess: function() {
          myPlaceHolder.parentNode.removeChild(myPlaceHolder);
        }
      });
}

/* ---------------------------------------

  Ajax handling

--------------------------------------- */
Window.keepMultiModalWindow=true;
Windows.overlayShowEffectOptions = null;
Windows.overlayHideEffectOptions = null;

function createALoadingWindow() {
	if (loadingWindow)
		return;
		
	var window = new Window({className: 'alphacube', resizable: false, maximizable: false, minimizable: false, closable: false, draggable: false, hideEffect:Element.hide,
       showEffect:Element.show, width: 50, height: 50, destroyOnClose: false});
    window.setHTMLContent('<div style="text-align: center;"><img style="vertical-align: middle" src="/images/icons/loader.gif" alt="Loading..." ></div>');
    loadingWindow = window;
}
Event.observe(window, 'load', createALoadingWindow);

var loadingWindow;
var showLoading = false;

var noticeId=null;
var hasErrors = false;

function showLoadingWindow() {
   if (!loadingWindow) {
      createALoadingWindow();
    }

   if (!showLoading) {
      showLoading = true;
      loadingWindow.showCenter(true);
   } 
}

function hideLoadingWindow() {
   if (loadingWindow) {
   		showLoading = false;
   		loadingWindow.hide();
   }
}

Ajax.Responders.register({
  onCreate: function(request) {
  	if (request.options.hideIndicator) return;
  	showLoadingWindow();
  },
  
  onComplete: function(request, transport) {
    if (Ajax.activeRequestCount < 1) {
      hideLoadingWindow.defer(0.2);
    } 
		/*
	  if (404 == transport.status) {
	    location.pathname = '/urlnotfound';
	  }
	  if (500 == transport.status) {
	    location.pathname = '/errors/error500.php';
	  }
	  if (506 == transport.status) {
	    location.pathname = '/errors/unavailable.php';
	  }
	  */
  }, 

  onFailure: function(transport) {
	  hideLoadingWindow.defer(0.2);
  },

  onException: function(request, exp) {
	  hideLoadingWindow.defer(0.2);
  }
}); 

function getForm(element) {
  while(element.parentNode) {
    element = element.parentNode;
    if (element.tagName == 'FORM') {
      return $(element);
    }
  }
}


function isLoggedIn() {
	return $('login_form') == null;
}

function loginIfNot(ref, text) {
	if (!isLoggedIn()) {
		login(ref, text);
		return false;
	}
	return true;
}


/* ---------------------------------------

  Autocompleter

--------------------------------------- */
CuSoonAutocompleter = Class.create(Ajax.Autocompleter, {
	lis:   null,
	def: null,

	initialize: function($super, element, update, url, options) {
		options.frequency = options.frequency || 0.3;
		options.autoSelect = false;
		options.onShow = options.onShow || function(element, update){ 
            Position.clone(element, update, {
            	setWidth: false,
            	setHeight: false, 
            	offsetTop: element.offsetHeight
          	});
          	update.show();
      	 };
      	options.onHide = 	
      		function(element, update){ update.hide(); };
      	options.hideIndicator = options.hideIndicator || true;
      	
	
		$super(element, update, url, options);

		this.element.observe('click', this.onArrow.bind(this));
		this.element.observe('focus', this.onArrow.bind(this));
		this.element.observe('blur',  this.restoreInitValue.bind(this));
		
		this.options.minChars = 0;
		if (!options.tokens)
			this.options.tokens = [];
		this.index = -1;
		this.restoreInitValue();
	},
	
	getTokenBounds: function() {
	    return [this.element.value.length ? 0 : -1, this.element.value.length];
    },
    
    setDefault: function(def) {
    	this.def = def;
    	this.update.innerHTML = def;
    },
	
	restoreInitValue: function() {
		if (!this.element.value) {
			this.element.value = this.options.initValue;
			this.element.setStyle('color: #888888;');
		}
		else {
			this.element.setStyle('color: #000000;');
		}
	},
	
	startEditing: function() {
		if (this.element.value == this.options.initValue) {
			this.element.value = '';
		}
		this.element.setStyle('color: #000000;');
	},
	
	onArrow: function(event) {
		this.element.focus();
		this.hasFocus = true;
		this.hasChanged = false;
		this.startEditing();
		
		this.updateChoices(this.update.innerHTML); 
			
		// Event.stop(event);
	},
	
	getEntry: function(index) {
    	return this.lis[index];
    },
    
    getUpdatedChoices: function($super) {
	    if (this.getToken().length == 0 && this.def) {
	    	this.updateChoices(this.def);
	    	this.changed = true;
	    }
	    else {
	    	$super();
	    }
    },
    
    updateChoices: function(choices) {
	    if(!this.changed && this.hasFocus) {
	      this.update.innerHTML = choices;
	      Element.cleanWhitespace(this.update);
	      Element.cleanWhitespace(this.update.down());
	
	      if(this.update.getElementsByTagName('li')) {
	        this.lis = this.update.getElementsByTagName('li');
		    this.entryCount = this.lis.length;
	        
	        for (var i = 0; i < this.entryCount; i++) {
	          var entry = this.getEntry(i);
	          entry.autocompleteIndex = i;
	          this.addObservers(entry);
	        }
	      } else { 
	        this.entryCount = 0;
	      }
	
	      this.stopIndicator();
	      this.index = -1;
	      
	      if(this.entryCount==1 && this.options.autoSelect) {
	        this.selectEntry();
	        this.hide();
	      } else {
	        this.render();
	      }
	    }
	  }
});

/* ---------------------------------------

  Dynamic regions

--------------------------------------- */
function toggleContents(container) {
  $A($(container).getElementsByClassName('toggle')).each(function(item) {item.toggle();});
  return false;
}

 function addBookmark()
 {
   var url=location.href;
   var title=document.title;

   if (window.sidebar) { // Mozilla Firefox Bookmark
     window.sidebar.addPanel(title, url,"");
   }
   else if( window.external ) { // IE Favorite
     window.external.AddFavorite( url, title);
   }

   return false;
 }

/* JSONP Cross Domain Ajax Calls with Script Trick */
var JsonRPCCounter = 0;
var JsonRPCStore = {};

function jsonRpc(url, params, callback, timeout, callbackFunctionName) {
   var p = "";
   var s = document.createElement("script");
   var id = "cb" + ++JsonRPCCounter;
   if (timeout) {
      timeout = setTimeout(function() {
         jsonRpcCleanup(id, s);
         callback(null);
      }, timeout);
   }
   JsonRPCStore[id] = function(data1, data2, data3) {
      if (timeout) clearTimeout(timeout);
      callback(data1, data2, data3);
      jsonRpcCleanup(id, s);
   };
   var p = "&" + $H(params).toQueryString();
   callbackFunctionName = callbackFunctionName || 'callback';
   s.src = url + "?" + callbackFunctionName + "=JsonRPCStore." + id + p;
   document.body.appendChild(s);
}

function jsonRpcCleanup(id, s) {
   delete JsonRPCStore[id];
   setTimeout(function() { document.body.removeChild(s) }, 0);
}


