// init

Shadowbox.init({ players:   ["html", "iframe"] });

// Google Analytics
try {
	var pageTracker = _gat._getTracker("UA-10440245-1");
	pageTracker._trackPageview();
} catch(err) {
}


var SCROLL_PADDING = 13;
var CONTENT_X = 228 + 13;
var CONTENT_Y = 180 + 30;

var Html5Initializer = function() {
	this.initialize();
};
Html5Initializer.prototype = {
	initialize : function() {
		// for IE to HTML5
		document.createElement("section");
		document.createElement("article");
		document.createElement("aside");
		document.createElement("header");
		document.createElement("footer");
		document.createElement("nav");
		document.createElement("dialog");
		document.createElement("figure");
		document.createElement("audio");
		document.createElement("video");
		document.createElement("embed");
		document.createElement("m");
		document.createElement("meter");
		document.createElement("time");
		document.createElement("canvas");
		document.createElement("command");
		document.createElement("datagrid");
		document.createElement("details");
		document.createElement("datalist");
		document.createElement("datatemplate");
		document.createElement("rule");
		document.createElement("nest");
		document.createElement("event-source");
		document.createElement("output");
		document.createElement("progress");
	}
};


var Beautifl = function() {
	this.initialize();
}
Beautifl.prototype = {

	scroller : null,
	scrollbar : null,
	isShiftDown : false,
	layoutMode : null,
	winP : null,
	isShowPreview : false,
	checkNewWindow : false,
	checkRollover : false,
	isParmaLink: false,
	searchBox : null,

	initialize : function() {
		$(window).resize($.proxy(this.resizeHandler, this));
		$(document).ready($.proxy(this.readyHandler, this));
	},

	readyHandler : function(event) {

		if (location.search.indexOf("?id=") != -1) {
			this.isShowPreview = true;
			this.isParmaLink = true;
		} else {
			this.initContent();
		}


		this.initSidebar();
		this.initToolbar();
		this.initScrollbar();
		this.initToolTipPreview();
		this.initPreviewWindow();
		this.searchBox = new SearchBox();

		this.layoutMode = $.cookie('layoutMode');
		this.resizeHandler();
	},

	initContent : function() {
		$("div.cell").css("display", "block");
		$("a.screenshot")
				.mouseenter($.proxy(this.thumbnail_rollOverHandler, this))
				.mouseleave($.proxy(this.thumbnail_rollOutHandler, this));

		$("a.screenshot").mousemove($.proxy(this.thumbnail_mosueMoveHandler, this));

		this.screenShot = $("<p id='screenshot'><img width='233' height='233' alt='Screenshot' /></p>");
		this.screenShot
				.hide()
				.css("pointer-events", "none")
		$("body").append(this.screenShot);
	},

	thumbnail_rollOverHandler : function(event) {

		var o = event.target.parentNode;
		$(o).stop().fadeTo("fast", 0.5);

		if (! this.checkRollover) return;

		var xOffset = 20;
		var yOffset = 280;

		var xoff = (event.pageX < 610) ? xOffset : -280;
		var src = $(o).find("img").attr("src");

		o.title = "";

		this.screenShot.find("img").attr("src", src.split("archives_s").join("archives"))
		this.screenShot
				.css("top", (event.pageY - yOffset) + "px")
				.css("left", (event.pageX + xoff) + "px")
				.stop()
				.clearQueue()
				.show();
		if ($.support.opacity)
			this.screenShot.animate({opacity:1}, 250);

		this.isShowScreenShot = true;

	},

	screenShot : null,
	isShowScreenShot:false,

	thumbnail_rollOutHandler : function(event) {
		var o = event.target.parentNode;

		this.hideScreenShot();

		$(o).stop().fadeTo("fast", 1);
	},


	hideScreenShot: function() {
		if (!this.isShowScreenShot) return;
		this.isShowScreenShot = false;
		this.screenShot
				.stop()
				.clearQueue();

		if ($.support.opacity)
			this.screenShot.animate({opacity:0}, 750)
					.queue(function() {
						$(this).hide();
					});
		else
			this.screenShot.hide();
	},


	thumbnail_mosueMoveHandler : function(event) {
		var xOffset = 20;
		var yOffset = 280;

		var xoff = (event.pageX < 610) ? xOffset : -280;

		// ie bug fix
		if (!this.screenShot) return;

		this.screenShot
				.css("top", (event.pageY - yOffset) + "px")
				.css("left", (event.pageX + xoff) + "px");
	},

	initSidebar : function() {
		$(".gnavi img").hover(function() {
					$(this).stop().fadeTo("fast", 0);
				}, function() {
					$(this).stop().fadeTo("fast", 1);
				});

		$("a.bnr img").hover(function() {
					$(this).stop().fadeTo("fast", 0);
				}, function() {
					$(this).stop().fadeTo("fast", 1);
				});
	},

	initToolbar : function() {

		switch ($.cookie('isRollOver')) {

			case "false":
				$("#rollOverImg").attr("src", "/imgs/interface-rollover.png");
				this.checkRollover = false;
				break;

			case "true":

				$("#rollOverImg").attr("src", "/imgs/interface-rollover-on.png");
				this.checkRollover = true;
				break;

			default:
				if ($.browser.msie) {
					$("#rollOverImg").attr("src", "/imgs/interface-rollover.png");
					this.checkRollover = false;
				}
				else {
					$("#rollOverImg").attr("src", "/imgs/interface-rollover-on.png");
					this.checkRollover = true;
				}
		}


		switch ($.cookie('isNewWin')) {
			case "true":
				this.checkNewWindow = true;
				$("#winImg").attr("src", "/imgs/interface-win-on.png");
				$("a.screenshot")
						.attr("target", "_blank")
						.unbind("click", $.proxy(this.clickHandler, this));
				break;
			default:
				this.checkNewWindow = false;
				$("#winImg").attr("src", "/imgs/interface-win.png");
				$("a.screenshot")
						.attr("target", "")
						.bind("click", $.proxy(this.clickHandler, this));
		}

		$("#winImg").click($.proxy(this.btnWindow_clickHandler, this));
		$("#rollOverImg").click($.proxy(this.btnRollover_clickHandler, this));

		$("#gridImg").click($.proxy(this.btnLayoutGrid_clickHandlr, this));
		$("#listImg").click($.proxy(this.btnLayoutList_clickHandlr, this));


	},

	initPreviewWindow : function() {
		$("#closePreview").bind("click", $.proxy(this.btnClose_clickHandler, this));
	},

	btnWindow_clickHandler : function(event) {
		this.checkNewWindow = !this.checkNewWindow;
		$("#winImg").attr("src", this.checkNewWindow ? "/imgs/interface-win-on.png" : "/imgs/interface-win.png")
		$.cookie('isNewWin', this.checkNewWindow, { expires: 7 });
		if (this.checkNewWindow) {
			$("a.screenshot")
					.attr("target", "_blank")
					.unbind("click", $.proxy(this.clickHandler, this));
		} else {
			$("a.screenshot")
					.attr("target", "")
					.bind("click", $.proxy(this.clickHandler, this));
		}
	},

	btnRollover_clickHandler : function(event) {
		this.checkRollover = !this.checkRollover;
		$("#rollOverImg").attr("src", this.checkRollover ? "/imgs/interface-rollover-on.png" : "/imgs/interface-rollover.png")
		$.cookie('isRollOver', this.checkRollover, { expires: 7 });
		if (this.checkRollover) {
		} else {
		}
	},

	btnLayoutGrid_clickHandlr : function(event) {
		this.layoutMode = "grid";
		$.cookie('layoutMode', this.layoutMode, { expires: 7 });
		this.resizeHandler()
	},

	btnLayoutList_clickHandlr : function(event) {
		this.layoutMode = "list";
		$.cookie('layoutMode', this.layoutMode, { expires: 7 });
		this.resizeHandler()
	},




	initScrollbar : function() {
		this.scroller = new jsScroller(document.getElementById("content"), 760, ($(window).height() - CONTENT_Y));
		this.scrollbar = new jsScrollbar(document.getElementById("Scrollbar-Container"), this.scroller, true, this.scrollbarEvent);
		this.swfWheel = new SWFWheel("wrap");
		this.swfWheel.onScroll = $.proxy(this.scrollHandler, this);

		$(document).keydown($.proxy(this.document_keyDownHandler, this));
		$(document).keyup($.proxy(this.document_keyUpHandler, this));
	},

	scrollHandler : function (delta) {
		this.scrollbar.myScrollbarWheel(- delta);

		this.hideScreenShot();
	},

	document_keyDownHandler : function(event) {

		if (this.isSearchFocus) return;

		switch (event.keyCode) {
			case 32:
				this.isShiftDown ? this.scrollbar.myKeyDown(true) : this.scrollbar.myKeyDown(false);
				return false;
				break;
			case 16:
				this.isShiftDown = true;
				return false;
				break;
		}
	},

	document_keyUpHandler : function(event) {
		switch (event.keyCode) {
			case 16:
				this.isShiftDown = false;
				return false;
				break;
		}
	},

	initToolTipPreview : function() {
		var xOffset = 0;
		var yOffset = -20;
		$(".interface img")
				.hover(
				function(e) {
					this.a = this.alt;
					this.alt = "";
					$("body").append("<div id='toolTip'>" + this.a + "</div>");
					$("#toolTip")
							.css("top", (e.pageY - xOffset) + "px")
							.css("left", (e.pageX + yOffset) + "px")
							.fadeIn("fast");
				},
				function() {
					this.alt = this.a;
					$("#toolTip").remove();
				})
				.mousemove(function(e) {
					$("#toolTip")
							.css("top", (e.pageY - yOffset) + "px")
							.css("left", (e.pageX + xOffset) + "px");
				});
	},

	resizeHandler : function() {
		var $cell = $(".cell");

		var stageW = $(window).width();
		var stageH = $(window).height();

		var previewAreaW = this.isShowPreview ? 465 : 0;

		if (this.layoutMode == "grid" || this.layoutMode == null) {
			var ITEM_WIDTH = 184 + 6;
			var ITEM_HEIGHT = 184;
			var cols = Math.floor((stageW - CONTENT_X - previewAreaW) / ITEM_WIDTH);
			cols = Math.max(1, cols);
			$("#content").css("width", cols * ITEM_WIDTH);

			var l = $cell.length;
			for (var i = 0; i < l; i++) {
				var obj = $cell[i];
				obj.style.left = ((i % cols) * ITEM_WIDTH) + "px";
				obj.style.top = Math.floor(i / cols) * ITEM_HEIGHT + "px";
			}

			$cell.find("a.screenshot img")
					.width("170px")
					.height("170px");

			$("#content")
					.addClass("gridLayout")
					.removeClass("listLayout");

		} else {
			var ITEM_WIDTH = 375 + 6;
			var ITEM_HEIGHT = 88;

			var cols = Math.floor((stageW - CONTENT_X - previewAreaW) / ITEM_WIDTH);
			cols = Math.max(1, cols);
			$("#content").css("width", cols * ITEM_WIDTH + "px");

			var l = $(".cell").length;
			for (var i = 0; i < l; i++) {
				var obj = $(".cell")[i];
				obj.style.left = ((i % cols) * ITEM_WIDTH) + "px";
				obj.style.top = Math.floor(i / cols) * ITEM_HEIGHT + "px";
			}

			$cell.find("a.screenshot img")
					.width("70px")
					.height("70px");

			$("#content")
					.addClass("listLayout")
					.removeClass("gridLayout");

		}
		$(".Scroller-Container").css("height", Math.ceil($(".cell").length / cols) * ITEM_HEIGHT + "px")

		var myHeight = stageH - CONTENT_Y;
		$("#content").css("height", myHeight);

		$("div.Scrollbar-Down").css("top", myHeight - SCROLL_PADDING);
		$("div.Scrollbar-Track").css("height", myHeight - SCROLL_PADDING * 2)

		this.scroller.swapContent(document.getElementById("content"), 760, (stageH - CONTENT_Y));
		this.scrollbar = new jsScrollbar(document.getElementById("Scrollbar-Container"), this.scroller, true, this.scrollbarEvent);

		if (this.layoutMode == "list") {
			$("#gridImg").attr("src", "/imgs/interface-grid.png");
			$("#listImg").attr("src", "/imgs/interface-list-on.png");
		} else {
			$("#gridImg").attr("src", "/imgs/interface-grid-on.png");
			$("#listImg").attr("src", "/imgs/interface-list.png");
		}

		$("#main").width(stageW - 220);
		$("#container").height(stageH - 51);

		if (stageW < 1045) {
			$("#interface")
					.css("right", "-177px")
			$("#rollOverBox")
					.css("display", "none")
					.css("windowBox", "none")
		} else {
			$("#interface")
					.css("right", "7px")
			$("#rollOverBox")
					.css("display", "block")
					.css("windowBox", "block")
		}

		if (this.isShowPreview) {
			$("#Scrollbar-Container").animate({right: 517 - 35}, 300, "easeOutExpo");
			$("#preview")
					.css("width", 465)
					.css("display", "block")
					.animate({right:0}, 300, "easeOutExpo")
		}
		else {
			$("#preview")
					.animate({right:-465}, 600, "easeOutExpo")
			$("#Scrollbar-Container")
					.animate({right:17}, 600, "easeOutExpo");
		}

		if (this.isParmaLink) {
			$("#preview")
					.css("width", "100%")
					.css("display", "block")

			$("#sortBox").hide();
			$("#pagingTop").hide();
			$("#interface").hide();
			$("#closePreview").hide();
			$("#pagingBottom").hide();
			$("#preview div.header").hide();

		}
	},

	scrollbarEvent : function(o, type) {
		return;
		if (type == "mousedown") {
			if (o.className == "Scrollbar-Track") o.style.backgroundColor = "#E3E3E3";
			else o.style.backgroundColor = "#BBB";
		} else {
			if (o.className == "Scrollbar-Track") o.style.backgroundColor = "#EEE";
			else o.style.backgroundColor = "#CCC";
		}
	},

	previousPreviewUrl : null,
	previousCell : null,
	clickHandler : function (event) {
		//var winP = window.open(event.target.parentNode.href + "&mode=blogparts", 'preview', 'innerWidth=465,innerHeight=500,status=yes,menubar=yes,toolbar=yes,location=yes');
		//winP.focus();

		if (this.previousPreviewUrl == event.target.parentNode.href)
			return false;

		this.previousPreviewUrl = event.target.parentNode.href;

		var metas = $(event.target.parentNode.parentNode.parentNode);
		var title = metas.find("span.title").text();
		var user = metas.find("span.user span.inline").text();
		var id = this.previousPreviewUrl.split("?id=")[1];
		this.previousCell = event.target.parentNode.parentNode.parentNode;

		$("#previewContent")
				.html('<iframe src="' + this.previousPreviewUrl + '&mode=blogparts" width="465" height="485" frameborder="0" scrolling="no" ></iframe>');

		$("#btnGoWonderfl")
				.attr("href", this.previousPreviewUrl);

		$("#btnTweet")
				.attr("href", "http://twitter.com/share?text=" + escape(title + " by " + user + " #wonderfl ") + "&url=" + escape("http://beautifl.net/?id=" + id));

		if (!this.isShowPreview) {
			this.isShowPreview = true;
			this.resizeHandler();

			var targetY = Number($(this.previousCell).css("top").split("px").join(""));
			this.scrollbar.scrollTo(0, targetY, true);
		}

		this.hideScreenShot();

		return false;
	},

	btnClose_clickHandler : function(event) {

		$("#previewContent")
				.html('');

		this.isShowPreview = false;
		this.resizeHandler();

		var targetY = Number($(this.previousCell).css("top").split("px").join(""));
		this.scrollbar.scrollTo(0, targetY, true);

		this.previousPreviewUrl = null;
		this.previousCell = null;
	}

};

/**
* Incremental Search Box Class
* @author clockmaker
*/
function SearchBox() {
	this.initialize();
}
SearchBox.prototype = {

	SEARCH_DEFAUTL_WORD : "Search...",
	searchItemSelectedIndex: -1,
	searchItemLength: 0,
	searchIntervalId: 0,
	searchResultIntervalId : 0,
	isShowSearchResult : false,
	isSearchFocus : false,
	searchXmlhttp : null,

	initialize : function() {
		$('#incrementalSearch')
				.keydown($.proxy(this.search_keyDownHandler, this))
				.focus($.proxy(this.search_focusHandler, this))
				.blur($.proxy(this.search_blurHandler, this))
				.val(this.SEARCH_DEFAUTL_WORD);

		$("#searchResultContainer").hide();

		if ($.support.opacity)
			$("#searchResultContainer").css("opacity", 0);
	},

	search_focusHandler : function(event) {
		this.isSearchFocus = true;
		$("#search").addClass("focus");
		$("#search").removeClass("blur");
		$("#searchBody").stop().animate({width: 160}, 500, "easeInOutExpo");

		if ($('#incrementalSearch').val() == this.SEARCH_DEFAUTL_WORD) {
			$('#incrementalSearch').val("");
		}
	},

	search_blurHandler : function(event) {
		this.isSearchFocus = false;
		$("#search").removeClass("focus");
		$("#search").addClass("blur");
		$("#searchBody").stop().animate({width: 100}, 500, "easeInOutExpo");

		if ($('#incrementalSearch').val() == "") {
			$('#incrementalSearch').val(this.SEARCH_DEFAUTL_WORD);
		}

		this.searchResultIntervalId = setTimeout($.proxy(this.hideSearchResult, this), 500)
	},

	showSearchResult : function() {

		var $o = $("#searchResultContainer");
		if (!this.isShowSearchResult) {
			this.isShowSearchResult = true;
			$o.clearQueue().stop().show();

			if ($.support.opacity)
				$o.animate({opacity:1}, 400, "easeOutExpo");
		} else {
			$o.show();
		}
	},

	hideSearchResult : function() {
		if (this.isShowSearchResult) {
			var $o = $("#searchResultContainer");

			this.isShowSearchResult = false;
			$o.clearQueue().stop();
			if ($.support.opacity)
				$o.animate({opacity:0}, 600, "easeOutExpo").queue(function() {
					$(this).hide()
				});
			else
				$o.hide();
		}
	},

	search_keyDownHandler : function(event) {

		if ($(event.target).val() == this.SEARCH_DEFAUTL_WORD) return;

		switch (event.keyCode) {
			case 40:
				this.setFocusSearchItem(1);
				return false;
			case 38:
				this.setFocusSearchItem(-1);
				return false;
			case 13:
				this.clickSearchItem();
				return false;
		}

		clearInterval(this.searchIntervalId);
		this.searchIntervalId = setTimeout($.proxy(this.sendForm, this), 150);
	},

	sendForm : function() {

		var query = $("#incrementalSearch").val()
				.replace(/^\s+|\s+$/g, '')
				.replace(/\s+/g, ' ')
				.split(' ');

		if (query[0] === '') {
			$("#searchResultContainer").html("").hide();
			return;
		}

		// abort
		if (this.searchXmlhttp) this.searchXmlhttp.abort();

		// async load
		this.searchXmlhttp = $.ajax({
			url : 'http://beautifl.net/search.php',
			data : {
				key : query.join(",")
			},
			dataType : 'jsonp',
			jsonp : 'callback',
			success: $.proxy(this.search_successHandler, this)
		});

	},


	setFocusSearchItem : function(direction) {

		this.searchItemSelectedIndex += direction;
		if (this.searchItemSelectedIndex < -1) this.searchItemSelectedIndex = -1;
		else if (this.searchItemSelectedIndex > this.searchItemLength - 1) this.searchItemSelectedIndex = this.searchItemLength - 1;

		this.updateFocusSearchItem();
	},

	updateFocusSearchItem : function() {

		for (var i = 0; i < this.searchItemLength; i++) {
			var $o = $("#searchItem_" + i);

			i == this.searchItemSelectedIndex ? $o.addClass("selected") : $o.removeClass("selected");
		}
	},

	clickSearchItem : function() {
		if (this.searchItemSelectedIndex > -1) {
			var $o = $("#searchItem_" + this.searchItemSelectedIndex);
			location.href = $o.attr("href");
		}
	},

	search_successHandler : function(data, status) {

		this.searchItemSelectedIndex = -1;

		var str = "";
		var len = data.length;
		if (len > 10) len = 10;
		for (var i = 0; i < len; i++) {
			try {
				str += '<a id="searchItem_' + i + '" href="http://beautifl.net/?id=' + data[i].id + '">';
				str += '    <div class="searchItem clearfix">';
				str += '        <div class="thumb">';
				str += '            <img src="archives_s/' + data[i].wid + '.jpg" width="50" height="50" />';
				str += '        </div>';
				str += '        <div class="meta">';
				str += '            <span class="searchTitle">' + data[i].title + '</span><br />';
				str += '            <span class="searchUser">' + data[i].user + '</span>';
				str += '        </div>';
				str += '    </div>';
				str += '</a>';
			} catch(e) {
			}
		}


		if (len == 0) {
			str += '    <div class="searchItem clearfix">';
			str += '        <div class="thumb">';
			str += '        </div>';
			str += '        <div class="meta">';
			str += '            <span class="searchTitle">No Result</span><br />';
			str += '            <span class="searchUser">Sorry, but you are looking for something that does not exist.</span>';
			str += '        </div>';
			str += '    </div>';
		}

		$("#searchResultContainer").html(str);
		this.showSearchResult();

		this.searchItemLength = len;
		this.updateFocusSearchItem();
	}
};


var html5Initializer = new Html5Initializer();
var beautifl = new Beautifl();


// ------------------------
// wonderfl api
// ------------------------
initLoad();
var users;
function initLoad() {
	var url = "/api/users-db.json";
	$.getJSON(url, null, function(data) {
		users = data;
		userProfilePreview();

	});
}

function loadUserData(userName) {
	var user;
	for (var i = 0; i < users.length; i++) {
		if (users[i].name == userName) {
			user = users[i];
			break;
		}
	}
	return user;
}

function userProfilePreview() {
	userProfileX = 20;
	userProfileY = 20;
	$("span.user span.inline").hover(function(e) {
				if (! beautifl.checkRollover) return;
				var user = loadUserData(this.innerHTML);
				var des = (user.description.length != 0) ? user.description + "<br />" : "";
				$("body").append("<p id='userProfile'>"
						+ "<img src='/api/imgs/" + user.name + ".png' width='32' height='32 alt='User profile' />" + "<br />"
						+ user.name + "<br />"
						+ des
						+ "</p>");
				$("#userProfile")
						.css("top", (e.pageY + userProfileY) + "px")
						.css("left", (e.pageX + userProfileX) + "px")
						.fadeIn("fast");
			},
			function() {
				$("#userProfile").remove();
			});
	$("span.user a").mousemove(function(e) {
		$("#userProfile")
				.css("top", (e.pageY + userProfileY) + "px")
				.css("left", (e.pageX + userProfileX) + "px");
	});
}
