window.addEvent('domready',function() {
	//winkelwagen ophalen
	if($('winkelwagen')) {
		var winkelwagen = new Cart('nl');
		winkelwagen.load();
	}

	
	if($$('.product-add') && $$('.product-aantal')) {
		$$('.product-add').addEvent('click',function(e) {
			e.stop();
			var product_id = this.get('id').replace('product-add-','');
			var aantal = $('product-aantal-'+product_id).get('value');
			var attribute = 0;
			//checken op attributen todo
			if($('product-attribute').get('value') > 0) {
				attribute = $('product-attribute').get('value');
			}
			
			var customData = new Array();
			var elements = $$('input.customData');
			elements.each(function(element) {
				var data = new Object();
				var id = element.get('id').replace('fileIdphoto','').replace('textField','');
				var value = element.get('value');
				if(value != 0 && value != '') {
					data.id = id;
					data.value = value;
					customData.include(data); 
				}
				element.set('value','');
			});
			customData = JSON.encode(customData);
			if(aantal > 0) {
				$('product-aantal-'+product_id).set('value',1);
				winkelwagen.addProduct(product_id,aantal,attribute,customData);
				$$('img.photo').each(function(element) {
					//console.log(element);
					element.set('src',"/download.php?fileId=0&amp;w=160&amp;h=120&amp;mode=origineel");
				});
			}
		});
	}
	
	$$('.zoeken').addEvent('click',function(e) {
		var value = this.getPrevious().get('value');
		var field = this.getNext();
		if(value.length < 3) {
			e.stop();
			field.set('html','Minimaal 4 characters');
		    return false;
		} else {
			field.set('html','');
		}
	});
	
});

function confirmDelete(url,bericht) {
	var a = confirm(bericht);
	if ( a == true ){
		location.href=url;
	}
}

function number_format(number, decimals, dec_point, thousands_sep) {
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');    }
    return s.join(dec);
}


var Product = new Class({
	Implements: [Events],
	initialize: function(lang) {
		this.attributes = new Array();
		//current localization
		this.lang = lang;
		
		//localizations
		this.locals = new Array();
		//nederlands
		this.locals['nl'] = new Object();
		this.locals['nl'].combo_not_excist = "Combinatie bestaat niet";
		//engels
		this.locals['en'] = new Object();
		this.locals['en'].combo_not_excist = "Combo dont excist";
	},
	load: function() {
		
	},
	addAttribute: function(product_attribute_id, attribute_ids) {
		var attribute = new Array();
		attribute['id'] = product_attribute_id;
		attribute['attribute_ids'] = attribute_ids;
		this.attributes.push(attribute);
	},
	findAttribute: function(group_id) {
		var choice = new Array();
		
		Array.each($$('.customfield-'+group_id),function(element,index) {
			if(element.getStyle('display') == '' || element.getStyle('display') == 'block') {
				element.setStyle('display','none');
				Array.each(element.getElementsByTagName('input'),function(inputelement) { //leegruimen die zooi!
					inputelement.set('value','');
				});
			}
		});
		
		var defaultProduct = true;
		
		Array.each($$('#attributes select'), function(element, index){
			if(element.get('value') != 0) { 
				defaultProduct = false; 
				choice.push(element.get('value'));
				//customfield
				
				
				if($('customfield-'+element.get('value'))) { //heeft customfield
//					console.log($('customfield-'+element.get('value')));
					if($('customfield-'+element.get('value')).getStyle('display') == 'none') {
						$('customfield-'+element.get('value')).setStyle('display','');
					}
				}
			}
		});
		
		var nbAttributesEquals = 0;
		
		if(defaultProduct) { //hoofdproduct is geselecteerd
			location.reload();
			// todo met ajax laten genereren    // Maurice: voor todo stond apenstaartje. Explorer gaat hierop kapot.
			
			return;
		}

		var result = false;
		Array.each(this.attributes,function(att,att_index) {
			nbAttributesEquals = 0;
			Array.each(this.attributes[att_index]['attribute_ids'],function(id,index) {
				if(choice.contains(this.attributes[att_index]['attribute_ids'][index])) {
					nbAttributesEquals++;
				} else {
					nbAttributesEquals--;
				}
			},this);
			
			if (!result && nbAttributesEquals == choice.length) {
				var _self = this;
				var request = new Request( {
					method: 'get', 
					url:'/webshop_v2/ajax/product.php?action=getProductAttribute&id='+this.attributes[att_index]['id'],
					evalScripts: true,
			        onSuccess: function(html) {
			        	$('product-info').set('html',html);
			        },
			        onRequest: function() {
			        	
			        },
			        onFailure: function() {
			        	result = false;
			        	return;
			        }
				});
				request.send();
				result = true;
				return;
			}
		},this);
		
		if(!result) {
			//combo bestaat niet
			
        	$('product-info').set('html',this.locals[this.lang].combo_not_excist);
		}
	},
	log: function(log_var) {
		console.log(log_var);
	}
});


/**
 * Winkelwagen JSHelper (ajax loader) dinges..
 */
var Cart = new Class({
	Implements: [Events],
	initialize: function(lang) {
		//current localization
		this.lang = 'nl';
		
		this.forceReloadWindow = false; // Het forceren van window reload bij ajax functies.
		
		//localizations
		this.locals = new Array();
		//nederlands
		this.locals['nl'] = new Object();
		this.locals['nl'].delete_product_from_cart = "Product uit winkelwagen verwijderen?";
		this.locals['nl'].delete_custom_from_product = "Aangepaste Data van product verwijderen?";
		//engels
		this.locals['en'] = new Object();
		this.locals['en'].delete_product_from_cart = "Delete product from cart?";
		this.locals['en'].delete_custom_from_product = "Delete custom data from product?";
	},
	load: function() {
		var request = new Request( {
			method: 'get', 
			url:'/webshop_v2/ajax/winkelwagen.php',
			evalScripts: true,
			onRequest: function() {
//				$('winkelwagen').set('html','Laden...');
			},
	        onSuccess: function(html) {
	        	$('winkelwagen').set('html',html);
	        },
	        onFailure: function() {
	        	$('winkelwagen').set('text', 'Winkelwagen ophalen mislukt / Cart loading failed');
	        }
		});
		request.send();
	},
	addProduct: function(product_id,product_aantal,product_attribute_id,data) {
		if(product_aantal < 1) return;
		var request = new Request( {
			method: 'post', 
			url:'/webshop_v2/ajax/winkelwagen.php?action=add_product&customData='+data,
			evalScripts: true,
			data: {
				id: product_id,
				aantal: product_aantal,
				attribute_id: product_attribute_id
			},
			onRequest: function() {
				//$('winkelwagen').set('html','Laden...');
			},
	        onSuccess: function(html) {
	        	$('winkelwagen').set('html',html);
	        	var childs = $('winkelwagen').getChildren();
				var table = childs[0];
				var highlight = new Fx.Morph(table, {
					duration: 1500,
					link: 'cancel',
					transition: 'quad:out'
				});
				$('winkelwagen').addEvents({			
					burn: function() {
						highlight.start({
							backgroundColor: ['#00FF00', '#ffffff'],
							opacity: [0.5, 1]
						});
					}
				});
				//$('winkelwagen').fireEvent('burn');
	        },
	        onFailure: function() {
	        	$('winkelwagen').set('text', 'Winkelwagen ophalen mislukt / Cart loading failed');
	        }
		});
		request.send();
	},
	remove: function(row_id) {
		//confirm deletevar 
		a = confirm(this.locals[this.lang].delete_product_from_cart);
		var forceReloadWindow = this.forceReloadWindow;
		
		if ( a == true ) {
			var request = new Request( {
				method: 'get', 
				url:'/webshop_v2/ajax/winkelwagen.php?action=remove_row&id='+row_id,
				evalScripts: true,
				onRequest: function() {
					//$('winkelwagen').set('html','Laden...');
				},
		        onSuccess: function(html) {
		        	if($('winkelwagen') && !forceReloadWindow) {
		        		$('winkelwagen').set('html',html);
		        	} else {
		        		location.reload();
		        	}
		        },
		        onFailure: function() {
		        	$('winkelwagen').set('text', 'Winkelwagen ophalen mislukt / Cart loading failed');
		        }
			});
			request.send();
		}
	},
	removeCustom: function(custom_id,row_id) {
		//confirm deletevar 
		//console.log(custom_id);
		//console.log(row_id);
		
		a = confirm(this.locals[this.lang].delete_custom_from_product);
		if ( a == true && custom_id && row_id) {
			var request = new Request( {
				method: 'get', 
				url:'/webshop_v2/ajax/winkelwagen.php?action=remove_custom&id='+custom_id+'&row_id='+row_id,
				evalScripts: true,
				onRequest: function() {
					//$('winkelwagen').set('html','Laden...');
				},
		        onSuccess: function(html) {
		        	if($('winkelwagen')) {
		        		$('winkelwagen').set('html',html);
		        	} else {
		        		location.reload();
		        	}
		        },
		        onFailure: function() {
		        	$('winkelwagen').set('text', 'Winkelwagen ophalen mislukt / Cart loading failed');
		        }
			});
			request.send();
		}
	},
	increase: function(row_id) {
		if(row_id || row_id == 0) {
			var request = new Request( {
				method: 'get', 
				url:'/webshop_v2/ajax/winkelwagen.php?action=increase&row_id='+row_id,
				evalScripts: true,
				onRequest: function(e) {
					/*Array.each($$('button'),function(element,index) {
						element.set('disabled','disabled');
					});*/
				},
		        onSuccess: function(html) {
		        	location = location.href;
		        }
			});
			request.send();
		}
	},
	decrease: function(row_id) {
		if(row_id || row_id == 0) {
			var request = new Request( {
				method: 'get', 
				url:'/webshop_v2/ajax/winkelwagen.php?action=decrease&row_id='+row_id,
				evalScripts: true,
				onRequest: function(e) {
					/*Array.each($$('button'),function(element,index) {
						element.set('disabled','disabled');
					});*/
				},
		        onSuccess: function(html) {
		        	location = location.href;
		        }
			});
			request.send();
		}
	},
	increaseCustom: function(custom_id,row_id) {
		if(custom_id && row_id) {
			var request = new Request( {
				method: 'get', 
				url:'/webshop_v2/ajax/winkelwagen.php?action=increaseCustom&id='+custom_id+'&row_id='+row_id,
				evalScripts: true,
				onRequest: function(e) {
					/*Array.each($$('button'),function(element,index) {
						element.set('disabled','disabled');
					});*/
				},
		        onSuccess: function(html) {
		        	location = location.href;
		        }
			});
			request.send();
		}
	},
	decreaseCustom: function(custom_id,row_id) {
		if(custom_id && row_id) {
			var request = new Request( {
				method: 'get', 
				url:'/webshop_v2/ajax/winkelwagen.php?action=decreaseCustom&id='+custom_id+'&row_id='+row_id,
				evalScripts: true,
				onRequest: function(e) {
					/*Array.each($$('button'),function(element,index) {
						element.set('disabled','disabled');
					});*/
				},
		        onSuccess: function(html) {
		        	location = location.href;
		        }
			});
			request.send();
		}
	},
	log: function(log_var) {
		//console.log(log_var);
	}
	
});
