/**
*
*	NMUtilities
*
**/
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);  
   }
   
   
};



/**
*
*	NMInPlaceEditor
*
**/
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();
  },
  
  
  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;
  },
  
  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
});



/**
*
*	Cookie
*
**/
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');
  }
};



/**
*
*	Ugc
*
**/
var Ugc = { 
  Version: '0.1',
  QUICK_LOGIN_ON: true,
  
  load: function() {
     
    	js_files = [];
    	
    	for(i=0; i<js_files.length;i++){
    	    document.write('<script src="/is-bin/intershop.static/WFS/BC-ZR-Site/-/de_DE/src/js/' + js_files[i] +
	    	'" type="text/javascript"><\/script>');
    	}

  }
}

Ugc.load();



/**
*
*	ModalDialog
*
**/
var isMDActive = false;
 
function initModalDialog() {
	
}


function activateModalDialog(){
	isMDActive = true;
}

/**
 * Opens a modal window
 * @param {String} content HTML content
 * @param {Object} params
 */
var ModalDialog = function()
{
  var title = "";
  //var params = {width:'294',height:'313',use_fade:'true',use_resize:'true'};
  var params = {use_fade:'true',use_resize:'true'};

  /* public methods */
  var _pub = {
    
    //close_label: 'Close',
    
    show: function(id, given_params){
      
      if(checkQuickLogin()){   
      	 _pub.hide();
         if( id.indexOf('#') == -1) id = '#' + id;
         //checkParams(given_params);
         iBox.showURL(id, title, given_params);
      } 
    },
    
    showText: function(text, given_params){
    	if(checkQuickLogin()){   
	   _pub.hide();
	   //checkParams(given_params);
	   iBox.show(text, title, params);
    	}
    },
    
    hide: function(){
    	if(checkQuickLogin()){  
		iBox.hide();
	}
    }
    
       
  };


  var checkQuickLogin = function()
  {
  
    
    if(!Ugc.QUICK_LOGIN_ON|| !isMDActive){
    	return false;
    }
    
    return true;

  }
    
  /* private methods */
  var checkParams = function(given_params)
  {
  	if(given_params){
  	
            if (given_params.width)     params.width = given_params.width;
	    if (given_params.height)    params.height = given_params.height;
	    if (given_params.fade_in)   params.fade_in = given_params.fade_in;
	    if (given_params.can_resize)params.can_resize = given_params.can_resize;
	    if (given_params.title)     title = given_params.title;
	    
  	}

  }
  
  return _pub;
}();
initModalDialog();
Event.observe(window, "load", activateModalDialog);

	function setSiteCatalystCommons() {
		var tsc1 = s.getQueryParam("tsc1");
		if (tsc1) s.eVar16 = tsc1;
		var tsc2 = s.getQueryParam("tsc2");
		if (tsc2) s.eVar17 = tsc2;
	}
	
	function trackTwoPricesLayerForSC() {
		setSiteCatalystCommons();
		Tracking.track({
	   		pageName: 'Vorteilskommunikation_2',
	   		hier1:'Vorteilskommunikation',
	   		channel:'Vorteilskommunikation',
	   		server:'http://www.derclub.de'
   		});
	}
	
	function trackConversionLayerForSC() {
		setSiteCatalystCommons();
	   	Tracking.track({
	   		pageName: 'Vorteilskommunikation_3',
	   		hier1:'Vorteilskommunikation',
	   		channel:'Vorteilskommunikation',
	   		server:'http://www.derclub.de',
	   		events:'event17'
   		});
 	}
