var NMUtilities = {
   
   //removes all HTML-tags
   removeHTMLTags: function (val){
       var regex = /(<([^>]+)>)/gi;
       return val.replace(regex, "");
   },
   
   //preserves <br>-tags, removes all other HTML-tags
   replaceHTMLTags: function (val){
       val = val.replace(/<br>/gi, "|break|");
       val = val.replace(/</gi, "&lt;");
       val = val.replace(/>/gi, "&gt;");
       val = val.replace("|break|", "<br>");
       return val;
   },
   
   //String in UTF-8 enkodieren
   encodeUTF8: function( s ){
    var stmp = s;
    try{
        stmp = unescape( encodeURIComponent( s ) );
    }catch(error){
        return s;
    }
    
    return stmp;
   },

   //UTF-8-String dekodieren
   decodeUTF8: function( s ){
	  var stmp = s;
	  try{
	      stmp = decodeURIComponent( escape( s ) );
	  }catch(error){
	      return s;
	  }
	  return stmp;
   },
   
   //Sowohl führende, als auch angehängte Leerzeichen werden entfernt
   trim: function(val){
 	return val.replace(/^\s+/, '').replace(/\s+$/, '');
   },
   
   //Check: Email-Adresse
   isValidEmail: function(val){
   	var regex = /^.+@.+\...+$/;
        return regex.test(val);  
   }
   
   
   /*
   function: trim(txt) {
      	for(var str='',tmp=[],y=-1,x=0;x<txt.length;x++) {
      		if(txt.charAt(x)!=" ") {
      			(tmp[((y==-1)?0:y)]==undefined)?tmp[((y==-1)?0:y)]=txt.charAt(x):tmp[((y==-1)?0:y)]+=txt.charAt(x);
      		}
      		else {
      			(tmp[((y==-1)?0:y)]!=undefined)?y++:"";
      		}
      	}
      	for(var x=0;x<tmp.length;x++) {
      		(x<tmp.length-1)?str+=tmp[x]+" ":str+=tmp[x];
      	}
      
      	return str;
   },*/
   
   /*
   //Sesson-Cookie OHNE DATUM eingeben (null), NICHT -1
   //setCookie("CookieName" , "85000", null);
   function setCookie(name, value, expires, path, domain, secure) {
   var curCookie = name + "=" + escape(value) +
   	((expires) ? "; expires=" + expires : "") +
   	((path) ? "; path=" + path : "") +
   	((domain) ? "; domain=" + domain : "") +
   	((secure) ? "; secure" : "")
   document.cookie = curCookie
   }*/
   
   /*
   function getCookieValue(name) {
   	var start = document.cookie.indexOf(name+"=");
   	var len = start+name.length+1;
   	if ((!start) && (name != document.cookie.substring(0,name.length))) return '';
   	if (start == -1) return '';
   
   	var end = document.cookie.indexOf(";",len);
   	if (end == -1) end = document.cookie.length;
   	return unescape(document.cookie.substring(len,end));
   }*/
   
   /*
   determineBasketCounterCookie: function() {
     if (Cookie.get('BasketCounter')) {
       counterValue = Cookie.get('BasketCounter');
       if (counterValue == null || counterValue == '')
         counterValue = '0';
       return counterValue;
     } else {
       return '0';
     }
   },
        
   determineLoginStatusByCookie: function() {
     if (Cookie.get('LoginCounter')) {
       loginValue = Cookie.get('LoginCounter');
       if (loginValue == null || loginValue == '')
         loginValue = 0;
       return loginValue;
     } else {
       return 0;
     }
   }
    */
   /*
   setIq: function() {
     if (!top.frames['SILENT'])
       bIqUsed = determineIqCookie();  
           
   },*/
   
   /*
   determineIqCookie: function() {
        if (Cookie.get('IqCounter')) {
          counterValue = Cookie.get('IqCounter');
          if (counterValue == null || counterValue == '')
            counterValue = false;
          counterValue = (counterValue == 'true');
          return counterValue;
        } else {
          return false;
        }
   }*/
  
   
      
};


var Voting = {
  changeRadioButton: function(id) {
  
      Voting.activateRadioButton(id);

      var params = id.split("_");

      if(params.length == 5){

	  var voting_id = params[1];
	  var order_no = params[3];
	  var new_id = "voting_" + voting_id + "_answer_";

	  for(i=1;i<99;i++){
	      if(i != order_no){
		  if($(new_id + i + "_button")) {
		      Voting.deactivateRadioButton(new_id + i + "_button");
		  } else {
		      break;
		  }
	      }
	  }

      }
  
  
  },
  deactivateRadioButton: function(id){
      if($(id) && $(id).src.indexOf("_selected")!= -1){
	  var image_src = $(id).src;
	  var image_src_ending = image_src.substring(image_src.length-4,image_src.length);
	  $(id).src = image_src.substring(0,image_src.length-13) + image_src_ending;

      }
  },
  activateRadioButton: function (id){
  
      if($(id)){

	  var image_src = $(id).src;
	  if(image_src.indexOf("_selected")== -1){
	      var image_src_ending = image_src.substring(image_src.length-4,image_src.length);
	      $(id).src = image_src.substring(0,image_src.length-4) + '_selected' + image_src_ending;
	      Voting.setOptionOrderNo(id);
	  }

      }
  },
  setOptionOrderNo: function(id){
  
      var params = id.split("_");

      if(params.length == 5){
	  var voting_id = params[1];
	  var order_no = params[3];
	  var item = $('voting_'+ voting_id + '_votingOptionOrderNo');
	  if(item){
	      item.value = order_no;

	  }
      }
  },
  showVoteButton: function(val, id){
     if(val){
     	$('voting_' + id + '_button_abstimmen_inactive').hide();
     	$('voting_' + id + '_button_abstimmen').show();
     	
     } else {
     	$('voting_' + id + '_button_abstimmen').hide();
     	$('voting_' + id + '_button_abstimmen_inactive').show();
     }
     return true;
  },
  checkVotingState: function(id){
      if($(id)){
	  $('voting_' + id + '_warning').hide();
	  var isButtonSelected = false;
	  $$('.voting_' + id + '_button').each(function(item){
	      if(item.src.indexOf('selected')!= -1) isButtonSelected = true

	  });

	  if(!isButtonSelected){
	      $('voting_' + id + '_warning').show();
	      return false;
	  }
	  return true;

      }
      return false;
  
   },
   enableAjax: function(id){
      if($('voting_' + id + '_ajax')) $('voting_' + id + '_ajax').value = "true";
   },
   doVote: function(id){
  
     $('voting_' + id + '_button_abstimmen').hide();
     $('voting_' + id + '_button_abstimmen_inactive').show();
     if(!id || !$('voting_' + id + '_form')) return true;
        Voting.enableAjax(id);

	$('voting_' + id + '_form').request({
	      method: 'post',
	      onException: function(request, exception) {
		  $('voting_' + id + '_button_abstimmen').show();
		  $('voting_' + id + '_button_abstimmen_inactive').hide();
	      },

	      onSuccess: function(request) {

		  Voting.show_voting_result(request, id);
		  //showVotingResultJSON(request, id);


	      }
	});

	return false;
   },
  
   show_voting_result: function(request, id){
           
	  res = request.responseText;

	  if($('voting_' + id + '_teaser') && res ) $('voting_' + id + '_teaser').update(res);
 	        	  
           
   },
   show_voting_result_main: function(request, id){
        
      	  res = request.responseText;
      
      	  if($('voting_' + id + '_teaser') && res ) $('voting_' + id + '_teaser').update(res);
      	  Voting.initMainResultSize(id);
      	        	  
        
   },
   show_voting_result_main789: function(request, id){
  
	  res = request.responseText;

	  if($('voting_' + id + '_teaser') && res ) $('voting_' + id + '_teaser').update(res);
	  Voting.initMain789ResultSize(id);
	  	  
  
   },
   show_voting_result_pda: function(request, id){
     
   	  res = request.responseText;
   
   	  if($('voting_' + id + '_teaser') && res ) $('voting_' + id + '_teaser').update(res);
	  Voting.initPDAResultSize(id);
   
   },
   
   initVotingMainTeaserSize: function(id){
                                                                               
                                                                               
                                                                               
       var border_header = 4;
       var border_footer = 4;

       var voting_height = $('voting_' + id).offsetHeight;

       $('voting_' + id + '_shadow').style.height = voting_height+border_header+border_footer +16 + "px";

       var bg_height = voting_height+85+border_header+border_footer +19+15+ "px";
       $('voting_' + id + '_bg').style.height = bg_height;


       $('voting_' + id + '_footer').style.top = voting_height+85+border_footer+15+ "px";

       $('voting_' + id + '_teaser').style.height = bg_height;
   },
   
   
   initMainResultSize2: function(id) {
          
          if($("main_" + id + "_result")) {
          
     
            var border_header = 4;
            var border_footer = 4;
      
            var voting_height = $('result_' + id).offsetHeight;
      
            $('result_' + id + '_shadow').style.height = voting_height+border_header+border_footer + "px";
      
            $('result_' + id + '_bg').style.height = voting_height+border_header+border_footer +19+ "px";
      
            $('result_' + id + '_footer').style.top = voting_height+border_footer+ "px";
      
          }
      },
      
   initVotingMainSize2: function(id){
     
         if($('voting_' + id)) {
   
   	  var border_header = 4;
   	  var border_footer = 4;
   
   	  var voting_height = $('voting_' + id).offsetHeight;
   
   	  $('voting_' + id + '_shadow').style.height = voting_height+border_header+border_footer +16 + "px";
   
   
   	  $('voting_' + id + '_bg').style.height = voting_height+border_header+border_footer +19+15+ "px";
   
   
   	  $('voting_' + id + '_footer').style.top = voting_height+border_footer+15+ "px";
   	  
   
         }
     
     
    },
   
   
   initMainResultSize: function(id) {
       
       if($("main_" + id + "_result")) {
       
  
         var border_header = 4;
         var border_footer = 4;
   
         var voting_height = $('result_' + id).offsetHeight;
   
         $('result_' + id + '_shadow').style.height = voting_height+border_header+border_footer + "px";
   
         $('result_' + id + '_bg').style.height = voting_height+85+border_header+border_footer +19+ "px";
   
         $('result_' + id + '_footer').style.top = voting_height+85+border_footer+ "px";
   
       }
   },
   initVotingMainSize: function(id){
  
      if($('voting_' + id)) {

	  var border_header = 4;
	  var border_footer = 4;

	  var voting_height = $('voting_' + id).offsetHeight;

	  $('voting_' + id + '_shadow').style.height = voting_height+border_header+border_footer +16 + "px";


	  $('voting_' + id + '_bg').style.height = voting_height+85+border_header+border_footer +19+15+ "px";


	  $('voting_' + id + '_footer').style.top = voting_height+85+border_footer+15+ "px";
	  

      }
  
  
    },
    initVotingMain789Size: function(id){
    
	if($('voting_' + id)) {

	    var border_header = 4;
	    var border_footer = 4;

	    var voting_height = $('voting_' + id).offsetHeight;

	    $('voting_' + id + '_shadow').style.height = voting_height+border_header+border_footer +5 + "px";

	    $('voting_' + id + '_bg').style.height = voting_height+62+border_header+border_footer +5+19+"px";

	    $('voting_' + id + '_footer').style.top = voting_height+62+border_footer+5+ "px";

	}
    
    
    },
    initMain789ResultSize: function(id){
    
	   if($("main_" + id + "_789_result")) {

	       var border_header = 4;
	       var border_footer = 4;

	       var voting_height = $('result_' + id).offsetHeight;

	       $('result_' + id + '_shadow').style.height = voting_height+border_header+border_footer + "px";

	       $('result_' + id + '_bg').style.height = voting_height+65+border_header+border_footer +19+ "px";

	       $('result_' + id + '_footer').style.top = voting_height+65+border_footer+ "px";

	   }
    
    
    },
    initVotingPDASize: function(id){
    
	    if($('voting_' + id)) {

		var border_header = 4;
		var border_footer = 4;

		var voting_height = $('voting_' + id).offsetHeight;

		$('voting_' + id + '_shadow').style.height = voting_height+border_header+border_footer + 15 + "px";

		$('voting_' + id + '_bg').style.height = voting_height+61+border_header+border_footer +30+ "px";

		$('voting_' + id + '_footer').style.top = voting_height+61+border_footer+ 15 + "px";

	    }
    
    
    },
    
    initPDAResultSize: function(id){
                    
   
	   if($("pda_" + id + "_result")) {

	       var border_header = 4;
	       var border_footer = 4;

	       var voting_height = $('result_' + id).offsetHeight;

	       $('result_' + id + '_shadow').style.height = voting_height+border_header+border_footer + "px";

	       $('result_' + id + '_bg').style.height = voting_height+61+border_header+border_footer +19+ "px";

	       $('result_' + id + '_footer').style.top = voting_height+61+border_footer+ "px";

	   }

    }
                        
    
};

var NMEffects = {
	addShadow: function (element) {
		if (element) {
			var a = new Element('div', { 'style':'position:absolute;background-color:#666;' }).setOpacity(0.3);
			var a2 = new Element('div', { 'style':'position:absolute;background-color:#666;' }).setOpacity(0.1);
			var iefix = null;
			if (Prototype.Browser.IE) {
				var version = parseFloat(navigator.appVersion.split("MSIE")[1]);
				if (version < 7 ) {
					iefix = new Element('iframe',{ 'style':'position:absolute;' }).setOpacity(0.0);
				}
			}
			
			
			element.observe("element:dimension",function() {
				if(iefix){
					$(element).insert({before:iefix});
				}
				$(element).insert({before:a}).insert({before:a2});
				a.clonePosition(element,{offsetLeft:-1,offsetTop:-1}).setStyle({"width":a.getWidth()+4,"height":a.getHeight()+4});
				a2.clonePosition(a,{offsetLeft:3,offsetTop:3});
				if (iefix) {
					iefix.clonePosition(a);
				}
			});
			element.observe("element:hide",function() {
				a.hide();
				a2.hide();
				
				if (iefix) {
					iefix.hide();
				}
			});
			element.observe("element:show",function() {
				
				
				a.show();
				a2.show();
				if (iefix) {
					iefix.show();
				}				
				element.fire("element:dimension");
				
			});
			
			if(element.visible()) {
				element.fire("element:dimension");
			}
		}
	}

};

var NMCore = {
	fixIESelect: function () {
    		if((typeof Prototype=='undefined') || 
       		   (typeof Element == 'undefined') || 
       		   (typeof Element.Methods=='undefined')) {
       		 	alert("Prototype required");
       			return;
       		} else {
       			//alert(navigator.userAgent);
       			Event.observe(window,'load',function(){
       				var select = $$('select');
       				if (select) {
       					for(var i=0;i<select.length;i++) {
       						select[i].absolutize();
       						var dimselect = select[i].getDimensions();
       						dimselect.height=19;
       						var el1 = new Element('div', {'style':'padding:1px 0px 0px 2px;border:1px solid #7F9DB9;background-color:#FFF;background-image:url(/webroot/gfx/global/selectbox_arrowdown.gif);background-repeat:no-repeat;background-position:right;color:#666;font-weight:bold;'}).update(select[i].options[0].text);
       						select[i].replace(el1);
       						el1.setStyle(dimselect);
       						
       						//var el2 = new Element('div', {'style':'position:absolute;padding:0px 0px 0px 0px;border:1px solid #7F9DB9;background-color:#FFF;color:#5E7893;font-weight:bold;'});
       						//el1.insert({after:el2});
       						//el2.clonePosition(el1,{offsetLeft:0,offsetTop:0});
       						
       						
       					}
       				}
       			});
       		}
       	}

};
//NMCore.fixIESelect();

var NMInPlaceEditor = Class.create(Ajax.InPlaceEditor,{

  
  initialize: function(element, url, options) {
    this.url = url;
    this.element = element = $(element);
    this.prepareOptions();
    this._controls = { };
    Object.extend(this.options, options || { });
    if (!this.options.formId && this.element.id) {
      this.options.formId = this.element.id + '-inplaceeditor';
      if ($(this.options.formId))
        this.options.formId = '';
    }
    if (this.options.externalControl)
      this.options.externalControl = $(this.options.externalControl);
    if (!this.options.externalControl)
      this.options.externalControlOnly = false;
    this._originalBackground = this.element.getStyle('background-color') || 'transparent';
    this.element.title = this.options.clickToEditText;
    this._boundCancelHandler = this.handleFormCancellation.bind(this);
    this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
    this._boundFailureHandler = this.handleAJAXFailure.bind(this);
    this._boundSubmitHandler = this.handleFormSubmission.bind(this);
    this._boundWrapperHandler = this.wrapUp.bind(this);
    this.registerListeners();
  },
  
  
  /*
  initialize : function($super, element, url, options) {
  
      if (!options.emptyText)        options.emptyText      = 'click to edit';
      if (!options.emptyClassName)   options.emptyClassName = 'inplaceeditor-empty';
  
      $super(element, url, options);
  
      this.checkEmpty();
  },*/
  
  /*
  checkEmpty : function() {
  	alert("t2");
      if (this.element.innerHTML.length == 0 && this.options.emptyText) {
  
        this.element.appendChild(
            new Element('span', { className : this.options.emptyClassName }).update(this.options.emptyText)
          );
      }
  
    },*/
  
   
  
  
  checkForEscapeOrReturn: function(e) {
    if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return;
    if (Event.KEY_ESC == e.keyCode)
      this.handleFormCancellation(e);
    else if (Event.KEY_RETURN == e.keyCode)
      this.handleFormSubmission(e);
  },
  createControl: function(mode, handler, extraClasses) {
    var control = this.options[mode + 'Control'];
    var text = this.options[mode + 'Text'];
    if ('button' == control) {
      var btn = document.createElement('input');
      btn.type = 'submit';
      btn.value = text;
      btn.className = 'editor_' + mode + '_button';
      if ('cancel' == mode)
        btn.onclick = this._boundCancelHandler;
      this._form.appendChild(btn);
      this._controls[mode] = btn;
    } else if ('link' == control) {
      var link = document.createElement('a');
      link.href = '#';
      link.appendChild(document.createTextNode(text));
      link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
      link.className = 'editor_' + mode + '_link';
      if (extraClasses)
        link.className += ' ' + extraClasses;
      this._form.appendChild(link);
      this._controls[mode] = link;
    } else if ('image' == control) {
    	var image = document.createElement('img');

    	if(text == 'Speichern'){
    		image.src = "/webroot/gfx/ugc/profile/speichern_02.gif";
    		
    	} else if(text == 'Abbrechen'){
    		image.src = "/webroot/gfx/ugc/profile/abbrechen_02.gif";
    		
    	}
    	image.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
    	image.className = 'editor_' + mode + '_image';
    	this._form.appendChild(image);
    	this._controls[mode] = image;
    	
      }
    
    
  },
  createEditField: function() {
    var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
    var fld;
    /*
    var editor_table = document.createElement('table');
    var editor_tr = document.createElement('tr');
    var editor_td = document.createElement('td');
    editor_table.appendChild(editor_tr);
    editor_tr.appendChild(editor_td);
    */
   
    
    if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) {
      fld = document.createElement('input');
      fld.type = 'text';
      var size = this.options.size || this.options.cols || 0;
      if (0 < size) fld.size = size;
    } else {
      fld = document.createElement('textarea');
      fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows);
      fld.cols = this.options.cols || 40;
    }
    fld.name = this.options.paramName;
    fld.value = text; // No HTML breaks conversion anymore
    fld.className = 'editor_field';
    if (this.options.submitOnBlur)
      fld.onblur = this._boundSubmitHandler;
    this._controls.editor = fld;
    if (this.options.loadTextURL)
      this.loadExternalText();
    /*  
    editor_td.appendChild(this._controls.editor);
    this._form.appendChild(this.editor_table);
    */  
    this._form.appendChild(this._controls.editor);
  },
  createForm: function() {
    var ipe = this;
    function addText(mode, condition) {
      var text = ipe.options['text' + mode + 'Controls'];
      if (!text || condition === false) return;
      ipe._form.appendChild(document.createTextNode(text));
    };
    this._form = $(document.createElement('form'));
    this._form.id = this.options.formId;
    this._form.addClassName(this.options.formClassName);
    this._form.onsubmit = this._boundSubmitHandler;
    this.createEditField();
    if ('textarea' == this._controls.editor.tagName.toLowerCase())
      this._form.appendChild(document.createElement('br'));
    if (this.options.onFormCustomization)
      this.options.onFormCustomization(this, this._form);
    addText('Before', this.options.okControl || this.options.cancelControl);
    this.createControl('ok', this._boundSubmitHandler);
    addText('Between', this.options.okControl && this.options.cancelControl);
    this.createControl('cancel', this._boundCancelHandler, 'editor_cancel');
    addText('After', this.options.okControl || this.options.cancelControl);
  },
  destroy: function() {
    if (this._oldInnerHTML)
      this.element.innerHTML = this._oldInnerHTML;
    this.leaveEditMode();
    this.unregisterListeners();
  },
  enterEditMode: function(e) {
    if (this._saving || this._editing) return;
    this._editing = true;
    this.triggerCallback('onEnterEditMode');
    if (this.options.externalControl)
      this.options.externalControl.hide();
    this.element.hide();
    this.createForm();
    this.element.parentNode.insertBefore(this._form, this.element);
    if (!this.options.loadTextURL)
      this.postProcessEditField();
    if (e) Event.stop(e);
  },
  enterHover: function(e) {
    if (this.options.hoverClassName)
      this.element.addClassName(this.options.hoverClassName);
    if (this._saving) return;
    this.triggerCallback('onEnterHover');
  },
  
  
  getText: function() {
  
    return this.element.innerHTML;
  },
  
  /*
  getText : function($super) {
    
        if (empty_span = this.element.select('.' + this.options.emptyClassName).first()) {
          empty_span.remove();
        }
    	alert("t1");
        return $super();
    
  },
  
  onComplete : function($super, transport) {
      
          this.checkEmpty();
          return $super(transport);
      
  },*/
  
  handleAJAXFailure: function(transport) {
    this.triggerCallback('onFailure', transport);
    if (this._oldInnerHTML) {
      this.element.innerHTML = this._oldInnerHTML;
      this._oldInnerHTML = null;
    }
  },
  handleFormCancellation: function(e) {
    this.wrapUp();
    if (e) Event.stop(e);
  },
  handleFormSubmission: function(e) {
    var form = this._form;
    var value = $F(this._controls.editor);
    this.prepareSubmission();
    var params = this.options.callback(form, value) || '';
    if (Object.isString(params))
      params = params.toQueryParams();
    params.editorId = this.element.id;
    if (this.options.htmlResponse) {
      var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions);
      Object.extend(options, {
        parameters: params,
        encoding: 'UTF-8',
        onComplete: this._boundWrapperHandler,
        onFailure: this._boundFailureHandler
      });
      new Ajax.Updater({ success: this.element }, this.url, options);
    } else {
      var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
      Object.extend(options, {
        parameters: params,
        encoding: 'UTF-8',
        onComplete: this._boundWrapperHandler,
        onFailure: this._boundFailureHandler
      });
      new Ajax.Request(this.url, options);
    }
    if (e) Event.stop(e);
  },
  leaveEditMode: function() {
    this.element.removeClassName(this.options.savingClassName);
    this.removeForm();
    this.leaveHover();
    this.element.style.backgroundColor = this._originalBackground;
    this.element.show();
    if (this.options.externalControl)
      this.options.externalControl.show();
    this._saving = false;
    this._editing = false;
    this._oldInnerHTML = null;
    this.triggerCallback('onLeaveEditMode');
  },
  leaveHover: function(e) {
    if (this.options.hoverClassName)
      this.element.removeClassName(this.options.hoverClassName);
    if (this._saving) return;
    this.triggerCallback('onLeaveHover');
  },
  loadExternalText: function() {
    this._form.addClassName(this.options.loadingClassName);
    this._controls.editor.disabled = true;
    var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
    Object.extend(options, {
      parameters: 'editorId=' + encodeURIComponent(this.element.id),
      onComplete: Prototype.emptyFunction,
      onSuccess: function(transport) {
        this._form.removeClassName(this.options.loadingClassName);
        var text = transport.responseText;
        if (this.options.stripLoadedTextTags)
          text = text.stripTags();
        this._controls.editor.value = text;
        this._controls.editor.disabled = false;
        this.postProcessEditField();
      }.bind(this),
      onFailure: this._boundFailureHandler
    });
    new Ajax.Request(this.options.loadTextURL, options);
  },
  postProcessEditField: function() {
    var fpc = this.options.fieldPostCreation;
    if (fpc)
      $(this._controls.editor)['focus' == fpc ? 'focus' : 'activate']();
  },
  prepareOptions: function() {
    this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions);
    Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks);
    [this._extraDefaultOptions].flatten().compact().each(function(defs) {
      Object.extend(this.options, defs);
    }.bind(this));
  },
  prepareSubmission: function() {
    this._saving = true;
    this.removeForm();
    this.leaveHover();
    this.showSaving();
  },
  registerListeners: function() {
    this._listeners = { };
    var listener;
    $H(Ajax.InPlaceEditor.Listeners).each(function(pair) {
      listener = this[pair.value].bind(this);
      this._listeners[pair.key] = listener;
      if (!this.options.externalControlOnly)
        this.element.observe(pair.key, listener);
      if (this.options.externalControl)
        this.options.externalControl.observe(pair.key, listener);
    }.bind(this));
  },
  removeForm: function() {
    if (!this._form) return;
    this._form.remove();
    this._form = null;
    this._controls = { };
  },
  showSaving: function() {
    this._oldInnerHTML = this.element.innerHTML;
    this.element.innerHTML = this.options.savingText;
    this.element.addClassName(this.options.savingClassName);
    this.element.style.backgroundColor = this._originalBackground;
    this.element.show();
  },
  triggerCallback: function(cbName, arg) {
    if ('function' == typeof this.options[cbName]) {
      this.options[cbName](this, arg);
    }
  },
  unregisterListeners: function() {
    $H(this._listeners).each(function(pair) {
      if (!this.options.externalControlOnly)
        this.element.stopObserving(pair.key, pair.value);
      if (this.options.externalControl)
        this.options.externalControl.stopObserving(pair.key, pair.value);
    }.bind(this));
  },
  wrapUp: function(transport) {
    this.leaveEditMode();
    // Can't use triggerCallback due to backward compatibility: requires
    // binding + direct element
    this._boundComplete(transport, this.element);
  }
});

Object.extend(Ajax.InPlaceEditor.prototype, {
  dispose: Ajax.InPlaceEditor.prototype.destroy
});

var Cookie = {
  set: function(name, value, daysToExpire, path, domain, secure) {
    var expire = '';
    
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }   
	path = path ? "; path=" + path : "";
	domain = domain ? "; domain=" + domain : "";
	secure = secure ? "; secure=" : "";
	    
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire + path + domain + secure );
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') === '1');
  }
};

