var combiprices = new Array();
function submit_form(name){
try {
	f = document.forms[name];
	if(typeof f == 'object')f.submit();
	return false;
} catch(e){ 
	alert(e.description); 
	return false;
	}
}

function togglePromocode(btn){
	if (btn.hasClass('promotiecode_open')){
		btn.removeClass('promotiecode_open');
		$('promotiecode').setStyle('display','none');
	} else {
		btn.addClass('promotiecode_open');
		$('promotiecode').setStyle('display','block');
	}
}

function price_to_int(str){
	try {
		str = str.replace(',', '.');
		str = str.replace(new RegExp(/[^0-9.]/g), '');
		return str;
	} catch(e){  };
}

function check_code(code, price){
/*
	var request = new Request.JSON({
				url: '/check_code.php',
				onComplete: function(jsonObj) {
					alert(jsonObj);
				}
			}).post({'code':code, 'price':price});
*/

	$('incentivecode').value = $('incentivecode').value.toUpperCase();

	var req = new Request.HTML({

		url: '/check_code.php',

		onSuccess: function(txt){
			if ( txt != 'error' ) {
				$('yourprice').set('text', '');
				$('yourprice').adopt(txt);
			}
		}

	}).post({'code':code, 'price':price});


}

function format_price(str){
	try {
		str += '';
		if(str.indexOf('.') > -1){
			str = Math.round(str*100)/100;
			str += '';
			p = str.split('.');
			val = p[0]; cent=p[1];
			while(cent.length < 2){cent+='0';}
		} else {
			val = str;
			cent = '00';
		}
		return '&euro; '+val+','+cent;
	} catch(e){  };
}
var article;
_obj = function(id){
	obj = document.getElementById(id);
	if(!obj){}else{
		if(typeof(obj) == 'object' && obj.tagName){
			objs = 'TABLE THEAD TBODY TFOOT TR TD DIV FORM SPAN INPUT SELECT STRONG LABEL';
			if(objs.indexOf(obj.tagName) > -1){
				return obj;	
			}
		}
	}
//	alert(id +' niet gevonden');
	return new Object();
}
function calc_price(i, art){
	//alert('calc'+i);
	try {
		if(!art){ art=false; } else { article = art; }
		if(typeof i == 'object')i = i.id.substring(i.id.indexOf('_')+1)*1;
		s = _obj('size_'+i).value;
		c = _obj('color_'+i).value;
		a = _obj('amount_'+i).value;
		if(a == ''){  _obj('amount_'+i).value = '1'; }
		for(j=0; j<combiprices.length; j++){
			if(combiprices[j].id == article+c+'-'+s.substring(0,6)){
				pp = combiprices[j].pr;
				ppf = price_to_int(combiprices[j].pr);
				ppk = ppf.replace('.',',');
				ppp = format_price(ppf);
				pt = a > 0 ? ppf*a : 0;
				ptk = format_price(pt);
				
				_obj('totaltxt_'+i).innerHTML = ptk;
				_obj('totalprice_'+i).value = pt;
				_obj('label_'+i).value = article+'##'+c+'-'+s.substring(0,6);
				_obj('pricetxt_'+i).innerHTML = ppp;
				_obj('price_'+i).value = ppf;
			}
		}
		t = _obj('total_price');
		if(t.tagName && t.tagName == 'TD'){
			tot = 0;
			table = _obj('cart');
			tbody = table.getElementsByTagName('TBODY')[0];
			trs =  tbody.getElementsByTagName('TR');
			for(x=0; x<trs.length; x++){
				if(trs[x].id.length > 0){
					//price_to_int(combiprices[j].pr)
					p = _obj('totaltxt_'+trs[x].id);
					if(!p){}else{p = price_to_int(p.innerHTML);
					tot = tot + (p*1);
					}
				}
			}
			t.innerHTML = format_price(tot);
		}
		if(i > 1){
			if(s != '' && c != ''){
				hold = document.getElementById('table_dynamic');
				trs = hold.getElementsByTagName('TR');
				if(trs.length == i){
					clone = trs[i-1].cloneNode(true);
					elms = new Array('SELECT','INPUT','STRONG');
					for(z=0; z<elms.length; z++){
						csel = clone.getElementsByTagName(elms[z]);
						for(j=0; j<csel.length; j++){
							if(csel[j].id != ''){
								parts = csel[j].id.split('_');
								csel[j].id = parts[0]+'_'+(i+1);
								switch(elms[z]){
									case 'INPUT':
										csel[j].value = '';
										break;
									case 'STRONG':
										csel[j].innerHTML = '';
										break;
								}
							}
						}
					}
					hold.appendChild(clone);
				} 
			}
		}
	} catch(e){ 
		alert(e.description); 
	};
}

function submit_cart(type, other_vars){
	f = document.forms['cart'];
	if(!type){ calc_price(1);
	} else {
		switch(type){
			case 'check_amount':
				inp = f.getElementsByTagName('INPUT');
				ok = true;
				for(i=0; i<inp.length; i++){
					if(inp[i].id.substring(0,7) == 'amount_'){
						if(!check_errors_onkeypress(inp[i], 'IS_NUMERIC', true, true))ok=false;
					}
				}
				if(!ok)return false;
				break;
			case 'recalculate':
				f.action = url_prefix+'/shop/cart/update.html';
				break;
			case 'order':
				f.action = url_prefix+'/shop/order.html';
				break;
			case 'delete_and_recalculate':
				if(!other_vars)other_vars=false;
				else {
					inp = f.getElementsByTagName('INPUT');
					for(i=0; i<inp.length; i++){
						if(inp[i].type == 'text'){
							if(inp[i].name.indexOf(other_vars) > -1){
								inp[i].value = 0;
								f.action = url_prefix+'/shop/cart/update.html';
							} else {
								//inp[i].value = 'skip';
								inp[i].disabled = true;
							}
						}
					}
				
				}
				break;
			case 'shipping':
				f = document.forms[type];
				break;
		}
	}
	if(typeof f == 'object')f.submit();
	return false;
}


document.getElementsByClassName = function (needle)
{
    var s = [document.documentElement || document.body], i = 0, r = [], l = 0, e;
    var re = new RegExp('(^|\\s)' + needle + '(\\s|$)');

    do
    {
        e = s[i];

        while (e)
        {
            if (e.nodeType == 1)
            {
                if (e.className && re.test(e.className)) r[l++] = e;

                s[i++] = e.firstChild;
            }

            e = e.nextSibling;
        }
    }
    while (i--);

    return r;
}

set_address = function(str){
	try {
		p = str.split('###');
		f = document.forms['address'];
		if(typeof(f) == 'object'){
			f.check_id.value = p[0];
			sp = p[1].split(' ');
			nr = sp[sp.length-1];
			f.street.value = p[1].substring(0, p[1].length-nr.length);
			f.streetnumber.value = nr;
			f.zipcode.value = p[3];
			f.city.value = p[4];
			f.country.value = p[5];
		}
	} catch(e){
		alert(e.desciption);	
	}
}

select_address = function(){
	a = document.getElementById('address_select');
	if(typeof(a) == 'object'){
		d = document.getElementsByTagName('DIV');
		for(i=0; i<	d.length; i++){
			if(d[i].className.indexOf('c_grey') > -1 && d[i].getElementsByTagName('INPUT')[0].name == 'address'){
				d[i].onmouseover = function(){
					this.style.background='#666666';
					this.style.cursor = 'pointer';
				}
				d[i].onmouseout = function(){
					if(!this.getElementsByTagName('INPUT')[0].checked)this.style.background='#999999';
				}
				d[i].onclick = function(){
					par =  document.getElementById('address_select');
					//d = par.parentNode.getElementsByTagName('DIV');
					for(i=0; i<	d.length; i++){
						if(d[i].className.indexOf('c_grey') > -1){
							if(d[i].getElementsByTagName('INPUT')[0].checked){
								d[i].style.background='#999999';
								d[i].getElementsByTagName('INPUT')[0].checked = false;
							}
						}
					}
					this.getElementsByTagName('INPUT')[0].checked = true;
					document.forms['address'].check_id.value = 'N';	
				}
			};
		}
		f = document.forms['address'];
		if(typeof(f) == 'object'){
			//alert('object');
			inp = f.getElementsByTagName('INPUT');	
			//alert(inp.length);
			for(i=0; i<inp.length; i++){
				inp[i].onkeypress = inp[i].onfocus = function(){
					this.form.check_id.value = 'Y';	
				}
			/*	inp[i].onfocus = function(){
					alert(this);
					alert(this.form.check_id);
					this*.form.check_id.value = 'Y';	
				}*/
			}
		}
	}
}
function switchAdvancedElements(classe, hide, label){
	if(!hide)hide=false;
	if ( classe ) {
		obj = document.getElementsByClassName(classe);
		for(i=0; i<obj.length; i++){
			if(label && obj[i].className.indexOf('lab_organisationname') > -1){
				obj[i].innerHTML = label+'*';	
			}
			obj[i].style.display=!hide ? 'block' : 'none';
		}
	}
}

value_is_valid = function(value, type){
	while(value.substr(0, 1) == ' ')value = value.substring(1);
	if(type.indexOf('|EMPTY') > -1){
		type = type.substring(0, type.indexOf('|EMPTY'));
		if(value == '')return true;
	}
	switch(type){
		case 'NOT_EMPTY':
			if(value.length > 0)return true;
			break;
		case 'IS_COUNTRYCODE':
			reg = new RegExp(/[A-Z]{2}/i);
			if(value.match(reg) && value.length == 2)return true;
			break;
		case 'IS_DATE':
			reg = new RegExp(/[0-9]{2}-[0-9]{2}-[0-9]{4}/gi);
			if(value.match(reg) && value.length == 10)return true;
			break;
		case 'IS_URL':
			reg = new RegExp(/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi);
			if(value.match(reg))return true;
			break;
		case 'IS_NUMERIC':
			reg = new RegExp(/^[0-9]*$/);
			if(value.match(reg))return true;
			break;
		case 'IS_EMAIL':
			reg = new RegExp(/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
			if(value.match(reg))return true;
			break;
		case 'IS_PHONENUMBER':
			f = new Array('-',' ','(',')','+');
			for(i=0; i<f.length; i++){
				value = value.replace(f[i], '');
			}
			reg = new RegExp(/^\d{10,15}/g);
			if(value.match(reg) && value.length < 16)return true;
			break;
		default:
			if(type.substring(0,1) == '[' && type.substring(type.length-1) == ']'){
				type = type.substring(1, type.length-1);
				switch(type.substring(0,7)){
					case '!STRING': return type.substring(7) == value ? false : true; break;
					case 'REGEXP:': 
						try {
							regexp = '[^'+type.substring(7)+']';
							reg = new RegExp(regexp, 'gi');
							if(!value.match(reg))return true;
						} catch(e){}
						break;
				}
			}
	}
	return false;
}
check_errors_onkeypress = function(obj, type, skip_classname, check_now){
	if(!skip_classname)skip_classname=false;
	if(!check_now)check_now=false;
	//value_is_valid(this.value, this.rel) == false
	if(typeof(obj) == 'object'){
		if(!skip_classname)obj.className += ' fielderror';
		obj.rel = type;
		obj.onkeypress = obj.onkeyup = obj.onkeydown = obj.onblur = function(){
			try {
				if(this.className.indexOf('fielderror') > -1 && value_is_valid(this.value, this.rel)){
					this.className = this.className.replace('fielderror','');
					l = document.getElementById('rel_'+this.id);
					if(typeof l == 'object'){
						l.className = l.className.replace('labelerror','');
					}
				} 
				else if(this.className.indexOf('fielderror') == -1 && value_is_valid(this.value, this.rel) == false){
					this.className += ' fielderror';
					l = document.getElementById('rel_'+this.id);
					if(typeof l == 'object'){
						l.className += ' labelerror';
					}
				}
			} catch(e){}
		}
		// checken voor label
		if(obj.id){
			labels = obj.parentNode.getElementsByTagName('LABEL');
			if(labels.length == 0)labels = obj.parentNode.parentNode.getElementsByTagName('LABEL');
			for(x=0; x<labels.length; x++){
				f = labels[x].getAttribute('for');
				if(!f){
					f = labels[x].attributes["for"].value;
				}
				if(f == obj.id){
					 if(!skip_classname)labels[x].className += ' labelerror';
					 labels[x].id = 'rel_'+obj.id;
				}
				
			}
		}
	}
	if(check_now){
		valid = value_is_valid(obj.value, obj.rel);
		if(!valid)obj.className += ' fielderror';
		return valid;
	}
};
showFormErrors = function(form, fieldstr){
	f = document.forms[form];
	if(typeof(f) == 'object' && fieldstr.length > 0){
		fields = fieldstr.split(',');
		fe = f.getElementsByTagName('*');
		for(i=0; i<fe.length; i++){
			if(fe[i].name){
				for(j=0; j<fields.length; j++){
					parts = fields[j].split('::');
					if(fe[i].name == parts[0]){
						check_errors_onkeypress(fe[i], parts[1]);
					} 
				}
			}
		}
	}
};
_convert = function(inp){
	s = l = ''; for(i=0;i<inp.length;i=i+3){ s+= (inp.substring(i, i+3));i=i+3; }
	for(i=0;i<s.length;i=i+3){ if((s.substring(i, 3+i)*1/3) != ''){ l+= String.fromCharCode((s.substring(i, 3+i)*1/3)); } }
	document.write(l);
};

checkRelatedElement = function(_this){
	try {
		c = _this.className+'';
		m = c.match(/rel_([a-z_0-9]+)/gi);
		m = m+'';
		v = c.match(/val_([a-z_0-9]+)/gi);
		v = v+'';
		ma = _this.value == v.substring(4) ? true : false;
		obj = document.getElementById(m.substring(4));
		obj.style.display = !ma ? 'block' : 'none';
		if(obj.id){
			par = obj.parentNode;
			labels = par.getElementsByTagName('LABEL');
			if(labels.length == 0){
				par = obj.parentNode.parentNode;
				labels = par.getElementsByTagName('LABEL');
			}
			br = par.getElementsByTagName('BR');
			for(x=0; x<labels.length; x++){
				f = labels[x].getAttribute('for');
				if(!f){
					f = labels[x].attributes["for"].value;
				}
				if(f == obj.id){
					 labels[x].style.display = !ma ? 'block' : 'none';
					 labels[x].id = 'rel_'+obj.id;
				}				
			}
			if(get_nextsibling(obj).tagName == 'BR'){
				 get_nextsibling(obj).style.display = !ma ? 'block' : 'none';
			}
		}	
	} catch(e){};
}
checkFormRelations = function(form){
	r = document.getElementsByClassName('related');
	for(i=0; i<r.length; i++){
		r[i].onchange = function(){
			checkRelatedElement(this);
		}
		checkRelatedElement(r[i]);
	}
	
}

var to;
var curelm;
window.addEvent('domready', function(){					 
	/* Topmenu tabjes laden en mouseovers instellen */
	if($$('a.bottomsub_a').length > 0){
		$$('a.bottomsub_a').addEvents({
			'mouseenter': function(){ 
				curelm = this;
				if ( $type(to) == 'number' ) {$clear(to);} 
				$$('div.bottomsub').setStyle('display','none');
				$(this.get('rel')).setStyle('display','block');
			},
			'mouseleave': function(){ 
				to= (function(){ $$('div.bottomsub').setStyle('display','none'); }.bind(this)).delay(1000) ;
			}
		});
		$$('div.bottomsub').addEvents({
			'mouseleave':function(){
				to= (function(){ this.setStyle('display','none'); }.bind(this)).delay(1000) ;
			}, 
			'mouseenter':function(){if ( $type(to) == 'number' ) {$clear(to)}}
		});

	}
});

