
$(document).ready(function() {
	Favorites.init();
});

var Favorites = {

	items: [],  // item is ['description', 'id', 'category', 'picture_src']
	categories: {
		'Laatat': '/tuote?tuotenumero=',
		'Kylpyhuonekalusteet': '/tuote?tuotenumero=',
		'Muut tuotteet': '/tuote?tuotenumero=',
		'Ideat': '/idea?idea='
	},
	listeners: { remove: [], add: [] },  // event callbacks
	
	init: function() {
		this.load();
		this.listeners['remove'].push(this.update_empty_status);
		this.listeners['add'].push(this.update_empty_status);
	},

	add: function(item, picture) {
		if (! this.has(item)) {
			this.items.push(item);
			this.store();
			if ($(picture).length > 0) {
				this.animate($(picture), function() {
					$(this).hide();
					Favorites.create_node(item, true);
					Favorites.event('add');
				});
			} else {
				Favorites.create_node(item, true);
				Favorites.event('add');
			}
		}
	},

	/* @param item reference or id as string */
	remove: function(item, all) {
		var kept_items = [];
		for (var i = 0; i < this.items.length; i++)
			if (all || (typeof item == 'string' ? item : item[1]) == this.items[i][1]) {
				this.remove_node($('#favorites LI.item-' + this.items[i][1]));
				this.event('remove');
			} else kept_items.push(this.items[i]);
		this.items = kept_items;
		this.store();
	},
	
	event: function(type) {
		$.each(this.listeners[type], function() {
			window.setTimeout(this, 0);  // poor man' yield()
		});
	},
	
	empty: function() {
		this.remove(null, true);
	},
	
	/* @param item array or tuotenumero as string */
	has: function(item) {
		for (var i = 0; i < this.items.length; i++)
			if ((typeof item == 'string' ? item : item[1]) == this.items[i][1])
				return true;
		return false;
	},
	
	create_node: function(item, fade) {

		var li = $(document.createElement('li')).hide().addClass('item-' + item[1])
			.css('clear', 'both')
			.css('position', 'relative')
			.css('margin-left', '-18px')
			.css('padding-left', '18px');

		var trash = $(document.createElement('img')).addClass('delete clickable')
			.attr('src', '/files/laattapiste/img/icon_delete.png')
			.attr('title', 'Poista suosikeista')
			.css('position', 'absolute')
			.css('left', '0')
			.click(function() { Favorites.remove($(this).parents('li').get(0).f_item) })
			.appendTo(li);

		var a = $(document.createElement('a'))
			.attr('href', this.categories[item[2]] + item[1])
			.attr('title', 'Näytä suosikki')
			.text(item[0]).appendTo(li);

		li.get(0).f_item = item;  // for later use

		var category = item[2];
		var category_class = 'category_' + normalize(category);
		if ($('#favorites').find('.' + category_class).length == 0) {
			var ul = $(document.createElement('UL')).addClass(category_class);
			var h3 = $(document.createElement('H3')).text(category);
			$('#favorites .empty').after(ul).after(h3);
			//$('#favorites').append(h3).append(ul);
		}

		$('#favorites').find('.' + category_class).append(fade ? li.fadeIn() : li.show());
	},
	
	remove_node: function(node) {
		$(node).fadeOut('fast', function() {
			var ul = $(this.parentNode);
			$(this).remove();
			if (ul.children().length == 0) {
				ul.prev('H3').remove();
				ul.remove();
			}
		});
	},
	
	store: function() {
		$.cookie('favorites', serialize_array(this.items), { expires: 180, path: '/' });
	},
	
	load: function() {
		var stored = eval($.cookie('favorites'))
		if (stored) {
			this.items = stored;
			$.each(this.items, function() { Favorites.create_node(this) });
			this.update_empty_status();
		}
	},
	
	animate: function(original, callback) {
		var target = $('#favorites').offset();
		target.top += $('#favorites').height();
		var clone = original.clone()
			.css('position', 'absolute')
			.css('top', original.offset().top + 'px')
			.css('left', original.offset().left + 'px')
			.css('width', original.width())
			.css('height', original.height())
			.css('opacity', 0.5)
			.appendTo('#document')
			.animate({ top: target.top + 'px', left: target.left + 'px', width: '12px', height: '12px' },
				{ complete: callback, duration: 500 });
	},
	
	update_empty_status: function() {
		$('#favorites .empty').css('display',
			Favorites.items.length == 0 ? 'block' : 'none');
		$('#favorites .checkout, #favorites UL, #favorites.H3').css('display',
			Favorites.items.length == 0 ? 'none' : 'block');
	},
	
	items_by_category: function() {
		var items_by_category = {};
		$.each(this.items, function() {
			var cat = this[2];
			if (undefined == items_by_category[cat])
				items_by_category[cat] = [];
			items_by_category[cat].push(this);
		});
		return items_by_category;
	},

	draw_checkout_cart: function() {

		if ($('.content UL.favorite_category').length == 0)
			return false;
			
		$('.content UL.favorite_category LI').not('.default').remove();
		$('.content UL.favorite_category')
			.removeClass('favorite_category_thumbs')
			.removeClass('favorite_category_list')
			.addClass('favorite_category_' + Session.get('fav_cart_layout', 'thumbs'));
		
		var layout = Session.get('fav_cart_layout', 'thumbs');
		
		$.each(this.items, function() {

			var f = {
				desc: this.length > 0 ? this[0] : '',
				id: this.length > 1 ? this[1] : '',
				category: this.length > 2 ? this[2] : '',
				thumb: this.length > 3 ? this[3] : ''
			};

			var li = $(document.createElement('li'))
				.addClass('item')
				.attr('title', f.desc)
				.attr('id', 'cart_item_' + normalize(f.id));

			var a = $(document.createElement('a'))
				.attr('href', Favorites.categories[f.category] + f.id)
				.appendTo(li);
			
			if (layout == 'thumbs') {
				var img = f.thumb ? $(document.createElement('img'))
					.attr('src', f.thumb)
					.attr('alt', f.desc)
					.appendTo(a) :
					$(document.createElement('div'))
						.addClass('no_image')
						.text(f.desc)
						.appendTo(a);
			} else {
				a.text(f.desc);
			}

			$('.content UL.category_' + normalize(f.category)).append(li);
		});

		$('.content UL.favorite_category').each(function() {
			if ($(this).children().length == 0) {
				var li = $(document.createElement('li'))
					.text('Ei suosikkeja.')
					.addClass('default')
					.addClass('small')
					.appendTo(this);
			} else {
				$('LI:odd', this).addClass('odd');
				if ($(this).hasClass('favorite_category_thumbs'))
					$('LI:nth-child(3n+2)', this).css('margin', '0 29px');
				//$('LI', this).css('marginBottom', '29px');
			}
		});
		
		this.listeners['remove'].push(function() {
			Favorites.draw_checkout_cart();
		});
	},
	
	cart_print: function() {},  // replaced by regular url, safe to remove?
	
	cart_popup: function() {

		var container = $('#static_popup');
		var form = $('#favorite_form');

		if (! this.cart_popup_box) {
			this.cart_popup_box = new Popup();
			this.cart_popup_box.append(container);

			// add star for required fields
			$('.required', form).each(function() {
				var span = $('SPAN', this.parentNode);
				span.css('paddingRight', 0);
				span.text(span.text() + ' *');
			});
			
			// bind action to checkboxes
			var checkbox_selector = '.section-first INPUT[type=checkbox]';
			$(checkbox_selector, form).click(function() {
				$($(this).attr('value')).css('display', this.checked ? 'block' : 'none');
				if (0 == $(checkbox_selector + ':checked', form).length) {
					$($(checkbox_selector, form).not(this).attr('checked', true).val()).show();
				}
			});
			
			// if any store selected, check "lähetä myymälään"
			$('SELECT[name=store]', form).change(function() {
				if ($(this).val() != '')
					$($('.section-first INPUT[name=send_to_store]', form)
						.attr('checked', true).val()).show();
				$('#store-info-container .store-info').hide();
				$('#store-info-' + $(this).val()).show();
			});
			
			form.submit(function() { return Favorites.cart_send() });
			container.show();
		}

		$('.sent_ok').hide();
		$(form).show();
		this.cart_popup_box.show();
	},
	
	cart_send: function() {

		var form = $('#favorite_form');

		if (! this.cart_validate(form))
			return false;

		var animation = $('#favorite_form .ajax-loader');
		animation.show();
		
		var params = { mail_sendnow: '1' };

		var recipients = [];
		var body = [];

		if ($('.section-first INPUT[name=send_to_email]:checked', form).length > 0) {
			recipients.push($('INPUT[name=recipient_email]', form).val());
		}
		
		if ($('.section-first INPUT[name=send_to_store]:checked', form).length > 0) {
			var pid = $('SELECT[name=store]', form).val();
			//var email = $().load('/ajax_email_for_store?pid=' + pid);
			recipients.push(pid);
			body.push("LÄHETTÄJÄ\n");
			body.push('Nimi: ' + $('INPUT[name=sender_name]', form).val());
			body.push('Sähköposti: ' + $('INPUT[name=sender_email]', form).val());
			body.push('Puhelin: ' + $('INPUT[name=phone]', form).val());
			body.push('Osoite: ' + $('INPUT[name=address]', form).val() + ', '
				+ $('INPUT[name=zip]', form).val() + ' ' + $('INPUT[name=city]', form).val());
		}

		body.push('Viesti: ' + $('TEXTAREA[name=msg]', form).val() + "\n\n");
		
		body.push("SUOSIKIT\n");
		var items_by_category = this.items_by_category();
		for (cat in items_by_category) {
			body.push(cat + "\n");
			$.each(items_by_category[cat], function(i) {
				var item = new Item(this);
				body.push((i + 1) + '. ' + item.desc + ', ' + item.abs_url());
			});
			body.push("\n");
		}
		
		params['recipient'] = recipients.join(', ');
		params['sender'] = $('INPUT[name=sender_email]', form).val();
		params['body'] = body.join("\n");

		jQuery.post(form.attr('action'), params, function(data, status) {
			animation.hide();
			if (data.indexOf('OK') != -1) {
				$(form).hide();
				$('.sent_ok').show();
				$('.sent_ok INPUT[name=ok]').click(function() {
					if ($('.sent_ok INPUT[name=clear]:checked').length > 0)
						Favorites.empty();
					Favorites.cart_popup_box.close();
				});
			} else {
				alert('Valitettavasti lähetys epäonnistui. ' +
					'Tarkista, että syötit sähköpostiosoitteet oikein.');
			}
		});

		return false;  // form will never be sent via non-ajax request
	},
	
	cart_validate: function(form) {
		$('.required', form).each(function() {
			if ($(this).parents('.section').eq(0).css('display') != 'none')
				$(this)[$(this).val() == '' ? 'addClass' : 'removeClass']('error');
		});
		var errors = $('.error', form);
		if (errors.length > 0) {
			alert('Ole hyvä ja täytä kaikki tähdellä (*) merkityt kentät.');
			errors.get(0).focus();
			return false;
		}
		if ($('[name=send_to_store]', form).attr('checked') && $('SELECT[name=store]').val() == '') {
			alert('Valitse myymälä.');
			return false;
		}
		return true;
	}
	
};

Item = function(item_arr) {
	this.desc = item_arr[0];
	this.id = item_arr[1];
	this.category = item_arr[2];
	this.picture = item_arr[3];
}

Item.prototype.url = function() {
	return Favorites.categories[this.category] + encodeURIComponent(this.id);
}

Item.prototype.abs_url = function() {
	return 'http://www.laattapiste.fi' + this.url();
}

function serialize_array(arr) {
	var items = [];
	for (var i = 0; i < arr.length; i++)
		items.push((typeof arr[i] == 'object' ?
			serialize_array(arr[i]) :
			"'" + (arr[i] == undefined ? '' : arr[i]) + "'")); 
	return '[' + items.join(',') + ']';
}

function normalize(str) {
	return str.replace(/[^A-Za-z0-9_]/, '_').toLowerCase();
}

