/**
* JavaScript functions for cookiehandling
*
* @package    StWD
* @access	  public
* @author	  Dominique Stender <dstender@st-webdevelopment.de?>
* @copyright  2004 (Dominique Stender); All rights reserved
* @version    1.0.0
*/

  /**
  * Sets a cookie
  *
  * @param string name Name of the cookie
  * @param string value Value of the cookie
  * @param string expired Time when the cookie will expire
  * @param string path path for which the cookie is valid
  * @param string domain domain for which the cookie is valid
  * @param string secure flag weather the cookie is SSL enabled or not
  * @return void
  */
  function cookie_set(name, value, expires, path, domain, secure) {
    var cur_cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
    document.cookie = cur_cookie;
  } // end: function  cookie_set()



  /**
  * retrieves the contents of a cookie
  *
  * @param string name Name of the cookie
  * @return mixed string containing the cookies value, NULL if the cookie does not exist
  */
  function cookie_get(name) {
    var dc      = document.cookie;
    var prefix  = name + "=";
    var begin   = dc.indexOf("; " + prefix);

    if (begin == -1) {
      begin = dc.indexOf(prefix);

      if (begin != 0) {
        return null;
      } // end: if
    } else {
      begin += 2;
    } // end: if
    var end = document.cookie.indexOf(";", begin);

    if (end == -1) {
      end = dc.length;
    } // end: if

    return unescape(dc.substring(begin + prefix.length, end));
  } // end: function cookie_get()


  /**
  * removes a cookie
  *
  * @param string name Name of the cookie
  * @param path path for which the cookie is valid
  * @param string domain domain for which the cookie is valid
  * @return void
  */
  function cookie_delete(name, path, domain) {
    if (get_cookie(name)) {
      document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    } // end: if
  } // end: function cookie_delete()



  /**
  * Minor fixes for dates
  *
  * @param date an instance of the Date object
  * @return void
  */
  function fix_date(date) {
    var base = new Date(0);
    var skew = base.getTime();

    if (skew > 0) {
      date.setTime(date.getTime() - skew);
    } // end: if
  } // end: function fix_date()

/*
 * function.js
 *
 * The content of this file is (c) 2003 - 2007 dmc
 * digital media center GmbH
 * All rights reserved
 *
 * This software is the confidential and proprietary
 * information of dmc digital media center GmbH.
 *
 */


/**
 * global functions used by many extensions
 *
 * $Id: functions.js 12259 2009-06-15 04:12:42Z dst $
 */

	/**
	* flag to prevent double submits by doubleclicks on buttons
	*/
	var doubleclickFormSubmitFlag = false;

	/**
	* performs a form submit of the form defined by ctype and uid
	* and prevents a double click form submit
	*
	* @access public
	* @param  ctype    the name of the extension
	* @param  uid      the uid of the pageelement
	* @return void
	*/
	function doubleclickCheckFormSubmit(ctype, uid) {
		var form			= document.getElementById(ctype + '[' + uid + ']' + '[form]');

		if (doubleclickFormSubmitFlag == false) {
			if (form) {
				doubleclickFormSubmitFlag = true;
				form.submit();
			} // end: if
		} // end: if
	} // end: function

	/**
	* Change the value of the object with the given id
	*
	* @access	public
	* @param  	id    		the id of the form element to get changed
	* @param  	newValue    the new value for the form element to get changed
	* @return	boolean		result of the change
	*/
	function changeFormElementvalue(id, newValue) {
		var returnValue		= false;
		var formElement		= document.getElementById(id);

		if (formElement) {
			formElement.value = newValue;
			returnValue = true;
		} // end: if

		return returnValue;
	} // end: if

	/**
	* Trigger "needs cookie" warning in layer.
	*
	* @access public
	* @return void
	*/
	function cookieWarning(cookieName, getName, warnText) {
		var cookieSessionId = cookie_get(cookieName);
		var myDiv 			= false;

		if (typeof document.getElementById('mb3HeaderWarnings') == 'object') {
			myDiv = document.getElementById('mb3HeaderWarnings');

			if (!cookieSessionId
				&& document.location.href.indexOf(getName + '=') == -1) {

				myDiv.innerHTML 			= warnText;
				myDiv.style['visibility']	= 'visible';
				myDiv.style['display']		= 'block';
			} // end: if
		}
	} // end: function

	/**
	* Redirects the user if no session cookie is set and URL-based sessionIds are
	* allowed within the system.
	*
	* @access public
	* @return void
	*/
	function noCookieRedirect(cookieName, getName, sessionId) {
		var cookieSessionId = cookie_get(cookieName);
		var paramAppend		= '&';
		var redirectString	= getName + '=' + sessionId;

		if (cookieSessionId == null) {
			// no cookie set in browser

			// fix appender-char if no params exist
			if (document.location.href.indexOf('?') == -1) {
				// appended & because typo3 has a small bug
				// if there is no 'id=' in the query typo3 thinks that ftu=... is the id
				paramAppend = '?&';
			}

			// redirect to self with url-param
			document.location.href = document.location.href + paramAppend + redirectString;
		} // end: if
	} // end: function

	var dmcOnloadFuncs = new Array();
	/**
	* calls specified functions for the body onLoad Event
	* the function which wants to be called, adds itself to an array and than it gets called
	* current function calls:
	* __utmSetTrans() - send the Google Analytics Form @ the basket checkout (wk step6) - according global variable: utmTrans
	* __initZoom() - initiate the zoom-layer-script - according global variable: initZoom
	* __foofoo() - sample for further function calls  - according global variable: foofoo
	*
	* @access	public
	* @return	void
	*/
	function dmcOnLoad() {

		for(var i=0; i<dmcOnloadFuncs.length; i++) {

			if (typeof dmcOnloadFuncs[i] == 'function') {
				dmcOnloadFuncs[i]();
			}
		}
	} // end: function

	/**
	*
	* @access public
	* @param  func
	* @return void
	*/
	function addOnloadFunction(func) {
		if (typeof func == 'function') {
			dmcOnloadFuncs.push(func);
		}
	} // end: function

	/**
	*
	* @access public
	* @param  url
	* @param  name
	* @param  parameter
	* @return popuphandler
	*/
	function openWindow(url, name, parameter) {
		// Wenn ein Parameter uebergeben wird --> diesen uebernehmen
		if (parameter) {
			size = parameter;
		}

		var popuphandler = window.open(url,name,size);
		popuphandler.window.focus();

		return popuphandler;
	} // end: function

	/**
	*
	* @access public
	* @param  url
	* @param  name
	* @param  parameter
	*/
	function openJQueryPopupWindow(url, name, parameter) {
				
		name	 = '<span style="font-size:17px;font-weight:bold">'+name+'</span>';
		popupurl = url+"?TB_iframe=true&";
		
		// Wenn ein Parameter uebergeben wird --> diesen uebernehmen
		if (parameter) {
			size = parameter.replace(/\,/g, "&");
			popupurl = url+"?TB_iframe=true&"+size;
		}

		tb_show(name, popupurl, false);

	} // end: function


	/*
	Copyright (c) 2005 JSON.org

	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 Software shall be used for Good, not Evil.

	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.
	*/

	var JSON = {
		org: 'http://www.JSON.org',
		copyright: '(c)2005 JSON.org',
		license: 'http://www.crockford.com/JSON/license.html',

		stringify: function (arg) {
	    	var c, i, l, s = '', v;
	    	var numeric = true;

	    	switch (typeof arg) {
	    		case 'object':
	      			if (arg) {
	        			if(Array.prototype.isPrototypeOf(arg)){
	          			// do a test whether all array keys are numeric
	          				for (i in arg) {
	            				if (isNaN(i) || !isFinite(i)) {
	              					numeric = false;
	              					break;
	            				} // end: if
	          				} // end: for

	          				if (numeric == true) {
	            				for (i = 0; i < arg.length; ++i) {
	              					if (typeof arg[i] != 'undefined') {
	                					v = this.stringify(arg[i]);
	                					if (s) {
	                  						s += ',';
	                					} // end: if
	                					s += v;
	              					} else {
	                					s += ',null';
	              					} // end: if
	            				} // end: for
	            				return '[' + s + ']';
	          				} else {
	            				for (i in arg) {
	                				v = arg[i];
	                				if (typeof v != 'undefined' && typeof v != 'function') {
	                  					v = this.stringify(v);
	                  					if (s) {
	                    					s += ',';
	                  					}
	                  					s += this.stringify(i) + ':' + v;
	                				} // end: if
	            				} // end: for
	            				// return as object
	            				return '{' + s + '}';
	          				} // end: if
	        			} else if (typeof arg.toString != 'undefined') {
	          				for (i in arg) {
	            				v = arg[i];
	            				if (typeof v != 'undefined' && typeof v != 'function') {
	              					v = this.stringify(v);
	              					if (s) {
	                					s += ',';
	              					} // end: if
	              					s += this.stringify(i) + ':' + v;
	            				} // end: if
	          				} // end: for
	          				return '{' + s + '}';
	        			} // end: if
	      			} // end: if
	      			return 'null';

				case 'number':
	      			return isFinite(arg) ? String(arg) : 'null';

				case 'string':
			      	l = arg.length;
					s = '"';
	      			for (i = 0; i < l; i += 1) {
	        			c = arg.charAt(i);
	        			if (c >= ' ') {
	          				if (c == '\\' || c == '"') {
	            				s += '\\';
	          				} // end: if
	          				s += c;
			        	} else {
	          				switch (c) {
	            				case '\b':
	              					s += '\\b';
	              					break;
	            				case '\f':
	              					s += '\\f';
	              					break;
	            				case '\n':
	              					s += '\\n';
	              					break;
	            				case '\r':
	              					s += '\\r';
	              					break;
	            				case '\t':
	              					s += '\\t';
	              					break;
	            				default:
	              					c = c.charCodeAt();
	              					s += '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
	          				} // end: if
	        			} // end: if
	      			} // end: for
	      			return s + '"';

				case 'boolean':
	      			return String(arg);

	   			default:
	      			return 'null';
	    	} // end: switch
	  	},

		parse: function (text) {
	    	var at = 0;
	    	var ch = ' ';

	    	function error(m) {
	      		throw {
	        		name: 'JSONError',
	        		message: m,
	        		at: at - 1,
	        		text: text
	      		};
	    	} // end: function

	    	function next() {
	      		ch = text.charAt(at);
	      		at += 1;
	      		return ch;
	    	} // end: function

	    	function white() {
	      		while (ch != '' && ch <= ' ') {
	        		next();
	      		} // end: while
	    	} // end: function

	    	function str() {
	      		var i, s = '', t, u;

	      		if (ch == '"') {
					outer:      while (next()) {
	          			if (ch == '"') {
	            			next();
	            			return s;
	          			} else if (ch == '\\') {
	            			switch (next()) {
	            				case 'b':
	              					s += '\b';
	              					break;
	            				case 'f':
	              					s += '\f';
	              					break;
	            				case 'n':
	              					s += '\n';
	              					break;
	            				case 'r':
	              					s += '\r';
	              					break;
	            				case 't':
	              					s += '\t';
	              					break;
	            				case 'u':
	              					u = 0;
	              					for (i = 0; i < 4; i += 1) {
	                					t = parseInt(next(), 16);
	                					if (!isFinite(t)) {
	                  						break outer;
	                					} // end: if
	                					u = u * 16 + t;
	              					} // end: for
	              					s += String.fromCharCode(u);
	              					break;
	            				default:
	              					s += ch;
	            			} // end: switch
	          			} else {
	            			s += ch;
	          			} // end: if
	        		} // end: while
	      		} // end: if
	      		error("Bad string");
	    	} // end: function

	    	function arr() {
	      		var a = [];

	      		if (ch == '[') {
	        		next();
	        		white();
	        		if (ch == ']') {
	          			next();
	          			return a;
	        		} // end: if
	        		while (ch) {
	          			a.push(val());
	          			white();
	          			if (ch == ']') {
	            			next();
	            			return a;
	          			} else if (ch != ',') {
	            			break;
	          			} // end: if
	          			next();
	          			white();
	        		} // end: while
	      		} // end: if
	      		error("Bad array");
	    	} // end: function

	    	function obj() {
	      		var k, o = {};

	      		if (ch == '{') {
	        		next();
	        		white();
	        		if (ch == '}') {
	          			next();
	          			return o;
	        		} // end: if
	        		while (ch) {
	          			k = str();
	          			white();
	          			if (ch != ':') {
	            			break;
	          			}
	          			next();
	          			o[k] = val();
	          			white();
	          			if (ch == '}') {
	            			next();
	            			return o;
	          			} else if (ch != ',') {
	            			break;
	          			} // end: if
	          			next();
	          			white();
	        		} // end: while
	      		} // end: if
	      		error("Bad object");
	    	} // end: function

	    	function assoc() {
	      		var k, a = [];

	      		if (ch == '<') {
	        		next();
	        		white();
	        		if (ch == '>') {
	          			next();
	          			return a;
	        		}
	        		while (ch) {
	          			k = str();
	          			white();
	          			if (ch != ':') {
	            			break;
	          			} // end: if
	          			next();
	          			a[k] = val();
	          			white();
	          			if (ch == '>') {
	            			next();
	            			return a;
	          			} else if (ch != ',') {
	            			break;
	          			} // end: if
	          			next();
	          			white();
	        		} // end: while
	      		} // end: if
	      		error("Bad associative array");
	    	} // end: function

	    	function num() {
	      		var n = '', v;

		  		if (ch == '-') {
	        		n = '-';
	        		next();
	      		} // end: if
	      		while (ch >= '0' && ch <= '9') {
	        		n += ch;
	        		next();
	      		} // end: while
	      		if (ch == '.') {
	        		n += '.';
	        		while (next() && ch >= '0' && ch <= '9') {
	          			n += ch;
	        		} // end: while
	      		} // end: if
	      		if (ch == 'e' || ch == 'E') {
	        		n += 'e';
	        		next();
	        		if (ch == '-' || ch == '+') {
	          			n += ch;
	          			next();
	        		} // end: if
	        		while (ch >= '0' && ch <= '9') {
	          			n += ch;
	          			next();
	        		} // end: while
	      		} // end: if
	      		v = +n;
	      		if (!isFinite(v)) {
	        		error("Bad number");
	      		} else {
	        		return v;
	      		} // end: if
	    	} // end: function

	    	function word() {

			  	switch (ch) {
	        		case 't':
	          			if (next() == 'r' && next() == 'u' && next() == 'e') {
	            			next();
	            			return true;
	          			} // end: if
	          			break;
	        		case 'f':
	          			if (next() == 'a' && next() == 'l' && next() == 's' &&
	              			next() == 'e') {
	            			next();
	            			return false;
	          			} // end: if
	          			break;
	        		case 'n':
	          			if (next() == 'u' && next() == 'l' && next() == 'l') {
	            			next();
	            			return null;
	          			} // end: if
	          			break;
	      		} // end: switch
	      		error("Syntax error");
	    	} // end: function

	    	function val() {

		  		white();
	      		switch (ch) {
	        		case '{':
	          			return obj();
	        		case '[':
	          			return arr();
	        		case '<':
	          			return assoc();
	        		case '"':
	          			return str();
	        		case '-':
	          			return num();
	        		default:
	          			return ch >= '0' && ch <= '9' ? num() : word();
	      		} // end: switch
	    	} // end: function

	    	return val();
	  	}
	};




/*
 * function.js
 *
 * The content of this file is (c) 2003 - 2007 dmc
 * digital media center GmbH
 * All rights reserved
 *
 * This software is the confidential and proprietary
 * information of dmc digital media center GmbH.
 *
 */


/**
 * tooltip methods for the newsletter extension
 *
 * $Id: functions.js 12160 2009-06-12 06:42:20Z dst $
 */

var mouseX 			= 0;
var mouseY 			= 0;
var tooltip 		= null;

/**
*
* @access public
* @param  e
* @return void
*/
function getMouseXY(e) {

	if (document.all) {
		mouseX = window.event.x + document.body.scrollLeft;
		mouseY = window.event.y + document.body.scrollTop;

	} else {
		var Element = e.target;

		var CalculatedTotalOffsetLeft 	= 0;
		var CalculatedTotalOffsetTop 	= 0;
		while (Element.offsetParent)
		{
			CalculatedTotalOffsetLeft = Element.offsetLeft;
			CalculatedTotalOffsetTop = Element.offsetTop;
			Element = Element.offsetParent;
		} ;

		mouseX = e.pageX - CalculatedTotalOffsetLeft;
		mouseY = e.pageY - CalculatedTotalOffsetTop;
	} // end: if
} // end: function

/**
*
* @access public
* @param  x
* @param  y
* @return void
*/
function updateTooltip(x, y) {

	if (tooltip != null) {
		tooltip.style.left	= (x + 10) + 'px';
		tooltip.style.top 	= (y + 10) + 'px';
	} // end: if
} // end: function

/**
*
* @access public
* @param  id
* @return void
*/
function showTooltip(id) {
	tooltip = document.getElementById(id);

	if (tooltip.innerHTML != '') {
		tooltip.style.display 		= 'block';
		tooltip.style.visibility	= 'visible';
	} // end: if
} // end: function

/**
*
* @access public
* @return void
*/
function hideTooltip() {
	tooltip.style.display 		= 'none';
	tooltip.style.visibility	= 'hidden';

	tooltip = null;
} // end: function


var  target_url = "";
var  target_urls = {}; 

/**
 * 
 *  change newsletter action
 * @param ctype
 * @param uid
 * @return
 */
function changeAction(ctype, uid){
	var elem =  jQuery('#newslettermode');
	var form= document.getElementById(ctype + '_' + uid + '_' + 'form'); 
	var external_link = false;
	
	if (elem){
		switch(elem.val()){
		   case 'n':
			    target_url = target_urls['subscribe'];
			    
			    break;
			case 'w':
				 target_url =  target_urls['recommendation'];
		    	break;

 			case 'c':
 				 target_url = target_urls['datachange'];
	    		break;

	     	case 'x':
	    	 	target_url = target_urls['unsubscribe'];
			    break;
		
	     	case 'v':
	    	 	target_url = target_urls['lastnewsletterurl'];
	    	 	external_link = true;
	    	 	break;
		} // switch
		
		if (target_url.length > 0){
			if (external_link){
				// create new window for external link
				window.open(target_url);
				return false;
			}else{
				form.action = target_url;
				form.submit();
			}
		} //if
	} //if
} //if

function displayMe(box){
	if(box == 1){
		Delete_Cookie('nlSwitch');
		Set_Cookie('nlSwitch', '1');
		$("#main .dmc_mb3_newsletter_subscribe").css({'display':'block'});
		$("#nlSelBox #nlSel_01").addClass('active');
		
		if($('#nlSelBox #nlSel_02').hasClass('active')) {
			$("#nlSelBox #nlSel_02").removeClass('active');
			$("#main .dmc_mb3_newsletter_recommend").css({'display':'none'});
		}
		
		if($('#nlSelBox #nlSel_03').hasClass('active')) {
			$("#nlSelBox #nlSel_03").removeClass('active');
			$("#main .dmc_mb3_newsletter_change").css({'display':'none'});
		}
		
		if($('#nlSelBox #nlSel_04').hasClass('active')) {
			$("#nlSelBox #nlSel_04").removeClass('active');
			$("#main .dmc_mb3_newsletter_unsubscribe").css({'display':'none'});
		}
		
	}else if(box == 2){
		Delete_Cookie('nlSwitch');
		Set_Cookie('nlSwitch', '2');
		if($('#nlSelBox #nlSel_01').hasClass('active')) {
			$("#nlSelBox #nlSel_01").removeClass('active');
			$("#main .dmc_mb3_newsletter_subscribe").css({'display':'none'});
		}
		
		$("#main .dmc_mb3_newsletter_recommend").css({'display':'block'});
		$("#nlSelBox #nlSel_02").addClass('active');
		
		if($('#nlSelBox #nlSel_03').hasClass('active')) {
			$("#nlSelBox #nlSel_03").removeClass('active');
			$("#main .dmc_mb3_newsletter_change").css({'display':'none'});
		}
		
		if($('#nlSelBox #nlSel_04').hasClass('active')) {
			$("#nlSelBox #nlSel_04").removeClass('active');
			$("#main .dmc_mb3_newsletter_unsubscribe").css({'display':'none'});
		}
		
	}else if(box == 3){
		Delete_Cookie('nlSwitch');
		Set_Cookie('nlSwitch', '3');
		if($('#nlSelBox #nlSel_01').hasClass('active')) {
			$("#nlSelBox #nlSel_01").removeClass('active');
			$("#main .dmc_mb3_newsletter_subscribe").css({'display':'none'});
		}
		
		if($('#nlSelBox #nlSel_02').hasClass('active')) {
			$("#nlSelBox #nlSel_02").removeClass('active');
			$("#main .dmc_mb3_newsletter_recommend").css({'display':'none'});
		}
		
		$("#main .dmc_mb3_newsletter_change").css({'display':'block'});
		$("#nlSelBox #nlSel_03").addClass('active');
		
		if($('#nlSelBox #nlSel_04').hasClass('active')) {
			$("#nlSelBox #nlSel_04").removeClass('active');
			$("#main .dmc_mb3_newsletter_unsubscribe").css({'display':'none'});
		}
		
	}else if(box == 4){
		Delete_Cookie('nlSwitch');
		Set_Cookie('nlSwitch', '4');
		if($('#nlSelBox #nlSel_01').hasClass('active')) {
			$("#nlSelBox #nlSel_01").removeClass('active');
			$("#main .dmc_mb3_newsletter_subscribe").css({'display':'none'});
		}
		
		if($('#nlSelBox #nlSel_02').hasClass('active')) {
			$("#nlSelBox #nlSel_02").removeClass('active');
			$("#main .dmc_mb3_newsletter_recommend").css({'display':'none'});
		}
		
		if($('#nlSelBox #nlSel_03').hasClass('active')) {
			$("#nlSelBox #nlSel_03").removeClass('active');
			$("#main .dmc_mb3_newsletter_change").css({'display':'none'});
		}
		
		$("#main .dmc_mb3_newsletter_unsubscribe").css({'display':'block'});
		$("#nlSelBox #nlSel_04").addClass('active');
	}
}


/**************************** SET COOKIE ********************************/

function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

// var path = '/';
/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

// alert('Name: '+name+', Value: '+value+', Expires: '+expires+', Path: '+path+', Domain: '+domain+', Secure: '+secure);

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );

}



/**************************** GET COOKIE ********************************/

function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}



/**************************** DELETE COOKIE ********************************/

function Delete_Cookie( name, path, domain ) {
if ( Get_Cookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


	var dmc_mb3_product_pi1mediaActive	= '';
	var dmc_mb3_product_pi1mediaIndex	= 0;
	var stockTypeCode_soldOut = 3;
	
	var whitelistTypes = new Array();
	whitelistTypes['Color'] = 'Color';
	whitelistTypes['Size'] = 'Size';
	
	var hideComponentSizeNotCombination = new Array();
	hideComponentSizeNotCombination['Size'] = 'Size';
	
	function productToggle(uid, id, imageNum, state) {
		dmc_mb3_product_pi1mediaIndex = imageNum;

		/* gather necessary objects */
		var mainImage	= document.getElementById('dmc_mb3_product_pi1' + uid + 'MainImage');
		var toggleImage	= document.getElementById('dmc_mb3_product_pi1' + uid + 'Product' + id + 'Opener');
		var productBody	= document.getElementById('dmc_mb3_product_pi1' + uid + 'Product' + id + 'Body');

		/* if state is 1 or 0, transform it to the other
			(user supplies target state, switch statement checks for current state */
		if (state == 1 || state == 0) {
			state = (state + 1) % 2;

		} else if (productConf[uid][id]) {
			state = productConf[uid][id]['state'];
		} /* end: if */

		if (mainImage) {
			switch (state) {
				case 0:

					if (productConf[uid][id]['large'][imageNum]) {
						mainImage.src					= productConf[uid][id]['large'][imageNum];

						/* handle grey activity indicator below thumbnails */
						var oldActive	= false;
						var newActive	= document.getElementById('dmc_mb3_product_pi1' + uid + id + imageNum + 'mediaActive');

						if (dmc_mb3_product_pi1mediaActive != '') {
							oldActive	= document.getElementById(dmc_mb3_product_pi1mediaActive);
						} /* end: if */

						if (oldActive) {
							gfxToggle(oldActive, 'clear.gif', 'but_detail_thumb_on.gif');
						} /* end: if */

						if (newActive) {
							gfxToggle(newActive, 'clear.gif', 'but_detail_thumb_on.gif');
							dmc_mb3_product_pi1mediaActive = 'dmc_mb3_product_pi1' + uid + id + imageNum + 'mediaActive';
						} /* end: if */

					} else if (productConf[uid][id]['large']['default']) {
						mainImage.src	= productConf[uid][id]['large']['default'];
					} /* end: if */

					if (toggleImage) {
						toggleImage.src					= dmc_mb3_product_pi1ToggleImageOff;
					} /* end: if */

					if (productBody) {
						productBody.className			= 'productBodyVisible';
					} /* end: if */

					if (typeof productConf[uid][id]['state'] != undefined) {
						productConf[uid][id]['state']	= 1;
					} /* end: if */
					break;

				case 1:
					if (toggleImage) {
						toggleImage.src				 		= dmc_mb3_product_pi1ToggleImageOn;
					} /* end: if */

					if (productBody) {
						productBody.className				= 'productBodyInvisible';
					} /* end: if */

					if (typeof productConf[uid][id]['state'] != undefined) {
						productConf[uid][id]['state']	= 0;
					} /* end: if */
					break;

				default:
			} /* end: switch */
		} /* end: if */
	}

	//wdo@adva
	function productToggleImage(uid,id,imageNum,state,zoomPath) {

		dmc_mb3_product_pi1mediaIndex = imageNum;
		var mainImage   = document.getElementById('dmc_mb3_product_pi1'+uid+'MainImage');
		var toggleImage = document.getElementById('dmc_mb3_product_pi1'+uid+'Product'+id+'Opener');
		var productBody = document.getElementById('dmc_mb3_product_pi1'+uid+'Product'+id+'Body');
		var zoomLink    = document.getElementById('dmc_mb3_product_pi1'+uid+'ZoomLink');
		
		if(state == 1 || state == 0){
			state = (state+1)%2;
		} 
		else if(productConf[uid][id])
		{
			state = productConf[uid][id]['state'];
		}
		
		//window.console.log('ZoomLink: '+zoomLink+"\nZoomPath: "+zoomPath);
		
		if(mainImage) {
			switch(state) {
				case 0:
					if(productConf[uid][id]['large'][imageNum]) {
						mainImage.src = productConf[uid][id]['large'][imageNum];
						var oldActive = false;
						var newActive = document.getElementById('dmc_mb3_product_pi1'+uid+id+imageNum+'mediaActive');
						if(dmc_mb3_product_pi1mediaActive != '') {
							oldActive = document.getElementById(dmc_mb3_product_pi1mediaActive);
						}
						if(oldActive) {
							gfxToggle(oldActive, 'clear.gif', 'but_detail_thumb_on.gif');
						}
						if(newActive) {
							gfxToggle(newActive, 'clear.gif', 'but_detail_thumb_on.gif');
							dmc_mb3_product_pi1mediaActive='dmc_mb3_product_pi1'+uid+id+imageNum+'mediaActive';
						}
					}
					else if(productConf[uid][id]['large']['default']){
						mainImage.src=productConf[uid][id]['large']['default'];
					}
					if(toggleImage){
						toggleImage.src=dmc_mb3_product_pi1ToggleImageOff;
					}
					if(productBody){
						productBody.className='productBodyVisible';
					}
					if(typeof productConf[uid][id]['state'] != undefined){
						productConf[uid][id]['state']=1;
					}
					break;
				case 1:
					if(toggleImage){
						toggleImage.src=dmc_mb3_product_pi1ToggleImageOn;
					}
					if(productBody){
						productBody.className='productBodyInvisible';
					}
					if(typeof productConf[uid][id]['state'] != undefined){
						productConf[uid][id]['state']=0;
					}
					break;
				default:
			}

			zoomLink.href = zoomPath;
		}
	}

	

	function initProduct(uid, id) {

		if(typeof productConf[uid][id] == 'undefined') return;

		/* gather necessary objects */
		var variation		= '';
		var size			= '';
		var color			= '';
		var productBody		= document.getElementById('dmc_mb3_product_pi1' + uid + 'Product' + id + 'Body');
		var toggleImage		= document.getElementById('dmc_mb3_product_pi1' + uid + 'Product' + id + 'Opener');
		var state			= productConf[uid][id]['state'];

		/* check whether a single article is preselected */
		for (var tmpVariation in productConf[uid][id]['articles']) {

			for (var tmpSize in productConf[uid][id]['articles'][tmpVariation]) {

				for (var tmpColor in productConf[uid][id]['articles'][tmpVariation][tmpSize]) {

					if (productConf[uid][id]['articles'][tmpVariation][tmpSize][tmpColor]['selected'] == '1') {
						variation	= tmpVariation;
						size		= tmpSize;
						color		= tmpColor;

					} /* end: if */
				} /* end: for */
			} /* end: for */
		} /* end: for */

		fillVariationForm(uid, id, variation, color, size);

		variation	= currentVariation(uid, id);
		size		= currentSize(uid, id, variation);
		color		= currentColor(uid, id, variation, size);

		displayArtNumber(uid, id, variation, size, color);
		displayPrice(uid, id, variation, size, color);
		displayAvailability(uid, id, variation, size, color);

		if (toggleImage
			&& productBody) {
			switch (state) {
				case 1:
					productBody.className	= 'productBodyVisible';
					toggleImage.src			= dmc_mb3_product_pi1ToggleImageOff;
					break;

				case 0:
					productBody.className	= 'productBodyInvisible';
					toggleImage.src			= dmc_mb3_product_pi1ToggleImageOn;
					break;

				default:
			} /* end: switch */
		} /* end: if */
	}
	
	function changeProduct(uid, id, startFrom) {

		/* gather necessary objects */
		var variationForm	= document.getElementById('productVariationForm_' 	+ uid + '_' + id);
		var sizeForm		= document.getElementById('productSizeForm_' 		+ uid + '_' + id);
		var colorForm		= document.getElementById('productColorForm_' 		+ uid + '_' + id);
		var variation		= currentVariation(uid, id);
		var size			= currentSize(uid, id, variation);
		var color			= currentColor(uid, id, variation, size);
		var articlePk		= productConf[uid][id]['articles'][variation][size][color]['articlePk'];
		var priceSummaryDiv	= document.getElementById('priceSummary_' + uid + '_' + id);
		var amountTextForm	= document.getElementById('productAmountForm_' 		+ uid + '_' + id);
		
		switch (startFrom) {
			case 'variation':
				fillSizeForm(uid, id, variation);
				break;

			case 'size':
				fillColorForm(uid, id, variation, size);
				break;

			case 'color':
				setGravure(uid, id, variation, size, color);
				break;

			default:
		} /* end: switch */

		variation		= currentVariation(uid, id);
		size			= currentSize(uid, id, variation);
		color			= currentColor(uid, id, variation, size);

		displayArtNumber(uid, id, variation, size, color);
		displayPrice(uid, id, variation, size, color);
		displayAvailability(uid, id, variation, size, color);
		
/*
		if(blockPriceConf[uid][articlePk][0]){
			content = "<table style='background:#EFEFEF'><tr><td>"+hintMinQtyText+"</td><td>"+hintMaxQtyText+"</td><td>"+hintPriceText+"</td></tr>";
			for(var i=0; i < blockPriceConf[uid][articlePk].length; i++) {
				minQty		= blockPriceConf[uid][articlePk][i]['minQuantity'];
				maxQty		= blockPriceConf[uid][articlePk][i]['maxQuantity'];
				blockPrice	= blockPriceConf[uid][articlePk][i]['blockPrice'];
				content = content+"<tr><td>"+minQty+"</td><td>"+maxQty+"</td><td>"+blockPrice+"</td></tr>";
			} // end: for
			if(priceSummaryDiv){
				priceSummaryDiv.innerHTML = content + "</table>";
			}

			changeDisplayBlockPrice(uid, id);

		} // end: if
*/
	}

	function addToBasket(uid, id) {
		var form			= document.getElementById('productForm_' + uid);
		var amountForm		= document.getElementById('productAmountForm_' + uid + '_' + id);
		var pkForm			= document.getElementById('productBasketPk_' + uid);
		var productPkForm	= document.getElementById('productBasketProductPk_' + uid);
		var variation		= currentVariation(uid, id);
		var size			= currentSize(uid, id, variation);
		var color			= currentColor(uid, id, variation, size);
		var amount			= 0;

		if (amountForm) {
			if(amountForm.nodeName == 'SELECT') {
				amount = amountForm.options[amountForm.selectedIndex].value;
			} else if (amountForm.nodeName == 'INPUT'
				&& (amountForm.type == 'text'
					|| amountForm.type == 'hidden')) {
				amount = amountForm.value;
			}
		}
		
		if (form && pkForm && productPkForm && amount > 0) {
			pkForm.value		= productConf[uid][id]['articles'][variation][size][color]['articlePk'];
			productPkForm.value = id;
			form.submit();
		} else if(amount < 1 || isNaN(parseInt(amount))) {
			alert(errorAmountText);
		} // end: if
	}

	function addToBasketSubmit(uid, id, target, popup, url, popupParams) {
		if (popup) {
			var form			= document.getElementById('productForm_' + uid);
			form.action 		= url;

			// do NOT load page from 'url' variable here! race condition w/ 2 Apache threads!
			window.open('/clear.gif', target, popupParams);
		}

		addToBasket(uid, id);
	}


	function changeItemInBasket(uid, id) {
		var form			= document.getElementById('productForm_' + uid);
		var amountForm		= document.getElementById('productAmountForm_' + uid + '_' + id);
		var pkForm			= document.getElementById('productBasketPk_' + uid);
		var productPkForm	= document.getElementById('productBasketProductPk_' + uid);
		var variation		= currentVariation(uid, id);
		var size			= currentSize(uid, id, variation);
		var color			= currentColor(uid, id, variation, size);
		var amount			= 0;

		if (amountForm) {
			if(amountForm.nodeName == 'SELECT') {
				amount = amountForm.options[amountForm.selectedIndex].value;
			} else if (amountForm.nodeName == 'INPUT'
				&& (amountForm.type == 'text'
					|| amountForm.type == 'hidden')) {
				amount = amountForm.value;
			}
		}

		if (form && pkForm && productPkForm && amount > 0) {
			pkForm.value		= productConf[uid][id]['articles'][variation][size][color]['articlePk'];
			productPkForm.value = id;
			form.submit();
			window.close();
		} else if(amount < 1 || isNaN(parseInt(amount))) {
			alert(errorAmountText);
		}// end: if

		return false;
	}

	function removeItemSubmit(uid, action, callBackFunc) {
		var form			= document.getElementById('productForm_' + uid);
		var actionField		= document.getElementById( 'productFormAction_' + uid );
		actionField.value   = action;

		form.submit();
		callBackFunc();		
		window.close();

		return false;
	}

	function displayArtNumber(uid, id, variation, size, color) {
		var artNumberDiv			= document.getElementById('productArtNumber_' 			+ uid + '_' + id);
		var articleOrderNumberDiv	= document.getElementById('productArticleOrderNumber_' + uid + '_' + id);

		if (artNumberDiv) {
			artNumberDiv.innerHTML	= productConf[uid][id]['articles'][variation][size][color]['artNumber'];
// CCC [dst] 21.12.2005 - compatible to CH only!
//									+ ' '
//									+ productConf[uid][id]['articles'][variation][size][color]['adCode'];
		} /* end: if */

		if (articleOrderNumberDiv) {
			articleOrderNumberDiv.innerHTML = productConf[uid][id]['articles'][variation][size][color]['articleOrderNumber'];
		} /* end: if */
	}

	function displayPrice(uid, id, variation, size, color) {
		var priceDiv		= document.getElementById('productPrice_' 		+ uid + '_' + id);
		var oldPriceDiv		= document.getElementById('productOldPrice_'	+ uid + '_' + id);
		var oldPriceWrap	= document.getElementById('productOldPrice_'	+ uid + '_' + id + '_wrap');
		var currentReducedPriceDiv = document.getElementById('productCurrentReducedPrice_'+ uid + '_' + id);

		if (priceDiv) {
			priceDiv.innerHTML	= productConf[uid][id]['articles'][variation][size][color]['price'];
		} /* end: if */

//		if (oldPriceDiv && oldPriceWrap) {
		if (oldPriceDiv) {
			var oldPrice 	= productConf[uid][id]['articles'][variation][size][color]['oldPrice'];
			var currentReducedPrice 	= productConf[uid][id]['articles'][variation][size][color]['currentReducedPrice'];
			oldPrice 		= parseFloat(oldPrice.replace(/,/g, '.'));
			currentReducedPrice = parseFloat(currentReducedPrice.replace(/,/g, '.'));

			if (oldPrice > 0) {
				oldPriceDiv.innerHTML			= productConf[uid][id]['articles'][variation][size][color]['oldPrice'];
				oldPriceWrap.style.visibility	= 'visible';
				oldPriceWrap.style.display		= 'inline';

			} else {
				oldPriceWrap.style.visibility	= 'hidden';
				oldPriceWrap.style.display		= 'none';
			}
			
			if (currentReducedPrice > 0) {
				oldPriceDiv.innerHTML			= productConf[uid][id]['articles'][variation][size][color]['currentReducedPrice'];
				oldPriceWrap.style.visibility	= 'visible';
				oldPriceWrap.style.display		= 'inline';
				currentReducedPriceDiv.style.visibility='visible';
				currentReducedPriceDiv.style.display='inline';

			} else {
				oldPriceWrap.style.visibility	= 'hidden';
				oldPriceWrap.style.display		= 'none';
				currentReducedPriceDiv.style.visibility='hidden';
				currentReducedPriceDiv.style.display='none';
			}

		}

	}

	
	function displayAvailability(uid, id, variation, size, color) {
		var availDiv	= document.getElementById('productAvail_' 		+ uid + '_' + id);

		if (availDiv) {
			availDiv.innerHTML	= productConf[uid][id]['articles'][variation][size][color]['stockType'];
			availDiv.className	= productConf[uid][id]['articles'][variation][size][color]['stockTypeClass'];
		} /* end: if */
	}
	
	function setVariation(uid, id, variation) {
		var variationForm	= document.getElementById('productVariationForm_' 	+ uid + '_' + id);
		var index			= 0;

		if (variationForm) {
			if(variationForm.nodeName == 'SELECT') {
				for (var tmpVariation in productConf[uid][id]['articles']) {

					if (tmpVariation == variation) {
						variationForm.selectedIndex = index;
					} /* end: if */

					index++;
				} /* end: for */
			} else if (variationForm.nodeName == 'INPUT'
				&& (variationForm.type == 'text'
					|| variationForm.type == 'hidden')
				) {

				variationForm.value = variation;
			}/* end: if*/
		} /* end: if */
	}

	function firstVariation(uid, id) {
		/* find first variation */
		for (var returnValue in productConf[uid][id]['articles']) {
			break;
		} /* end: for */

		return returnValue;
	}

	function currentVariation(uid, id) {
		var returnValue		= '';
		var variationForm	= document.getElementById('productVariationForm_' 	+ uid + '_' + id);

		if (variationForm) {
			if(variationForm.nodeName == 'SELECT' && variationForm.selectedIndex != -1) {
				returnValue = variationForm.options[variationForm.selectedIndex].value;
			} else if (variationForm.nodeName == 'INPUT'
				&& (variationForm.type == 'text'
					|| variationForm.type == 'hidden')
				) {

				returnValue = variationForm.value;
			}/* end: if*/
		} else {
			returnValue = firstVariation(uid, id);
		} /* end: if */

		return returnValue;
	}

	function fillVariationForm(uid, id, variation, color, size) {
		var variationForm	= document.getElementById('productVariationForm_' 	+ uid + '_' + id);
		var tmpVariation	= false;
		var index			= 0;

		if (variationForm) {
			if(variationForm.nodeName == 'SELECT') {
				/* clear all options */
				for (var j = variationForm.length; j >= 0; j--) {
					variationForm.options[j] = null;
				} /* end: for */

			/* fill with new variations */
			for (tmpVariation in productConf[uid][id]['articles']) {

				if (tmpVariation == variation) {
					variationForm.options[variationForm.length]	= new Option(tmpVariation, tmpVariation, false, true);

					variationForm.selectedIndex					= index;

				} else {
					variationForm.options[variationForm.length]	= new Option(tmpVariation, tmpVariation, false, false);
				} /* end: if */

					index++;
				} /* end: for */

				/* set selected */
				if (variationForm.selectedIndex == -1) {
					variationForm.selectedIndex = 0;
				} /* end: if */
			} else if (variationForm.nodeName == 'INPUT'
				&& (variationForm.type == 'text'
					|| variationForm.type == 'hidden')
				) {

				variationForm.value = variation;
			}/* end: if*/
		} /* end: if */

		/* fill size form */
		fillSizeForm(uid, id, currentVariation(uid, id), size, color);
	}

	function setSize(uid, id, variation, size) {
		var sizeForm	= document.getElementById('productSizeForm_' 	+ uid + '_' + id);
		var index		= 0;

		if (sizeForm) {
			if(sizeForm.nodeName == 'SELECT') {
				for (var tmpSize in productConf[uid][id]['articles'][variation]) {

					if (tmpSize == size) {
						sizeForm.selectedIndex = index;
					} /* end: if */

					index++;
				} /* end: for */
			} else if (sizeForm.nodeName == 'INPUT'
				&& (sizeForm.type == 'text'
					|| sizeForm.type == 'hidden')
				) {

				sizeForm.value = size;
			}/* end: if*/
		} /* end: if */
	}

	function firstSize(uid, id, variation) {
		/* find first size */
		for (var returnValue in productConf[uid][id]['articles'][variation]) {
			break;
		} /* end: for */

		return returnValue;
	}

	function currentSize(uid, id, variation) {
		var returnValue		= '';
		var sizeForm		= document.getElementById('productSizeForm_' 	+ uid + '_' + id);

		if (sizeForm) {
			if (sizeForm.nodeName == 'SELECT' && sizeForm.selectedIndex != -1) {
				returnValue = sizeForm.options[sizeForm.selectedIndex].value;
			} else if (sizeForm.nodeName == 'INPUT'
				&& (sizeForm.type == 'text'
					|| sizeForm.type == 'hidden')
				) {

				returnValue = sizeForm.value;
			}/* end: if*/
		} else {
			returnValue = firstSize(uid, id, variation);
		} /* end: if */

		return returnValue;
	}

	function fillSizeForm(uid, id, variation, size, color) {
		var sizeForm	= document.getElementById('productSizeForm_' 	+ uid + '_' + id);
		var tmpSize		= false;
		var sizeOld		= false;
		var sizeOldName	= false;
		var index		= 0;

		if (sizeForm) {
			if(sizeForm.nodeName == 'SELECT') {
				/* remember old state */
				sizeOld = sizeForm.selectedIndex;

			if (sizeOld != -1) {
				sizeOldName = sizeForm.options[sizeOld].value;
			} /* end: if */

			/* clear all options */
			for (var j = sizeForm.length; j >= 0; j--) {
				sizeForm.options[j] = null;
			} /* end: for */

			/* fill with new sizes */
			for (tmpSize in productConf[uid][id]['articles'][variation]) {

				if (tmpSize == size
					|| tmpSize == sizeOldName) {

					sizeForm.options[sizeForm.length]	= new Option(tmpSize, tmpSize, false, true);
					sizeForm.selectedIndex				= index;

				} else {
					sizeForm.options[sizeForm.length]	= new Option(tmpSize, tmpSize, false, false);
				} /* end: if */

					index++;
				} /* end: for */
			} else if (sizeForm.nodeName == 'INPUT'
				&& (sizeForm.type == 'text'
					|| sizeForm.type == 'hidden')
				) {

				sizeForm.value = size;
			}/* end: if*/
		} /* end: if */

		/* fill color form */
		fillColorForm(uid, id, variation, currentSize(uid, id, variation), color);
	}

	function setColor(uid, id, variation, size, color) {
		var colorForm	= document.getElementById('productColorForm_' 	+ uid + '_' + id);
		var index		= 0;

		if (colorForm) {
			if(colorForm.nodeName == 'SELECT') {
				for (var tmpColor in productConf[uid][id]['articles'][variation][size]) {

					if (tmpColor == color) {
						colorForm.selectedIndex = index;
					} /* end: if */

					index++;
				} /* end: for */
			} else if (colorForm.nodeName == 'INPUT'
				&& (colorForm.type == 'text'
					|| colorForm.type == 'hidden')
				) {

				colorForm.value = color;
			}/* end: if*/
		} /* end: if */
	}

	function firstColor(uid, id, variation, size) {
		/* find first color */
		for (var returnValue in productConf[uid][id]['articles'][variation][size]) {
			break;
		} /* end: for */

		return returnValue;
	}

	function currentColor(uid, id, variation, size) {
		var returnValue		= '';
		var colorForm		= document.getElementById('productColorForm_' 	+ uid + '_' + id);

		if (colorForm) {
			if (colorForm.nodeName == 'SELECT' && colorForm.selectedIndex != -1) {
				returnValue = colorForm.options[colorForm.selectedIndex].value;
			} else if (colorForm.nodeName == 'INPUT'
				&& (colorForm.type == 'text'
					|| colorForm.type == 'hidden')
				) {

				returnValue = firstColor(uid, id, variation, size);//colorForm.value;
			}/* end: if*/
		} else {
			returnValue = firstColor(uid, id, variation, size);
		} /* end: if */

		return returnValue;
	}

	function fillColorForm(uid, id, variation, size, color) {
		var colorForm		= document.getElementById('productColorForm_' 	+ uid + '_' + id);
		var tmpColor		= false;
		var colorOld		= false;
		var colorOldName	= false;
		var index			= 0;

		if (colorForm) {
			if(colorForm.nodeName == 'SELECT') {
				/* remember old state */
				colorOld = colorForm.selectedIndex;

				if (colorOld != -1) {
					colorOldName = colorForm.options[colorOld].value;
				} /* end: if */

				/* clear all options */
				for (var j = colorForm.length; j >= 0; j--) {
					colorForm.options[j] = null;
				} /* end: for */

				/* fill with new colors */
				for (tmpColor in productConf[uid][id]['articles'][variation][size]) {

					if (tmpColor == color
						|| tmpColor == colorOldName) {

						colorForm.options[colorForm.length]	= new Option(tmpColor, tmpColor, false, true);
						colorForm.selectedIndex = index;

					} else {
						colorForm.options[colorForm.length]	= new Option(tmpColor, tmpColor, false, false);
					} /* end: if */

					index++;
				} /* end: for */
			} else if (colorForm.nodeName == 'INPUT'
				&& (colorForm.type == 'text'
					|| colorForm.type == 'hidden')
				) {

				colorForm.value = color;
			}/* end: if*/
		} /* end: if */

		/* set gravure */
		setGravure(uid, id, variation, size, currentColor(uid, id, variation, size));
	}

	function setGravure(uid, id, variation, size, color) {
		var gravureForm		= document.getElementById('productGravureForm_' + uid + '_' + id);
		var gravureTitle	= document.getElementById('productGravureTitle_' + uid + '_' + id);
		var gravureText		= document.getElementById('productGravureText_' + uid + '_' + id);

		if (gravureForm && gravureTitle && gravureText) {
			/* set current state */
			gravureForm.maxLength = productConf[uid][id]['articles'][variation][size][color]['gravureLength'];
			gravureText.innerHTML = productConf[uid][id]['articles'][variation][size][color]['gravureText'];

			if (gravureForm.maxLength == 0) {
				gravureForm.style.visibility	= 'hidden';
				gravureTitle.style.visibility	= 'hidden';
				gravureText.style.visibility	= 'hidden';
				gravureForm.style.display		= 'none';
				gravureTitle.style.display		= 'none';
				gravureText.style.display		= 'none';

			} else {
				gravureForm.style.visibility	= 'visible';
				gravureTitle.style.visibility	= 'visible';
				gravureText.style.visibility	= 'visible';
				gravureForm.style.display		= 'inline';
				gravureTitle.style.display		= 'block';
				gravureText.style.display		= 'block';
			} /* end: if */
		} /* end: if */
	}

	if (!productConf) {
		var productConf = new Array();
	} // end: if

	if (!blockPriceConf) {
		var blockPriceConf = new Array();
	} // end: if

// --- component specific functions --------------------------------------------

	// initialize js vars
	var articlePk		= new Array();
	var changeEvent		= false;
	var articleIndex	= false;
	var combiArray		= new Array();

	// options colour in list box
	var enableColor		= '#333333';
	var disableColor	= '#d2d2d2'; //change the color to #000000. '#d2d2d2';

	// flag for unselect on ctrl+click, if false unselects on second click
	var bindCtrlKey		= true;

	if (!componentConf) {
		var componentConf	= new Array();
	} // end: if

	/**
	 * Initializes product components
	 *
	 * @access public
	 * @return void
	 **/
	function initProductComponent(uid, id) {
		
		articlePk[uid] = 0;
		if(typeof productConf[uid][id] == 'undefined') return;

		// gather necessary objects
		var productBody		= document.getElementById('dmc_mb3_product_pi1' + uid + 'Product' + id + 'Body');
		var toggleImage		= document.getElementById('dmc_mb3_product_pi1' + uid + 'Product' + id + 'Opener');
		var state			= productConf[uid][id]['state'];
		var changeArticle	= false;

		componentDisplayVignette(uid, id, productConf[uid][id]['articles'][0]['_ATTRIBUTES_']);
		componentDisplayGravure(uid, id, productConf[uid][id]['articles'][0]['_ATTRIBUTES_']);
		
		// IF A PRODUCT HAS NO Color you have to SET empty Color
		for(var i=0; i < productConf[uid][id]['articles'].length; i++) {
			if (typeof productConf[uid][id]['articles'][i]['Color'] == 'undefined') {
				productConf[uid][id]['articles'][i]['Color'] = new Array();
				productConf[uid][id]['articles'][i]['Color']['value'] = 'empty';  //wdo@adva: Fehlerquelle CADE??
				productConf[uid][id]['articles'][i]['Color']['display'] = '';
			}
		}

		// fills all input fields with components for each article
		for(var i=0; i < productConf[uid][id]['articles'].length; i++) {

			// no. of components in each article
			for(var componentName in productConf[uid][id]['articles'][i]) {

				// fill all components
				fillComponents(uid, id, componentName, productConf[uid][id]['articles'][i][componentName]['value'], productConf[uid][id]['articles'][i][componentName]['display'], false);

			} // end: for
		} // end: for

		// find selected component combination, if any
		changeArticle		= initSelectedComponents(uid, id, productConf[uid][id]['articles']);

		// disable components
		if(productConf[uid][id]['articles'].length > 1) {
			// disable all
			if(changeArticle !== false) {
				disableAllComponents(uid, id, false);

				changeComponents(uid, id, productConf[uid][id]['articles'][changeArticle]);
			} // end: if
		} // end: if
		
		// highlight combinations
		colorCombinations(uid, id);
		
		if (toggleImage
			&& productBody) {
			switch (state) {
				case 1:
					productBody.className	= 'productBodyVisible';
					toggleImage.src			= dmc_mb3_product_pi1ToggleImageOff;
					break;

				case 0:
					productBody.className	= 'productBodyInvisible';
					toggleImage.src			= dmc_mb3_product_pi1ToggleImageOn;
					break;

				default:
			} // end: switch
		} // end: if

	} // end: function initProductComponent

	/**
	 * Finds selected article and stores related components for later usage
	 * Used in change product pages
	 *
	 * @access public
	 * @return void
	 **/
	function initSelectedComponents(uid, id, pConf) {

		// init vars
		var componentIndex	= false;
        var first_article = -1;
		var first_good_article = -1;
		var first_sold_article = -1;
		// find the selected article if any (change product)
		for(var i=0; i < productConf[uid][id]['articles'].length; i++) {
            if (first_article == -1) {
              first_article = i;
            }
			if (first_good_article == -1) {
				if (productConf[uid][id]['articles'][i]['_ATTRIBUTES_']['stockType'] > stockTypeCode_soldOut) {
					first_good_article = i;
				} else if (productConf[uid][id]['articles'][i]['_ATTRIBUTES_']['stockType'] == stockTypeCode_soldOut 
							&& first_sold_article == -1 )  {
					first_sold_article = i;
				}
			}
			if(productConf[uid][id]['articles'][i]['_ATTRIBUTES_']['selected'] == 1
				|| productConf[uid][id]['articles'].length == 1) {

				// component index
				componentIndex	= i;

				// store all values in combi array
				fillCombiArray(uid, id, i);

			} // end: if
		} // end: for

		if ((componentIndex == false)
			&& (first_good_article != -1)) {
			componentIndex = first_good_article;
		}
		
		//first_good_article empty set the fist sold article
		if ((componentIndex == false)
			&& (first_sold_article != -1)) {
			componentIndex = first_sold_article;
		}
		
        // first_article as fallback
        if ((componentIndex == false)
			&& (first_article != -1)) {
			componentIndex = first_article;
		}
		
		// find the selected article
		if(componentIndex !== false) {

			// set global
			articleIndex = componentIndex;
			if (typeof productConf[uid][id]['articles'][componentIndex]['Color'] == 'undefined') {
				productConf[uid][id]['articles'][componentIndex]['Color'] = new Array();
				productConf[uid][id]['articles'][componentIndex]['Color']['value'] = 'empty';
				productConf[uid][id]['articles'][componentIndex]['Color']['display'] = '';
			}
			combiArray['Color'] = productConf[uid][id]['articles'][componentIndex]['Color']['value'];
			combiArray['Size'] = productConf[uid][id]['articles'][componentIndex]['Size']['value'];
			
			fillCombiArray(uid, id, componentIndex);
			
			// display attributes
			setAttributeDisplay(uid, id, productConf[uid][id]['articles'][componentIndex]);
		} // end: if

		return componentIndex;

	} // end: function initSelectedComponents

	/**
	 * Fills/sets the components into list box/text box/div
	 *
	 * @access public
	 * @return void
	 **/
	function fillComponents(uid, id, componentName, componentValue, componentDisplay, clearField) {

		// get the component form id
		var componentName	= componentName;
		var cId				= componentConf[uid][componentName];
		if(typeof cId == 'undefined') return;

		// init vars
		var cForm			= document.getElementById(cId);
		var componentValue	= componentValue;
		var clearField		= clearField;
		var alreadyAdded	= false;

		// if component type field exists
		if (cForm && componentValue != '') {

			// list box
			if(cForm.nodeName == 'SELECT') {

				// clear all options from list box
				if(clearField == true) {

					for (var j = cForm.length; j >= 0; j--) {
						cForm.options[j] = null;
					} // end: for
				} // end: if

				// check for duplicate values
				alreadyAdded	= componentAlreadyAdded(componentValue, cForm);
				if(alreadyAdded == true) {
					return;
				} // end: if

				if(typeof combiArray[componentName] != 'undefined'
					&& combiArray[componentName] == componentValue) {
					// fill selected options
					cForm.options[cForm.length]	= new Option(componentDisplay, componentValue, false, true);
				} else {
					// fill options
					cForm.options[cForm.length]	= new Option(componentDisplay, componentValue, false, false);
				} // end: if
			} else if (cForm.nodeName == 'INPUT'
				&& (cForm.type == 'text'
					|| cForm.type == 'hidden')
				) {

				// text/hidden field
				cForm.value = componentValue;

			} else if(cForm.nodeName == 'DIV') {
				if (typeof whitelistTypes[componentName] != 'undefined') {
					combiArray[componentName] = componentValue;
				}
				// for single value
				if(articlePk[uid] > 0 && articleIndex !== false) {
					cForm.innerHTML	= componentDisplay;
				} else {
					cForm.innerHTML	= componentDisplay;
					//cForm.innerHTML	= componentValue;
				} // end: if

			} // end: if

		} // end: if
	} // end: function fillComponents

	/**
	 * Finds articles for selected component combinations and fills field
	 *
	 * @access public
	 * @return void
	 **/
	function componentChangeProduct(uid, id, componentName) {
		// get form id
		var componentName	= componentName;
		var cId				= componentConf[uid][componentName];
		if(typeof cId == 'undefined') return;
		// gather necessary objects
		var componentForm		= document.getElementById(cId);
		var componentValue		= currentComponent(uid, id, componentForm);
		var componentName		= componentName;
		var componentIndex		= false;
		var clearFields			= false;
		var matchComponentValue	= false;
		var matchFound			= false;
		var priceSummaryDiv		= document.getElementById('priceSummary_' + uid + '_' + id);
		var amountTextForm		= document.getElementById('productAmountForm_' 		+ uid + '_' + id);

		// set change event flag
		changeEvent				= true

		// update combi array
		combiArray[componentName]	= componentValue;
		
		// disable all
		disableAllComponents(uid, id, false);

		// set combi display
		matchFound	= setCombiDisplay(uid, id, true);
		// if no match found call the 
		if(matchFound == false) {
			//save the color
			var theColor = combiArray['Color'];
			combiArray = new Array();
			combiArray['Color'] = theColor;
			combiArray[componentName] = componentValue;
			combiArray['Size'] = colorCombinations(uid, id);
			matchFound	= setCombiDisplay(uid, id, true);
		}
		
		return;
	} // end: function componentChangeProduct

	/**
	 * Updates component display based on selected combination
	 *
	 * @access public
	 * @return boolean
	 **/
	function setCombiDisplay(uid, id, matchFlag) {
		var matchFound		= false;
		var currentIndex	= false;
		var matchFlag		= matchFlag;
		var numOfCombi		= 0;
		// look for matching components in all articles
		for(var i=0; i < productConf[uid][id]['articles'].length; i++) {

			var combiCount		= 0;
			var matchCount		= 0;

			// all components
			for(var componentType in combiArray) {

				// get component value
				matchComponentValue	= productConf[uid][id]['articles'][i][componentType]['value'];
				// if component type and value matches with the currently selected one
				// ColorFamily cannot be selected by User, should not play a role if
				// it matches as there are no values for selection in frontend
				if(combiArray[componentType] == matchComponentValue || componentType == 'ColorFamily' || componentType == 'Color family' ) {
					// no. of matching components
					matchCount++;
				} // end: if

				// no. of selected components
				combiCount++;

			} // end: for
			// if all selected combination matches
			if(matchCount == combiCount) {
				// set current matching index
				currentIndex	= i;
				// update list
				changeComponents(uid, id, productConf[uid][id]['articles'][i]);

				// we have at least one match
				matchFound	= true;
				// find article matching selected component combination
				findCombiArticle(i, uid, id);

				// set no. of combinations found
				numOfCombi++;

			}  // end: if

		} // end: for
		if(numOfCombi == 1
			&& currentIndex !== false) {
			// store all values in combi array
			fillCombiArray(uid, id, currentIndex);
			// update list
			changeComponents(uid, id, productConf[uid][id]['articles'][currentIndex]);
			// find article matching selected component combination
			findCombiArticle(currentIndex, uid, id);
			// color Other combinations
			colorCombinations(uid, id);
		}
		return matchFound;

	} // end: function setCombiDisplay

	/**
	 * Finds the next possible match within the selected combination and
	 * discards least found component
	 *
	 * @access public
	 * @return boolean
	 **/
	function findNextCombiMatch(uid, id, componentName, componentValue) {

		// init vars
		var matchFound	= false;
		var validCombi	= new Array();

		for(var componentType in combiArray) {

			if(componentType != componentName) {

				for(var i=0; i < productConf[uid][id]['articles'].length; i++) {

					var matchValue	= productConf[uid][id]['articles'][i][componentType]['value'];
					var curValue	= productConf[uid][id]['articles'][i][componentName]['value'];

					if(matchValue == combiArray[componentType]
						&& curValue == componentValue) {

						// if in array
						if(typeof validCombi[componentType] == 'undefined') {
							validCombi[componentType]	= 1;
						} else {
							// add
							var num = validCombi[componentType];
							validCombi[componentType]	= num + 1;
						} // end: if
					} // end: if

				} // end: for
			} // end: if
		} // end: for

		// clean combi array based on valid combination found
		for(var combiType in combiArray) {

			if(combiType != componentName
				&& typeof validCombi[combiType] == 'undefined') {
				delete combiArray[combiType];
			}

		} // end: for

		// update display
		matchFound	= setCombiDisplay(uid, id, false);

		// still match was not found.. remove the least matching combi
		if(matchFound == false) {

			// remove the least matching combination
			var validCombi = sortAssoc(validCombi);

			for(var combiType in validCombi) {
				delete combiArray[combiType];
				break;
			} // end: for

			matchFound	= setCombiDisplay(uid, id, false);

		} // end: if

		return matchFound;

	} // end: function findNextCombiMatch

	function colorCombinations(uid, id) {
		// init vars
		matchCount	= 0;
		comCount	= 0;
		var colorTypes = new Array();
		
		// find matching article
		for(var componentType in componentConf[uid]) {
			
			var cId		= componentConf[uid][componentType];
			var cForm	= document.getElementById(cId);
			
			if(cForm && cForm.nodeName == 'SELECT') {

				if(typeof combiArray[componentType] != 'undefined') {
					for (var i = 0; i < productConf[uid][id]['articles'].length; i++){
						if (typeof whitelistTypes[componentType] == 'undefined') {
							continue;
						}
						if (productConf[uid][id]['articles'][i][componentType]['value'] == combiArray[componentType]) {

							if (typeof colorTypes[componentType] == 'undefined') {
								colorTypes[componentType] = new Array();
							}
							colorTypes[componentType][combiArray[componentType]] = combiArray[componentType];
						}
					}
				} // end: if

			} else if(cForm && cForm.nodeName == 'DIV') {
				if (typeof whitelistTypes[componentType] != 'undefined') {
					if (typeof colorTypes[componentType] == 'undefined') {
						colorTypes[componentType] = new Array();
					}
					colorTypes[componentType][combiArray[componentType]] = combiArray[componentType];
				}
			}
		} // end: for
		
		/*
		 * there are products without Color. these products do not have a element
		 * drawn in the form.  this happens so far for products which do not have
		 * any color set. 
		 */
		if(typeof componentConf[uid]['Color'] == 'undefined') {

			if(typeof combiArray['Color'] != 'undefined') {
				for (var i = 0; i < productConf[uid][id]['articles'].length; i++){
					if (typeof whitelistTypes['Color'] == 'undefined') {
						continue;
					}
					if (productConf[uid][id]['articles'][i]['Color']['value'] == combiArray['Color']) {

						if (typeof colorTypes['Color'] == 'undefined') {
							colorTypes['Color'] = new Array();
						}
						colorTypes['Color'][combiArray['Color']] = combiArray['Color'];
					}
				}
			} // end: if
		}

		var highlightTypes = new Array();
		var remember_type_value = false;
		for(var i = 0; i < productConf[uid][id]['articles'].length; i++){
			// productConf[179][105318]['articles'][0]['Color']
			remember_type_value = false;
			for (var componentType in productConf[uid][id]['articles'][i]) {

				if (typeof colorTypes[componentType] != 'undefined') {
					// is da value in der liste drin
					for(var value in colorTypes[componentType]){
						if (productConf[uid][id]['articles'][i][componentType]['value'] == value) {
							remember_type_value = true;
							break;
						}
					}
				}
				if (remember_type_value) {
					break;
				}

			}
			if (remember_type_value) {

				// remember all colors, size and other components
				for (var componentType in productConf[uid][id]['articles'][i]) {
					if (typeof whitelistTypes[componentType] == 'undefined') {
						continue;
					}
					if (typeof highlightTypes[componentType] == 'undefined') {
						highlightTypes[componentType] = new Array();
					}
					highlightTypes[componentType][productConf[uid][id]['articles'][i][componentType]['value']] = productConf[uid][id]['articles'][i][componentType]['display'];
				}

			}
		}
		var returnValue = '';
		for(var componentType in componentConf[uid]) {
			var cId		= componentConf[uid][componentType];
			var cForm	= document.getElementById(cId);

			if (typeof whitelistTypes[componentType] == 'undefined') {
				continue;
			}
			
			if(cForm) {
				if(cForm.nodeName == 'SELECT') {
					if (typeof hideComponentSizeNotCombination[componentType] != 'undefined') {
			
							if (returnValue == ''){
								returnValue = cForm.options[cForm.selectedIndex].value;
							} // end: if
						
							for (var j = cForm.length -1; j >=0; j--) {							
								if (typeof highlightTypes[componentType][cForm.options[j].value] == 'undefined') {

									if(returnValue == cForm.options[j].value) {
										returnValue = '';
									} // end: if

									cForm.remove(j);
									
								}  // end: if
							} // end: for
						
							for (var ValueStr in highlightTypes[componentType]) {
								fillComponents(uid, id, componentType, ValueStr, highlightTypes[componentType][ValueStr], false);
							}// end: for
							
							if (returnValue == ''){
								returnValue = cForm.options[0].value;
							}// end: if
						
					} // end: if
				} else {
					if ( typeof hideComponentSizeNotCombination[componentType] == 'undefined' ) {
						continue;
					} // end: if
					
					for (var ValueStr in highlightTypes[componentType]) {
						returnValue = ValueStr;
						break;
					}
					
				} // end: if, else
			} // end: if
		} // end: for
		
		// return the first Size if the selector is empty
		return returnValue;
	}

	/**
	 * Updates fields with selected component combination
	 *
	 * @access public
	 * @return void
	 **/
	function changeComponents(uid, id, pConf) {

		// fill form with selected combination
		for(var componentType in pConf) {
			var cId		= componentConf[uid][componentType];
			var cForm	= document.getElementById(cId);

			if(cForm) {
				if(cForm.nodeName == 'SELECT') {

					for (var j = 0; j < cForm.length; j++) {

						if(cForm.options[j].value == pConf[componentType]['value']) {
							// enable
							cForm.options[j].style.color 	= enableColor;
							// set selected

							if(pConf[componentType]['value'] == combiArray[componentType]) {
								cForm.options[j].selected	= true;
							} // end: if

							// nfa@adva
							if ( productConf[uid][id]['articles'][j]['_ATTRIBUTES_']['stockType'] < 3 ) {

								// alert('AUSVERKAUFT ! ' + cForm.options[j].value);
								cForm.options[j].style.color = '#bbbbbb';
								cForm.options[j].style.textDecoration = 'line-through';
							}
						}
					} // end: for
				} else if(cForm.nodeName == 'DIV') {
					combiArray[componentType] = pConf[componentType]['value'];
					// for single value
					cForm.innerHTML	= pConf[componentType]['display'];

				} // end: if
			} // end: if

		} // end: for
	
	} // end: function changeComponents


	/**
	 * Checks if a value is already added in list box
	 *
	 * @access public
	 * @return boolean
	 **/
	function componentAlreadyAdded(cValue, cForm) {

		returnValue	= false;

		for (var j = 0; j < cForm.length; j++) {
			if(cForm.options[j].value == cValue) {
				return true;
			} // end: if
		} // end: for

		return returnValue;

	} // end: function componentAlreadyAdded

	/**
	 * Sets article attributes like price, article order no.
	 *
	 * @access public
	 * @return void
	 **/
	function setAttributeDisplay(uid, id, pConf) {
		// set article pk
		articlePk[uid]	= pConf['_ATTRIBUTES_']['articlePk'];

		// set various attributes
		componentDisplayArtNumber(uid, id, pConf['_ATTRIBUTES_']);
		componentDisplayPrice(uid, id, pConf['_ATTRIBUTES_']);
		componentDisplayUVP(uid, id, pConf['_ATTRIBUTES_']);
		componentDisplayAvailability(uid, id, pConf['_ATTRIBUTES_']);
		componentDisplayVignette(uid, id, pConf['_ATTRIBUTES_']);
		componentDisplayGravure(uid, id, pConf['_ATTRIBUTES_']);
		componentDisplayMainImage(uid, id, pConf['_ATTRIBUTES_']);

	} // end: function setAttributeDisplay

	/**
	 * Displays article order no.
	 *
	 * @access public
	 * @return void
	 **/
	function componentDisplayArtNumber(uid, id, pconf) {
		var artNumberDiv			= document.getElementById('productArtNumber_' 			+ uid + '_' + id);
		var articleOrderNumberDiv	= document.getElementById('productArticleOrderNumber_' + uid + '_' + id);

		if (artNumberDiv) {
			if(typeof pconf != 'undefined') {
				artNumberDiv.innerHTML	= pconf['artNumber'];
			} else {
				artNumberDiv.innerHTML	= attributeInfoText;
			}
// CCC [dst] 21.12.2005 - compatible to CH only!
//									+ ' '
//									+ pconf['adCode'];
		} // end: if

		if (articleOrderNumberDiv) {
			if(typeof pconf != 'undefined') {
				articleOrderNumberDiv.innerHTML = pconf['articleOrderNumber'];
			} else {
				//articleOrderNumberDiv.innerHTML	= attributeInfoText;
				articleOrderNumberDiv.innerHTML	= '-----/---';
			}
		} // end: if
	} // end: function componentDisplayArtNumber

	/**
	 * Displays article price
	 *
	 * @access public
	 * @return void
	 **/
	function componentDisplayPrice(uid, id, pconf) {
		var priceDiv		= document.getElementById('productPrice_' 		+ uid + '_' + id);
		var priceDivAdditional = document.getElementById('productPriceAdditional_' 	+ uid + '_' + id);
		var oldPriceDiv		= document.getElementById('productOldPrice_'	+ uid + '_' + id);
		var savingsDiv		= document.getElementById('productSavings_'		+ uid + '_' + id);
		var savingsAmountDiv= document.getElementById('productSavingsAmount_'+ uid + '_' + id);
		var oldPriceWrap	= document.getElementById('productOldPrice_'	+ uid + '_' + id + '_wrap');
		var savingsWrap		= document.getElementById('productSavings_'		+ uid + '_' + id + '_wrap');
		var additionalPriceWrap	= document.getElementById('productAdditionalPrice_'	+ uid + '_' + id + '_wrap');
		var additionalPriceDiv	= document.getElementById('productAdditionalPrice_'	+ uid + '_' + id);
		var currentReducedPriceDiv = document.getElementById('productCurrentReducedPrice_'+ uid + '_' + id);
		var vendorDeliveryWrap	= document.getElementById('productVendorDelivery_'	+ uid + '_' + id + '_wrap');

		if (priceDiv) {
			if(typeof pconf != 'undefined') {
				priceDiv.innerHTML	= pconf['price'];
			} else {
				priceDiv.innerHTML	= attributeInfoText;
				if (oldPriceWrap != null) {
					oldPriceWrap.style.visibility	= 'hidden';
					oldPriceWrap.style.display		= 'none';
				}
				if (savingsWrap != null) {
					savingsWrap.style.visibility	= 'hidden';
					savingsWrap.style.display		= 'none';
				}
				if (additionalPriceWrap != null) {
					additionalPriceWrap.style.visibility	= 'hidden';
					additionalPriceWrap.style.display	= 'none';
				}
				if (currentReducedPriceDiv != null) {
					currentReducedPriceDiv.style.visibility='hidden';
					currentReducedPriceDiv.style.display='none';
				}
				if (vendorDeliveryWrap != null) {
					vendorDeliveryWrap.style.visibility='hidden';
					vendorDeliveryWrap.style.display='none';
				}
				if (priceDivAdditional != null) {
					priceDivAdditional.style.visibility='hidden';
					priceDivAdditional.style.display='none';
				}
			}
		} // end: if

		//if (priceDiv && oldPriceDiv && savingsDiv && oldPriceWrap && savingsWrap) {
		//if (priceDiv && oldPriceDiv && oldPriceWrap) {
		if (priceDiv && oldPriceDiv) {
			var oldPrice 	= 0;
			var fPrice		= 0;
			var savings		= '';
			var currentReducedPrice=0;
			var addPrice	= 0;

			if(typeof pconf != 'undefined') {
				oldPrice 	= pconf['oldPrice'];
				patt = /[\D]*/g;
				oldPrice = oldPrice.replace(patt, '');
				
				fPrice 	= parseFloat(oldPrice.replace(/,/g, '.'));

				savings 	= pconf['savings'];
				
				if (typeof pconf['currentReducedPrice'] != 'undefined') {
					currentReducedPrice 	= pconf['currentReducedPrice'];
					currentReducedPrice 	= currentReducedPrice.replace(patt, '');
					currentReducedPrice 	= parseFloat(currentReducedPrice.replace(/,/g, '.'));
				}
			}
			if (fPrice > 0 && savings != '' && currentReducedPrice == 0) {
				if(typeof pconf != 'undefined') {
					
					oldPriceDiv.innerHTML			= pconf['beforeText']  + '&nbsp;' + pconf['oldPrice'];
					
					priceDiv.innerHTML				= '';
					
					if(pconf['priceFormatCode'] != '') {
						priceDiv.innerHTML			+= '<span class="priceFormatCodeInner">' + pconf['priceFormatCode'] + '&nbsp;</span>';
					}/* end: if */
					
					if(pconf['oldPrice'] != '') {
						priceDiv.innerHTML			+= '<span class="nowFromInner priceNow">' + '&nbsp;</span>' + pconf['price'] + '';
					} else {
						priceDiv.innerHTML			+= '<span class="ProductPriceText">' + pconf['price'] + '&nbsp;</span>';
					}/* end: if */
					
					if (savingsDiv != null) {
					savingsDiv.innerHTML			= pconf['savingText'] + '&nbsp;' +pconf['savings'];
					} /* end: if */
					if (savingsAmountDiv != null) {
					savingsAmountDiv.innerHTML		= '<span class="red bold">' + pconf['savingsAmountText'] + '&nbsp;' + pconf['savingsAmount'] + '</span>';
					} /* end: if */
					if (priceDivAdditional != null) {
						priceDivAdditional.innerHTML		= pconf['nowFromText'] + '&nbsp;' + pconf['price'];
					} /* end: if */
					
				} /* end: if */
				if (oldPriceWrap != null) {
					oldPriceWrap.style.visibility	= 'visible';
					oldPriceWrap.style.display		= 'inline';
				}
				if (savingsWrap != null) {
					savingsWrap.style.visibility	= 'visible';
					savingsWrap.style.display		= 'inline';
				}
				if (currentReducedPriceDiv != null) {
					currentReducedPriceDiv.style.visibility='hidden';
					currentReducedPriceDiv.style.display='none';
				}
				if (priceDivAdditional != null) {
					priceDivAdditional.style.visibility='visible';
					priceDivAdditional.style.display='inline';
				}
			} else if (currentReducedPrice > 0) {
				if(typeof pconf != 'undefined') {
					if ( fPrice > 0 ) {
						oldPriceDiv.innerHTML			= pconf['oldPrice'];
					} else {
						oldPriceDiv.innerHTML			= pconf['price'];
					}
					
					priceDiv.innerHTML				= '<span class="nowFromInner priceNow">' + pconf['nowFromText'] + '&nbsp;</span>';
					
					if(pconf['priceFormatCode'] != '') {
						priceDiv.innerHTML			+= '<span class="priceFormatCodeInner">' + pconf['priceFormatCode'] + '&nbsp;</span>';
					}/* end: if */

					if(pconf['currentReducedPrice'] != '') {
						priceDiv.innerHTML			+= '<span class="currentPriceInner priceNow">' + pconf['currentReducedPrice'] + '&nbsp;</span>';
					} else {
						priceDiv.innerHTML			+= '<span class="newCurrentPriceInner">' + pconf['currentReducedPrice'] + '&nbsp;</span>';
					}/* end: if */
					if (savingsDiv != null) {
					savingsDiv.innerHTML			= pconf['savingText'] + '&nbsp;' +pconf['savings'];
					} /* end: if */
					if (savingsAmountDiv != null) {
					savingsAmountDiv.innerHTML		= '<span class="red bold">' + pconf['savingsAmountText'] + '&nbsp;' + pconf['savingsAmount'] + '</span>';
					} /* end: if */
					if (priceDivAdditional != null) {
						priceDivAdditional.innerHTML		= pconf['nowFromText'] + '&nbsp;' + pconf['price'];
					} /* end: if */

				}
				if (oldPriceWrap != null) {
					oldPriceWrap.style.visibility	= 'visible';
					oldPriceWrap.style.display		= 'inline';
				}
				if (savingsWrap != null) {
					savingsWrap.style.visibility	= 'visible';
					savingsWrap.style.display		= 'inline';
				}
				if (currentReducedPriceDiv != null) {
					currentReducedPriceDiv.style.visibility='visible';
					currentReducedPriceDiv.style.display='inline';
				}
				if (priceDivAdditional != null) {
					priceDivAdditional.style.visibility='visible';
					priceDivAdditional.style.display='inline';
				}
			} else {
				if(typeof pconf != 'undefined') {
					priceDiv.innerHTML			= '<span class="ProductPriceText">'+pconf['price']+'</span>';
				}
				if (priceDivAdditional != null) {
					priceDivAdditional.innerHTML		= pconf['price'];
				} /* end: if */
				if (oldPriceWrap != null) {
					oldPriceWrap.style.visibility	= 'hidden';
					oldPriceWrap.style.display		= 'none';
				}
				if (savingsWrap != null) {
					savingsWrap.style.visibility	= 'hidden';
					savingsWrap.style.display		= 'none';
				}
				if (currentReducedPriceDiv != null) {
					currentReducedPriceDiv.style.visibility='hidden';
					currentReducedPriceDiv.style.display='none';
				}
				if (priceDivAdditional != null) {
					priceDivAdditional.style.visibility='visible';
					priceDivAdditional.style.display='inline';
				}
			} // end: if
		} // end: if

		if (additionalPriceWrap && additionalPriceDiv) {
			if (typeof pconf != 'undefined') {
				
				addPrice 	= pconf['additionalPrice'];
				patt = /[\D]*/g;
				addPrice = addPrice.replace(patt, '');
				
				if ((pconf['additionalPrice'] != ( ( typeof(emptyPrice) === 'undefined' ) ? '0,00 €' : emptyPrice ))
						&& (pconf['additionalPrice'] != '0,00 €')
						&& (addPrice > 0)) {
					additionalPriceDiv.innerHTML			= pconf['additionalPrice'];
					additionalPriceWrap.style.visibility	= 'visible';
					additionalPriceWrap.style.display		= 'inline';
				} else {
					additionalPriceWrap.style.visibility	= 'hidden';
					additionalPriceWrap.style.display	= 'none';
				}
			} else {
				additionalPriceWrap.style.visibility	= 'hidden';
				additionalPriceWrap.style.display	= 'none';
			}
		}
		
		if (vendorDeliveryWrap) {
			if (typeof pconf != 'undefined') {
				if ( pconf['vendorDelivery'] ) {
					vendorDeliveryWrap.style.visibility	= 'visible';
					vendorDeliveryWrap.style.display	= 'inline';
				} else {
					vendorDeliveryWrap.style.visibility	= 'hidden';
					vendorDeliveryWrap.style.display	= 'none';
				} //if
			} else {
				vendorDeliveryWrap.style.visibility	= 'hidden';
				vendorDeliveryWrap.style.display	= 'none';
			} //if
		} //if
			
	} // end: function componentDisplayPrice

	/**
	 * Displays article availability status
	 *
	 * @access public
	 * @return void
	 **/
	function componentDisplayAvailability(uid, id, pconf) {
	
		// sdu@adva: 
		$('#stockCodeThing').val(pconf['stockType']);
		
		if(typeof pconf == 'undefined') return;
		var availDiv	= document.getElementById('productAvail_' + uid + '_' + id);

		if (availDiv) {
			if(typeof pconf['stockTypeText'] !== 'undefined' && pconf['stockTypeText'] !== '') {
				availDiv.innerHTML	= pconf['stockTypeText'];
			}
		} // end: if

		var availImage	= document.getElementById('productAvailImage_' + uid + '_' + id);

		if (availImage) {
			availabilityImagePrefix = document.getElementById('availabilityImagePrefix_' + uid + '_' + id).value;
			availImage.src	= availabilityImagePrefix + pconf['stockType'] + '.gif';
		} // end: if

	} // end: function componentDisplayAvailability
		
	
		/**
	 * wdo@adva ADDED:	
	 * Displays article UVP = Component SellingPoints
	 *
	 * @access public
	 * @return void
	 **/
	function componentDisplayUVP(uid, id, pconf) {

		if(typeof pconf == 'undefined') return;
		var UVPDiv	= document.getElementById('productUVP_' + uid + '_' + id);
		var UVPSavingDiv	= document.getElementById('productUVPSaving_' + uid + '_' + id);

		if (UVPDiv) {
			if(typeof pconf['UVP'] !== 'undefined') {
				if(pconf['UVP'] !== '') {
					UVPDiv.innerHTML = 'UVP: ';
				} else {
					UVPDiv.innerHTML = '';
				}
				UVPDiv.innerHTML	+= pconf['UVP'];
			}

			if(typeof pconf['UVPSavings'] !== 'undefined') {
				UVPSavingDiv.innerHTML	= pconf['UVPSavings'];
			} else {
				UVPSavingDiv.innerHTML = '';
			}
		} // end: if
		
	} // end: function componentDisplayUVP

	
	/**
	 * Display article based Main Image
	 *
	 * @access public
	 * @return void
	 **/
	function componentDisplayMainImage(uid, id, pconf) {

		if(typeof pconf == 'undefined') return;
		var imageObject	= document.getElementById('dmc_mb3_product_pi1' + uid + 'MainImage');

		if (imageObject) {
			if(typeof pconf['image560'] !== 'undefined' && pconf['image560'] !== '') {
				imageObject.src	= pconf['image560'];
			} // end: if
		} // end: if

	} // end: function componentDisplayMainImage
	
	/**
	 * Displays Vignettes
	 *
	 * @access public
	 * @return void
	 **/
	function componentDisplayVignette(uid, id, pconf) {

		if(typeof pconf == 'undefined') return;

		var vignetteDiv	= document.getElementById('vignetteImageDiv_' + uid + '_' + id);
		var vignetteImagePrefix = document.getElementById('vignetteImagePrefix_' + uid + '_' + id).value;

		if(vignetteDiv && vignetteImagePrefix) {

			if(typeof pconf['mediaObject'] != 'undefined' && pconf['mediaObject'] != '') {
				var vignetteImageName = pconf['mediaObject'];
			} else {
				if(vignetteDiv.firstChild) {

					if(jQuery) {
						$('#vignetteImageDiv_' + uid + '_' + id).slideUp('slow');
					}/* end: if */

					vignetteDiv.removeChild(vignetteDiv.firstChild);
				}/* end: if */
				return;
			}/* end: if */

			if (vignetteDiv.firstChild) {
				vignetteDiv.firstChild.setAttribute('src', vignetteImagePrefix + vignetteImageName + '.gif');
			} else {

				if(jQuery) {
					$('#vignetteImageDiv_' + uid + '_' + id).hide();
				}/* end: if */

				vignetteImage = document.createElement("img");
				vignetteImage.setAttribute('src', vignetteImagePrefix + vignetteImageName + '.gif');
				vignetteImage.setAttribute('alt', 'Vignette');
				vignetteDiv.appendChild(vignetteImage);

				if(jQuery) {
					$('#vignetteImageDiv_' + uid + '_' + id).show();
				}/* end: if */

			}/* end: if */

		}/* end: if */

	}/* endfunction: componentDisplayVignette */
	
	
	/**
	 * Displays Gravure Field if gravureLength greather than 0
	 *
	 * @access public
	 * @return void
	 **/
	function componentDisplayGravure(uid, id, pconf) {

		if(typeof pconf == 'undefined') return;

		var gravureDiv	= $('#gravureDiv_' + uid + '_' + id);
		
		if(gravureDiv) {
					
			if(pconf['gravureLength'] != '' && pconf['gravureLength']>0) {
				
				if(gravureDiv.css('display') != 'block') {
					// set the max gravure length with the old document.getElementId
					var inputElem = document.getElementById('productGravureForm_' + uid + '_' + id);
					inputElem.maxLength = parseInt(pconf['gravureLength'],10);
					
					gravureDiv.show('slow');
				}/* end: if */
				
				$('#productGravureForm_' + uid + '_' + id + '_flag').val(1);
				gravureDiv.css('display','block');
				
			} else {
				
				if(gravureDiv.css('display') != 'none') {
					gravureDiv.hide('slow');
				}/* end: if */
				
				$('#productGravureForm_' + uid + '_' + id + '_flag').val(0);
				
				gravureDiv.css('display','none');
			}/* end: if */

		}/* end: if */

	}/* endfunction: componentDisplayGravure */


	/**
	 * Finds and returns current selected value for the given component
	 *
	 * @access public
	 * @return string
	 **/
	function currentComponent(uid, id, cform) {
		var returnValue		= '';
		var variationForm	= cform;

		if (variationForm) {
			if(variationForm.nodeName == 'SELECT' && variationForm.selectedIndex != -1) {
				returnValue = variationForm.options[variationForm.selectedIndex].value;
			} else if (variationForm.nodeName == 'INPUT'
				&& (variationForm.type == 'text'
					|| variationForm.type == 'hidden')
				) {

				returnValue = variationForm.value;
			} // end: if
		} else {
			returnValue = firstComponent(uid, id);
		} // end: if
 
		return returnValue;
	} // end: function currentComponent


	/* nfa@adva */
	/**
	 * bestimmten Cookie auslesen
	 *
	 * @access public
	 * @return void
	 **/
	function readCookie(name) {
		var all_cookies = document.cookie;
		if (all_cookies == '') {
			return false;
		}
		var start = all_cookies.indexOf(name+'=');
		if (start == -1) {
			return false;
		}
		start += name.length+1;
		var end = all_cookies.indexOf(';', start);
		if (end == -1) {
			end = all_cookies.length;
		}
		var cookie_wert = all_cookies.substring(start, end);
		var a = cookie_wert.split(';');
		for (var i=0; i<a.length; i++) {
			a[i] = a[i].split('=');
		}
		return true;
	}

	/**
	 * Submits add to basket form
	 *
	 * @access public
	 * @return void
	 **/
	function componentAddToBasket(uid, id) {

		var form			= document.getElementById('productForm_' + uid);
		var amountForm		= document.getElementById('productAmountForm_' + uid + '_' + id);
		var pkForm			= document.getElementById('productBasketPk_' + uid);
		var productPkForm	= document.getElementById('productBasketProductPk_' + uid);
		var variation		= currentVariation(uid, id);
		var size			= currentSize(uid, id, variation);
		var color			= currentColor(uid, id, variation, size);
		var amount			= 0;
		var meterWareMeter	= document.getElementById('productMWmeter_' + uid + '_' + id);
		var meterWareCMeter	= document.getElementById('productMWcentimeter_' + uid + '_' + id);
		var meter			= 0;
		var centimeter		= 0;
		var nometaware		= 0;
	
		// nfa@adva:
		/* var test = readCookie('soldout');
		// alert('Wert von test: '+test);
		if ( test === true) {
			form.submit();
		}*/

		if (amountForm) {
			if(amountForm.nodeName == 'SELECT') {
				amount = amountForm.options[amountForm.selectedIndex].value;
			} else if (amountForm.nodeName == 'INPUT'
				&& (amountForm.type == 'text'
					|| amountForm.type == 'hidden')) {
				amount = amountForm.value;
			} // end: if
		} // end: if
		
		if (meterWareMeter || meterWareCMeter) {
			if ( meterWareMeter.value > 0 ) {
				meter = meterWareMeter.value
			}
			
			if ( meterWareCMeter.value > 0 ) {
				centimeter = meterWareCMeter.value
			}
		} else {
			// no metaware for this client
			nometaware = 1;
		}

		if (form && pkForm && productPkForm && amount > 0 && articlePk[uid] > 0 && ( nometaware || meter > 0 || centimeter > 0)) {
			pkForm.value		= articlePk[uid];
			productPkForm.value = id;
			form.submit();
		} else if(articlePk[uid] == 0) {
			alert(errorInfoText);
		} else if(amount < 1 || isNaN(parseInt(amount))) {
			alert(errorAmountText);
		} else if (meterWareMeter && meterWareCMeter && meter < 1 && centimeter < 1) {
			alert(errorMeterwareText);
		} // end: if
		
	} // end: function componentAddToBasket


	/**
	 * Submits add to basket form
	 *
	 * @access public
	 * @return void
	 **/
	function componentAddToBasketSubmit(uid, id, target, popup, url, popupParams) {
		if (popup) {
			var form			= document.getElementById('productForm_' + uid);
			form.action 		= url;

			// do NOT load page from 'url' variable here! race condition w/ 2 Apache threads!
			window.open('/clear.gif', target, popupParams);
		} // end: if
		componentAddToBasket(uid, id);
		
		
	} // end: function componentAddToBasketSubmit


	/**
	 *  check if the gravure text need to be deleted
	 * 
	 * @param uid
	 * @param id
	 * @return void
	 */
	function removeGravureTextIfNeed(uid, id){
		var gravureElem 	= document.getElementById('productGravureForm_' + uid + '_' + id);
		
		if (gravureElem){
			if ($('#productGravureForm_' + uid + '_' + id + '_flag').length){
				// if flag is not set, remove the gravure text
				if ( $('#productGravureForm_' + uid + '_' + id + '_flag').val() == 0){
					gravureElem.value = "";
				}
			}
		}
		
	}

	/**
	 * Submits change article form
	 *
	 * @access public
	 * @return boolean
	 **/
	function changeComponentInBasket(uid, id) {
		var form			= document.getElementById('productForm_' + uid);
		var amountForm		= document.getElementById('productAmountForm_' + uid + '_' + id);
		var pkForm			= document.getElementById('productBasketPk_' + uid);
		var productPkForm	= document.getElementById('productBasketProductPk_' + uid);
		var amount			= 0;
		var gravureElem 	= document.getElementById('productGravureForm_' + uid + '_' + id);

		if (amountForm) {
			if(amountForm.nodeName == 'SELECT') {
				amount = amountForm.options[amountForm.selectedIndex].value;
			} else if (amountForm.nodeName == 'INPUT'
				&& (amountForm.type == 'text'
					|| amountForm.type == 'hidden')) {
				amount = amountForm.value;
			} // end: if
		} // end: if
			
		if (gravureElem){
			if ($('#productGravureForm_' + uid + '_' + id + '_flag').length){
				// if flag is not set, remove the gravure text
				if ( $('#productGravureForm_' + uid + '_' + id + '_flag').val() == 0){
					gravureElem.value = "";
				}
			}
		}
		
		
		if (form && pkForm && productPkForm && amount > 0 && articlePk[uid] > 0) {
			pkForm.value		= articlePk[uid];
			productPkForm.value = id;
			form.submit();
			window.close();
		} else if(articlePk[uid] == 0) {
			alert(errorInfoText);
		} // end: if
		
		return false;
	} // end: function changeComponentInBasket

	/**
	 *
	 * @access public
	 * @return boolean
	 **/
	function uncheckComponent(uid, id, componentName, e) {

		if(changeEvent == true) {
			changeEvent	= false;
			return false;
		}

		if(bindCtrlKey == true) {
			// capture event
			if(typeof e == 'undefined') {
				e = window.event;
			} // end: if

			// if control+click
			if(e.ctrlKey === false) {
				return false;
			} // end: if
		} // end: if

		// get the component form id
		var componentName	= componentName;
		var cId				= componentConf[uid][componentName];
		if(typeof cId == 'undefined') return;

		// gather necessary objects
		var componentForm		= document.getElementById(cId);
		var componentValue		= currentComponent(uid, id, componentForm);
		var clearFields			= true;
		var matchComponentValue	= false;

		// disable all
		disableAllComponents(uid, id);

		// delete from combi array
		delete combiArray[componentName];

		// clear article attributes
		clearArticleAttributes(uid, id);

		// look for matching components in all articles
		for(var i=0; i < productConf[uid][id]['articles'].length; i++) {

			var combiCount		= 0;
			var matchCount		= 0;

			// all components
			for(var componentType in combiArray) {

				// get component value
				matchComponentValue	= productConf[uid][id]['articles'][i][componentType]['value'];

				// if component type and value matches with the currently selected one
				if(combiArray[componentType] == matchComponentValue) {
					// no. of mathicng components
					matchCount++;
				} // end: if

				// no. of selected components
				combiCount++;

			} // end: for

			// if all selected combination matches
			if(matchCount == combiCount) {

				// update list
				changeComponents(uid, id, productConf[uid][id]['articles'][i]);

			} // end: if

		} // end: for

		return false;
	} // end: function uncheckComponent

	/**
	 * Disables all components, clears div for components
	 *
	 * @access public
	 * @return void
	 **/
	function disableAllComponents(uid, id, removeSelection){

		for(var componentType in componentConf[uid]) {

			var cId		= componentConf[uid][componentType];
			var cForm	= document.getElementById(cId);

			if(cForm) {

				if(cForm.nodeName == 'SELECT') {

					for (var j = 0; j < cForm.length; j++) {
						if(removeSelection != false) {
							cForm.options[j].selected		= false;
						} // end: if
						// set disable colour
						//cForm.options[j].style.color 	= disableColor;
						cForm.options[j].style.display = 'block';
						cForm.options[j].style.visibility	= 'visible';

						// nfa@adva:
						if ( productConf[uid][id]['articles'][j]['_ATTRIBUTES_']['stockType'] < 3 ) {
							// alert('AUSVERKAUFT ! ' + cForm.options[j].value);
							cForm.options[j].style.color = '#bbbbbb';
							cForm.options[j].style.textDecoration = 'line-through';
						}
						
					} // end: for

				} else if(cForm.nodeName == 'DIV') {
					if(removeSelection != false) {
						// clear single value
						cForm.innerHTML	= '';
					} // end: if

				} // end: if
			} // end: if
		} // end: for
	} // end: function disableAllComponents

	/**
	 * Fills combi array with matching article components
	 *
	 * @access public
	 * @return void
	 **/
	function fillCombiArray(uid, id, currentIndex) {
		
		for(var cName in productConf[uid][id]['articles'][currentIndex]) {

			// do not store '_ATTRIBUTES_'
			if( cName != '_ATTRIBUTES_' ) {

				// check component type, only multiple (list) should be added
				var cId		= componentConf[uid][cName];
				var cForm	= document.getElementById(cId);

				if(cForm && cForm.nodeName == 'SELECT') {

					componentName				= cName;
					componentValue				= productConf[uid][id]['articles'][currentIndex][cName]['value'];
					combiArray[componentName] 	= componentValue;
					
					// nfa@adva
					if ( productConf[uid][id]['articles'][currentIndex]['_ATTRIBUTES_']['stockType'] < 3 ) {
						$("select", document.forms[1]).addClass("productSoldOut");
					}
					else {
						$("select", document.forms[1]).removeClass("productSoldOut");
					}
					
				} // end: if

			} // end: if
		} // end: for

	} // end: function fillCombiArray

	/**
	 * Deletes component from combi array which are not at all selected
	 *
	 * @access public
	 * @return void
	 **/
	function cleanCombiArray(uid, id){

		// clean combi array
		for(var componentName in combiArray) {

			var cId		= componentConf[uid][componentName];
			if(typeof cId == 'undefined') return;

			// gather necessary objects
			var isSelected	= false;
			var cForm		= document.getElementById(cId);

			if(cForm.nodeName == 'SELECT') {
				for (var j = 0; j < cForm.length; j++) {
					if(cForm.options[j].selected == true) {
						isSelected	= true;

							// nfa@adva:
							if ( productConf[uid][id]['articles'][j]['_ATTRIBUTES_']['stockType'] < 3 ) {
								cForm.options[j].style.color = '#bbbbbb';
								cForm.options[j].style.textDecoration = 'line-through';
							}

					} // end: if
				} // end: for

				if(isSelected == false) {
					delete combiArray[componentName];
				} // end: if

			} // end: if

		} // end: for

	} // end: function cleanCombiArray

	/**
	 * Finds article basked on selected component combination
	 *
	 * @access public
	 * @return void
	 **/
	function findCombiArticle(componentIndex, uid, id) {
		// init vars
		matchCount	= 0;
		comCount	= 0;

		// find matching article
		for(var componentType in componentConf[uid]) {

			var cId		= componentConf[uid][componentType];
			var cForm	= document.getElementById(cId);

			if(cForm && cForm.nodeName == 'SELECT') {

				if(typeof combiArray[componentType] != 'undefined') {
					matchCount++;
				} // end: if

				comCount++;

			} // end: if

		} // end: for

		// all combinations matched
		if(matchCount == comCount) {
			// set global
			articleIndex = componentIndex;

			setAttributeDisplay(uid, id, productConf[uid][id]['articles'][componentIndex]);
		} // end: if

	} // end: function findCombiArticle

	/**
	 * Removes article attributes
	 *
	 * @access public
	 * @return void
	 **/
	function clearArticleAttributes(uid, id){
		// reset article pk
		articlePk[uid]	= 0;

		componentDisplayArtNumber(uid, id);
		componentDisplayPrice(uid, id);
		componentDisplayUVP(uid, id);
		componentDisplayAvailability(uid, id);

	} // end: function clearArticleAttributes

	/**
	 * Sorts associative array by value in ASC order
	 *
	 * @access public
	 * @return array
	 **/
	function sortAssoc(inputArray) {
		var aTemp	= [];
		for (var sKey in inputArray) {
			aTemp.push([sKey, inputArray[sKey]]);
		}

		aTemp.sort(function () {
			return arguments[0][1] < arguments[1][1]
		});

		var aOutput = [];
		for (var nIndex = aTemp.length-1; nIndex >=0; nIndex--) {
			aOutput[aTemp[nIndex][0]] = aTemp[nIndex][1];
		}

		return aOutput;
	} // end: function sortAssoc

	/**
	 *
	 * @access public
	 * @return void
	 **/
	function initBlockPrice(uid, id, articlePk){
		var priceDiv		= document.getElementById('productPrice_' + uid + '_' + id);
		var priceSummaryDiv	= document.getElementById('priceSummary_' + uid + '_' + id);
		var blockPriceCnt 	= 0;
		if(blockPriceConf[uid][articlePk][0]) {
			if(priceDiv) {
				priceDiv.innerHTML 	= blockPriceConf[uid][articlePk][0]['blockPrice'];
			} // end: if

			if(priceSummaryDiv){
				content = "<table style='background:#EFEFEF'><tr><td>"+hintMinQtyText+"</td><td>"+hintMaxQtyText+"</td><td>"+hintPriceText+"</td></tr>";
				for(var i=0; i < blockPriceConf[uid][articlePk].length; i++) {
					minQty		= blockPriceConf[uid][articlePk][i]['minQuantity'];
					maxQty		= blockPriceConf[uid][articlePk][i]['maxQuantity'];
					blockPrice	= blockPriceConf[uid][articlePk][i]['blockPrice'];
					content = content+"<tr><td>"+minQty+"</td><td>"+maxQty+"</td><td>"+blockPrice+"</td></tr>";
				} // end: for
				priceSummaryDiv.innerHTML = content + "</table>";
			} // end: if
		} // end: if
	} // end: function

	function displayComponentBlockPrice(uid, id) {
		var priceDiv			= document.getElementById('productPrice_' + uid + '_' + id);
		var amountTextForm		= document.getElementById('productAmountForm_' + uid + '_' + id);
		var priceSummaryDiv		= document.getElementById('priceSummary_' + uid + '_' + id);
		var blockPriceForm		= document.getElementById('productBlockPriceForm_' + uid + '_' + id);
		var blockPriceNotepadForm	= document.getElementById('productBlockPriceForm_' + uid);


		amountEntered 	= amountTextForm.value;
		artPK 			= articlePk[uid];

		var matchingFound 	= 0;
		if(blockPriceConf[uid][artPK][0]) {
			if (priceDiv) {
				for(var i=0; i < blockPriceConf[uid][artPK].length; i++) {
					minQty		= blockPriceConf[uid][artPK][i]['minQuantity'];
					maxQty		= blockPriceConf[uid][artPK][i]['maxQuantity'];
					blockPrice	= blockPriceConf[uid][artPK][i]['blockPrice'];

					if(parseInt(amountEntered) >= minQty && parseInt(amountEntered) <= maxQty) {
						priceDiv.innerHTML	= blockPrice;
						if (blockPriceForm) {
							blockPriceForm.value = blockPrice;
						} // end: if
						if(blockPriceNotepadForm) {
							blockPriceNotepadForm.value = blockPrice;
						} // end: if
						matchingFound = 1;
					} // end: if

				} // end: for

				if(amountEntered == "") {
					priceDiv.innerHTML	= blockPriceConf[uid][artPK][0]['blockPrice'];
					if (blockPriceForm) {
						blockPriceForm.value = blockPriceConf[uid][artPK][0]['blockPrice'];
					} // end: if
					if(blockPriceNotepadForm) {
						blockPriceNotepadForm.value = blockPriceConf[uid][artPK][0]['blockPrice'];
					} // end: if
					matchingFound = 1;
				} // end: if

			} // end: if

			if(priceSummaryDiv){
				content = "<table style='background:#EFEFEF'><tr><td>"+hintMinQtyText+"</td><td>"+hintMaxQtyText+"</td><td>"+hintPriceText+"</td></tr>";
				for(var i=0; i < blockPriceConf[uid][artPK].length; i++) {
					minQty		= blockPriceConf[uid][artPK][i]['minQuantity'];
					maxQty		= blockPriceConf[uid][artPK][i]['maxQuantity'];
					blockPrice	= blockPriceConf[uid][artPK][i]['blockPrice'];
					content = content+"<tr><td>"+minQty+"</td><td>"+maxQty+"</td><td>"+blockPrice+"</td></tr>";
				} // end: for
				priceSummaryDiv.innerHTML = content + "</table>";
			} // end: if

			if(matchingFound == 0) {
				amountTextForm.value = "";
				alert(blockPriceErrorText);
			} // end: if

		} // end: if

	} // end: function

	/**
	 *
	 * @access public
	 * @return void
	 **/
	function changeDisplayBlockPrice(uid, id){
		var priceDiv			= document.getElementById('productPrice_' 		+ uid + '_' + id);
		var amountTextForm		= document.getElementById('productAmountForm_' 		+ uid + '_' + id);
		var variation			= currentVariation(uid, id);
		var size				= currentSize(uid, id, variation);
		var color				= currentColor(uid, id, variation, size);
		var articlePk			= productConf[uid][id]['articles'][variation][size][color]['articlePk'];
		var priceSummaryDiv		= document.getElementById('priceSummary_' + uid + '_' + id);
		var blockPriceForm		= document.getElementById('productBlockPriceForm_' + uid + '_' + id);
		var blockPriceNotepadForm	= document.getElementById('productBlockPriceForm_' + uid);

		amountEntered 	= amountTextForm.value;

		var matchingFound 	= 0;
		if(blockPriceConf[uid][articlePk][0]) {
			if (priceDiv) {
				for(var i=0; i < blockPriceConf[uid][articlePk].length; i++) {
					minQty		= blockPriceConf[uid][articlePk][i]['minQuantity'];
					maxQty		= blockPriceConf[uid][articlePk][i]['maxQuantity'];
					blockPrice	= blockPriceConf[uid][articlePk][i]['blockPrice'];

					if(parseInt(amountEntered) >= minQty && parseInt(amountEntered) <= maxQty) {
						priceDiv.innerHTML	= blockPrice;
						if (blockPriceForm) {
							blockPriceForm.value = blockPrice;
						} // end: if
						if(blockPriceNotepadForm) {
							blockPriceNotepadForm.value = blockPrice;
						} // end: if
						matchingFound = 1;
					} // end: if
				} // end: for

				if(amountEntered == "") {
					priceDiv.innerHTML	= blockPriceConf[uid][articlePk][0]['blockPrice'];
					if (blockPriceForm) {
						blockPriceForm.value = blockPriceConf[uid][articlePk][0]['blockPrice'];
					} // end: if
					if(blockPriceNotepadForm) {
						blockPriceNotepadForm.value = blockPriceConf[uid][articlePk][0]['blockPrice'];;
					} // end: if
					matchingFound = 1;
				} // end: if
			} // end: if

			if(priceSummaryDiv){
				content = "<table style='background:#EFEFEF'><tr><td>"+hintMinQtyText+"</td><td>"+hintMaxQtyText+"</td><td>"+hintPriceText+"</td></tr>";
				for(var i=0; i < blockPriceConf[uid][articlePk].length; i++) {
					minQty		= blockPriceConf[uid][articlePk][i]['minQuantity'];
					maxQty		= blockPriceConf[uid][articlePk][i]['maxQuantity'];
					blockPrice	= blockPriceConf[uid][articlePk][i]['blockPrice'];
					content = content+"<tr><td>"+minQty+"</td><td>"+maxQty+"</td><td>"+blockPrice+"</td></tr>";
				} // end: for
				priceSummaryDiv.innerHTML = content + "</table>";
			} // end: if

			if(matchingFound == 0) {
				amountTextForm.value = "";
				alert(blockPriceErrorText);
			} // end: if

		} // end: if

	} // end: function


	function intoBasket(id) {
			
		var form = document.getElementById("orderlineForm_"+id); /* uid hinzufuegen */
		form.submit();
	}
	
var shoppingbasketFormDoubleSubmit = false;
var noDeliverySelected;
var aboCount;

function checkDelivery()
{   
    noDeliverySelected = false;
    $('select#deliveryFrequency :selected').each(function(){
	        if ($(this).val()==0) {
	            noDeliverySelected = true;    
	        }
        }
	);
	    
    $('select#deliveryDay :selected').each(function(){
            if ($(this).val()==0) {
                noDeliverySelected = true;    
            }
        }
    );    
    if (noDeliverySelected) {
        $('#noDeliveryFrequency').show();
        $('#deliveryDay').focus();
    }
    else $('#noDeliveryFrequency').hide();
    
    return noDeliverySelected;
}

function shoppingbasketFormSubmit(ctype, uid, nextstepValue) {
	var form			= document.getElementById(ctype + '_' + uid + '_' + 'form');
	var nextstep		= document.getElementById(ctype + '[' + uid + ']' + '[nextstep]');
	var currentstep		= document.getElementById(ctype + '[' + uid + ']' + '[step]');
	
	if (nextstepValue==20 && aboCount>0) {
	    if (checkDelivery()) return false;
	}
	
	if (shoppingbasketFormDoubleSubmit == false) {
		if (form && nextstep && nextstepValue > 0) {
			shoppingbasketFormDoubleSubmit = true;
			if(currentstep.value != "15"){
				nextstep.value 	= nextstepValue;
			}
			form.submit();
		}
	}
}

/*
 * form submit with a target anchor
 */
function shoppingbasketFormSubmit2(ctype, uid, nextstepValue, anchor) {
	var form			= document.getElementById(ctype + '_' + uid + '_' + 'form');
	var nextstep		= document.getElementById(ctype + '[' + uid + ']' + '[nextstep]');
	if (shoppingbasketFormDoubleSubmit == false) {
		if (form && nextstep && nextstepValue > 0) {
			shoppingbasketFormDoubleSubmit = true;
			nextstep.value 	= nextstepValue;
			
			if (anchor && anchor.length){
				form.action = form.action + "#" + anchor;
			}
			form.submit();
		}
	}
}

var solvency = '';
function shoppingBasketValidateAndFormSubmit(formId, cType, uid, nextstepValue) {
	if ( $('#' + formId).valid() ) {
		if (solvency == '1'
		&& (nextstepValue == '21' || nextstepValue == '30')
		) {
			var b = $("body")
				.append("<div id='basketoverlay'></div><div id='basketoverlaycontent'></div>"); 
			var ol = $('#basketoverlay')
				.css({height:b.height()+'px'})
				.fadeIn();
			var l = $('<img>')
				.attr({id:"loading", src:'/fileadmin/resources/_CORE/img/global/loadingAnimation_2.gif'})
				.hide();
			var olc = $('#basketoverlaycontent')
				.append(l)
				.fadeIn();
			var resetLoading = function () {
				$('#loading').attr({src:$('#loading').attr('src')}).fadeIn();
			}
				
			shoppingbasketFormSubmit(cType, uid, nextstepValue);
			setTimeout(resetLoading,1);
		} else {
    		shoppingbasketFormSubmit(cType, uid, nextstepValue);
    	}
	} else {
		$.scrollTo($(".error:first").parent());
		$("#.error:first").focus();
	}
}

function shoppingBasketValidateAndFormSubmit2(formId, cType, uid, nextstepValue, anchor) {
	if ( $('#' + formId).valid() ) {
		shoppingbasketFormSubmit2(cType, uid, nextstepValue, anchor);
	} else {
		$.scrollTo($(".error:first").parent());
		$("#.error:first").focus();
	}
}


function shoppingBasketLogin(formId, cType, uid, nextstepValue) {
	if (  $('#basketloginnewcustomer:checked').length || $('#basketloginnopass:checked').length  ){
		
		var form			= document.getElementById(cType + '_' + uid + '_' + 'form');
		var nextstep		= document.getElementById(cType + '[' + uid + ']' + '[nextstep]');
		
			// no check the double submit flag
			if (form && nextstep && nextstepValue > 0) {
				nextstep.value 	= nextstepValue;
				form.submit();
			}
	} else {
		shoppingBasketValidateAndFormSubmit(formId, cType, uid, nextstepValue);
	}
}


function shoppingbasketFormSubmitDeleteDeliveryAddress(ctype, uid, nextstepValue){
	var form	= document.getElementById(ctype + '_' + uid + '_' + 'form');

		// form.action: delete delivery address;
	   var el = document.createElement('input');
	   el.type = 'hidden';
	   el.name = ctype + '[' + uid + ']' + '[deleteDeliveryAddress]';
	   el.value = "1";
	   form.appendChild(el);

	shoppingbasketFormSubmit(ctype, uid, nextstepValue);
}

// abweichende Lieferadresse loeschen, wenn nur der Radiobutton geklickt wurde
function shoppingbasketFormSubmitDeleteDeliveryAddress2(ctype, uid, nextstepValue){
	var field =  document.getElementById('delivery_to_different_adress');

		// form.action: delete delivery address;
	   var el = document.createElement('input');
	   el.type = 'hidden';
	   el.name = ctype + '[' + uid + ']' + '[deleteDeliveryAddress]';
	   el.value = "1";
	   field.appendChild(el);

	shoppingbasketFormSubmit(ctype, uid, nextstepValue);
}

function shoppingbasketFormChangeAction(ctype, uid, oldAction, newAction) {
	var form			= document.getElementById(ctype + '_' + uid + '_' + 'form');
	var action			= document.getElementById(ctype + '[' + uid + ']' + '[action][' + oldAction + ']');

	if (action) {
		action.value = newAction;
	}
}

/**
* This is used for the extension specific functions
*
* @package		mb3p
* @subpackage	shoppingbasketcached
* @access		public
* @author	    Boris Azar
* @version		1.0.0
*/
var dmc_mb3_shoppingbasketcached = {

	// public method for url decoding
	decode : function (data) {
		var lsRegExp = /\+/g;
		// Return the decoded string
		return this.decodeUtf8(unescape(String(data).replace(lsRegExp, " ")));
	},

	/**
	* decodes a string in utf8
	*
	* @param string 	utftext							string to be decoded
	* @return void
	*/
	decodeUtf8: function (utftext) {
		var plaintext = "";
		var i=0;
		var c=0;
		var c1=0;
		var c2=0;

		// while-Schleife, weil einige Zeichen uebersprungen werden
		while(i<utftext.length) {
			c = utftext.charCodeAt(i);
			if (c<128) {
				plaintext += String.fromCharCode(c);
				i++;
			} else if((c>191) && (c<224)) {
				c2 = utftext.charCodeAt(i+1);
				plaintext += String.fromCharCode(((c&31)<<6) | (c2&63));
				i+=2;
			} else {
				c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2);
				plaintext += String.fromCharCode(((c&15)<<12) | ((c2&63)<<6) | (c3&63));
				i+=3;
			}
		}

		return plaintext;
	 } // end: function

}

/**
* Shoppingbasketcached function
*
* @package		mb3p
* @subpackage	shoppingbasketcached
* @access		public
* @author	    Boris Azar
* @version		1.0.0
*/

/**
* Sets a cookie
*
* @param string 	basketAmountContainerId			id of the basketAmountContainer
* @param string 	articlesAmountContainerId		id of the articlesAmountContainer
* @return void
*/
function fillShoppingBasketWithData(basketAmountContainerId, articlesAmountContainerId, tipText) {
	var articlesAmountContainer = document.getElementById(articlesAmountContainerId);
	var basketAmountContainer = document.getElementById(basketAmountContainerId);

	var cookieData = cookie_get('mb3pc');

	if (cookieData && typeof cookieData != 'undefined') {

		var data = JSON.parse(cookieData);
		if (data) {
			// get the articlesAmountContainer object and set data in it
			if (articlesAmountContainer
				&& typeof data.shoppingbasket.articlesAmount != 'undefined') {

				// do not forget to decode the data (+ signs are converted back to spaces)
				articlesAmountContainerValue = dmc_mb3_shoppingbasketcached.decode(data.shoppingbasket.articlesAmount);

				// get the articlesAmountContainer object and set data in it
				if (articlesAmountContainer) {
					// do not forget to decode the data (+ signs are converted back to spaces)
					articlesAmountContainer.innerHTML = articlesAmountContainerValue;
				} // end: if

			} // end: if

			// get the basketAmountContainer object and set data in it
			if (basketAmountContainer
				&& typeof data.shoppingbasket.basketAmount != 'undefined') {

				// do not forget to decode the data (+ signs are converted back to spaces)
				basketAmountContainerValue = dmc_mb3_shoppingbasketcached.decode(data.shoppingbasket.basketAmount);

				// get the basketAmountContainer object and set data in it
				if (basketAmountContainer) {
					// do not forget to decode the data (+ signs are converted back to spaces)
					basketAmountContainer.innerHTML = basketAmountContainerValue;
				} // end: if
			} // end: if

			resetCookie();
		} // end: if
	} // end: if
} // end: function

function resetCookie() {
	var cookieData = cookie_get('mb3pc');
	if (cookieData && typeof cookieData != 'undefined') {
		var data = JSON.parse(cookieData);

		if (data) {
			data.shoppingbasket.basketAddStatus = "0";
			cookieDataUpdated = JSON.stringify(data);
			cookie_set('mb3pc',cookieDataUpdated,'','/');
		}// end: if

	} // end: if
}// end: function

function isBasketEmpty(){
	var cookieData  = cookie_get('mb3pc');
	var retval 	    = true;

	if (cookieData && typeof cookieData != 'undefined') {

		var data = JSON.parse(cookieData);
		if (data) {
			if (typeof data.shoppingbasket != 'undefiend' && data.shoppingbasket.articlesAmount != 0) {
				retval = false;
			}
		}
	}
	return retval;
}

/**
* performs delivery address name change submit defined by ctype and uid
*
* @access public
* @param ctype the name of the extension
* @param uid the uid of the pageelement
* @return void
*/
function deliveryAddressChangeName(ctype, uid) {
	var form = document.getElementById(ctype + '_' + uid + '_' + 'form');
	if (form) {
		document.getElementById(ctype + '[' + uid + ']' + '[action]' + '[changeDeliveryCustomer]').value = "loadDeliveryAddress";
		form.submit();
	} // end: if
} // end: function

/**
*
* @access privat
* @return void
**/
function changeValidation(targetId, elementId, newsletterBoxId){
	if(document.getElementById(elementId).checked) {
		addIgnoreClass(targetId);
		unCheck(newsletterBoxId);
	} else {
		removeIgnoreClass(targetId);
	}
}

/**
 *
 * @access public
 * @return void
 **/
function changeBonusWishValidation(objSelect, divId, formId){
	 
	 
	if(objSelect.options[objSelect.selectedIndex].value != '000000') {
		removeIgnoreClasses(divId);

	} else {
		setOverallIgnoreClass(divId);
		$('#'+formId).valid();	
		//reset input values if no bonus selected	
		$("#" + divId) . find("input") . val('');
	}
}


/**
 * looks and sets errormessage
 * because only Bonus OR voucher can be inserted
 *
 * @access public
 * @return void
 **/
function setBonusVoucherValidation(checkId1, checkId2){
	if(document.getElementById(checkId1).value) {
		document.getElementById(checkId2).value = '';
		removeIgnoreClass(checkId1);
	}
}

/**
* switches the ignore fields depending on which deliverytype is selected
*
* @access public
* @return void
**/
function changeDeliveryIgnores(elementId) {
	deliveryTypes = new Array(
		"delivery_to_different_adress",
		"delivery_to_dhlpackstation",
		"delivery_to_kiala");

	for(var i=0;i < deliveryTypes.length; i++) {
		setOverallIgnoreClass(deliveryTypes[i]);
	}
	removeIgnoreClasses(elementId);
}

function getKialaPoints(ctype, uid, nextuid, url) {
	var zip = document.getElementById(ctype+'['+uid+'][delivery][kialaZip]').value;	
	var protocol = window.location.protocol;
	var host = window.location.host;
	var pattern = {
		protocol:new RegExp('(http://|https://)'),
		host:new RegExp(host)
	};
	
	url = url.replace(pattern.protocol, '');
	url = url.replace(pattern.host, '');

	if (protocol == 'https:') {
		url = 'https://'+host+''+url;
	} else {
		url = 'http://'+host+''+url;
	}

	if (zip != '') {
		url += '?'+ctype+'['+nextuid+'][delivery][kialaZip]='+zip;
	}
	
	$('#kialaLoading').toggle();
	$.ajax({
		type: "GET",
		url: url,
		dataType: "html",
		success: function(content){
			$('#kialaLoading').toggle();
			document.getElementById(ctype+'['+uid+'][delivery][kialaStation]').innerHTML = content;
		}
	});

}



	function addToNotepad(uid, id) {

		var form				= document.getElementById('notepadForm_' + uid);
		var notepadArticlePk	= document.getElementById('notepadArticlePk_' + uid);
		var notepadProductPk	= document.getElementById('notepadProductPk_' + uid);
		var notepadAmount		= document.getElementById('notepadAmount_' + uid);

		var amountForm		= document.getElementById('productAmountForm_' + uid + '_' + id);
		var variation		= currentVariation(uid, id);
		var size			= currentSize(uid, id, variation);
		var color			= currentColor(uid, id, variation, size);
		var amount			= 0;

		if (amountForm) {
			if(amountForm.nodeName == 'SELECT') {
				amount = amountForm.options[amountForm.selectedIndex].value;
			} else if (amountForm.nodeName == 'INPUT'
				&& (amountForm.type == 'text'
					|| amountForm.type == 'hidden')) {
				amount = amountForm.value;
			} // end: if
		} // end: if

		if(amount == "") {
			artPk 	= productConf[uid][id]['articles'][variation][size][color]['articlePk'];
			if(blockPriceConf[uid][artPk][0]) {
				amount 	= blockPriceConf[uid][artPk][0]['minQuantity'];
			} else {
				amount 	= 1;
			}
		} // end: if

		if (form && notepadArticlePk && notepadProductPk && amount > 0) {
			notepadArticlePk.value 	= productConf[uid][id]['articles'][variation][size][color]['articlePk'];
			notepadProductPk.value 	= id;
			notepadAmount.value		= amount;
			form.submit();
		} else if(amount < 1 || isNaN(parseInt(amount))) {
			alert(errorAmountText);
		} // end: if
	}

	function componentAddToNotepad(uid, id, errorInfoText) {
		var form				= document.getElementById('notepadForm_' + uid);
		var notepadArticlePk	= document.getElementById('notepadArticlePk_' + uid);
		var notepadProductPk	= document.getElementById('notepadProductPk_' + uid);
		var notepadAmount		= document.getElementById('notepadAmount_' + uid);
		var notepadGravure		= document.getElementById('notepadGravure_' + uid);
		var notepadMeterwareMeter	= document.getElementById('notepadMeterwareMeter_' + uid);
		var notepadMeterwareCentimeter	= document.getElementById('notepadMeterwareCentimeter_' + uid);
		
		var gravure			= document.getElementById('productGravureForm_' + uid + '_' + id);
		var meterwareMeter	= document.getElementById('productMWmeter_' + uid + '_' + id);
		var meterwareCMeter	= document.getElementById('productMWcentimeter_' + uid + '_' + id);
		var amountForm		= document.getElementById('productAmountForm_' + uid + '_' + id);
		var amount			= 0;
		
		if (amountForm) {
			if(amountForm.nodeName == 'SELECT') {
				amount = amountForm.options[amountForm.selectedIndex].value;
			} else if (amountForm.nodeName == 'INPUT'
				&& (amountForm.type == 'text'
					|| amountForm.type == 'hidden')) {
				amount = amountForm.value;
			} // end: if
		} // end: if

		if(amount == "") {
			if(articlePk[uid] > 0) {
				artPk 	= articlePk[uid];
				//if(blockPriceConf[uid][artPk][0]) {
				//	amount 	= blockPriceConf[uid][artPk][0]['minQuantity'];
				//} else {
					amount 	= 1;
				//} // end: if
			} // end: if
		} // end: if		
		
		if (form && notepadArticlePk && notepadProductPk && amount > 0 && articlePk[uid] > 0) {
			notepadArticlePk.value 	= articlePk[uid];
			notepadProductPk.value 	= id;
			notepadAmount.value		= amount;
			if (gravure && gravure.value != "") {				
				notepadGravure.value = gravure.value;
			}
			if (meterwareMeter && meterwareMeter.value != "") {
				notepadMeterwareMeter.value = meterwareMeter.value;
			}
			if (meterwareCMeter && meterwareCMeter.value != "") {
				notepadMeterwareCentimeter.value = meterwareCMeter.value;
			}
			form.submit();			
		} else if(articlePk[uid] == 0) {
			alert(errorInfoText);
		} else if(amount < 1 || isNaN(parseInt(amount))) {
			alert(errorAmountText);
		} // end: if
	}


	/**
	* This is used for the extension specific functions
	*
	* @package		mb3p
	* @subpackage	notepadcached
	* @access		public
	* @author	    Boris Azar
	* @version		1.0.0
	*/
	var dmc_mb3_notepadcached = {

		// public method for url decoding
		decode : function (data) {
			var lsRegExp = /\+/g;
			// Return the decoded string
			return this.decodeUtf8(unescape(String(data).replace(lsRegExp, " ")));
		},

		/**
		* decodes a string in utf8
		*
		* @param string 	utftext							string to be decoded
		* @return void
		*/
		decodeUtf8: function (utftext) {
			var plaintext = "";
			var i=0;
			var c=0;
			var c1=0;
			var c2=0;

			// while-Schleife, weil einige Zeichen uebersprungen werden
			while(i<utftext.length) {
				c = utftext.charCodeAt(i);
				if (c<128) {
					plaintext += String.fromCharCode(c);
					i++;
				} else if((c>191) && (c<224)) {
					c2 = utftext.charCodeAt(i+1);
					plaintext += String.fromCharCode(((c&31)<<6) | (c2&63));
					i+=2;
				} else {
					c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2);
					plaintext += String.fromCharCode(((c&15)<<12) | ((c2&63)<<6) | (c3&63));
					i+=3;
				}
			}

			return plaintext;
		 } // end: function

	}

	/**
	* Notepadcached function
	*
	* @package		mb3p
	* @subpackage	notepadcached
	* @access		public
	* @author	    Boris Azar
	* @version		1.0.0
	*/

	/**
	* Sets a cookie
	*
	* @param string 	notepadAmountContainerId			id of the notepadAmountContainer
	* @param string 	notepadArticleAmountContainerId		id of the notepadArticleAmountContainer
	* @return void
	*/
	function fillNotepadWithData(notepadAmountContainerId, notepadArticleAmountContainerId, tipText) {
		var notepadArticlesAmountContainer = document.getElementById(notepadArticleAmountContainerId);
		var notepadAmountContainer = document.getElementById(notepadAmountContainerId);

		var cookieData = cookie_get('mb3pc');
		if (cookieData && typeof cookieData != 'undefined') {

			var data = JSON.parse(cookieData);
			if (data && typeof data.notepad != 'undefined') {
				// get the notepadArticlesAmountContainer object and set data in it
				if (notepadArticlesAmountContainer
					&& typeof data.notepad.articlesAmount != 'undefined') {

					// do not forget to decode the data (+ signs are converted back to spaces)
					notepadArticlesAmountContainerValue = dmc_mb3_notepadcached.decode(data.notepad.articlesAmount);

					// get the notepadArticlesAmountContainer object and set data in it
					if (notepadArticlesAmountContainer) {
						// do not forget to decode the data (+ signs are converted back to spaces)
						notepadArticlesAmountContainer.innerHTML = notepadArticlesAmountContainerValue;
					} // end: if

				} // end: if

				// get the notepadAmountContainer object and set data in it
				if (notepadAmountContainer
					&& typeof data.notepad.notepadAmount != 'undefined') {

					// do not forget to decode the data (+ signs are converted back to spaces)
					notepadAmountContainerValue = dmc_mb3_notepadcached.decode(data.notepad.notepadAmount);

					// get the notepadAmountContainer object and set data in it
					if (notepadAmountContainer) {
						// do not forget to decode the data (+ signs are converted back to spaces)
						notepadAmountContainer.innerHTML = notepadAmountContainerValue;
					} // end: if
				} // end: if

				if(data.notepad.notepadAddStatus == 1) {
					showToolTip(notepadAmountContainerId,tipText);
				} // end: if

				resetNotepadCookie();
			} // end: if
		} // end: if
	} // end: function

	function resetNotepadCookie() {
		var cookieData = cookie_get('mb3pc');
		if (cookieData && typeof cookieData != 'undefined') {
			var data = JSON.parse(cookieData);

			if (data) {
				data.notepad.notepadAddStatus = "0";
				cookieDataUpdated = JSON.stringify(data);
				cookie_set('mb3pc',cookieDataUpdated,'','/');
			} // end: if

		} // end: if
	} // end: function

	function isNotepadEmpty(){
		var cookieData  = cookie_get('mb3pc');
		var retval 	    = true;

		if (cookieData && typeof cookieData != 'undefined') {

			var data = JSON.parse(cookieData);
			if (data) {
				if (typeof data.notepad != 'undefined' && data.notepad.articlesAmount != 0) {
					retval = false;
				}
			}
		}
		return retval;
	}

	function checkAllCheckboxes(formName,checkboxName){
		for (var i = 0; i < document.forms[formName].elements.length; i++) {
			if(document.forms[formName].elements[i].type == 'checkbox'
				&& document.forms[formName].elements[i].name.match(checkboxName)) {
				document.forms[formName].elements[i].checked = true;
			}
		}
	}

	function uncheckAllCheckboxes(formName,checkboxName){
		for (var i = 0; i < document.forms[formName].elements.length; i++) {
			if(document.forms[formName].elements[i].type == 'checkbox'
				&& document.forms[formName].elements[i].name.match(checkboxName)) {
				document.forms[formName].elements[i].checked = false;
			}
		}
	}
	
    function checkGiftdeskLimit(formName,checkboxName,size,maxsize,toomuchtext1,toomuchtext2){
		var marked = 0;
		for (var i = 0; i < document.forms[formName].elements.length; i++) {
			if(document.forms[formName].elements[i].type == 'checkbox'
				&& document.forms[formName].elements[i].name.match(checkboxName)
				&& document.forms[formName].elements[i].checked == true) {
				marked++;
			}			
		}
		var total = size + marked; 
		if (total > maxsize) {
			var toomuch = total - maxsize;
			alert(toomuchtext1 + toomuch + toomuchtext2);
		} else {
			document.forms[formName].submit();
		}
	}
    
    /**
     * function for gift desk submit
     * @param formName
     * @param checkboxName
     * @param size
     * @param maxsize
     * @param toomuchtext1
     * @param toomuchtext2
     * @return
     */
    function checkGiftdeskLimitAndSubmit(ctype,uid, checkboxName,size,maxsize,toomuchtext1,toomuchtext2){
		var marked = 0;
		for (var i = 0; i < document.forms[ctype].elements.length; i++) {
			if(document.forms[ctype].elements[i].type == 'checkbox'
				&& document.forms[ctype].elements[i].name.match(checkboxName)
				&& document.forms[ctype].elements[i].checked == true) {
				marked++;
			}			
		}
		var total = size + marked; 
		if (total > maxsize) {
			var toomuch = total - maxsize;
			alert(toomuchtext1 + toomuch + toomuchtext2);
		} else {
			// submit		
			if ($('#' + ctype).valid()){
				document.forms[ctype].submit();
			}
		}
    }
// TAKE CARE TO NOT USE is(':visible') on table-rows
// to make sure that IE will work correctly

var orderLinesColection = new Array();
var errors = new Array();
var minimumOnceChangedFields = new Object();

var artnumber_first = null;
var artnumber_second = null;
var description = null;

var errorlineStart = null;
var errorlineEnd = null;


function orderFormChangeAction(ctype, uid, actionName, actionValue, additionalParam) {
    var form			= document.getElementById(ctype + '[' + uid + ']' + '[form]');
    var action			= document.getElementById(ctype + '[' + uid + ']' + '[action]');

    if(additionalParam != null) {
        additionalParam	= '[' + additionalParam + ']';
    }

    if (action) {
        action.name		= ctype + '[' + uid + '][action][' + actionName + ']' + additionalParam;
        action.value	= actionValue;
    }

    return true;
}

function setDivVisible(field) {

    if (document.getElementById('selectbox_' + field).length > 0) {
        document.getElementById('selectdiv_' +field).className = 'fieldVisible';
        document.getElementById('selectdiv_' +field).style.visibility = 'visible';
    }
}

function setupFields() {

    for (var lineNumber=0; lineNumber < numberOfOrderlines; lineNumber++) {
        updateSize(lineNumber);
    }
}

function updateSize(lineNumber) {
    // find size text field and clear it
    var inputSizeExt = document.getElementById('text_size_' + lineNumber);
    var inputSizeInt = document.getElementById('size_' + lineNumber);
    var alreadyUpdated = inputSizeExt.alreadyUpdated;
    var oldSize = '';
    var oldSizeStillAvailable = false;

    if (!alreadyUpdated) {
        inputSizeExt.alreadyUpdated = true;
    } else {
        inputSizeExt.className = inputSizeExt.className.replace('formError', 'noError');
        oldSizeExt = inputSizeExt.value;
        oldSizeInt = inputSizeInt.value;
        inputSizeExt.value = '';
        inputSizeInt.value = '';
    }

    // removes all options from the selectbox
    var selectboxSize = document.getElementById('selectbox_size_'+lineNumber);
    for (var i=selectboxSize.length; i > 0; i--) {
        selectboxSize.options[i-1] = null;
    }

    //break if no changes yet
    if(artnumber_first == null) return;
    // adds available options from the array to the selectbox
    var artnumber = artnumber_first.value + '' + artnumber_second.value;


    if (artnumber) {
        if (orderLinesColection.length&&orderLinesColection[lineNumber]&&artnumber.indexOf(orderLinesColection[lineNumber]['artikel']['artnr'])>-1) {
            for (var size in orderLinesColection[lineNumber]['sizes']) {
                if (typeof(orderLinesColection[lineNumber]['sizes'][size]) == 'object') {

                    var sizeExt = orderLinesColection[lineNumber]['sizes'][size]['artikel']['ausgroe'];
                    var sizeInt = orderLinesColection[lineNumber]['sizes'][size]['artikel']['groesse'];

                    if (size == '-') {
                        sizeExt = size;
                    }

                    // [di] Exception for Jungborn
                    if(self.name=="jbdemain" || self.name == 'jbatmain') {
                        switch (size) {
                            case '001' :
                                sizeExt = "ganze Bohne";
                                break;
                            case '002':
                                sizeExt = "gemahlen";
                                break;
                        }
                    }

                    if (oldSizeExt !== '' && sizeExt == oldSizeExt) {
                        oldSizeStillAvailable = true;
                    }

                    newoption = new Option(sizeExt, sizeInt);
                    selectboxSize.options[selectboxSize.length] = newoption;
                }
            }
        }
    }
    if (oldSizeStillAvailable) {
        inputSizeExt.value = oldSizeExt;
        inputSizeInt.value = oldSizeInt;
    } else {
        //preset the first option if there is only one or invalid option
        if (selectboxSize.length == 1 ||
            (selectboxSize.length > 0 && (!inputSizeExt.value))) {
            inputSizeExt.value = selectboxSize.options[0].text;
            inputSizeInt.value = selectboxSize.options[0].value;
        }
    }

    updateStaticFields(lineNumber);
}

function updateStaticFieldsOnBlur(lineNumber) {
	if(!orderLinesColection[lineNumber]) {
		return;
	}
	
	updateStaticFields(lineNumber);
}

function updateStaticFields(lineNumber) {

    // sets static fields depending on the selection of the fields
    // 'artnumber', 'variation', 'size', 'color' and 'amount'
    if ( artnumber_first == null || artnumber_second == null ) {
        return false;
    } //if

    var artnumber 			= artnumber_first.value + '' + artnumber_second.value;
    var sizeExt 	   		= document.getElementById('text_size_'+lineNumber).value;
    var sizeInt 	   		= document.getElementById('size_'+lineNumber).value;
    var size				= "";
    var amountField 		= document.getElementById('text_amount_'+lineNumber);
    // default settings
    var amountNum = '';
    var description = '';
	var lieferaussage = '';
    var imageURL	= clearGif;
    var imageHeight = 1;
    var productlink = '#';
    var singlePrice = '';
    var	totalPrice 	= '';
    var	stocktype	= '';
    var currency	= '&euro;';

    if (sizeExt == '-') {
        size = sizeExt;
    } else {
        size = sizeInt;
    }

    // field that depend on articlenumber only
    if (artnumber && orderLinesColection.length && orderLinesColection[lineNumber]
        && orderLinesColection[lineNumber]['artikel']&&artnumber.indexOf(orderLinesColection[lineNumber]['artikel']['artnr']>-1)) {
    /*
		// if set it could display the producttext even before size and color is chosen.
		if(orderLinesColection[lineNumber]['properties']){
			imageURL	= orderLinesColection[lineNumber]['properties']['imageURL'];
			imageHeight = 40;
			productlink = 'product/' + orderLinesColection[lineNumber]['properties']['productPk'] + '/group/' + orderLinesColection[lineNumber]['properties']['groupPk'] + productURL;
		}
*/	}

    // fields that depend on all attributes
    if (artnumber && orderLinesColection.length && orderLinesColection[lineNumber]&& orderLinesColection[lineNumber]['sizes']
        && orderLinesColection[lineNumber]['sizes'][size]) {
        singlePriceNum 	= (parseFloat(orderLinesColection[lineNumber]['sizes'][size]['preis'])).toFixed(2);
        amountNum 		= parseInt(amountField.value);

        if (isNaN(amountNum) || amountNum <= 0) {
            amountNum = 1;
        } else if (amountNum > 100) {
            amountNum = 100;
        }
        amountField.className = amountField.className.replace('formError', 'noError');

        if (isNaN(singlePriceNum))  {
            singlePrice = '';
        } else {
            singlePrice = singlePriceNum+' '+currency;
        }
        if (isNaN(singlePriceNum))  {
            totalPrice = '';
        } else {
            totalPrice = (singlePriceNum * amountNum).toFixed(2)+' '+currency;
        }
        description = orderLinesColection[lineNumber]['sizes'][size]['artbez'];
		lieferaussage = orderLinesColection[lineNumber]['sizes'][size]['lieferaussage']['liefaus'];
        /*		if (description == ''){
			description = orderLinesColection[lineNumber]['properties']['text'];
		}
*/		stocktype	= stockTypeCodes[orderLinesColection[lineNumber]['sizes'][size]['lieftext']];
    }
	//set availibility Text
	if(availabilityTexts[lieferaussage] != undefined) {
		availabilityText = availabilityTexts[lieferaussage]
	} else {
		availabilityText = '';
	}

    document.getElementById('text_amount_'+lineNumber).value = amountNum;
    //	document.getElementById('label_singleprice_'+lineNumber).innerHTML = singlePrice.replace('.',',');
    //	document.getElementById('label_totalprice_'+lineNumber).innerHTML = totalPrice.replace('.',',');
    document.getElementById('label_description_'+lineNumber).innerHTML = "<div class='orderform_description'>" + description + "</div>";
  	document.getElementById('label_availability_'+lineNumber).innerHTML = availabilityText ;
  //	document.getElementById('label_stocktype_'+lineNumber).innerHTML = stocktype;
    //	document.getElementById('label_image_'+lineNumber).src = imageURL;
    //	document.getElementById('label_image_'+lineNumber).width = imageHeight;
    //	document.getElementById('productlink_'+lineNumber).value = productlink;
	setAvailabilityColor(lieferaussage, lineNumber);

    if (javaErrorcheck) {
        errorCheck(lineNumber);
    }
}

function errorCheck(lineNumber) {

    var error      = false;
    var errorLabel = "";
    var sizeExt 	= document.getElementById('text_size_'+lineNumber).value;
    var sizeInt 	= document.getElementById('size_'+lineNumber).value;
    var size		= "";
    var classname  	= "";
    var artnumber   = artnumber_first.value + '' + artnumber_second.value;
    var lnf         = 0;

    if (sizeExt == '-') {
        size = sizeExt;
    } else {
        size = sizeInt;
    }

    if (artnumber.length > 0 ) {
        if( orderLinesColection.length && orderLinesColection[lineNumber] &&
            orderLinesColection[lineNumber]['artikel'] &&
            artnumber.indexOf( orderLinesColection[lineNumber]['artikel']['artnr'] ) > -1
            ) {
            classname = artnumber_first.className.replace("formError", "noError");
            artnumber_first.className = classname;
            classname = artnumber_second.className.replace("formError", "noError");
            artnumber_second.className = classname;
            classname = document.getElementById('text_size_' +lineNumber).className.replace("formError", "noError");
            document.getElementById('text_size_' +lineNumber).className = classname;
            classname = document.getElementById('text_amount_' +lineNumber).className.replace("formError", "noError");
            document.getElementById('text_amount_' +lineNumber).className = classname;
			        $('.formErrors').eq(1).html('');
            if (size.length > 0) {
                if (orderLinesColection[lineNumber]['sizes'][size]) {
                    classname = document.getElementById('text_size_' +lineNumber).className.replace("formError", "noError");
                    document.getElementById('text_size_' +lineNumber).className = classname;
                } else {
                    errorLabel = 'size';
                }
            }
        } else {
            errorLabel = 'artnumber';
        }
		/*  wdo@adva: turns into a bug if article not found
				if (orderLinesColection[lineNumber]['sizes'][size]['lieferaussage']['liefaus'] < 3) {				
					errorLabel = 'availability';
				}		
		*/		
		if (orderLinesColection[lineNumber] != null    && orderLinesColection[lineNumber]['sizes'][size]['lieferaussage']['liefaus'] < 3) {				
					errorLabel = 'availability';
				}		
    } else {
        classname = artnumber_first.className.replace("formError", "noError");
        artnumber_first.className = classname;
        classname = artnumber_second.className.replace("formError", "noError");
        artnumber_second.className = classname;

        // BUGFIX: is(':visible') will not work correctly in IE on rows
        //         so we have to chack manually
        if ( $('.monogram_'+lineNumber).css('display') != 'none' ) {
            $('.monogram_'+lineNumber).toggle();
            orderLinesColection[lineNumber] = undefined;
        } //if

        if ( $('.meterware_'+lineNumber).css('display') != 'none' ) {
            $('.meterware_'+lineNumber).toggle();
            orderLinesColection[lineNumber] = undefined;
        } //if

        $('.formErrors').eq(1).html('');
    }

    if (errorLabel.length > 0) {
        classname = artnumber_first.className.replace("noError", "formError");
        artnumber_first.className = classname;
        classname = artnumber_second.className.replace("noError", "formError");
        artnumber_second.className = classname;
        lnf = parseInt(lineNumber) + 1;
        handleErrors(true, lnf, errorLabel);

        // BUGFIX: is(':visible') will not work correctly in IE on rows
        //         so we have to chack manually
        if ( $('.monogram_'+lineNumber).css('display') != 'none' ) {
            $('.monogram_'+lineNumber).toggle();
            orderLinesColection[lineNumber] = undefined;
        } //if

        if ( $('.meterware_'+lineNumber).css('display') != 'none' ) {
            $('.meterware_'+lineNumber).toggle();
            orderLinesColection[lineNumber] = undefined;
        } //if

        javaErrorcheck = false;
        updateStaticFields(lineNumber);
    } else {
        lnf = parseInt(lineNumber) + 1;
        if(lnf){
            handleErrors(false, lnf, errorLabel);
        }
    }
}

function handleErrors(addError, lineNumber, errorLabel) {
    var errorLines = '';

    if (addError){
        errors[lineNumber] = errorLabel;
    } else {
        delete(errors[lineNumber]);
    }
    for (var i in errors){
        if(errors[i]){
            if (errorlineStart){ // user defined the errorline start
                errorLines += errorlineStart + i + ': ' + errorTexts[errors[i]];
            }else{
                errorLines += '<li>Zeile ' + i + ': ' + errorTexts[errors[i]];
            }

            if (errorlineEnd){ // user defined the errorline end
                errorLines += '</div><div class="clear">' + errorlineEnd;
            }else{
                errorLines += '</li>';
            }
        }
    }
    if (errorLines != ''){
        $('.formErrors').eq(1).html('<p>' + errorTexts['summary'] + ':</p><ul>' + errorLines + '</ul>');
    } else {
        $('.formErrors').eq(1).html('');
    }
}

function fieldOnFocus(field, lineNumber) {
    if(document.getElementById('selectbox_'+field+'_'+lineNumber).selectedIndex<0){
        document.getElementById('selectbox_'+field+'_'+lineNumber).selectedIndex = 0;
    }
    setDivVisible(field+'_'+lineNumber);

    if($.browser.msie && (parseInt($.browser.version) == 6 || parseInt($.browser.version) == 7)){
        return;
    }
    else{
        document.getElementById('selectbox_'+field+'_'+lineNumber).focus();
    }
}

function fieldOnBlur(field, lineNumber) {
    document.getElementById('selectdiv_'+field+'_'+lineNumber).className = 'fieldHidden';
    document.getElementById('selectdiv_'+field+'_'+lineNumber).style.visibility = 'hidden';
    fieldOnChange(field, self, lineNumber);
}

function fieldOnChange(field, self, lineNumber) {
    var index = self.selectedIndex;
    if(index >= 0) {
        document.getElementById('text_'+field+'_'+lineNumber).value = self.options[index].text;
        if (field == 'size') {
            document.getElementById('size_'+lineNumber).value = self.options[index].value;
        }
    };
}

function addOrderline(lineNumber) {
	if(lineNumber < 29) {
		var numberOfOrderlines = parseInt(document.getElementById('numberOfOrderlines').value);

        // if actual lineNumer is the last line of the orderform
        if ((numberOfOrderlines-1) == parseInt(lineNumber)) {

            template = $('#orderlineTemplate table tbody').html();

			if(!(numberOfOrderlines%2)) {
				//alert('numberOfOrderlines: ' + numberOfOrderlines);
            	template = template.replace(/<tr><td style=/g, '<tr class="bgGray"><td style=');
            	//alert(template);
			}

            template = template.replace(/JSMARKERNUM/g, numberOfOrderlines);
            template = template.replace(/JSMARKERPLUS/g, (numberOfOrderlines + 1));
            template = template.replace(/JSMARKERMOD2/g, (numberOfOrderlines % 2));

            $('#addOrderline_' + numberOfOrderlines).replaceWith(template);
            $('#numberOfOrderlines').val(numberOfOrderlines + 1);
        }
    }
}

/*

function addOrderline_empty(lineNumber) {
	if(lineNumber < 29) {
        var numberOfOrderlines = parseInt(document.getElementById('numberOfOrderlines').value);
		
        // if actual lineNumer is the last line of the orderform
        if ((numberOfOrderlines-1) == parseInt(lineNumber)) {
            template = document.getElementById('orderlineTemplate').innerHTML;
            template = template.replace(/JSMARKERNUM/g, numberOfOrderlines);
            template = template.replace(/JSMARKERPLUS/g, (numberOfOrderlines + 1));
            template = template.replace(/JSMARKERMOD2/g, (numberOfOrderlines % 2));
            document.getElementById('addOrderline_'+numberOfOrderlines).innerHTML = template;
            document.getElementById('numberOfOrderlines').value = numberOfOrderlines + 1;
        }
    }
}

function addOrderline_ul(lineNumber) {
	if(lineNumber < 29) {
        var numberOfOrderlines = parseInt(document.getElementById('numberOfOrderlines').value);

        // if actual lineNumer is the last line of the orderform
        if ((numberOfOrderlines-1) == parseInt(lineNumber)) {
            template = document.getElementById('orderlineTemplate').innerHTML;
            template = template.replace(/JSMARKERNUM/g, numberOfOrderlines);
            template = template.replace(/JSMARKERPLUS/g, (numberOfOrderlines + 1));
            template = template.replace(/JSMARKERMOD2/g, (numberOfOrderlines % 2));
            document.getElementById('addOrderline_'+numberOfOrderlines).innerHTML = '<ul>' + template + '</ul>';
            document.getElementById('numberOfOrderlines').value = numberOfOrderlines + 1;
        }
    }
}

*/


function retrieveArticleData(lineNumber,eventSender) {
    initVars(lineNumber);
    var okToRequest = false;
    var artnumber = artnumber_first.value + artnumber_second.value;

    mapFieldAsMinimumOnceEdited(eventSender);


    ajaxCall = false;
    javaErrorcheck = true;

    if(alreadyOnceChangedFields(lineNumber)){
        //errorTest
        okToRequest = makeMiniValidation(lineNumber);
        if (okToRequest) {
            if(orderLinesColection.length&&orderLinesColection[lineNumber]!=undefined
                &&orderLinesColection[lineNumber]['artikel']['artnr']==artnumber){
            //article data already exists
            } else {
                ajaxCall = useAjax;
            }
        }

        if (ajaxCall) {
            var url		= '/typo3conf/ext/dmc_mb3_orderform/ajaxGetArticleData.php';
            var data	= 'artnumber='+artnumber_first.value+'&artnumber_second='+artnumber_second.value+'&clientPk='+clientPk+'&languagePk='+languagePk+'&langIso2='+langIso2+'&lineNumber='+lineNumber;

            $.ajax({
                type		: 'POST',
                url		: url,
                data		: data,
                dataType	: 'json',
                success	: function(result){
                    response(result);
                }
            });

        } else {
            updateSize(lineNumber);
        }
    }
}

function response(result) {

    var artnumber = result['artnumber'];
    var lineNumber = result['lineNumber'];
    var text = '';

    if (result['status'] == 'found') {
        orderLinesColection[result['lineNumber']] = result;

        if (result['artbez'] && $('.description_'+lineNumber).css('display') == 'none') {
            $('.description_'+lineNumber).toggle();
        }
        if (result['gravnr'] && $('.monogram_'+lineNumber).css('display') == 'none') {
            orderLinesColection[result['lineNumber']]['hasMonogram']=true;
            $('.monogram_'+lineNumber).toggle();
        }
        if (result['vme']=='02' && $('.meterware_'+lineNumber).css('display') == 'none' ){
            orderLinesColection[result['lineNumber']]['isMeterware']=true;
            $('.meterware_'+lineNumber).toggle();
        }
    }

    artnumber_first.value = result['artnumber'];
    artnumber_second.value = result['artnumber_second'];
    // description.value = text;


    updateSize(lineNumber);
    if (result['status'] == 'found') {
        fieldOnFocus('size', lineNumber);
    }
}

function productInfoPopup(productlinkId,titleId) {

    var popupurl = document.getElementById(productlinkId).value;
    var title = document.getElementById(titleId);
    if (title) {
        title = title.textContent;
    } else {
        title = '';
    }
    openJQueryPopupWindow(popupurl,title,'width=705,height=510,scrollbars=yes,resizable=no,toolbar=no,status=no,directories=no,menubar=no,location=no')

}

function mapFieldAsMinimumOnceEdited( eventSender ) {
    minimumOnceChangedFields[eventSender.id] = ! minimumOnceChangedFields[eventSender.id];
}

function alreadyOnceChangedFields( lineNumber ) {

    if(minimumOnceChangedFields[artnumber_first.id] == minimumOnceChangedFields[artnumber_second.id]){
        return true;
    } else {
        return false;
    }
}

function makeMiniValidation( lineNumber ) {

    firstValidation = artnumber_first.value.match(/\d{5}/);
    secondValidation = artnumber_second.value.match(/\d(.+)?/);
    return (firstValidation && secondValidation);
}

function initVars(lineNumber){
    artnumber_first = document.getElementById('text_artnumber_'+lineNumber);
    artnumber_second = document.getElementById('text_artnumbersecond_'+lineNumber);
// description = document.getElementById('label_description_'+lineNumber);
}

function checkReadyToSend(){
    var thereAreOrderlines = false;

    for (var i in orderLinesColection){
        if (orderLinesColection[i]){
            thereAreOrderlines = true;
        }
    }
    if ( thereAreOrderlines ){
        for (var i in errors){
            if (errors[i]){
                return false;
            }
        }
		

        return true;
    } else {

        return false;
    }
}

/**
 *
 * @access public
 * @return void
 **/
function gotoNextField(object, num) {
    if(object) {
        var artnumber = object.id.search(/artnumber_.+/);
        var artnumbersecond = object.id.search(/artnumbersecond.+/);
        var val = object.value;

        if(artnumber>0 && val.length>=5) {
            $(object).nextAll(":input:first").focus();
            document.getElementById('text_artnumbersecond_' + num).select();
        } else if(artnumbersecond>0 && val.length>=3) {
            $('#text_size_' + num).focus();
        }
    }
}

/**
 * set availibility Color
 *
 * @access public
 * @return void
 **/
function setAvailabilityColor(lieferaussage,lineNumber) {

	var availabilityColor= 'black';
	
	if(lieferaussage < 3) {
		availabilityColor = '#ff3300'; //red - ausverkauft 
	} else if(lieferaussage == 3)	{
		availabilityColor = '#cccc00'; //yellow - geringer bestand
	} else if(lieferaussage == 4)	{
		availabilityColor = '#66cc33'; //green - wird nachgeliefert
	}
	
	document.getElementById('text_amount_'+lineNumber).style.color = availabilityColor;
	document.getElementById('label_description_'+lineNumber).style.color = availabilityColor;
	document.getElementById('label_availability_'+lineNumber).style.color = availabilityColor;
	document.getElementById('text_size_'+lineNumber).style.color = availabilityColor;
	document.getElementById('text_artnumbersecond_'+lineNumber).style.color = availabilityColor;
	document.getElementById('text_artnumber_'+lineNumber).style.color = availabilityColor;
}

/**
 * update availibilty on changing size
 *
 * @access public
 * @return void
 **/
function updateAvailability( lineNumber ) {
	javaErrorcheck = true;
	updateStaticFields(lineNumber);
}
/*
 * function.js
 *
 * The content of this file is (c) 2003 - 2007 dmc
 * digital media center GmbH
 * All rights reserved
 *
 * This software is the confidential and proprietary
 * information of dmc digital media center GmbH.
 *
 */


/**
 * functions to set pco actions
 *
 * $Id: functions.js 12168 2009-06-12 06:47:08Z dst $
 */


	/**
	* set a pco action to a defined action form field
	*
	* @access public
	* @param  ctype       the name of the extension
	* @param  uid         the uid of the pageelement
	* @param  newAction   the name of the pco action
	* @return void
	*/
	function pcoFormSetAction(ctype, uid, newAction) {

		var action			= document.getElementById(ctype + '[' + uid + ']' + '[pcoAction]');

		if (action) {
			action.value = newAction;
		} // end: if
	} // end: function


/******************************************************************************
* Name     : $Id: ffsuggest.js 1919 2009-09-23 12:40:33Z e-kampokon $
* Funktion : Vorschlagsskript
* Erstellt : 18/06/07, Jenisch
******************************************************************************/
function FFSuggest() {

	var pRequest;
	var pLayer;
	var pDebug					= false;
	var pInstanceName			= "";
	var pSearchURL				= "";
	var pQueryParamName			= "";
	var pFormname 				= "";
	var pLayerName				= "";
	var pQueryInput;
	var pSuggest				= new Array();
	var pLastQuery;
	var pCurrentSelection		= 0;
	var pCellSpacing			= 0;
	var pHighlightBgColor 		= "#D5D5D5";
	var pHighlightTextColor 	= "#FFFFFF";
	var pStandardBgColor 		= "#FCFCFC";
	var pStandardTextColor 		= "#666666";
	var pSuggestQueryStyle 		= "padding: 2px 15px 2px 10px;";
	var pSuggestTypeStyle 		= "padding: 2px 5px 2px 15px; text-align:right;";
	var submitted				= false;
	var pTexte                  = new Array();

	this.init = function(searchURL, formname, queryParamName, divLayername, instanceName, debugMode, arrTexte) {
		pSearchURL		    = searchURL;
		pFormname		    = formname;
		pQueryParamName	    = queryParamName;
		pLayerName		    = divLayername;
		pInstanceName	    = instanceName;
		pDebug			    = debugMode;
		//pDebug			= false;
		pTexte              = arrTexte;

		if (pSearchURL == "") {
			if (pDebug) alert("no searchurl defined");
			return null;
		} else if (pInstanceName == "") {
			if (pDebug) alert("no instancename defined");
			return null;
		} else if (pFormname == "") {
			if (pDebug) alert("no formname defined");
			return null;
		} else if (pQueryParamName == "") {
			if (pDebug) alert("no queryparamname defined");
			return null;
		} else if (pLayerName == "") {
			if (pDebug) alert("need a layer for output");
		}
		pQueryInput = document[pFormname][pQueryParamName];
		pQueryInput.onkeyup	= handleKeyPress;
		pQueryInput.onfocus	= showLayer;
		pQueryInput.onblur	= hideLayer;
		document[pFormname].onsubmit = handleSubmit;
	}

	this.setHighlightColors = function(highlighBackgroundColor, highlighTextColor) {
		pHighlightBgColor	= highlighBackgroundColor;
		pHighlightTextColor	= highlighTextColor;
	}

	this.setStandardColors = function(standardBackgroundColor, standardTextColor) {
		pStandardBgColor	= standardBackgroundColor;
		pStandardTextColor	= standardTextColor;
	}

	this.setCellspacing = function(cellspacing) {
		pCellSpacing = cellspacing;
	}

	function handleSubmit() {
		submitted = true;
		if (pSuggest[pCurrentSelection] != undefined) {
			var arrCurrent = pSuggest[pCurrentSelection].split('###');
			/*
			 * it seems that this was never working, and i also dont know how it should
			 * i have not found code where the keyword filterkategorie is used
			 *
			if (arrCurrent[2] == "category") {
				document[pFormname]["filterkategorie"].value = "__" + arrCurrent[0] + "__";
				document[pFormname][pQueryParamName].value = "";
			}
			else {*/
				document[pFormname][pQueryParamName].value = arrCurrent[0];
			/*}*/
		}
	}

	this.handleClick = function() {
		handleSubmit();
		document[pFormname].submit();
	}

	this.handleMouseOver = function(pos) {
		var tblCell = getTableCell(pos);
		unmarkAll();
		if (tblCell != null) {
			highlightSuggest(tblCell);
			pCurrentSelection = pos;
		}
	}

	this.handleMouseOut = function(pos) {
		var tblCell = getTableCell(pos);
		if (tblCell != null) {
			unmarkSuggest(tblCell);
			pCurrentSelection = -1
		}
	}

	function handleKeyPress(evt) {
		evt = (evt) ? evt : ((event) ? event : null);
		var keyCode = evt.keyCode;
		if (keyCode == 38) {
			moveSelection("up")
		} else if (keyCode == 40) {
			moveSelection("down");
		} else {
			if (pQueryInput.value == "") {
				hideLayer();
				if (pLayer != null) pLayer.innerHTML = "";
				return null;
			}
			if (pLastQuery != pQueryInput.value && pQueryInput.value.length > 2) startAjax();
			pLastQuery = pQueryInput.value;
		}
	}

	function moveSelection(direction) {
		var pos = pCurrentSelection;
		if (direction == "up")	pos--;
		else 					pos += 1;

		if (pos < 0) {
			unmarkAll();
			pQueryInput.focus();
			pCurrentSelection	= -1;
		} else {
			var tblCell = getTableCell(pos);
			if (tblCell != null) {
				unmarkAll();
				highlightSuggest(tblCell);
				pCurrentSelection = pos;
			}
		}

		var query = pQueryInput.value;
		pQueryInput.value = "";
		pQueryInput.focus();
		pQueryInput.value = query;
	}

	function startAjax() {
		var query = pQueryInput.value;
		var requestURL = pSearchURL + "&" + pQueryParamName + "=" + escape(query);

		try {
			if( window.XMLHttpRequest ) {
				pRequest = new XMLHttpRequest();
			} else if( window.ActiveXObject ) {
				pRequest = new ActiveXObject( "Microsoft.XMLHTTP" );
			} else {
				if (pDebug) alert( "" );
			}

			pLayer = document.getElementById(pLayerName);
			if (pLayer != null) {
				if (query != "") {

					pRequest.open( "GET", requestURL, true );
					pRequest.onreadystatechange = callbackAjax;
					pRequest.send( null );
				} else {
					hideLayer();
				}
			} else {
				if (pDebug) alert( "no layer for output found" );
			}
		} catch( ex ) {
			hideLayer();
			if (ex == undefined) {
				if (pDebug) alert( "Error: " + ex.getmessage );
			} else {
				if (pDebug) alert( "Error: " + ex );
			}
		}
	}

	function hideLayer() {
		if (pLayer != null) {
			pLayer.style.visibility = "hidden";
		}
	}

	this.hideLayerOutsideCall = function() {
		if (pLayer != null) {
			pLayer.style.visibility = "hidden";
		}
	}

	function showLayer() {
		if (pLayer != null && pSuggest != null && pSuggest.length >= 1) {
			pLayer.style.visibility	= "visible";
		}
	}

	function callbackAjax() {
		if (submitted == false) {
			if (pRequest.readyState == 4) {
				if (pRequest.status != 200) {
					hideLayer();
					if (pDebug) alert( "Error (" + pRequest.status + "): " + pRequest.statusText );
				} else {
					handleResponse(pRequest.responseText);
				}
			}
		}
}

	function handleResponse(text) {
		pCurrentSelection = -1;
		pSuggest = new Array();
		pSuggest = text.split("\n");
		var outputText = '<table width="100%" cellpadding="' + pCellSpacing + '" cellspacing="0" class="' + pLayerName + '" border="0" onMouseDown="' + pInstanceName + '.handleClick();">';
		outputText += '<tr class="suggestHeader" ><th class="suggestHeader" nowrap="nowrap" colspan="3">' + pTexte["suggestion"] + ' ...</th></tr>';

		var pNewSuggest = new Array();
		for (var i in pSuggest) {
			var firstChar = pSuggest[i].charCodeAt(0);
			if (firstChar != 13 && firstChar != 10 && pSuggest[i].length >= 1) {
				pNewSuggest.push(pSuggest[i]);
			}
		}
		pSuggest = pNewSuggest;
		var query = pQueryInput.value;
		for (var i in pSuggest) {
			pSuggestParts = new Array();
			pSuggestParts = pSuggest[i].split("###");
			if (pSuggestParts[1] != "") {
				pSuggestParts[1] = pSuggestParts[1].split(" ");
				pSuggestParts[1] = pSuggestParts[1][0] + ' ' + pTexte[pSuggestParts[1][1]];
			}

			outputText += '<tr  id="' + pLayerName + '_' + i + '" style="background-color: ' + pStandardBgColor + '; padding: 2px 0px;" onMouseOver="' + pInstanceName + '.handleMouseOver(' + i + ');" onMouseOut="' + pInstanceName + '.handleMouseOut(' + i + ');">'
								+ '<td nowrap="nowrap" style="'+ pSuggestQueryStyle +';">' + pSuggestParts[0].replace(new RegExp("("+query+")","ig"),'<span class="suggestContent">$1</span>') + '</td>'
								+'<td nowrap="nowrap" style="'+ pSuggestTypeStyle +'" width="100%">' + pTexte[pSuggestParts[2]] + '</td>'
								+'<td nowrap="nowrap" align="right" style="'+ pSuggestTypeStyle +'" width="30%">' + pSuggestParts[1] + '</td>'
						+'</tr>';
		}
		//outputText += '<tr><td  style="height:25px; background-color: ' + pStandardBgColor + '; color: ' + pStandardTextColor + '; border-top:solid 1px #5C637D; font-size:9px;" colspan="3" align="right"></td></tr></table>';

		if (pSuggest.length >= 1) {
			showLayer();
			pLayer.innerHTML		= outputText;
		} else {
			hideLayer();
			pLayer.innerHTML		= "";
		}
	}

	function highlightSuggest(tblCell) {
		tblCell.style.backgroundColor	= pHighlightBgColor;
		tblCell.style.color				= pHighlightTextColor;
	}

	function unmarkSuggest(tblCell) {
		tblCell.style.backgroundColor	= pStandardBgColor;
		tblCell.style.color				= pStandardTextColor;
	}

	function unmarkAll() {
		var tblCell;
		for (var i in pSuggest) {
			tblCell = getTableCell(i);
			if (tblCell != null) {
				unmarkSuggest(tblCell);
			}
		}
	}

	function getTableCell(pos) {
		var tblCell;
		tblCell = document.getElementById(pLayerName + "_" + pos);
		return tblCell;
	}
}

// this function works in combination with product extension
// it uses the productConf array created by the product extension
// so it may not work anywhere else than productdetail pages...
function articleRecommendLink(uid, id, url, title,parameter) {
	var artNumber 		= '';
	var variation		= '';
	var size			= '';
	var color			= '';
    var name			= 'popup_productRecommend';
	// find currently selected article number
	variation	= currentVariation(uid, id);
	size		= currentSize(uid, id, variation);
	color		= currentColor(uid, id, variation, size);
	artNumber	= productConf[uid][id]['articles'][variation][size][color]['artNumber'];
	popupurl = url.replace('%s', artNumber);
	openJQueryPopupWindow(popupurl, title, parameter);
}

/**
* flag to prevent double submits by doubleclicks on buttons
*/
var loginFormSubmitFlag = false;
var logoutFormSubmitFlag = false;
var changePasswordSubmitFlag = false;
var autoLoginSubmitFlag = false;
var billingAddressSubmitFlag = false;
var deliveryAddressSubmitFlag = false;
var paymentTypeSubmitFlag = false;
var userProfileSubmitFlag = false;
var userNameSubmitFlag = false;
var deliveryTypeSubmitFlag = false;
var accountDeleteSubmitFlag = false;

var userFormSubmitFlag = false;

/**
* performs login form submit defined by ctype and uid
* and prevents a double click form submit
*
* @access public
* @param ctype the name of the extension
* @param uid the uid of the pageelement
* @return void
*/
function loginFormSubmit(ctype, uid) {
	var form = document.getElementById(ctype + '[' + uid + ']' + '[form]' + '[login]');
	if (loginFormSubmitFlag == false) {
		if (form) {
			loginFormSubmitFlag = true;
			form.submit();
		} // end: if
	} // end: if
} // end: function


/**
* performs user form submit defined by ctype and uid
* and prevents a double click form submit
*
* @access public
* @param ctype the name of the extension
* @param uid the uid of the pageelement
* @return void
*/
function userFormSubmit(ctype, uid) {
	var form = document.getElementById(ctype + '_' + uid + '_' + 'form');

	if ( $('#' + ctype + '_' + uid + '_' + 'form').valid() ) {
		if (userFormSubmitFlag == false) {
			if (form) {
				userFormSubmitFlag = true;
				form.submit();
			} // end: if
		} // end: if
	} else {
		$.scrollTo($(".error:first").parent());
		$("#.error:first").focus();
	}
} // end: function


/**
* performs change password form submit defined by ctype and uid
* and prevents a double click form submit
*
* @access public
* @param ctype the name of the extension
* @param uid the uid of the pageelement
* @return void
*/
function changePasswordFormSubmit(ctype, uid) {
	var form = document.getElementById(ctype + '[' + uid + ']' + '[form]' + '[changePassword]');
	if (changePasswordSubmitFlag == false) {
		if (form) {
			changePasswordSubmitFlag = true;
			form.submit();
		} // end: if
	} // end: if
} // end: function


/**
* performs auto login form submit defined by ctype and uid
* and prevents a double click form submit
*
* @access public
* @param ctype the name of the extension
* @param uid the uid of the pageelement
* @return void
*/
function autoLoginFormSubmit(ctype, uid) {
	var form = document.getElementById(ctype + '[' + uid + ']' + '[form]' + '[changeAutoLogin]');
	if (autoLoginSubmitFlag == false) {
		if (form) {
			autoLoginSubmitFlag = true;
			form.submit();
		} // end: if
	} // end: if
} // end: function

/**
* performs billing address form submit defined by ctype and uid
* and prevents a double click form submit
*
* @access public
* @param ctype the name of the extension
* @param uid the uid of the pageelement
* @return void
*/
function billingAddressFormSubmit(ctype, uid) {
	var form = document.getElementById(ctype + '[' + uid + ']' + '[form]' + '[billingcustomer]');
	if (billingAddressSubmitFlag == false) {
		if (form) {
			billingAddressSubmitFlag = true;
			form.submit();
		} // end: if
	} // end: if
} // end: function

/**
* performs delivery address form submit defined by ctype and uid
* and prevents a double click form submit
*
* @access public
* @param ctype the name of the extension
* @param uid the uid of the pageelement
* @return void
*/
function deliveryAddressFormSubmit(ctype, uid) {
	var form = document.getElementById(ctype + '[' + uid + ']' + '[form]' + '[deliverycustomer]');
	if (deliveryAddressSubmitFlag == false) {
		if (form) {
			deliveryAddressSubmitFlag = true;
			form.submit();
		} // end: if
	} // end: if
} // end: function


/**
* delete the existing delivery address defined by ctype and uid
*
* @access public
* @param ctype the name of the extension
* @param uid the uid of the pageelement
* @return void
*/
function deliveryAddressDelete(ctype, uid) {
	var form = document.getElementById(ctype + '[' + uid + ']' + '[form]' + '[deliverycustomer]');
	if (form) {
		document.getElementById(ctype + '[' + uid + ']' + '[action]' + '[changeDeliveryCustomer]').value = "deleteDeliveryCustomer";
		form.submit();
	} // end: if
} // end: function


/**
* performs delivery address name change submit defined by ctype and uid
*
* @access public
* @param ctype the name of the extension
* @param uid the uid of the pageelement
* @return void
*/
function deliveryAddressChangeName(ctype, uid) {
	var form = document.getElementById(ctype + '[' + uid + ']' + '[form]' + '[deliverycustomer]');
	if (form) {
		document.getElementById(ctype + '[' + uid + ']' + '[action]' + '[changeDeliveryCustomer]').value = "loadDeliveryAddress";
		form.submit();
	} // end: if
} // end: function


/**
* performs paymenttype form submit defined by ctype and uid
* and prevents a double click form submit
*
* @access public
* @param ctype the name of the extension
* @param uid the uid of the pageelement
* @return void
*/
function paymentTypeFormSubmit(ctype, uid) {
	var form = document.getElementById(ctype + '[' + uid + ']' + '[form]' + '[paymenttype]');
	if (paymentTypeSubmitFlag == false) {
		if (form) {
			paymentTypeSubmitFlag = true;
			form.submit();
		} // end: if
	} // end: if
} // end: function

/**
* performs paymenttype form submit defined by ctype and uid
* and prevents a double click form submit
*
* @access public
* @param ctype the name of the extension
* @param uid the uid of the pageelement
* @return void
*/
function deliveryTypeFormSubmit(ctype, uid) {
	var form = document.getElementById(ctype + '[' + uid + ']' + '[form]' + '[deliverytype]');
	if (deliveryTypeSubmitFlag == false) {
		if (form) {
			deliveryTypeSubmitFlag = true;
			form.submit();
		} // end: if
	} // end: if
} // end: function

/**
* performs userprofile form submit defined by ctype and uid
* and prevents a double click form submit
*
* @access public
* @param ctype the name of the extension
* @param uid the uid of the pageelement
* @return void
*/
function userProfileFormSubmit(ctype, uid) {
	var form = document.getElementById(ctype + '[' + uid + ']' + '[form]' + '[profile]');
	if (userProfileSubmitFlag == false) {
		if (form) {
			userProfileSubmitFlag = true;
			form.submit();
		} // end: if
	} // end: if
} // end: function

/**
* performs logout form submit defined by ctype and uid
* and prevents a double click form submit
*
* @access public
* @param ctype the name of the extension
* @param uid the uid of the pageelement
* @return void
*/
function logoutFormSubmit(ctype, uid) {
	var form = document.getElementById(ctype + '[' + uid + ']' + '[form]' + '[logout]');
	if (logoutFormSubmitFlag == false) {
		if (form) {
			logoutFormSubmitFlag = true;
			form.submit();
		} // end: if
	} // end: if
} // end: function

/**
* performs username change form submit defined by ctype and uid
* and prevents a double click form submit
*
* @access public
* @param ctype the name of the extension
* @param uid the uid of the pageelement
* @return void
*/
function changeUserNameSubmit(ctype, uid) {
	var form = document.getElementById(ctype + '[' + uid + ']' + '[form]' + '[changeUsername]');
	if (userNameSubmitFlag == false) {
		if (form) {
			userNameSubmitFlag = true;
			form.submit();
		} // end: if
	} // end: if
} // end: function

/**
* performs account delete form submit defined by ctype and uid
* and prevents a double click form submit
*
* @access public
* @param ctype the name of the extension
* @param uid the uid of the pageelement
* @return void
*/
function accountDeleteFormSubmit(ctype, uid) {
	var form = document.getElementById(ctype + '[' + uid + ']' + '[form]' + '[accountDelete]');
	if (accountDeleteSubmitFlag == false) {
		if (form) {
			accountDeleteSubmitFlag = true;
			form.submit();
		} // end: if
	} // end: if
} // end: function

function getBike(formname,fieldname,boxnum,clientpk,isocode2) {
	var pickerBox = document.getElementById('pickerBox'+boxnum);
	var pickerBox1 = document.getElementById('pickerBox1');
	var pickerBox2 = document.getElementById('pickerBox2');
	if(pickerBox1 && pickerBox2 && pickerBox) {
		if(pickerBox1.style.display == 'none' && pickerBox1.id == pickerBox.id) {
			pickerBox1.innerHTML = poloPickerGenerateHTML(boxnum,formname,fieldname);
			pickerBox1.style.display = 'block';
			pickerBox2.style.display = 'none';
		}
		else if(pickerBox2.style.display == 'none' && pickerBox2.id == pickerBox.id) {
			pickerBox2.innerHTML = poloPickerGenerateHTML(boxnum,formname,fieldname);
			pickerBox2.style.display = 'block';
			pickerBox1.style.display = 'none';
		}
		else {
			pickerBox.style.display='none';
		} // end: if
	} // end: if
	else if((pickerBox1&&pickerBox)) {
		if(pickerBox1.style.display == 'none' && pickerBox1.id == pickerBox.id) {
			pickerBox1.innerHTML = poloPickerGenerateHTML(boxnum,formname,fieldname);
			pickerBox1.style.display = 'block';
		}
		else {
			pickerBox.style.display='none';
		} // end: if
	} // end: if
}// end: function

/**
* toggles order detail, close all other container concernig the boxPrefix and
* toggles the innHTML of the link concerning the linkPrefix
*
* @access	public
* @param	integer		num 		number identifing the row
* @param	string		offContent 	innerHTML of the link in off state
* @param	string		onContent 	innerHTML of the link in on state
* @param	string		boxPrefix 	prefix of the toggle container
* @param	string		linkPrefix 	prefix of the link that toggles
* @see		$('')
* @return	void
*/
function toggleDetail(num, offContent, onContent) {

	var boxPrefix 	= (arguments[3]) ? arguments[3] : 'detail-';
	var linkPrefix 	= (arguments[4]) ? arguments[4] : 'detaillink-';

	var pattern  = boxPrefix +'(.*)';

	var divs = document.getElementsByTagName('div');
	for (var i = 0; i < divs.length; i++) {

		var regex = '/'+ pattern +'/.exec(divs[i].id)';
		var match = eval(regex);

		if (match) {

			if (divs[i].id == boxPrefix + num) {

				divs[i].style.display = ( divs[i].style.display == 'none' ) ? "block" : "none";
				document.getElementById(linkPrefix + num).innerHTML = (document.getElementById(linkPrefix + num).innerHTML == offContent ) ? onContent : offContent;

			} else {

				divs[i].style.display = 'none';
				document.getElementById(linkPrefix + match[1]).innerHTML = offContent;
			}
		}
	}
}// end: function



/**
 * simple check the user login
 */
function simpleCheckLogin(ctype, uid){
	var form= document.getElementById(ctype + '_' + uid + '_' + 'form');
	// check field values
	if (jQuery('#user_customernumberfirstpart') &&
		jQuery('#user_customernumberfirstpart').val().length > 0 &&
		jQuery('#user_customernumberlastpart') &&
		jQuery('#user_customernumberlastpart').val().length > 0 &&
		jQuery('#user_password') &&
		jQuery('#user_password').val().length > 0){
		// check submit flag
		if (loginFormSubmitFlag == false) {
			if (form) {
				loginFormSubmitFlag = true;
				jQuery('#user_customernumberfirstpart').removeClass('error');
				jQuery('#user_customernumberlastpart').removeClass('error');
				jQuery('#user_password').removeClass('error');
				form.submit();
			} // end: if
		} // end: if
	}else{
		// add error class
		if(jQuery('#user_customernumberfirstpart').val().length == 0) {
			jQuery('#user_customernumberfirstpart').addClass('error');
		} else {
			jQuery('#user_customernumberfirstpart').removeClass('error');
		}
		if(jQuery('#user_customernumberlastpart').val().length == 0) {
			jQuery('#user_customernumberlastpart').addClass('error');
		} else {
			jQuery('#user_customernumberlastpart').removeClass('error');
		}
		if(jQuery('#user_password').val().length == 0) {
			jQuery('#user_password').addClass('error');
		} else {
			jQuery('#user_password').removeClass('error');
		}
		return false;
	}

}
/**
* performs login form submit
* catch Enter keynum=13 and submit form
*
* @access public
* @param ctype the name of the extension
* @param formID form id
* @return bool
*/
 function evalKeyForSubmit(ctype, uid, e) {

	if( !e ) {
	    if( window.event ) {
	     //Internet Explorer
	      e = window.event;
	    } else {
	      return;
	    }
	  }
	  if( typeof( e.keyCode ) == 'number'  ) {
	    //DOM
	      e = e.keyCode;
	  } else if( typeof( e.which ) == 'number' ) {
	    //NS 4 compatible
	      e = e.which;
	  } else if( typeof( e.charCode ) == 'number'  ) {
	    //also NS 6+, Mozilla 0.9+
	      e = e.charCode;
	  } else {
	    //total failure, we have no way of obtaining the key code
	    return;
	  }
	  if(e == 13) {
       	 simpleCheckLogin(ctype, uid);
	     return false;
	  }
}

function pseudoLoginSubmit(formId, cType, uid) {
	if (  $('#basketloginnewcustomer:checked').length || $('#basketloginnopass:checked').length  ){
		closeThickboxFromThickbox();
	} else {
		if ( $('#' + formId).valid() ) {
			var form	= document.getElementById(cType + '_' + uid + '_' + 'form');
			form.submit();
		} else {
			$.scrollTo($(".error:first").parent());
			$("#.error:first").focus();
		}
	}
}



	function addToGiftdesk(uid, id) {

		var form				= document.getElementById('giftdeskForm_' + uid);
		var giftdeskArticlePk	= document.getElementById('giftdeskArticlePk_' + uid);
		var giftdeskProductPk	= document.getElementById('giftdeskProductPk_' + uid);
		var giftdeskAmount		= document.getElementById('giftdeskAmount_' + uid);
		var giftdeskGravure		= document.getElementById('giftdeskGravure_' + uid);

		var amountForm		= document.getElementById('productAmountForm_' + uid + '_' + id);
		var variation		= currentVariation(uid, id);
		var size			= currentSize(uid, id, variation);
		var color			= currentColor(uid, id, variation, size);
		var amount			= 0;



		if (amountForm) {
			amount = amountForm.value;
		}

		if (form && giftdeskArticlePk && giftdeskProductPk && amount > 0 && articlePk[uid]) {
			giftdeskArticlePk.value 	= articlePk[uid];
			giftdeskProductPk.value 	= id;
			giftdeskAmount.value		= amount;
			form.submit();
		}
	}

	function componentAddToGiftdesk(uid, id, errorInfoText) {
		var form				= document.getElementById('giftdeskForm_' + uid);
		var giftdeskArticlePk	= document.getElementById('giftdeskArticlePk_' + uid);
		var giftdeskProductPk	= document.getElementById('giftdeskProductPk_' + uid);
		var giftdeskAmount		= document.getElementById('giftdeskAmount_' + uid);
		var giftdeskGravure		= document.getElementById('giftdeskGravure_' + uid);
		var giftdeskMeterwareMeter	= document.getElementById('giftdeskMeterwareMeter_' + uid);
		var giftdeskMeterwareCentimeter	= document.getElementById('giftdeskMeterwareCentimeter_' + uid);
		
		var gravure			= document.getElementById('productGravureForm_' + uid + '_' + id);
		var meterwareMeter	= document.getElementById('productMWmeter_' + uid + '_' + id);
		var meterwareCMeter	= document.getElementById('productMWcentimeter_' + uid + '_' + id);
		var amountForm		= document.getElementById('productAmountForm_' + uid + '_' + id);
		var amount			= 0;

		if (amountForm) {
			if(amountForm.nodeName == 'SELECT') {
				amount = amountForm.options[amountForm.selectedIndex].value;
			} else if (amountForm.nodeName == 'INPUT'
				&& (amountForm.type == 'text'
					|| amountForm.type == 'hidden')) {
				amount = amountForm.value;
			} // end: if
		} // end: if

		if(amount == "") {
			if(articlePk[uid] > 0) {
				artPk 	= articlePk[uid];
				//if(blockPriceConf[uid][artPk][0]) {
				//	amount 	= blockPriceConf[uid][artPk][0]['minQuantity'];
				//} else {
					amount 	= 1;
				//} // end: if
			} // end: if
		} // end: if		
		
		if (form && giftdeskArticlePk && giftdeskProductPk && amount > 0 && articlePk[uid] > 0) {			
			giftdeskArticlePk.value 	= articlePk[uid];
			giftdeskProductPk.value 	= id;
			giftdeskAmount.value		= amount;
			if (gravure && gravure.value != "") {				
				giftdeskGravure.value = gravure.value;
			}
			if (meterwareMeter && meterwareMeter.value != "") {
				giftdeskMeterwareMeter.value = meterwareMeter.value;
			}
			if (meterwareCMeter && meterwareCMeter.value != "") {
				giftdeskMeterwareCentimeter.value = meterwareCMeter.value;
			}
			form.submit();
		} else if(articlePk[uid] == 0) {
			alert(errorInfoText);
		} else if(amount < 1 || isNaN(parseInt(amount))) {
			alert(errorAmountText);
		} // end: if
	}

	/**
	* This is used for the extension specific functions
	*
	* @package		mb3p
	* @subpackage	giftdeskcached
	* @access		public
	* @author	    Boris Azar
	* @version		1.0.0
	*/
	var dmc_mb3_giftdeskcached = {

		// public method for url decoding
		decode : function (data) {
			var lsRegExp = /\+/g;
			// Return the decoded string
			return this.decodeUtf8(unescape(String(data).replace(lsRegExp, " ")));
		},

		/**
		* decodes a string in utf8
		*
		* @param string 	utftext							string to be decoded
		* @return void
		*/
		decodeUtf8: function (utftext) {
			var plaintext = "";
			var i=0;
			var c=0;
			var c1=0;
			var c2=0;

			// while-Schleife, weil einige Zeichen uebersprungen werden
			while(i<utftext.length) {
				c = utftext.charCodeAt(i);
				if (c<128) {
					plaintext += String.fromCharCode(c);
					i++;
				} else if((c>191) && (c<224)) {
					c2 = utftext.charCodeAt(i+1);
					plaintext += String.fromCharCode(((c&31)<<6) | (c2&63));
					i+=2;
				} else {
					c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2);
					plaintext += String.fromCharCode(((c&15)<<12) | ((c2&63)<<6) | (c3&63));
					i+=3;
				}
			}

			return plaintext;
		 } // end: function

	}

	/**
	* Giftdeskcached function
	*
	* @package		mb3p
	* @subpackage	giftdeskcached
	* @access		public
	* @author	    Boris Azar
	* @version		1.0.0
	*/

	/**
	* Sets a cookie
	*
	* @param string 	giftdeskAmountContainerId			id of the giftdeskAmountContainer
	* @param string 	giftdeskArticleAmountContainerId		id of the giftdeskArticleAmountContainer
	* @return void
	*/
	function fillGiftdeskWithData(giftdeskAmountContainerId, giftdeskArticleAmountContainerId, tipText) {
		var giftdeskArticlesAmountContainer = document.getElementById(giftdeskArticleAmountContainerId);
		var giftdeskAmountContainer = document.getElementById(giftdeskAmountContainerId);

		var cookieData = cookie_get('mb3pc');
		if (cookieData && typeof cookieData != 'undefined') {

			var data = JSON.parse(cookieData);
			if (data && typeof data.giftdesk != 'undefined') {
				// get the giftdeskArticlesAmountContainer object and set data in it
				if (giftdeskArticlesAmountContainer
					&& typeof data.giftdesk.articlesAmount != 'undefined') {

					// do not forget to decode the data (+ signs are converted back to spaces)
					giftdeskArticlesAmountContainerValue = dmc_mb3_giftdeskcached.decode(data.giftdesk.articlesAmount);

					// get the giftdeskArticlesAmountContainer object and set data in it
					if (giftdeskArticlesAmountContainer) {
						// do not forget to decode the data (+ signs are converted back to spaces)
						giftdeskArticlesAmountContainer.innerHTML = giftdeskArticlesAmountContainerValue;
					} // end: if

				} // end: if

				// get the giftdeskAmountContainer object and set data in it
				if (giftdeskAmountContainer
					&& typeof data.giftdesk.giftdeskAmount != 'undefined') {

					// do not forget to decode the data (+ signs are converted back to spaces)
					giftdeskAmountContainerValue = dmc_mb3_giftdeskcached.decode(data.giftdesk.giftdeskAmount);

					// get the giftdeskAmountContainer object and set data in it
					if (giftdeskAmountContainer) {
						// do not forget to decode the data (+ signs are converted back to spaces)
						giftdeskAmountContainer.innerHTML = giftdeskAmountContainerValue;
					} // end: if
				} // end: if

				if(data.giftdesk.giftdeskAddStatus == 1) {
					showToolTip(giftdeskAmountContainerId,tipText);
				} // end: if

				resetGiftdeskCookie();
			} // end: if
		} // end: if
	} // end: function

	function resetGiftdeskCookie() {
		var cookieData = cookie_get('mb3pc');
		if (cookieData && typeof cookieData != 'undefined') {
			var data = JSON.parse(cookieData);

			if (data) {
				data.giftdesk.giftdeskAddStatus = "0";
				cookieDataUpdated = JSON.stringify(data);
				cookie_set('mb3pc',cookieDataUpdated,'','/');
			} // end: if

		} // end: if
	} // end: function

	function isGiftdeskEmpty(){
		var cookieData  = cookie_get('mb3pc');
		var retval 	    = true;

		if (cookieData && typeof cookieData != 'undefined') {

			var data = JSON.parse(cookieData);
			if (data) {
				if (typeof data.giftdesk != 'undefined' && data.giftdesk.articlesAmount != 0) {
					retval = false;
				}
			}
		}
		return retval;
	}



	function checkFieldsGiftdesk(uid, id, variation, size, color)
	{
		boolReturn = true;
		var amountFieldId = 'productAmountForm_'+uid+'_'+id;
		var yardWareFieldId = null;
		var gravureFieldId = 'giftdeskGravure_'+uid;
		var gravureFieldTextId = 'productGravureText_'+uid+'_'+id;
		var gravureFieldCount = parseInt(productConf[uid][id]['articles'][variation][size][color]['gravureText']);
		var gravureFieldLength = parseInt(productConf[uid][id]['articles'][variation][size][color]['gravureLength']);
		var gravureObj = document.getElementById('productGravureForm_'+uid+'_'+id);


		var gravureText = '';
		gravureTextPlain = '';
		var gravureTextArr = new Array();
		if (gravureObj && gravureFieldCount>0 && gravureFieldLength>0){

			for (var i=0; i<gravureFieldCount; i++)	{
				var iptValue = document.getElementById('productGravureText_' + uid + '_' + id + '_'+i).value;
				gravureTextArr[i] = iptValue;
			}

			gravureTextPlain = gravureTextArr.join('');
			gravureText = gravureTextArr.join(textGravureSeparator);

			// check valid characters

			strPattern = '/[^\x20-\xFF]/';

			if (gravureTextPlain.search(strPattern) != -1 || gravureTextPlain.search(textGravureSeparator)!=-1) {
				alert(noticeGravureError);
				boolReturn = false;
			} else {
				document.getElementById(gravureFieldId).value = gravureText;
			}

			// Wenn Feld leer dann Abfrage
			if (gravureTextPlain == "") {
				if (confirm(noticeGravureNo)) {
					document.getElementById(gravureFieldId).value = textGravureSeparator;
					// set separator if empty, otherwise we do not know if orderline has gravure;
				} else {
					boolReturn = false;
				}
			}
		} // end: gravure

		// Anzahl
		var amountObj = document.getElementById(amountFieldId);
		var yardWare = productConf[uid][id]['articles'][variation][size][color]['stockUnit'];

		if (amountObj)
		{
			// Meterware ?
			if (yardWare && yardWare== "M")
			{
				var splitText= noticeYardWare.split('||');
				if (confirm (splitText[0] + (amountObj.value * 10) + splitText[1] + amountObj.value + splitText[2]) == false)
				{
					amountObj.value = 1;
					amountObj.focus();
					boolReturn = false;
				}
			}
			else if (amountObj.value >= 10)
			{
				var splitText= noticeAmount.split('||');
				if (confirm (splitText[0] + amountObj.value + splitText[1]) == false)
				{
					amountObj.value = 1;
					amountObj.focus();
					boolReturn = false;
				}
			}else{
				// do nothing
			}
		}

		return boolReturn;
	}

	function addToGiftdeskSubmit(uid, id, target, popup, url, popupParams) {

		var variation		= currentVariation(uid, id);
		var size			= currentSize(uid, id, variation);
		var color			= currentColor(uid, id, variation, size);
		if (checkFieldsGiftdesk(uid, id, variation, size, color)){
			if (popup) {
				var form			= document.getElementById('giftdeskForm_' + uid);
				form.action 		= url;

				// do NOT load page from 'url' variable here! race condition w/ 2 Apache threads!
				var POPUP = window.open('/clear.gif', target, popupParams);
				POPUP.focus();
			}
			addToGiftdesk(uid, id);
		}
	}


	/**
	* This is used for the send2friend form to add new recipient rows on demand.
	* The variable 'myRowCounter' is located at the template 'TEMPLATE_08'.
	*
	* @package		mb3p
	* @subpackage	giftdesk
	* @access		public
	* @author	    Goran Zukolo <goran.zukolo@dmc.de>
	* @version		1.0.0
	*/
	function addRecipientRow() {

		// add article row
		if(myRowCounter > 0 && myRowCounter < 15) {

			// we need the old counter to identify the placeholder div
			var oldCounter = myRowCounter-1;
			// get the template code
			var tpl = $('#recipientRowTemplate').html();

			if( tpl != null ) {

				var rowHTML = '';

				// add 5 new rows
				for(var i=0; i<5; i++) {
					// replace the placeholder with the current counter
					tpl_tmp = tpl.replace(/PLACEHOLDER/g, myRowCounter);
					tpl_tmp = tpl_tmp.replace(/ROWCOUNTER/g, myRowCounter+1);

					rowHTML += tpl_tmp;
					// alter the counter by 1
					myRowCounter++;
				} // end: for

				// print the new article row
				$('#newRecipientRow_'+oldCounter).replaceWith(rowHTML);

			} // end: if
		} else {
			// we need the old counter to identify the placeholder div
			var oldCounter = myRowCounter-1;
			$('#newRecipientRow_'+oldCounter).replaceWith(noticeMaxRowsReached);
		}
	} // end: function addRecipientRow

	if(typeof 'componentAddToBasket' == 'function') {
		/**
		 * Submits add to basket form
		 *
		 * @access public
		 * @return void
		 **/
		function componentAddToBasket(uid, id) {
	
			//alert("nogo");
	
			var form			= document.getElementById('productForm_' + uid);
			var amountForm		= document.getElementById('productAmountForm_' + uid + '_' + id);
			var pkForm			= document.getElementById('productBasketPk_' + uid);
			var productPkForm	= document.getElementById('productBasketProductPk_' + uid);
			var variation		= currentVariation(uid, id);
			var size			= currentSize(uid, id, variation);
			var color			= currentColor(uid, id, variation, size);
			var amount			= 0;
	
			if (amountForm) {
				if(amountForm.nodeName == 'SELECT') {
					amount = amountForm.options[amountForm.selectedIndex].value;
				} else if (amountForm.nodeName == 'INPUT'
					&& (amountForm.type == 'text'
						|| amountForm.type == 'hidden')) {
					amount = amountForm.value;
				} // end: if
			} // end: if
	
			if (form && pkForm && productPkForm && amount > 0 && articlePk[uid] > 0) {
				pkForm.value		= articlePk[uid];
				productPkForm.value = id;
				form.submit();
			} else if(articlePk[uid] == 0) {
				alert(errorInfoText);
			} else if(amount < 1 || isNaN(parseInt(amount))) {
				alert(errorAmountText);
			} // end: if
	
		} // end: function componentAddToBasket
	}

	/**
	 * Submits add to basket form
	 *
	 * @access public
	 * @return void
	 **/
	function componentAddToBasketSubmit(uid, id, target, popup, url, popupParams) {
		if (popup) {
			var form			= document.getElementById('productForm_' + uid);
			form.action 		= url;

			// do NOT load page from 'url' variable here! race condition w/ 2 Apache threads!
			window.open('/clear.gif', target, popupParams);
		} // end: if

		componentAddToBasket(uid, id);

	} // end: function componentAddToBasketSubmit

