// init
var scroller  = null;
var scrollbar = null;
var SCROLL_PADDING = 13 ;
var CONTENT_X = 228 + 13;
var CONTENT_Y = 180 + 30;
var isShiftDown = false;
var layoutMode = null;

// 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");



// event 
$(window).resize(resizeHandler);

function resizeHandler(){
	
	if(layoutMode == "grid" ||layoutMode == null ){
		var ITEM_WIDTH = 184 + 6;
		var ITEM_HEIGHT = 190 ;
		var cols = Math.floor((getInnerWidth() - CONTENT_X) / ITEM_WIDTH);
		$("#content").css("width", cols * ITEM_WIDTH);
		
		var l = $(".cell").length;
		for(var i=0; i<l; i++){
			$(".cell")[i].style.left = ((i % cols) * ITEM_WIDTH) + "px";
			$(".cell")[i].style.top = Math.floor(i / cols) * ITEM_HEIGHT + "px";
			$(".cell")[i].style.width = "182px";
			$(".cell")[i].style.height = "182px";
		}
		$(".cell a.screenshot img").width("170px");
		$(".cell a.screenshot img").height("170px");
		$(".cell a.screenshot img").css("top", "-30px");
		
		$(".cell .thumb").width("170px");
		$(".cell .thumb").height("110px");
		
		$(".cell .meta").css("top", "120px");
		$(".cell .meta").css("left", "6px");
		
		$(".cell .meta .category").css("display", "none");
		$(".cell .meta .tag").css("display", "none");
		$(".cell .meta .date").css("display", "none");
	}else{
		var ITEM_WIDTH = 375 + 6;
		var ITEM_HEIGHT = 88;
		
		var cols = Math.floor((getInnerWidth() - CONTENT_X) / ITEM_WIDTH);
		$("#content").css("width", cols * ITEM_WIDTH + "px");
		
		var l = $(".cell").length;
		for(var i=0; i<l; i++){
			$(".cell")[i].style.left = ((i % cols) * ITEM_WIDTH) + "px";
			$(".cell")[i].style.top = Math.floor(i / cols) * ITEM_HEIGHT + "px";
			$(".cell")[i].style.width = "375px";
			$(".cell")[i].style.height = "82px";
		}
		
		$(".cell a.screenshot img").width("70px");
		$(".cell a.screenshot img").height("70px");
		$(".cell a.screenshot img").css("top", "0");
		
		$(".cell .thumb").width("70px");
		$(".cell .thumb").height("70px");
		
		$(".cell .meta").css("top", "6px");
		$(".cell .meta").css("left", "86px");
		
		$(".cell .meta .category").css("display", "inline");
		$(".cell .meta .tag").css("display", "inline");
		$(".cell .meta .date").css("display", "inline");
	}
	$(".Scroller-Container").css("height", Math.ceil($(".cell").length / cols) * ITEM_HEIGHT + "px")
		
	var myHeight = getInnerHeight() - CONTENT_Y;
	$("#content").css("height", myHeight);
	
	$("div.Scrollbar-Down").css("top", myHeight - SCROLL_PADDING);
	$("div.Scrollbar-Track").css("height", myHeight - SCROLL_PADDING * 2)
	
	scroller  = new jsScroller(document.getElementById("content"), 760, (getInnerHeight() - CONTENT_Y));
	scrollbar = new jsScrollbar(document.getElementById("Scrollbar-Container"), scroller, true, scrollbarEvent);
	
	if(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(getInnerWidth() - 220);
	$("#container").height(getInnerHeight() - 51);
	
	if(getInnerWidth() < 1070){
		$("#interface").css("right", "-177px")
		$("#rollOverBox").css("display", "none")
		$("#rollOverBox").css("windowBox", "none")
	}else{
		$("#interface").css("right", "10px")
		$("#rollOverBox").css("display", "block")
		$("#rollOverBox").css("windowBox", "block")
	}
}

function screenshotPreview(){		
	xOffset = 20;
	yOffset = 260;
	$("a.screenshot img").hover(function(e){
		if(! $("#rollOver")[0].checked) return;
		this.t = this.title;
		this.title = "";						 
		$("body").append("<p id='screenshot'><img src='"+ this.src +"' width='233' height='233' alt='Screenshot' /></p>");								 
		$("#screenshot")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");						
    },
	function(){
		this.title = this.t;	
		$("#screenshot").remove();
    });	
	$("a.screenshot").mousemove(function(e){
		var xoff = (e.pageX < 610) ? xOffset : -270; 
		$("#screenshot")
			.css("top",(e.pageY - yOffset) + "px")
			.css("left",(e.pageX + xoff) + "px");
	});			
};

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

$(document).ready(function(){
	layoutMode = $.cookie('layoutMode');
	resizeHandler();
	$(".cell").css("display", "block");
	
	scroller  = new jsScroller(document.getElementById("content"), 760, (getInnerHeight() - CONTENT_Y));
	scrollbar = new jsScrollbar (document.getElementById("Scrollbar-Container"), scroller, true, scrollbarEvent);
	screenshotPreview();
	toolTipPreview();
	
	$('.cell a.screenshot img').hover(function() {
		$(this).stop().fadeTo("fast", 0.5);
	}, function() {
		$(this).stop().fadeTo("fast", 1);
	});
	
	$(".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);
	});
	
	var swfwheel = new SWFWheel("wrap");
	
	$(document).keydown(function(e){
		switch(e.keyCode){
			case 32: isShiftDown ? scrollbar.myKeyDown(true) : scrollbar.myKeyDown(false); break;
			case 16: isShiftDown = true; break;
		}
	});
	$(document).keyup(function(e){
		switch(e.keyCode) {case 16: isShiftDown = false; break; }
	});
	
	if(navigator.userAgent.indexOf("MSIE") > -1){
		$("#rollOver").attr("checked", "")
		$("#rollOver").attr("disabled", "disabled")
	}
	else{
		if($.cookie('isRollOver') == null)  $("#rollOver").attr("checked", "checked");
		else if($.cookie('isRollOver') == "true") $("#rollOver").attr("checked", "checked");
		else $("#rollOver").attr("checked", "");
	}
	
	$("#rollOver").click(function(e){
		$.cookie('isRollOver', this.checked, { expires: 7 });//書き込み{保存days}
	});
	$("#rollOverImg").click(function(e){
		if($("#rollOver")[0].checked)   $("#rollOver").attr("checked", "")
		else                            $("#rollOver").attr("checked", "checked")						 
		$.cookie('isRollOver', this.checked, { expires: 7 });//書き込み{保存days}
	});
	
	switch($.cookie('isNewWin')){
		case null:
		case "true":
			$("#windowCheckBox").attr("checked", "checked");
			//$("a.screenshot").attr("target", "_blank");
			$("a.screenshot").bind("click", openNewWindow);
			break;
		default:
			$("#windowCheckBox").attr("checked", "");
			//$("a.screenshot").attr("target", "_self");
			$("a.screenshot").unbind("click", openNewWindow);
	}
	
	$("#windowCheckBox").click(function(e){
		$.cookie('isNewWin', this.checked, { expires: 7 });//書き込み{保存days}
		if(this.checked){
			//$("a.screenshot").attr("target", "_blank");
			$("a.screenshot").bind("click", openNewWindow);
		}else{
			//$("a.screenshot").attr("target", "");
			$("a.screenshot").unbind("click", openNewWindow);
		}
	});
	$("#winImg").click(function(e){
		if($("#windowCheckBox")[0].checked)   $("#windowCheckBox").attr("checked", "")
		else                                  $("#windowCheckBox").attr("checked", "checked")	
		$.cookie('isNewWin', $("#windowCheckBox")[0].checked, { expires: 7 });//書き込み{保存days}
		if($("#windowCheckBox")[0].checked){
			//$("a.screenshot").attr("target", "_blank");
			$("a.screenshot").bind("click", openNewWindow);
		}else{
			//$("a.screenshot").attr("target", "");
			$("a.screenshot").unbind("click", openNewWindow);
		}
	});
	
	$("#gridImg").click(function(e){
		layoutMode = "grid";
		$.cookie('layoutMode', layoutMode, { expires: 7 });//書き込み{保存days}
		resizeHandler()
	});
	$("#listImg").click(function(e){
		layoutMode = "list";
		$.cookie('layoutMode', layoutMode, { expires: 7 });//書き込み{保存days}
		resizeHandler()
	});
	
	
	$('#incrementalSearch').keyup(function() {
		// 検索クエリ
        var query = $(this).val()
            // 前後の空白文字をトリムして、
            .replace(/^\s+|\s+$/g, '')
            // 1個以上の空白文字を半角スペースにして、
            .replace(/\s+/g, ' ')
            // 半角スペースで区切って配列化
            .split(' ');

        // 検索クエリが無ければ終了
        if (query[0] === '') {
            return;
        }
		
		$.ajax({
			url : 'http://beautifl.net/search.php',
			data : {
				key : query.join(","),
			},
			dataType : 'jsonp',
			jsonp : 'callback',
			success: function(data, status) {
				
				var str = "";
				var len = data.length;
				if(len > 6) len = 6;
				for(var i=0; i<len; i++){
					str += '<div class="searchItem clearfix">';
					str += '    <div class="thumb">';
					str += '        <a href="http://beautifl.net/redirect.php?id=' + data[i].id + '"><img src="archives/'+ data[i].wid + '.jpg" width="60" height="60" /></a>';
					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>';
				}
				$("#searchResultContainer").html(str);
				
				if(data.length == 0){
					$("#searchResultContainer").css("display", "none");	
				}else{
					$("#searchResultContainer").css("display", "block");
				}
				
			}

		});
		
		$('#incrementalSearch').focus(function() {
			//
		});
		
		$('#incrementalSearch').blur(function() {
			$("#searchResultContainer").css("display", "none");
		});
		
	});

});

myTriggerMouseEvent = function(delta){
	scrollbar.myScrollbarWheel(delta);
}


function getInnerWidth(){
	return (navigator.userAgent.indexOf("MSIE") > -1)
		? document.documentElement.clientWidth
		: window.innerWidth;
}

function getInnerHeight(){
	return (navigator.userAgent.indexOf("MSIE") > -1)
		? document.documentElement.clientHeight
		: window.innerHeight;
}
	
function scrollbarEvent (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";
	}
}

var winP;
function openNewWindow(){
	winP = window.open(this.href + "&mode=blogparts", 'preview', 'innerWidth=465,innerHeight=500,status=yes,menubar=yes,toolbar=yes,location=yes');
	winP.focus();
	
	return false;
}

// ------------------------
// 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(! $("#rollOver")[0].checked) 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");
	});			
};