
String.prototype.format = function() {
    var txt = this,
        i = arguments.length;
    while (i--) {
        txt = txt.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }
    return txt;
};

function _(s) {
	return translations[s] || s;
}

(function($) {
	$.MuaTag = function(obj, opt) {
		opt = $.extend({
			selectionWidth: 80,
			selectionHeight: 80,
			selectionBorderWidth: 5
		}, opt);

		var tags = [];
		var src = obj.attr("src");
		var editorFlash;

		container = obj.wrap("<div></div>").parent();
		container.addClass("tag-editor");
		container.width(obj.width());
		$(obj).ready(function () {container.width(obj.width()); });
		var selection = null;
		var editor = null;

		function updateEditor () {
			var editor = getEditor();
			var spos = selection.position();
			var sw = selection.width();
			var l = spos.left + sw + (opt.selectionBorderWidth*3);
			if (l + editor.width() > obj.width()) {
				l = spos.left - editor.width() - opt.selectionBorderWidth
			};
			getEditor().css ({
				top: selection.position().top,
				left: l
			});
		}

		function getEditor() {
			if (editor) return editor;

			editor = $("<div></div>").appendTo(container);
			editor.addClass("tag-box");

			var inputSection = $("<div></div>").appendTo(editor);
			var productsSection = $("<div></div>").appendTo(editor);
			var productList = $("<ul></ul>").appendTo(productsSection);

			var buttons = $("<div></div>").addClass("tag-buttons").appendTo(editor);

			$("<label for='pname'>"+_('Type any brand or product name')+"</p>").appendTo(inputSection)
			var input = $("<input id='pname' type='text'/>").addClass("query").appendTo(inputSection);
			var lastReq = null;
			var timer;
			input.keyup(function () {
				productList.children().remove();
				var $this = $(this);
				q = $this.val() || "";
				if (q.length<3) return;
				if (timer) clearTimeout(timer);
				timer = setTimeout(function () {
					$.getJSON("/products/search?format=json&page_size=100", {q: q}, function (d) {
						if ($this.val() == q)
							productList.children().remove();
							if (!d.length) {
								var li = $('<li></li>').appendTo(productList);
								$('<div></div>').text(_('Help us adding this product')).appendTo(li);
								$('<div></div>').text(_('Brand')).appendTo(li);
								$('<input type="text" name="brand"/>').appendTo(li);
								$("<br/>").appendTo(li);$("<br/>").appendTo(li);
								$('<div></div>').text(_('Article Number')).appendTo(li);
								$('<input type="text" name="artnr"/>').appendTo(li);
								return;
							}
							$(d).each(function (i, v) {
								var name = v['productname-' + lang];
								var brand = v.brand;
								var url = v['url-' + lang];
								if (!name) return;
								var li = $("<li></li>").appendTo(productList);
								var input = $("<input type='checkbox' id='check_"+i+"'/>").appendTo(li);
								$("<label for='check_"+i+"'>"+name+"</label>").appendTo(li)
								li.hover(function() {
										$(this).addClass('product-list-hover');
									}, function() {
										$(this).removeClass('product-list-hover');
									});
								input.click(function (e) {
									pushTag(v["productname-"+lang], v['productno'], v['id'].match(/[^-]+$/)[0], v['url-'+lang]);
									e.stopPropagation();
								});
							});
					});
				}, 200); // Timer
			});

			function pushTag(name, no, id, url, brand) {
				var pos = selection.position();
				tags.push({	url: src, productname: name, x: pos.left, y: pos.top,
							w: selection.width(), h: selection.height(), _id: "",
							productno: no || "", productid: id || "", brand: brand || ""});
				save(function () {
					editorFlash.find("span").text(_("Tag for {0} saved").format(name));
					// editorFlash.find("a").text(url.length ? "Review {0} now !".format(name): "").attr('href', "/reviews/new"+url)
				});
			}

			$("<button>"+_("Tag")+"</button>").appendTo(buttons).click(function(){
				if (input.val()) {
					var brand = $("input[name=brand]", productList).val();
					var no = $("input[name=artnr]", productList).val();
					pushTag(input.val(), no, "", "", brand);
				}
			});
			$("<button>"+_("Cancel")+"</button>").appendTo(buttons).click(function () {
				stopEditing();
			});

			return editor;
		}

		function edit () {
			if (editorFlash) return;
			editorFlash = $("<div><span>"+_('Click on products to tag them')+"</span></div>").addClass("tag-flash")
				.addClass("info").prependTo(container.parent());
			$('<div><a href="#"></a></div>').appendTo(editorFlash);
			$("<button>"+_('Done tagging')+"</button>").appendTo(editorFlash).click(function () {
				if (opt.done) opt.done();
				stopEditing();
				container.unbind("click");
				$(".tag-flash").remove();
				editorFlash = null;
				load();
			});
			$("<br/>").appendTo(editorFlash);
			container.find("div.tag-holder").remove();
			container.click(function (evt) {
				if (!$(evt.target).is("img")) return;
				var x = evt.pageX - container.offset().left;
				var y = evt.pageY - container.offset().top;
				startEditing(x, y);
			});
		}

		function startEditing(x, y) {
			if (!selection) {
				selection = $("<div></div>").addClass("tag-selection").appendTo(container);
			}
			var w = Math.min(opt.selectionWidth, x, obj.width()-6-x);
			var h = Math.min(opt.selectionHeight, y, obj.height()-6-y);
			selection.css ({
				left: x-w,
				top: y-h,
				width: w*2,
				height: h*2
			});
			$("<img/>").attr('src', '/img/resize-rb.png')
				.css({position: 'absolute', right: 0, bottom: 0, width: 10, height: 10}).appendTo(selection);
			/*
			$("<img/>").attr('src', '/img/resize-rt.png')
				.css({position: 'absolute', right: 0, top: 0, width: 10, height: 10}).appendTo(selection);
			$("<img/>").attr('src', '/img/resize-lb.png')
				.css({position: 'absolute', left: 0, bottom: 0, width: 10, height: 10}).appendTo(selection);
			$("<img/>").attr('src', '/img/resize-lt.png')
				.css({position: 'absolute', left: 0, top: 0, width: 10, height: 10}).appendTo(selection);
			*/
			selection.draggable({drag: updateEditor}).resizable({resize: updateEditor});
			updateEditor();
		}

		function stopEditing() {
			$(".tag-box, .tag-selection").remove();
			editor = null;
			selection = null;
		}

		function tagList() {
			if (opt.nolist) return;
			var cnt = (opt.list || container);
			$(".tag-list", cnt).remove();
			var list = $("<div></div>").appendTo(cnt).addClass("tag-list");
			$("<div></div>").text(_("Products in this photo:")).appendTo(list).css("padding-right", 10).css("font-weight", "bold");
			list.append("<br/>");
			$(tags).each(function (i, v) {
				var item = $("<div></div>").appendTo(list);
				item.append($("<a></a>").attr("href", v.product ? v.product.url: "#").text(v.productname+" ")).hover(function () {
					$("#tag_"+v._id).addClass("hover").find("img.tag-icon").attr("src", "/img/tag_h.png");
				}, function () {
					$("#tag_"+v._id).removeClass("hover").find("img.tag-icon").attr("src", "/img/tag.png");
				})
				item.append("<br/>");
				if (v.product) {
					$("<a></a>").text(_('Write Review')).attr("href", "/reviews/new"+v.product['url-'+lang]).addClass("review")
						.appendTo(item);
				} else {
				  $("<a></a>").text(_('Write Review')).attr("href", "/reviews/new?tag=" + v._id).addClass("review")
            .appendTo(item);
				}
				if (opt.edit || (user && v.user_id == user.id)) {
					$("<a></a>").text(_('Remove')).attr("href", "#").addClass("remove").click(function () {
						tags = $.grep(tags, function (value) {
							return value._id != v._id;
						});
						tagList();
						save(load);
						return false;
					}).appendTo(item)
				}
				item.prepend("<br/>");
				item.prepend($("<img/>").attr("src",
						(v.product && v.product['listing_image']) ? v.product['listing_image'] :
							'/static/v2/images/product-listing-placeholder.png').width(192).height(170));
				$("<div></div>").appendTo(list).width(10).height(10);
			});
			$("<br/>").appendTo(list);
		}

		function save (cb) {
			stopEditing();
			$.post("/tagger/save_tags", {image_id: opt.imageId || "", url: src, "tags": JSON.stringify(tags), "ow": obj.width(), "oh": obj.height()}, function () {
				if (cb) cb();
			})
		}

		function getInfoBox(holder, v) {
			var infoBox = $("<div></div>").appendTo(holder).addClass("tag-info").addClass("drop-content");
			var product = v.product;
			var hover = $("<div></div>").addClass("tag-product-hover").appendTo(infoBox);
			if (product != null) {
				$("<img/>").attr("src", product.listing_image).appendTo(hover).width(100).height(100).attr("align", "left")
					.click(function () {location = product.url;});
				$("<a></a>").attr("href", product.url).text(product.title_h).appendTo($("<h4></h4>").appendTo(hover));
				$("<div></div>").addClass("price").text(product.price_h).appendTo(hover).css('margin-left', 20);

				$("<p></p>").addClass("price").text(product.price_h);
			} else {
				$("<h4></h4").text(v.productname).appendTo(hover);
			}
			return infoBox;
		}

		function load() {
			var cnt = opt.tagContainer ? $(opt.tagContainer) : container;
			$(".tag-holder", cnt).remove();
			$.getJSON("/tagger/get_tags", {url: src, published: opt.published || "", image_id: opt.imageId}, function (data) {
				tags = data;
				$(data).each(function (i, v) {
					if (v.product && !v.product['url-'+lang]) return;
					var th = $("<div></div>").addClass("tag-holder").appendTo(cnt);
					var a  = $("<a href='#'></a>").appendTo(th);
					var rh = v.oh ? (obj.height() / v.oh) : 1;
					var rw = v.ow ? (obj.width() / v.ow) : 1;
					var img = $("<img/>").addClass("tag-icon").attr("src", "/img/tag.png").appendTo(a);
					var left = (v.x +v.w/2-th.width()/2)*rw;
					var top = (v.y +v.h/2-th.height()/2)*rh;
					th.css({
						"left": left,
						"top": top
					});
					th.attr("id", "tag_"+v._id);
					th.data("tag", v);
					var info = getInfoBox(th, v);
					if (obj.width() - (left + info.width()) < 30) {
						info.css({left: "auto", right: info.width()-90});
					}
					if (obj.height() - (top + info.height()) < 30) {
						info.css({top: "auto", bottom: 20});
					}
					th.hover(function (e) {
						info.show();
						th.css('z-index', 20000);
					}, function () {info.hide(); th.css('z-index', 10000); }).click(function () {location = v.product.url; return false;});
				});
				tagList();
			});
		}

		// getEditor();
		if (opt.autoedit && opt.edit) {
		  load();
			edit();
			startEditing(obj.width()/2, obj.height()/2);
		}
		else
			load();
		// edit();
		if (opt.menu) {
			opt.menu.find(".edit-tag").click(function () {
				edit();
				return false;
			});
		}
	};

	attach = function (obj, opt) {
		$.MuaTag(obj, opt)
	}

	$.fn.muaTag = function (options) {
		this.each(function() {
			attach($(this), options);
		});
	}
})(jQuery);


