window.onload = function() {renderImgTag('taggedImg')};

var prodListCache = new Array();
var keyword = "";

function renderImgTag(className)
{
	// LOAD CSS
	var time = new Date().getTime();
	if($('#prodlist').length == 0)
		$('head').append('<link rel="stylesheet" href="http://asset.lovely-tag.pixnet.tw/stylesheets/imgTag.css?' + time + '" type="text/css">');

	var trav = null;
	// album
	if($('#imageFrame').length > 0) trav = $('#imageFrame img');
	// general purpose
	else if(className) trav = $('img.' + className);
	// fallback
//	else trav = $('img');

	trav.each(
		function(i) {
			// setup layer
			var layerDiv = $(document.createElement('div'));
			layerDiv.attr('id', 'divimg-' + i).addClass('divimg').width($(this).width()).height($(this).height());
			$(this).wrap(layerDiv);

			// handlers
			$(this).bind('mouseenter', function(e) {
				$(this).parent('div').children('.notetag').show(); //fadeIn('fast'); // <-- buggy in Opera
				$('#prodlist').hide();
			});
			$(this).bind('mouseleave', function(e) {
				if( e.relatedTarget && e.relatedTarget.nodeName != 'IMG'
				&& !$(e.relatedTarget).attr('class').match('note'))
					$(this).parent('div').children('.notetag').fadeOut('fast');
				$('#prodlist').hide();
			});

			$(this).attr('id', 'img-' + i).css({
//				'display': 'block',
				'width': $(this).width(),
				'height': $(this).height(),
				'left': $(this).position().left,
				'top': $(this).position().top
			});

			// append tags
			appendTag($(this).parent(), this.src);
		}
	);


	$(document.createElement('div')).attr('id', 'prodlist').css({
		'width': '210px'
	}).bind('mouseenter', function() {
		$(this).show();
	}).hide().appendTo('body');
}

function appendTag(obj, src)
{
// DEBUG
//	alert('img src: ' + src + ',\nencoded: ' + $.base64Encode(src));
	$.ajax({
		'type': 'GET',
		'url': 'http://asset.lovely-tag.pixnet.tw/get_photo',
		'dataType': 'jsonp',
		'data': {
			'objid': obj.attr('id'),
			'url': src
		},
		'jsonp': 'get_photo_callback'
	});
}

function get_photo_callback(objid, noteList)
{
	var obj = $('#' + objid);
	var pos = obj.position();
	if(noteList.length > 0)
	{
/*		var tagHint = $(document.createElement('div'));
		tagHint.attr({
			'id': 'notehint-' + obj.attr('id'),
			'title': '本圖有標籤可供檢閱'
		}).css({
			'position': 'absolute', 'left': pos.left+10+'px',
			'top': pos.top+10+'px'
		}).addClass('notehint').appendTo(obj);
*/		for(var i = 0; i < noteList.length; i++)
		{
			var tagObj = $(document.createElement('div'));
			tagObj.attr({
				'id': 'note' + obj.children('img:first').attr('id') + '-' + noteList[i].note.id,
				'title': noteList[i].note.note
			}).css({
				'position': 'absolute', 'left': noteList[i].note.left+pos.left + 'px',
				'top': noteList[i].note.top+pos.top + 'px'
			}).addClass('notetag').hide().appendTo(obj);
			if(noteList[i].note.icon_id != null) tagObj.addClass('notetag-' + noteList[i].note.icon_id);
			tagObj.bind('mouseenter', tagMouseEnterAction).bind('mouseleave', tagMouseLeaveAction);
		}
	}
}

function tagMouseEnterAction(e)
{
	$('.notetag').hide();
	$(this).show();

	// I have no idea why I have to write such a dirty code, but however it worked.. Orz
//	var leftMargin = ($(document).width() - $('#body-div').width())/2;
//	var browser = navigator.userAgent.toLowerCase();
//	if(browser.match('msie')) leftMargin -= 10;
//	var leftPos = parseInt($(this).css('width')) + parseInt($(this).css('left')) + leftMargin;
// fixed popup, not working well

	// initilize list div
	var listDiv = $('#prodlist');
	listDiv.empty().css({
//		'position': 'absolute', 'top': $(this).css('top'),
//		'left': leftPos + 'px', 'z-index': '130'
		'position': 'absolute', 'top': e.pageY - 4,
		'left': e.pageX - 8, 'z-index': '130'
	});

	// append data
	keyword = $(document.createElement('div')).addClass('listitem-more');
	keyword.append('<a href="http://channel.pixnet.net/lovely/fashionsearch?q=' + encodeURI($(this).attr('title'))
			+ '" title="' + $(this).attr('title') + '" target="_blank">' + $(this).attr('title')  + '</a>');
// buggy in IE
//	keyword.children('a:first').bind('click', function() {
//		window.open(this.href); return false;
//	});

	var noteid = $(this).attr('id').split('-')[2];
// DEBUG
//	alert('note id: ' + noteid);
	if(prodListCache[noteid] == null)
	{
		$.ajax({
			'type': 'GET',
			'async': false,
			'url': 'http://asset.lovely-tag.pixnet.tw/get_note',
			'dataType': 'jsonp',
			'data': 'note_id=' + noteid,
			'jsonp': 'get_note_callback'
		});
	} else showListDiv(noteid);
}

function get_note_callback(noteid, prodList)
{
	prodListCache[noteid] = $(document.createElement('div')).addClass('proditems');
	for(var i = 0; i < prodList.length; i++)
	{
		var listItem = $(document.createElement('div'));
		listItem.addClass((i%2==0)? 'listitem-even':'listItem-odd');
		listItem.append('<div class="prod-brandname"><span class="listitem-title">品牌</span>' + prodList[i].product.brand_name + '</div>');
//		listItem.append('<div class="prod-name"><span class="listitem-title">品名</span>'
//				+ '<a href="http://channel.pixnet.net/lovely/fashionsearch?q=' + encodeURI(prodList[i].product.name)
//				+ '">' + prodList[i].product.name + '</a></div>');
    if(prodList[i].product.series_name != null &&  prodList[i].product.series_name.length > 0 )
      listItem.append('<div class="prod-series-name "><span class="listitem-title">系列</span>' + prodList[i].product.series_name  + '</div>');
		listItem.append('<div class="prod-name"><span class="listitem-title">品名</span>' + prodList[i].product.name + '</div>');
		if(prodList[i].product.color_number.length > 0)
			listItem.append('<div class="prod-color"><span class="listitem-title">色號</span>' + prodList[i].product.color_number + '</div>');
		if(prodList[i].product.quantity != 0)
			listItem.append('<div class="prod-quantity"><span class="listitem-title">容量</span>' + prodList[i].product.quantity + '</div>');
    listItem.append('<div class="prod-price"><span class="listitem-title">價格</span>' + prodList[i].product.price);
		listItem.appendTo(prodListCache[noteid]);
	}

	showListDiv(noteid);
}

function showListDiv(noteid)
{
	if(prodListCache[noteid].length ==  0) return;
	var listDiv = $('#prodlist');

	prodListCache[noteid].appendTo(listDiv);
	keyword.appendTo(listDiv);

	listDiv.fadeIn('fast');
	$('#prodlist > *').show();
}

function tagMouseLeaveAction(e)
{
	$('#prodlist').hide();
}
