/**
 * usage: <script type="text/javascript" src="path/to/cart.blogparts.js#col=3&amp;row=1&amp;id=128501,128512,128490&amp;showcart=0&amp;type=zakka" charset="utf-8"></script>
 */

if (typeof BEYES == 'undefined') BEYES = {};
if (typeof BEYES.Badge == 'undefined') BEYES.Badge = {
	scripts : [],
	launched: false
};

new function() {
	var path = 'http://www.beyes.jp';

	new function() {
		var s = document.getElementsByTagName('script');
		var i = s.length;
		while (--i > 0) {
			var script = s[i];
			if (script.src.indexOf(path) == 0) {
				BEYES.Badge.scripts.push(script);
				return;
			}
		}
	};


	if (BEYES.Badge.launched) return;
	BEYES.Badge.launched = true;


	var figureString = function(str) {
		str = String(str);
		while (str != (str = str.replace(/^(-?\d+)(\d{3})/, '$1,$2')));
		return str;
	};

	var formatString = function(str, place) {
		place = place || 2;
		var str = String(str);
		while (str.length < place) str = '0'+str;
		return str;
	};

	var parseQuery = function(query) {
		var ret = {};
		$.each(query.split('&'), function() {
			if (!this) return;
			var p = $.map(this.split('='), function(n) {
				return decodeURIComponent(n);
			});
			ret[p[0]] = Number(p[1]) || p[1];
		});
		return ret;
	};

	var addCSS = function(href) {
		$.browser.msie ?
			document.createStyleSheet(href) :
			$('<link rel="stylesheet" type="text/css" href="'+href+'"/>').appendTo('head');
	};


	BEYES.Badge.Unit = function() {
		var options = arguments.length > 1 ?
			{
				container: arguments[0],
				id       : arguments[1]
			} :
			arguments[0];
		this.o = $.extend({
			container: null,
			id       : null,
			item     : null,
			count    : null,
			q        : null
		}, options);
		this.element = null;
	};
	BEYES.Badge.Unit.prototype = {
		show: function() {
			var self = this;
			var item = this.o.item;
			var disable = (item.sold_out_flag || item.coming_soon_flag || item.status == 5);

			switch (item.gender_type) {
				case 4: // zakka
					var col = this.o.q.col || 1;
					var timer = null;
					var unit = this.element = $([
						'<div class="unitZak01 unitZakType'+formatString((this.o.count + 1) % 16)+'">',
						'<h3 class="name">',
						'<a href="'+item.detail_url+'"><img src="'+path+item.product_img+'" alt="'+item.name+'" width="90" height="90"/></a>',
						'</h3>',
						'<p class="text">'+item.comment+'</p>',
						'</div>'
					].join(''))
						.appendTo(this.o.container)
						.hover(
							function(e) {
								if (tooltip.is(':visible')) return;
								var self = $(this);
								timer = setTimeout(function() {
									tooltip
										.css({
											top : self.offset().top - 136,
											left: self.offset().left - 22
										})
										.fadeIn(150);
								}, 300);
							},
							function(e) {
								if ($.browser.msie && e.toElement == tooltip[0]) return;
								else
									if (e.relatedTarget == tooltip[0]) return;
								if (timer) clearTimeout(timer);
								tooltip.fadeOut(300);
							}
						);
					if (this.o.count != null && (this.o.count + 1) % col == 0) unit.css('margin-right', 0);
					if (item.new_flag) unit.append('<div class="new">New</div>');

					var tooltip = $([
						'<div class="tooltipZak01 tooltipZakType'+formatString((this.o.count + 1) % 6)+'">',
						'<div class="tooltipZakWrapper">',
						'<p class="name">'+item.name+'</p>',
						'<dl class="info01">',
						'<dt class="price">Price</dt>',
						'<dd>¥'+figureString(item.selling_price)+' (税込)',
						'<dt class="brand">Brand</dt>',
						'<dd>'+item.brand_name+'</dd>',
						'</dl>',
						'<ul class="utility"><li class="cart"><a href="#"/></li></ul>',
						'</div>',
						'</div>'
					].join(''))
						.appendTo('body')
						// .prependTo(this.o.container)
						.bind('mouseleave', function(e) {
							if ($(e.relatedTarget).parents().index(self.element) != -1) return;
							tooltip.fadeOut(300);
						});

					var utility = $('.utility', tooltip);
					if (disable || !$('#beyesQuickCart').length)
						utility.addClass('disable').find('.cart').html('<span/>');
					else
						$('a', utility).click(function() {
							BEYES.Badge.QuickCart.add(item.id);
							tooltip.hide();
							return false;
						});
					break;

				default:
					var col = this.o.q.col || 3;
					var unit = this.element = $([
						'<div class="unit01 unit'+(['Men', 'Wom', ({ men: 'Men', women: 'Wom'})[this.o.q.type]][item.gender_type - 1])+'01">',
						'<div class="details">',
						'<h3 class="name">'+item.name+'</h3>',
						'<p class="beyes-thumb"><a href="'+item.detail_url+'"><img src="'+path+item.product_img+'" alt="'+item.name+'" width="130" height="130"/></a></p>',
						'<dl class="info01">',
						'<dt class="price"/><dd class="price"/>',
						'<dt class="brand"/><dd class="brand">'+item.brand_name+'</dd>',
						'</dl>',
						'<ul class="info02">',
						'<li class="copy">'+item.comment+'</li>',
						'</ul>',
						'</div>',
						'<ul class="utility">',
						'<li class="variation"><a href="#"/></li>',
						'<li class="cart"><a href="#"/></li>',
						'</ul>',
						'</div>'
					].join('')).appendTo(this.o.container);
					var details = $('.details', unit);
					if (this.o.count != null && (this.o.count + 1) % col == 0) unit.css('margin-right', 0);
					if (item.new_flag) details.append('<div class="new">New</div>');
					if (item.coming_soon_flag) details.append('<div class="comingSoon">Coming Soon</div>');
					if (item.sold_out_flag) {
						details.append('<div class="soldOut">Sold Out</div>');
						$('.beyes-thumb img', details).css('opacity', 0.25);
					}
					if (item.sale_flag)
						$('dd.price', details)
							.addClass('saleprice')
							.text('¥'+figureString(item.sale_selling_price)+' (税込)')
							.after('<dd class="price salepercent">['+item.sale_rate+'%off]</dd>');
					else
						$('dd.price', details)
							.text('¥'+figureString(item.selling_price)+' (税込)');

					if (item.gender_type == 1 || (item.gender_type == 3 && this.o.q.type == 'men'))
						$('.info02', unit).append('<li class="genre'+(['Ame', 'Eur', 'Dre', 'Mix', 'Cas', 'Bag'][item.genre_id - 1])+'">'+item.genre_name+'</li>');

					$('.variation a', unit).toggle(
						function() {
							details.hide();
							$(this).parent().removeClass().addClass('variationOpen');

							var variation = $('div.variation', unit);
							variation.length ?
								variation.fadeIn() :
								(function() {
									var variation = $('<div class="variation"><div class="variationWrapper"/></div>').hide().insertAfter(details);
									var container = $('<div/>').appendTo(variation.find('div'));
									for (var i = 0, length = item.stocks.length <= 4 ? 4 : item.stocks.length; i < length; i++) {
										var stock = item.stocks[i] || { color_img: '/img/item/color/c_noitem.gif' };
										var color = $([
											'<div class="item">',
											'<p class="beyes-thumb"><img src="'+path+stock.color_img+'" alt="" width="65" height="65"/></p>',
											'<ul class="size"/>',
											'</div>'
										].join('')).appendTo(container);
										if (i + 1 == length) color.css('margin-right', 0);
										$.each(stock.sizes || {}, function() {
											$('.size', color).append('<li><span>'+this.size_name+'</span>'+this.stock+'</li>');
										});
									}
									variation.fadeIn();

									container.width(66 * length - 1);
									var width  = container.width();
									var height = 0;
									$('.item', container).each(function() {
										height = Math.max(height, $(this).height(), 142);
									});
									if ($.browser.msie && $.browser.version < 7) variation.height(height);
									var scrolling = false;
									variation
										.mousemove(function(e) {
											if (scrolling) return;

											var offset = $(this).offset();
											var x = e.pageX - offset.left;
											var y = e.pageY - offset.top;
											var left = x < 75, right = x > 230, top = y < 50, bottom = y > 112;
											var options = {
												duration: 'slow',
												easing  : 'easeOutCubic',
												complete: function() { scrolling = false; }
											};

											if (left || right) {
												var margin = Math.round(parseFloat(container.css('margin-left')));
												var motion = 150;
												if (left) {
													var limit = 0;
													var move  = margin + motion;
													if (margin != limit) {
														scrolling = true;
														if (move > limit) move = limit;
														container.animate({ marginLeft: move }, options);
													}
												}
												if (right) {
													var limit = width * -1 + 263;
													var move  = margin - motion;
													if (margin != limit) {
														scrolling = true;
														if (move < limit) move = limit;
														container.animate({ marginLeft: move }, options);
													}
												}
											}

											if (top || bottom) {
												var margin = Math.round(parseFloat(container.css('margin-top')));
												var motion = 50;
												if (top) {
													var limit = 0;
													var move  = margin + motion;
													if (margin != limit) {
														scrolling = true;
														if (move > limit) move = limit;
														container.animate({ marginTop: move }, options);
													}
												}
												if (bottom) {
													var limit = height * -1 + 142;
													var move  = margin - motion;
													if (margin != limit) {
														scrolling = true;
														if (move < limit) move = limit;
														container.animate({ marginTop: move }, options);
													}
												}
											}
										});
								})();
							return false;
						},
						function() {
							$(this).parent().removeClass().addClass('variation');
							$('div.variation', unit).hide();
							details.fadeIn();
							return false;
						}
					);

					if (disable || !$('#beyesQuickCart').length)
						$('.utility', unit).addClass('disable').find('.cart').html('<span/>');
					else
						$('.cart a', unit)
							.hover(
								function() { $(this).parent().removeClass().addClass('cartOpen'); },
								function() { $(this).parent().removeClass().addClass('cart'); }
							)
							.click(function() {
								BEYES.Badge.QuickCart.add(item.id);
								$(this).triggerHandler('mouseleave');
								return false;
							});

					if ($.browser.msie && $.browser.version < 7)
						unit.hover(
							function() { $(this).addClass('hover'); },
							function() { $(this).removeClass('hover'); }
						);
			}
		}
	};

	BEYES.Badge.QuickCart = {
		container: null,
		timer: null,
		open: false,
		type: 'men'
	};
	BEYES.Badge.QuickCart.append = function(q) {
		if ($('#beyesQuickCart').length) return;
		q.type = BEYES.Badge.QuickCart.type = q.type || BEYES.Badge.QuickCart.type;
		var flashvars = $.extend(q, {
			widget: 1
		});
		var container = BEYES.Badge.QuickCart.container = $('<div id="beyesQuickCart"/>')
			.appendTo('body')
			.fl({
				id       : 'beyesQuickCartSWF',
				src      : path+'/swf/src/cart.swf',
				width    : '100%',
				height   : 275,
				flashvars: flashvars
			});

		if ($.browser.msie && $.browser.version < 7) {
			container.css({
				bottom   : 'auto',
				marginTop: 241
			});
			$(window).bind('scroll resize', function() {
				var bottom = $(window).scrollTop() + $(window).height();
				container.css('top', bottom - 275);
			});
		}
	};

	BEYES.Badge.QuickCart.add = function(id) {
		var self = BEYES.Badge.QuickCart;
		$('#beyesQuickCartSWF').fl().addItem(id);
		if (self.timer) {
			clearTimeout(self.timer);
			$('#beyesQuickCartAdded').hide().fadeIn();
		}
		if (self.open) {
			$('#beyesQuickCartAdded').remove();
			return;
		}

		var message = $('#beyesQuickCartAdded');

		if ($.browser.msie && $.browser.version < 7) {
			if (!message.length) {
				message = $('<div id="beyesQuickCartAdded"><p>商品が追加されました</p></div>');
				if (BEYES.Badge.QuickCart.type == 'zakka')
					$('p', message).css('background-position', '0 -160px');
				message.appendTo('body').fadeIn();
				$(window).bind('scroll resize.cart', function() {
					var bottom = $(window).scrollTop() + $(window).height();
					message.css('top', bottom - 115);
				});
			}
			$(window).trigger('resize.cart');
			self.timer = setTimeout(function() {
				message.fadeOut(function() { $(this).remove(); });
			}, 1000 * 2.5);

			return;
		}

		if (!message.length) {
			message = $('<div id="beyesQuickCartAdded"><p>商品が追加されました</p></div>');
			if (BEYES.Badge.QuickCart.type == 'zakka')
				$('p', message).css('background-position', '0 -160px');
			message
				.appendTo('body')
				.css({
					bottom: 25,
					opacity: 0
				})
				.animate({
					bottom: 35,
					opacity: 1
				});
		}
		self.timer = setTimeout(function() {
			message.animate({
				bottom : 45,
				opacity: 0
			}, function() {
				$(this).remove();
			});
		}, 1000 * 2.5);
	};

	BEYES.Badge.QuickCart.toggle = function(open) {
		var container = BEYES.Badge.QuickCart.container;
		var o = { height: 275 };
		var c = { height: 34 };
		if ($.browser.msie && $.browser.version < 7) {
			o.marginTop = 0;
			c.marginTop = o.height - c.height;
		}
		BEYES.Badge.QuickCart.open = open;
		open ?
			setTimeout(function() {
				clearTimeout(BEYES.Badge.QuickCart.timer);
				$('#beyesQuickCartAdded').remove();
				container.animate(o, { easing: 'easeOutCubic' });
			}, 0) :
			setTimeout(function() {
				container.animate(c, { easing: 'easeOutCubic' });
			}, 0);
	};

	var callback = function(script, initialize) {
		var query;
		if (!(query = /#(.+)$/.exec(script.src))) return;
		var q = parseQuery(query[1]);
		if (!q.id) return;
		q.col = q.col || 1;
		q.row = q.row || 1;

		if (initialize) addCSS(path+'/css/cart.blogparts.css');
		if (q.showcart) BEYES.Badge.QuickCart.append(q);

		var width, height;
		switch (q.type) {
			case 'zakka':
				width  = q.col * 105 + (q.col - 1) * 15 + 30;
				height = q.row * 165 + q.row * 15;
				break;
			default:
				width  = q.col * 305 + (q.col - 1) * 15 + 20;
				height = q.row * 178 + q.row * 10;
		}

		var container = $('<div class="beyesUnitListContainer"><div class="unitList01"/></div>')
			.width(width)
			.height(height)
			.insertAfter(script);
		var list = $('div', container).html('<p class="loading">connecting...</p>');
		if (q.type == 'zakka')
			list.css('padding', '0 15px');

			container.next('.beyesLogo')
				.addClass(q.type)
				.width(width);

		$.getJSON(path+'/api/blogparts/getProduct?callback=?&'+query[1], function(data) {
			if (data.error) {
				var status = 'Response includes error flag.';
				list.html(status);
				throw new Error(status);
			}
			var items = data.result.data;
			list.empty();
			$.each(items, function(i) {
				new BEYES.Badge.Unit({
					container: list,
					item     : this,
					count    : i,
					q        : q
				}).show();
			});
		});
	};


	var swfobject, $; // libs' namespase
	new function() {
		var lib = [
			{
				src     : path+'/js/lib/lib.js',
				complete: (function() {
					var _swfobject = window.swfobject || undefined;
					return function() {
						swfobject = window.swfobject;
						window.swfobject = _swfobject;

						$ = window.jQuery.noConflict(true);
						$.fn.fl = function(o) {
							if (!o) {
								var id = this.attr('id');
								return $.browser.msie ? window[id] : document[id];
							}

							o = $.extend({
								version: '9.0.47',
								params : {
									wmode            : 'transparent',
									allowscriptaccess: 'always'
								}
							}, o);
							if (swfobject.hasFlashPlayerVersion(o.version)) {
								o.attrs = $.extend(o.attrs || {}, {
									data  : o.src,
									width : o.width,
									height: o.height
								});
								if (o.flashvars) o.params.flashvars = $.param(o.flashvars);

								var element = o.id ?
									$('<div id="'+o.id+'"/>').appendTo(this) :
									this;
								swfobject.createSWF(
									o.attrs,
									o.params,
									element.attr('id')
								);
							}
							return this;
						};
					};
				})()
			}
		];

		var load = function() {
			var f = arguments.callee;
			var l = lib.shift();
			if (!l) {
				var s = BEYES.Badge.scripts;
				for (var i = 0, length = s.length; i < length; i++)
					callback(s[i], !i);
				return;
			}

			if (l.beforeSend) beforeSend();

			var script = document.createElement('script');
			script.type    = 'text/javascript';
			script.src     = l.src;
			script.charset = 'UTF-8';
			var done = false;
			script.onload = script.onreadystatechange = function() {
				if (
					!done && (!this.readyState ||
					this.readyState == 'loaded' || this.readyState == 'complete')
				) {
					done = true;
					if (l.complete) l.complete();
					f();
				}
			};	
			document.body.appendChild(script);
		};

		try {
			window.attachEvent ?
				window.attachEvent('onload', load) :
				window.addEventListener('load', load, false);
		}
		catch (e) { /* not supported */ }
	};
};
