/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);
        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

/**
  *	Ons Bedrijf Javascript functies voor het winkelwagentje
  *	Het winkelwagentje is in principe een array, met de volgende structuur:
  *	{
  *		(artikelnr): {
  *			naam: (artikelnaam),
  *			aantal: (aantal),
  *			prijs: (prijs) 
  *		}
  *	}
  **/

function shop_voeg_toe(artikelnr, aantal, naam, prijs) {
	var wagen = $.cookie("ob_winkelwagen");
	if (!wagen) {
		wagen = new Array();
		wagen = encode_wagen(wagen);
	}
		
	wagen = decode_wagen(wagen);
	if (wagen[artikelnr]) {
		var aant = parseInt(wagen[artikelnr]['aantal']);
		wagen[artikelnr]['aantal'] = parseInt(aantal) + aant;
	} else {
		var artikel = {
			"naam":   naam,
			"aantal": aantal,
			"prijs":  prijs
		}
		wagen[artikelnr] = artikel;
	}
	$.cookie("ob_winkelwagen", encode_wagen(wagen));
	alert("Het artikel is toegevoegd aan uw bestelformulier.");
	document.location.href='http://www.onsbedrijfbarneveld.nl/page/434';
}

function shop_verwijder(artikelnr) {
	var wagen = decode_wagen($.cookie("ob_winkelwagen"));
	delete wagen[artikelnr];
	$.cookie("ob_winkelwagen", encode_wagen(wagen));
	alert('Artikel verwijderd');
}

function shop_verander_aantal(artikelnr, aantal) {
	var wagen = decode_wagen($.cookie("ob_winkelwagen"));
	wagen[artikelnr]['aantal'] = aantal;
	$.cookie("ob_winkelwagen", encode_wagen(wagen));
}

function update_overzicht(edit, del) {
	var wagen = decode_wagen($.cookie("ob_winkelwagen"));
	$('.article_info').remove();
	var num = 0;
	var total_price = 0;
	for (i in wagen) {
		if (!i) {
			continue;
		}
		num ++;
	
		if (edit == 1) {
			var editable = '<td><input type="text" name="aantal_'+num+'" id="aantal_'+num+'" onchange="shop_verander_aantal(\''+i+'\', $(\'#aantal_'+num+'\').val()); update_overzicht();" class="inputtext_aantal" value="'+wagen[i]['aantal']+'" /></td>';
		} else {
			var editable = '<td><input type="text" name="aantal_'+num+'" id="aantal_'+num+'" onchange="shop_verander_aantal(\''+i+'\', $(\'#aantal_'+num+'\').val()); update_overzicht();" class="inputtext_aantal" value="'+wagen[i]['aantal']+'" /></td>';
		}
		
		total_price = total_price + (parseInt(wagen[i]['aantal']) * parseFloat(wagen[i]['prijs']));
		var price = wagen[i]['prijs'].replace('.',',');
		var split_price = price.split(",");
		if (split_price.length == 1) {
			price = split_price[0]+",00"
		} else if (split_price[1] < 10) {
			price = split_price[0]+","+split_price[1]+"0";
		}
		
		if (del == 1) {
			var del = '<td colspan="3"><input type="hidden" name="prijs_'+num+'" value="'+wagen[i]['prijs']+'" />&euro; '+price+' <a href="javascript: shop_verwijder(\''+i+'\'); update_overzicht(1,1);">[x]</a></td>';
		} else {
			var del = '<td colspan="3"><input type="hidden" name="prijs_'+num+'" value="'+wagen[i]['prijs']+'" />&euro; '+price+' <a href="javascript: shop_verwijder(\''+i+'\'); update_overzicht(1,1);">[x]</a></td>';
		}
		$('#article_total_price').before('<tr class="article_info">'+
			'<td>Artikel</td>'+
			'<td>'+i+' ('+wagen[i]['naam']+') <input type="hidden" name="artikel_'+num+'" value="'+i+'" /></td>'+
			'<td>Aantal</td>'+ editable +
			'<td>Bedrag</td>'+ del +
				
		'</tr>');
	}
	var price = String(total_price).replace('.',',');
	var split_price = price.split(",");
	if (split_price.length == 1) {
		price = split_price[0]+",00"
	} else if (split_price[1] < 10) {
		price = split_price[0]+","+split_price[1]+"0";
	}
	$('#total_price').text(price);
	$('#total_price_form').val(total_price);
}

function encode_wagen(wagen) {
	var str = '';
	for (i in wagen) {
		for (j in wagen[i]) {
			str += i+"="+j+"="+wagen[i][j]+"\n";
		}
	}
	return(str);
}

function decode_wagen(wagen) {
	wagen = wagen.split("\n");
	var ret = new Array();
	for (i in wagen) {
		var spl = wagen[i].split("=");
		if (!ret[spl[0]]) {
			ret[spl[0]] = new Array();
		}
		if (spl[0]) {
			ret[spl[0]][spl[1]] = spl[2];
		}
	}	
	return(ret);
}
