// (C) STRAWBERRIES
// STRAWBERRIES is a Dutch company, located in Amsterdam. For more
// information, see www.strawberries.nl or contact (+31) 20 5315151
//
// Created by: Patrick Klaassen
// Created date: july 2010


/**
 * Old Cookie cleanup
 */
Cookie.dispose('gamma.cartlist', {path: '/'});

//We define a custom event called "keyenter" which is based on the keyup event
Element.Events.keyenter = {
	base: 'keyup',
	condition: function(e){
		// We can basically put any logic here.
		// In this example we return true, when the pressed key is the
		// Enter-Button so the keyenter event gets fired.
		return e.key=='enter';
	}
};

/**
 * called on onsubmit to handle enter presses
 * @param pos the nth field
 * @returns
 */
var addToShoppingListOnEnter = function(pos){
	addShoppingItem({name: $$('div.cart-add').getElement('input')[pos].value});
}

/**
 * Makes the elements for the shopping list from cookie
 *
 * @param {String} item
 * @param {Object} newItem
 * @returns void
 */
var makeShoppingList = function(item, newItem) {
	var elAmountDiv = new Element('div', {
		'class': 'plusminvalue img'
	});

	var elInput = new Element('input', {
		'type': 'text',
		'maxlength': 3,
		'class': 'amount'
	});


	elInput.onblur = function(){
		item.amount = this.value;
		changeShoppingItem(item);
	};
//	var elInputField = $$('div.cart-add').getElement('input.text');
//	elInputField.addEvent('keyenter', function(e){
//		e.stop();
//		
//		var field = $$('div.cart-add').getElement('input')[0];
//		addShoppingItem({name: field.value});		
//		
//	});


	elInput.setAttribute('value', item.amount);
	elInput.inject(elAmountDiv);

	var elDeleteA = new Element('a', {
		'href': 'javascript:removeShoppingItem(\''+item.name+'\', \'sl-'+item.name.replace(/\s/gi, '_')+'\')',
		'title': 'verwijderen',
		'class': 'delete-s icon right'
	});
	elDeleteA.innerHTML = 'verwijderen';

	if(item.url){
		var elName = new Element('a', { 'href': item.url});

	}else{
		var elName = new Element('div', {
			'class': 'txt'
		});
	}

	elName.innerHTML = item.name;

	if ($chk(newItem)){
		var elCartitemDiv = new Element('div', {
			'class': 'cartitem imgtxt justadded',
			'id': 'sl-'+item.name.replace(/\s/gi, '_')
		});
	} else {
		var elCartitemDiv = new Element('div', {
			'class': 'cartitem imgtxt',
			'id': 'sl-'+item.name.replace(/\s/gi, '_')
		});
	}

	elAmountDiv.inject(elCartitemDiv);
	elDeleteA.inject(elCartitemDiv);
	elName.inject(elCartitemDiv);

	//clone cart item element
	var cartItemClone = elCartitemDiv.clone();
	//give cartItemClone an id; this is used to remove the item.
	cartItemClone.id = 'sl-'+item.name.replace(/\s/gi, '_')+'_page';

	//after 5 sec of delay, remove class 'justadded'
	if (elCartitemDiv.hasClass('justadded')) {
		(function(){ elCartitemDiv.removeClass('justadded'); }).delay(5000);
	}
	if (cartItemClone.hasClass('justadded')) {
		(function(){ cartItemClone.removeClass('justadded'); }).delay(5000);
	}

	elCartitemDiv.inject($('cartitems'), 'top');
	//if on shopping list page; then put also the items there
	if ($chk($$('#cart_inpage .cartitems')[0])) {
		cartItemClone.inject($$('#cart_inpage .cartitems')[0], 'top');
	}
}

/**
 * Set the scrollbars for shopping list
 *
 * @returns void
 */
var setShoppingScrollbars = function() {
	if ($$('.mid').scrollHeight > 250) {
		$$('.mid').setStyles({
			'height': '250px',
			'overflow': 'auto'
		});
	}
}

/**
 * Removes (one or more) the 'no item in shopping list' text
 *
 * @returns void
 */
var disposeNoItemsDiv = function() {
	var divs = $$('.no_items_in_shopping_list');
	divs.each(function(el) {
		el.dispose();
	});
}

/**
 * Add item to shopping list
 * @param {Object} item
 * @param {Element} element
 * @return Boolean
 */
function addShoppingItem(item, el) {

//testing inputValue
	var cleanInputValue = item.name.clean();
	var regExValue = '[\*\$\#\@]';
	var emptyValueText = 'Vul een product in';
	//flag to set when the amount should be changed from an already existing item.
	var changeAmount = false;

	if (cleanInputValue.test(regExValue) == true) {
		alert('Karakter ' + cleanInputValue.match(regExValue)[0] + ' is niet toegestaan.');
		return false;
	} else if (cleanInputValue.length <= 2 || cleanInputValue == emptyValueText) {
		alert('Geen juiste productnaam ingevuld.');
		return false;
	} else if (cookies.containsKey(cleanInputValue)) {
		if (!$chk(item.amount)) {
			alert('\''+cleanInputValue+'\' is al in uw boodschappenlijst.');
			return false;
		} else {
			changeAmount = true;
		}
	}

//testing amount
	//set default
	if (!$chk(item.amount)) item.amount = 1;

	//check if amount is not between 1 and 99
	if (item.amount < 1 || item.amount > 999) {
		alert('Vul een aantal in tussen 1 en 999.');
		return false;
	}

//everything is OK, so we put it in a cookie! :-)
	disposeNoItemsDiv();
	if (changeAmount) {//remove old line
		var id = 'sl-'+item.name.replace(/\s/gi, '_');
		$(id).dispose();
	}
	makeShoppingList(item, true);
	cookies.insertShoppingItem(item.name, item);

	//open shopping list if not already opened
	if (!$('cart').hasClass('cart_hover')) $('cart_link').fireEvent('click');

	//show the added to cart message
	var incartMessage = $('incart');
	if(incartMessage){
		$('incart').setStyle('display', 'block');
	}
	var el = $(el);
	if ($chk(el) && $chk(el.getParent())){
		var parent = el.getParent();
		if ($chk(parent.getParent())){
			var superparent = parent.getParent();
			if(	superparent.getElements('.incart')){
				var list = superparent.getElements('.incart');
				if($chk(list[0]) ) {
					var incart = list[0];
					incart.setStyle('display', 'block');
					(function() { incart.setStyle('display', 'none'); }).delay(5000);
				}
			}
		}
	}
	try{
		wa.productAddToCart(removeForbidden(item.name));
	}
	catch(e){}
	
	return true;
}

/**
 * Add the checked items from a klusadvies page to the shoppingcart.
 */
function addShoppingItems(){
	var elementList = document.getElementsByTagName("input");
	var shoppingList = new Array();
	for (i=0;i<elementList.length;i++){
		var inputElement = elementList[i];
		if (inputElement.type == 'checkbox' && inputElement.checked) {
			shoppingList.push(inputElement);
		}
	}
	for (i=0;i<shoppingList.length;i++){
		var inputElement = shoppingList[i];
		addShoppingItem({name:inputElement.name},inputElement.name);
	}
}

/**
 * Remove item from shopping list
 * @param {String} key
 */
function removeShoppingItem(key, id) {
	if ($chk(key)) {
		cookies.removeShoppingItem(key);
		//remove the item from the dropdown
		$(id).dispose();
		//and remove the item from the page
		if($chk($(id+'_page'))) {
			$(id+'_page').dispose();
		}
		
		try{
			wa.productRemoveFromCart(key);
		}
		catch(e){}
	}
}

/**
 * Remove all items from shopping list (removing cookie)
 *
 * @return void
 */
function removeAllShoppingItems() {
	if (confirm('Wilt u echt uw boodschappenlijst leegmaken?')) {
		//clear the cookie
		cookies.getShoppingList().each(function(value, key) {
			cookies.removeShoppingItem(key);
			try{
				wa.productRemoveFromCart(key);
			}
			catch(e){}
		});
		//remove items from the dropdown and the page
		$('cartitems').empty();
		if($chk($('cartitems-page'))){
			$('cartitems-page').empty();
		}
		//put the 'no products' message back in
		var elNoItemsDiv = new Element('div', {
			'style': 'padding: 10px 0;',
			'class': 'no_items_in_shopping_list'
		});
		elNoItemsDiv.innerHTML = 'Er staan geen producten op de boodschappenlijst';

		if ($chk($('cart_inpage'))) {
			var noItemsDivClone = elNoItemsDiv.clone();
			noItemsDivClone.inject($$('#cart_inpage .cartitems')[0]);
		}
		if ($chk($('cartitems'))) {
			elNoItemsDiv.inject($('cartitems'));
		}
	}
}

/**
 * Refreshes the value of item.name in the cookie store
 *
 * @param {Item} item
 * @returns {Boolean}
 */
function changeShoppingItem(item) {
	cookies.removeShoppingItem(item.name);
	cookies.insertShoppingItem(item.name, item);
	return true;
}

/**
 * Get the value of the key in the url
 * @param {String} variable
 * @returns String
 */
function getQueryByVariable(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
}

/**
 * Domready
 */
var cookies = undefined;
var shoppingframes = $('shoppingframe');

var initializedSF=1;
function initialize_SF(){
	
	if($chk(window.shoppingframe.cookies)){
		initializedSF=-1;
		initializeSF();
	}
	else{
		if(initializedSF>20){initializedSF=-1;}
		initializedSF++;
		setTimeout("initialize_SF()", 1000);
	}
}
window.addEvent('domready', function(){initialize_SF()});

function initializeSF(){

//	if (!$chk(cookies)) {
//		cookies = new CookieStorage();
//	}
	cookies = window.shoppingframe.cookies;
	var cart_list = $('cart');

	//If no items are in the shopping list you see this message
	//This will be removed if you add an item in the shopping list
	var elNoItemsDiv = new Element('div', {
		'style': 'padding: 10px 0;',
		'class': 'no_items_in_shopping_list'
	});
	elNoItemsDiv.innerHTML = 'Er staan geen producten op de boodschappenlijst';

	if ($chk($('cart_inpage'))) {
		var noItemsDivClone = elNoItemsDiv.clone();
		noItemsDivClone.inject($$('#cart_inpage .cartitems')[0]);
	}
	if ($chk($('cartitems'))) {
		elNoItemsDiv.inject($('cartitems'));
	}

	//get all items in cookie to make shopping list
	cookies.getShoppingList().each(function(value, key) {
		//if there are items in the cookie, remove the 'no items' message
		disposeNoItemsDiv();
		makeShoppingList(value);
	});

	//Set scrollbars in shopping list div
	setShoppingScrollbars();

	cart_list_fx = new Fx.Morph('cart', {duration: 400});

	//don't display shopping list
	$('cart').setStyle('display', 'none');

	//click event
	$('cart_link').addEvent('click', function(e){
		//check if the cart list is open
		if (cart_list.hasClass('cart_hover')) {
			//cart list slide in and removing the list
			cart_list.set('morph', {
				'link': 'chain',
				'return': 'element'
			}).morph({
				'height': [370,0],
				opacity: 0
			}).morph({
				'display': 'none'
			});
			cart_list.removeClass('cart_hover');

		} else {
			$('cart').setStyles({
				display: 'block',
				height: 'auto',
				opacity: 0
			});
			//cart list slide out
			cart_list_fx.start({
				'height': [0,370],
				'opacity': 1,
				'filter': 'alpha(opacity=100)',
				'display': 'block'
			});
			cart_list.addClass('cart_hover');

		}
	});

	//click event
	$('close_cart').addEvent('click', function(e){
			//cart list slide in and removing the list
			cart_list.set('morph', {
				'link': 'chain',
				'return': 'element'
			}).morph({
				'height': [$('cart').getSize().y,0],
				opacity: 0
			}).morph({
				'display': 'none'
			});
			cart_list.removeClass('cart_hover');

	});

	//if print is true, redirect to shopping list page and run print function
	if (getQueryByVariable('print') == 'print') {
		print_shopping_list.delay(1000);
	}

	// hook plus/min buttons
	for (i = 0; i < (plusmin = $$('.tocart .plusminvalue')).length; i++) {
		plusmin[i].getChildren('.plus')[0].addEvent('click', function(e) {
			if ($(e.target).getNext('.amount').get('value') < 99)
				$(e.target).getNext('.amount').set('value', parseInt($(e.target).getNext('.amount').get('value')) + 1);
			return false;
		});
		plusmin[i].getChildren('.min')[0].addEvent('click', function(e) {
			if ($(e.target).getNext('.amount').get('value') > 1)
				$(e.target).getNext('.amount').set('value', parseInt($(e.target).getNext('.amount').get('value')) - 1);
			return false;
		});
	}
}

/**
 * Print shopping list
 *
 * @param {Boolean} isHead
 * @return redirect
 */
function print_shopping_list(isHead) {
	//if isHead is true, redirect to shopping list page and run print function
	if ($chk(isHead) && isHead == true) {
		isHead = null;
		return setTimeout("location.href='/boodschappenlijst?print=print'", 1);
	}


	//shopping list element
	var elCart = $('cart_inpage');

	var amounts = new Array();
	var products = new Array();
	elCart.getElements('.amount').each(function(elm){
		amounts.push(elm.value);
	});
	elCart.getElements('.txt').each(function(elm){
		products.push(elm.innerHTML);
	});

	try{
		wa.doPrintCart(products.join(','), amounts.join(',')); 
	}
	catch(e){console.log(e);}
	
	//html, head and body elements
	var elHtml = new Element('html');
	var elHead = new Element('head');
	var elBody = new Element('body');
	var elCartClone = new Element('div', {'class': 'cart inpage'});
	elCartClone.innerHTML = elCart.innerHTML;

	//link element
	var elCss = new Element('link', {
		'href': '/static/css/print_shopping_list.css',
		'media': 'all',
		'rel': 'stylesheet',
		'type': 'text/css'
	});

	//inject css and js in head
	elCss.inject(elHead);

	//inject cart element in body
	elCartClone.inject(elBody);

	//inject head and body in html element
	elHead.inject(elHtml);
	elBody.inject(elHtml);

	//not existing element
	var not_existing_element = new Element('html');
	elHtml.inject(not_existing_element);

	//open popup and put html in it
	var windowObject = (window.open('', '', "width=740,height=325,top=200,left=250,toolbars=no,scrollbars=yes,status=no,resizable=yes"));
	windowObject.document.writeln(not_existing_element.innerHTML);
	$(windowObject.document.body).getElements('embed, object').each(function(e,i) {
		e.parentNode.removeChild(e);
	});
	windowObject.document.close();
	windowObject.focus();
	windowObject.print();
	windowObject.close();
	return setTimeout("location.href=location.href+'en'", 1);
}
