if(/msie/i.test(navigator.userAgent)){document.nativeGetElementById=document.getElementById;document.getElementById=function(id){var elem=document.nativeGetElementById(id);if(elem){if(elem.id==id)return elem;else for(var i=1;i<document.all[id].length;i++)if(document.all[id][i].id==id)return document.all[id][i];} return null;};} var $=function(id){return document.getElementById(id);};var basehref=function(){var bt=document.getElementsByTagName("base");return bt[0].href;};var dlhref=function(b){var u=document.location.href.split('/'),a=b==undefined ? 0 : b;var e=document.location.href.substr(document.location.href.length-1,1);if(e=='/')u.pop();for(var i=0; i < b; i++)u.pop();return e=='/' ? u.join('/')+'/' : u.join('/');};var remclass=function(classname,node){if(!node)node=document.getElementsByTagName("body")[0];else if(typeof node=='string')node=$(node);var e=node.getElementsByTagName("*");for(var i=0;i<e.length;i++){if(e[i].className.indexOf(classname)!= -1){var ca=e[i].className.split(' ');for(var j=0;j<ca.length;j++)if(ca[j]==classname)ca[j]="";nc=ca.join(' ');nc=nc.replace(/  /g,' ');if(nc.substring(nc.length-1,nc.length))nc=nc.substring(0,nc.length-1);e[i].className=nc;}}};var validate_form=function(f,p,t,n){remclass('form_err',f);var m='',e1=f.getElementsByTagName('input'),e2=f.getElementsByTagName('select'),e3=f.getElementsByTagName('textarea'),e=[];n=typeof(n)== "undefined"?"Formerror:":n;e=vfsub(e1,p,t);e.merge(vfsub(e2,p,t));e.merge(vfsub(e3,p,t));for(i in p)if( !! e[i])m += typeof(t[i])== "undefined"?"\n- "+i:"\n- "+t[i];if(m!==''){alert(n+m);return false;}else return true;};var vfsub=function(e,p,t){var m ={"merge":function(o){for(i in o)this[i]=o[i];}},b ={};for(i=0;i<e.length;i++)if(typeof(e[i].name)!= "undefined"){for(j in p){if(j==e[i].name){r=new RegExp(p[j], 'm');if(e[i].type=="radio"){if(typeof(b[j])== "undefined")b[j]=false;if(e[i].checked&&r.test(e[i].value))b[j]=true;}else if(!r.test(e[i].value)){m[j]=true;e[i].className += ' form_err';}}}}for(j in b)if(!b[j])m[j]=true;return m;};var ors_snap_slidein=function(id){var t=$(id);if(t.initheight-t.offsetHeight<2){t.style.height=t.initheight+'px';clearInterval(t.intrv);}else t.style.height=Math.ceil(t.offsetHeight+((t.initheight-t.offsetHeight)/3))+'px';};var ors_snap_slideout=function(id){var t=$(id);if(t.offsetHeight<2){t.style.display='none';clearInterval(t.intrv);}else t.style.height=Math.floor(t.offsetHeight-(t.offsetHeight/3))+'px';};var ors_snap_slide=function(t,o){if(typeof t.intrv!='undefined')clearInterval(t.intrv);if(!o)t.style.visibility='hidden';t.style.display='block';if(typeof t.initheight=='undefined'){t.initheight=t.offsetHeight;if(!o)t.style.height='1px';t.style.overflow='hidden';}t.style.visibility='visible';if(!o)t.intrv=window.setInterval("ors_snap_slidein('"+t.id+"')",40);else t.intrv=window.setInterval("ors_snap_slideout('"+t.id+"')",40);};var ors_toggle_snap=function(e){var e=!e?window.event:e,t=e.srcElement?e.srcElement:e.target,s=$(t.name);if(typeof s.intrv!='undefined')clearInterval(s.intrv);t.blur();if(t.checked)ors_snap_slide(s,false);else ors_snap_slide(s,true);};

var shopcart = {
  added: {
    node:     'sc_added',
    timeout:  6000,
    interval: 40,
    step:     20,
    ft:       null,
    oh:       null,
    check: function(){
      if($(shopcart.added.node) !== null) {
        if(($(shopcart.added.node).getElementsByTagName('div')).length > 0) {
          shopcart.added.oh = $(shopcart.added.node).parentNode.innerHTML;
          shopcart.added.ft = setInterval('shopcart.added.fade('+shopcart.added.step+')', 50);
      } }
    },
    fade: function(a){
      var t = $(shopcart.added.node), ie = /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
      if(t.style.opacity == undefined || t.style.opacity == ''){
        if(ie) t.style.filter = 'alpha(opacity=10)';
        t.style.opacity = a < 10 ? '0.0'+a : '0.'+a;
        t.style.display = 'block';
      } else {
        var v = parseInt(parseFloat(t.style.opacity)*100);
        if(v + a >= 100 || v + a <= 0){
          if(a > 0){
            if(ie) {
              t.parentNode.innerHTML = shopcart.added.oh;
              t = $(shopcart.added.node)
              t.style.display = 'block';
            }
            t.style.opacity = '1.0';
            setTimeout(function(){shopcart.added.ft = setInterval('shopcart.added.fade(-'+a+')', 50);}, shopcart.added.timeout);
          } else t.style.display = 'none';
          clearInterval(shopcart.added.ft);
        } else {
          var n = v + a;
          if(ie) t.style.filter = 'alpha(opacity='+n+')';
          t.style.opacity = n > 10 ? '0.'+n : '0.0'+n;
      } }
    }
  }
}

var dFormSend = function(a, v, m, t){
  var f = document.createElement('form');
  f.action = a.substr(0,1) != '/' ? a.substr(0,1) == '.' ? a.substr(1,1) == '.' ? dlhref((a.split('../').length)-1) : dlhref()+a.substr(2) : a : basehref()+a.substr(1,a.length);
  f.method = m == undefined ? 'post' : m;
  f.style.margin = '0px';
  f.style.padding = '0px';
  for (var k in v) {
    var i = document.createElement('input');
    i.type  = 'hidden';
    i.name  = k
    i.value = v[k];
    f.appendChild(i);
  }
  if(t != undefined) {
    if(typeof(t) == 'object'){
      var w = window.open('','dFormSendPopUp','location=0,status=0,toolbar=0,resizable=0,width='+t.w+',height='+t.h);
      f.target = 'dFormSendPopUp';
    } else f.target = t;
  }
  document.body.appendChild(f);
  f.submit();
  if(w != undefined) w.focus();
};

var co_confirm_submit = function(f){
  var n = f.getElementsByTagName('input'), ok = true;
  for(i in n) if(typeof(n[i].name) != 'undefined') if(/confirm\[agree\].*/.test(n[i].name)) if(!n[i].checked) ok = false;
  if(ok) f.submit();
  else alert("Haben Sie die AGB zur Kenntnis genommen?");
}
var co_address_submit = function(){
  var f = $('co_address');
  if(f.delivery.checked == true){
    if(validate_form(f, {
      'contact[email]'      : "^[_a-z0-9-]+(?:\\.[_a-z0-9-]+)*@[a-z0-9-]+(?:\\.[a-z0-9-]+)*\\.[a-z]{2,4}$",
      'contact[gender]'     : "(0|1)",
      'contact[surname]'    : "[^'\"\\\\]{1,255}",
      'contact[first_name]' : "[^'\"\\\\]{1,255}",
      'contact[phone]'      : "^[/()+ 0-9-]{6,20}$",
      'contact[street]'     : "[^'\"\\\\]{1,255}",
      'contact[house_no]'   : "(?:[^'\"\\\\]*[0-9][^'\"\\\\]*){1,15}",
      'contact[addition]'   : "[^'\"\\\\]{0,255}",
      'contact[zip]'        : "(?:[0-9a-zA-Z ]*[0-9][0-9a-zA-Z ]*){4,15}",
      'contact[city]'       : "[^'\"\\\\]{1,255}",
      'contact[country_id]' : "[0-9]{1,3}",
      'gender'              : "(0|1)",
      'surname'             : "[^'\"\\\\]{1,255}",
      'first_name'          : "[^'\"\\\\]{1,255}",
      'phone'               : "^[/()+ 0-9-]{6,20}$",
      'street'              : "[^'\"\\\\]{1,255}",
      'house_no'            : "(?:[^'\"\\\\]*[0-9][^'\"\\\\]*){1,15}",
      'addition'            : "[^'\"\\\\]{0,255}",
      'zip'                 : "(?:[0-9a-zA-Z ]*[0-9][0-9a-zA-Z ]*){4,15}",
      'city'                : "[^'\"\\\\]{1,255}",
      'country_id'          : "[0-9]{1,3}"
    }, {
      'contact[email]'      : "E-Mail-Adresse",
      'contact[gender]'     : "Anrede",
      'contact[surname]'    : "Nachname",
      'contact[first_name]' : "Vorname",
      'contact[phone]'      : "Telefonnnummer",
      'contact[street]'     : "Straßennamen",
      'contact[house_no]'   : "Hausnummer",
      'contact[addition]'   : "Zusatz",
      'contact[zip]'        : "Postleitzahl",
      'contact[city]'       : "Ort",
      'contact[country_id]' : "Land",
      'gender'              : "Lieferadresse: Anrede",
      'surname'             : "Lieferadresse: Vorname",
      'first_name'          : "Lieferadresse: Vorname",
      'phone'               : "Lieferadresse: Telefonnnummer",
      'street'              : "Lieferadresse: Straßennamen",
      'house_no'            : "Lieferadresse: Hausnummer",
      'addition'            : "Lieferadresse: Zusatz",
      'zip'                 : "Lieferadresse: Postleitzahl",
      'city'                : "Lieferadresse: Ort",
      'country_id'          : "Lieferadresse: Land"
    }, "Die folgenden Felder sind unvollständig oder falsch ausgefüllt:")) f.submit();
  } else {
    if(validate_form(f, {
      'contact[email]'      : "^[_a-z0-9-]+(?:\\.[_a-z0-9-]+)*@[a-z0-9-]+(?:\\.[a-z0-9-]+)*\\.[a-z]{2,4}$",
      'contact[gender]'     : "(0|1)",
      'contact[surname]'    : "[^'\"\\\\]{1,255}",
      'contact[first_name]' : "[^'\"\\\\]{1,255}",
      'contact[phone]'      : "^[/()+ 0-9-]{6,20}$",
      'contact[street]'     : "[^'\"\\\\]{1,255}",
      'contact[house_no]'   : "(?:[^'\"\\\\]*[0-9][^'\"\\\\]*){1,15}",
      'contact[addition]'   : "[^'\"\\\\]{0,255}",
      'contact[zip]'        : "(?:[0-9a-zA-Z ]*[0-9][0-9a-zA-Z ]*){4,15}",
      'contact[city]'       : "[^'\"\\\\]{1,255}",
      'contact[country_id]' : "[0-9]{1,3}"
    }, {
      'contact[email]'      : "E-Mail-Adresse",
      'contact[gender]'     : "Anrede",
      'contact[surname]'    : "Nachname",
      'contact[first_name]' : "Vorname",
      'contact[phone]'      : "Telefonnnummer",
      'contact[street]'     : "Straßennamen",
      'contact[house_no]'   : "Hausnummer",
      'contact[addition]'   : "Zusatz",
      'contact[zip]'        : "Postleitzahl",
      'contact[city]'       : "Ort",
      'contact[country_id]' : "Land"
    }, "Die folgenden Felder sind unvollständig oder falsch ausgefüllt:")) f.submit();
} };

var autoslide = function(id) {
  var e = $(id), n = e.name, s = $(n);
  e.onclick = ors_toggle_snap;
  if (!e.checked) s.style.display = 'none';
};

var img_put = function(from, into){
  var s = typeof from == "string" ? $(from) : from, t = typeof into == "string" ? $(into) : into;
  var n = s.src.replace(/(.+\/)[0-9]+\/[0-9]+(\/[0-9]+\/.+)/, "$1"+t.src.replace(/.+\/([0-9]+\/[0-9]+)\/[0-9]+\/.+/, "$1")+"$2");
	t.onload = function(){ apply_zoomable(n); };
  t.src = n;
}
var apply_zoomable = function(s){
  if($("main_img") !== null){
    var f = 3, t = $("main_img"), s = typeof s == "undefined" ? t.src : s;
    if(!/.+no_image\.jpg$/.test(s)){
      var d = s.replace(/.+\/([0-9]+)\/([0-9]+)\/[0-9]+\/.+/, "$1,$2").split(","), b = s.replace(/(.+\/)[0-9]+\/[0-9]+(\/[0-9]+\/.+)/, "$1"+(d[0]*f)+"/"+(d[1]*f)+"$2");
      setTimeout(function(){ MojoZoom.makeZoomable(t, b, undefined, 495, 360); }, 1);
  } }
};

/**
 * URL-Encode a value for PHP.
 * @param  {string} value       The value which is to be encoded
 * @return {string} enodedValue The PHP-compatible URL-encoded value
 */
var urlencode = function(str) {
  return escape(str).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
};

/**
 * Handle a request via an XMLHttpRequest.
 *   Upon a successfull (or, if in silent mode, unsuccesfull as well) call the request
 *   return object's function onAHAHParse is called with up to 2 parameters: the 1st is
 *   the XMLHttpRequest, the 2nd (only in silent mode) a boolean (succes or not).
 *
 * @copyright   ©2009 - 2010 Boe!end Media; Any dissemination, copying, implementation,
 *              distribution or use of (parts of) the following code without clear
 *              written and signed permission from copyrightholder is forbidden.
 * @author      Boe!end Media / Chris Volwerk
 * @version     1.7
 * @requires    getNewHttpObject
 * @requires    alertHttpErr
 * @param {string}  url       The url to be requested
 * @param {object}  target    The request return object
 * @param {string}  arguments The arguments to set (format as GET request)
 * @param {boolean} silent    Return succes to target (true) or use internal handling
 */
var bgProcess = function(u, t, a, s) {
  var h = getNewHttpObject(), a = typeof(a) == 'undefined' ? '' : a, s = typeof(s) == 'undefined' ? false : s, r;
  if(u == '.') u = document.location;
  else if(typeof(root) == "undefined") r = u == '' ? document.location : '';
  else r = root;
  if(/:\/\//.test(u)) r = '';
  function processAHAH(t,s) {
    if (h.readyState == 4) {
      if (h.status == 200) {
        if(s) t.onAHAHParse(h, true);
        else t.onAHAHParse(h);
      } else {
        if(s) t.onAHAHParse(h, false);
        else alertHttpErr(h);
  } } }
  h.onreadystatechange = function() {processAHAH(t,s);};
  h.open("post", r+u, true);
  h.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  h.send(a);
};


/**
 * Get a new XMLHttpRequest.
 * @returns XMLHttpRequestObject
 * @private Internal to {@link bgProcess}
 */
var getNewHttpObject = function() {
  var o = false;
  try {
    o = new ActiveXObject('Msxml2.XMLHTTP');
  } catch(e) {
    try {
      o = new ActiveXObject('Microsoft.XMLHTTP');
    } catch(e) {
      o = new XMLHttpRequest();
  } }
  if (!o) alert ("Unsupported Browser:/nBrowser does not support HTTP Request");
  return o;
};


/**
 * Alert the statuscode of an XMLHttpRequest in understandable English.
 * @param XMLHttpRequest
 */
var alertHttpErr = function(h) {
  var a = "Processing Error (";
  switch (h.status) {
    case 204: a+="204 No content"                  ; break;
    case 400: a+="400 Bad Request"                 ; break;
    case 401: a+="401 Unauthorized"                ; break;
    case 403: a+="403 Forbidden"                   ; break;
    case 404: a+="404 Not Found"                   ; break;
    case 408: a+="408 Request Timeout"             ; break;
    case 409: a+="409 Conflict with Resource State"; break;
    case 413: a+="413 Request Entity too large"    ; break;
    case 414: a+="414 Request URI too large"       ; break;
    case 500: a+="500 Internal Server Error"       ; break;
    case 501: a+="501 Not Implemented"             ; break;
    case 502: a+="502 Bad Gateway"                 ; break;
    case 503: a+="503 Service Unavailable"         ; break;
    case 504: a+="504 Gateway Timeout"             ; break;
    default:  a+=h.status+' '+h.statusText; break;
  }
  if(h.responseText != '') alert(a+")\n\nGiven reason:\n"+h.responseText+"\n ");
  else alert(a+")");
};

/**
 * Update product properties to match for a change in the variety of a product
 *   This one only works for a single variation!
 *   It is expected that the SelectNode's name contains only one (string of) numbers which refers to the variety group's id
 *   It is possible to pre-assing a variety property array for the group formatted as such
 *   var_gr_{var_gr_id} = [
 *      {'{property_of_variety}':'{value_of_this_property}', ... },
 *      {'{property_of_next_variety}':...
 *   ]
 *   Note that the same order is expected here as is in the SelectNode. And that all properties which are to be used are present!
 * @author  Boe!end Media / Chris Volwerk
 * @link    http://boe-end.nl/
 * @param {string}      listID     The id of the list, when using autoloading the cluster_id should be the only number present
 * @param {node|string} selectNode The node which holds the current variety
 * @param {object}      parameters Which property should be placed in which node (by id) like {'property':'node_id',...}
 *
 */
var var_put = function(list, container, param){
  if($(container) == null) alert("error in var_put:\ncould not find container element '"+container+"'");
  else {
    var l = window[list], p = param;
    if(typeof l == 'undefined') {
      for(var c in p) if($(p[c]) !== null) {
        var t = $(p[c]);
        t.className = t.className+" var_put_loading";
      }
      i = list.replace(/[^0-9]*([0-9]+).*/, '$1');
      bgProcess('.', {
        list:list, container:container, param:param, onAHAHParse:function(h){
          window[this.list] = typeof JSON != "undefined" ? JSON.parse(h.responseText) : eval("("+h.responseText+")");
          var_put(this.list, this.container, this.param);
        }
      }, 'autoform=product.var_data&cluster='+i, false);
    } else {
      var c = $(container), e = c.getElementsByTagName('select'), s = [], t = "", k = [];
      for(var i in e) if(typeof e[i].name != 'undefined') if(/var\[[0-9]+\]/.test(e[i].name)) s[e[i].name.replace(/var\[([0-9]+)\]/, "$1")*1] = e[i].value;
      e = c.getElementsByTagName('input');
      for(i=0; i<e.length; i++) if(typeof e[i].type != 'undefined') if(e[i].type.toLowerCase() == 'radio') if(typeof e[i].name != 'undefined') if(/var\[[0-9]+\]/.test(e[i].name)) if(e[i].checked) s[e[i].name.replace(/var\[([0-9]+)\]/, "$1")*1] = e[i].value;
      for(i in s) k.push(i);
      k.sort(function(a, b){return(a-b);});
      for(i in k) t = t == "" ? "T"+s[k[i]] : t+"_"+s[k[i]];
      var v = l[t];
      if(typeof v == 'undefined') alert("Sorry, dieses Produkt ist ausverkauft oder nicht mehr verfügbar");
      else {
        for(var c in p) if($(p[c]) !== null) {
          var t = $(p[c]);
          t.className = t.className.replace(/ ?var_put_loading/, "");
          if(/[^0-9]*(?:[0-9]+(?:,|\.)[0-9]+)[^0-9]*/.test(v[c])){
            var s = t.innerHTML.replace(/.*[0-9]+(,|.)[0-9]+.*/, "$1");
            var nv = v[c];
            if(s.length > 0 && /[0-9]+\.[0-9]+/.test(nv)) nv = nv.replace(/([0-9]+)\.|,([0-9]+)/, "$1"+s+"$2");
            t.innerHTML = t.innerHTML.replace(/([^0-9]*)(?:[0-9]+(?:,|\.)[0-9]+)([^0-9]*)/, "$1"+nv+"$2");
          }
          else t.innerHTML = v[c];
          t.outerHTML = t.outerHTML;
  } } } }
}


// table row color fix (can't us last child and such :(
var size_tr_fix = function(){
  if($('size_table') !== null){
    var c = 0, e = $('size_table').getElementsByTagName('tr');
    for(var i in e) if(typeof e[i].className != 'undefined') if(e[i].className == "measure_row1") if(++c == 2) e[i].className = "measure_row2";
} }

/**
 * Autoload on content loaded meuk
 * + preload css images
 */
function ContentLoaded(w, f) {
	var d = w.document,
		D = 'DOMContentLoaded', u = w.navigator.userAgent.toLowerCase(), v = parseFloat(u.match(/.+(?:rv|it|ml|ra|ie)[\/: ]([\d.]+)/)[1]);
	function init(e) {
		if (!document.loaded) {
			document.loaded = true;
			// pass a fake event if needed
			f((e.type && e.type == D) ? e : {
				type: D,
				target: d,
				eventPhase: 0,
				currentTarget: d,
				timeStamp: +new Date(),
				eventType: e.type || e
			});
		}
	}
	// safari < 525.13
	if (/webkit\//.test(u) && v < 525.13) {
		(function () {
			if (/complete|loaded/.test(d.readyState)) {
				init('khtml-poll');
			} else {
				setTimeout(arguments.callee, 10);
			}
		})();
	// internet explorer all versions
	} else if (/msie/.test(u) && !w.opera) {
		d.attachEvent('onreadystatechange',
			function (e) {
				if (d.readyState == 'complete') {
					d.detachEvent('on'+e.type, arguments.callee);
					init(e);
				}
			}
		);
		if (w == top) {
			(function () {
				try {
					d.documentElement.doScroll('left');
				} catch (e) {
					setTimeout(arguments.callee, 10);
					return;
				}
				init('msie-poll');
			})();
		}
	// browsers having native DOMContentLoaded
	} else if (d.addEventListener &&
		(/opera\//.test(u) && v > 9) ||
		(/gecko\//.test(u) && v >= 1.8) ||
		(/khtml\//.test(u) && v >= 4.0) ||
		(/webkit\//.test(u) && v >= 525.13)) {
		d.addEventListener(D,
			function (e) {
				d.removeEventListener(D, arguments.callee, false);
				init(e);
			}, false
		);
	// fallback to last resort for older browsers
	} else {
		// from Simon Willison
		var oldonload = w.onload;
		w.onload = function (e) {
			init(e || w.event);
			if (typeof oldonload == 'function') {
				oldonload(e || w.event);
			}
		};
	}
}

ContentLoaded(window, function (e) {
  size_tr_fix();
  apply_zoomable();
  shopcart.added.check();
});
