var jd = {};

(function(){

//================================================================
// variables
//================================================================
// IDs
var contentsID = '#contents',
	menu1ID = '#menu1',
	menu2ID = '#menu2',
	entryWrapID = '#entryWrap',
	entryBoxID = '#entryBox',
	commentAreaID = '#commentArea';

var	loading = 'loading';
var minW = 960,minH;

// ハッシュ
var hash,oldHash;
var selects = [];
var imgURL = '/wp-content/themes/jsdokusho/src/img/';

//================================================================
// ランダム文字列
//================================================================

var randomChar = (function(){
	var
		alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789[]{}.,;:+=_-?/><",
		length,
		speed = 50;

	var change = function(t,c,text,text2,len){
		len = len || c;
		text2 = text2 || '';
		text2 += text.charAt((c-len)*-1);
		var randomText = '';
		for(var i = len - text2.length; i > 0; i--){
			randomText += alphabet.charAt(Math.floor(Math.random()*52));
		};
		t.text(text2+randomText);
		c--;
		if(c > 0){
			setTimeout(function(){change(t,c,text,text2,len)},speed);
		};
	};

	return function(t){
		for(var i = 0; i < t.length; i++){
			change(
				$(t[i]),
				$(t[i]).text().length,
				$(t[i]).text()
			);
		};
	}
}());

//================================================================
// セッティング
//================================================================
var setting = function(){

	$("body").prepend('<div id="'+loading+'"></div>');
	loading = $("#"+loading);
	
	randomChar($(menu1ID+' a'));

	resize();
	// リサイズ登録
	$(window).bind('resize',jd.resize);

	// ハッシュイベント登録
	$(window).hashchange(hashClick);
	$(window).hashchange();
};

//================================================================
// クリックしたリストを選択状態のスタイルにする
//================================================================
var selected = (function(){
	var length, arr, id;
	//------------------------------------------------------------
	// トップ以外のページを直接開いた場合の処理
	//------------------------------------------------------------
	var set = (function(){
		var addClass = function(t,n,name){
			name = hash[0] === 'category' ? hash[1]: name;
			selects[n] = t.find('a[href*="'+name+'"]');
			selects[n].addClass('selected');
		};
		return function(n){
			n = hash[0] === 'category' ? n-1 : n ;
			while(n--){
				switch(n){
					case 0:
					addClass($(menu1ID),n,hash[n]);
					break;
					case 1:
					addClass($(menu2ID),n,hash[n]);
					break;
				};
			};
		}
	}());
	//------------------------------------------------------------
	return function(e){
		if(typeof e === 'number'){
			set(e);
		}else{
			length = (!!$(e.target).parents('#menu1').length) ? 0 : 1 ;
			if(selects[length]){
				selects[length].removeClass('selected');
			};
			selects[length] = $(this);
			$(this).addClass('selected');
		};
	}
}());


//================================================================
// リンク変更
//================================================================
// a要素のhref属性に#!を挿入
var cngA = (function(){
	var ctx,
		base = menu1ID,
		domain = location.hostname,
		url;
	return function(c){
		if(typeof base === 'string') base = $(base);
		ctx = c || base;
		$('a',ctx).each(function(i,t){
			t = $(t);
			url = t.attr('href').replace(domain,domain+'/#!');
			t.attr('href',url);
		}).bind('click',selected);
	}
}());

//================================================================
// データを取得
//================================================================

var getData = function(url,mode,callback){
	loading.css('display','block');
	getData.firing = true;
	$(entryBoxID).css('visibility','hidden');
	switch(mode){
		//--------------------------------------------------------
		// 全部読み込む
		//--------------------------------------------------------
		case 'all':
			$(menu2ID).load(url+' '+menu2ID+' > div',function(){
				$(entryWrapID).load(url+' '+entryBoxID,function(){
					getData.firing = false;
					loading.css('display','none');
					callback();
				});
			});
		break;
		//--------------------------------------------------------
		// リストだけ読み込む
		//--------------------------------------------------------
		case 'list':
			$(menu2ID).load(url+' '+menu2ID+' > div',function(){
				getData.firing = false;
				loading.css('display','none');
				callback();
			});
		break;
		//--------------------------------------------------------
		// エントリーだけ読み込む
		//--------------------------------------------------------
		case 'entry':
			$(entryWrapID).load(url+' '+entryBoxID,function(){
				getData.firing = false;
				loading.css('display','none');
				callback();
			});
		break;
	};
};
getData.firing = false;

//================================================================
// リストをスライドさせる
//================================================================
var slide = (function(){
	var list,entry,
		speed = 150;
	return function(mode,firing){
		list = $(menu2ID+' > div');
		entry = $(entryBoxID);
		// 停止指示があれば従う
		if(firing){
			slide.firing = true;
			list.stop();
			entry.stop();
		};
		switch(mode){
			//----------------------------------
			// 全て開く
			//----------------------------------
			case 'all':
				sizeChange(true);
				list.css({
					visibility:'visible',
					marginLeft:'-'+list.width() +'px'
				}).animate({marginLeft:0},speed,null,function(){
					entry.css({
						visibility:'visible',
						left:'-'+entry.width() +'px'
					}).animate({left:0},speed,null,function(){
						slide.firing = false;
					});
				});
			break;
			//----------------------------------
			// リストだけ開く
			//----------------------------------
			case 'list':
				sizeChange(true);
				list.css({
					visibility:'visible',
					marginLeft:'-'+list.width() +'px'
				}).animate({marginLeft:0},speed,null,function(){
					slide.firing = false;
				});
				entry.css({
					visibility:'visible',
					left:'-'+entry.width() +'px'
				});
			break;
			//----------------------------------
			// エントリーだけひらく
			//----------------------------------
			case 'entry':
				sizeChange(true);
				entry.css({
					visibility:'visible',
					left:'-'+entry.width() +'px'
				}).animate({left:0},speed,null,function(){
					slide.firing = false;
				});
			break;
			//----------------------------------
		}
	}
}());
slide.firing = false;

//================================================================
// ハッシュイベント
//================================================================

var hashClick = (function(){
	var first = true;
	var i;

	var loaded = function(m,callback){	
		return function(){
			switch(m){
				case 'all':
					// リンク変更
					cngA($(menu2ID));
					cngA($(entryBoxID));
					// SyntaxHighlighter再設定
					SyntaxHighlighter.highlight();
					// コメントタブ設定
					commentTabActivate();
					$(entryWrapID).css('background','none');
					if(typeof callback === "function") callback();
				break;
				case 'list':
					cngA($(menu2ID));
					$(entryWrapID).css('background','none');
					if(typeof callback === "function") callback();
				break;
				case 'entry':
					// リンク変更
					cngA($(entryBoxID));
					// SyntaxHighlighter再設定
					SyntaxHighlighter.highlight();
					// コメントタブ設定
					commentTabActivate();
					$(entryWrapID).css('background','none');
				break;
			};
			slide(m);
		}
	}

	return function(e){
		if(first){
			first = false;
			cngA();
		};
		// ハッシュ生成
		if(location.hash){
			hash = location.hash.replace('#!/','').replace(/\/$/,'').split('/');		
			for(i = 0; i<hash.length;i++){
				if(/^\?/.test(hash[i])) hash.splice(i,i);
			};
		};

		//----------------------------------------
		if(!hash){
			// トップページの処理
			if(location.pathname === '/'){
				cngA($(menu2ID));
			}else{
			// ハッシュフラグメントを含まないURLでアクセスした場合
				hash = location.pathname.replace(/\/$/,'').split('/');
				hash.shift();
				randomChar($(menu2ID+' a'));
				selected(hash.length);
				if(hash.length === 1){
					cngA($(menu2ID));
					slide('list');
				}else{
					cngA($(menu2ID));
					cngA($(entryBoxID));
					commentTabActivate();
					slide('all');
				};
			};
		}else{
			if(!oldHash){
			// ページが直接開かれた場合
				mode = hash.length === 2 ? 'all' : 'list' ;
				getData(location.href.replace('#!/',''),mode,loaded(mode,function(){
					randomChar($(menu2ID+' a'));
					selected(hash.length);
				}));
				oldHash = hash;
			}else{
			// リストをクリックしてページを開こうとした場合
				(function(){
					var mode;
					if(slide.firing){
						setTimeout(arguments.callee,0);
						return false;
					};

					if(hash[0] !== oldHash[0]) mode = 'list';
					if(hash[0] === oldHash[0]) mode = 'entry';
					
					// category処理
					if(
						(hash[0] === oldHash[0] && hash[0] === 'category') ||
						(hash[0] === 'category' && oldHash[0] !== 'category') ||
						((hash[0] !== 'category' && oldHash[0] == 'category') && hash.length === 1)
					){ mode = 'list' };
					if((hash[0] !== 'category' && oldHash[0] == 'category') && hash.length !== 1){
						mode = 'entry';
					}
					
					getData(location.href.replace('#!/',''),mode,loaded(mode,function(){
						randomChar($(menu2ID+' a'));				
						loading.css('display','none');
					}));
				}());
			
				oldHash = hash;
			};
		}

	}
})();

//================================================================

var commentTabActivate = (function(){
	var active,t;
	var set = function(t){
		active = $(commentAreaID+' > nav li[data-active="'+t+'"]');
		active.addClass('selected');
		active.unbind('click');
		$('#'+active.data().active).css('display','block');
	};
	//--------------------------------------------
	// インスタンス
	//--------------------------------------------
	return function(e){

		if(!e){
			// イベント登録
			$(commentAreaID+' > nav li').bind('click',arguments.callee);
			t = 'commentSet';
		}else{
			active.removeClass('selected');
			active.bind('click',arguments.callee);
			$('#'+active.data().active).css('display','none');
			t = $(e.target).data().active;
		};
		set(t);
		resize();
	}
}());

//================================================================
// 幅、高さの調節
//================================================================
var sizeChange = (function(){
	var cnt, menu1, menu2, entryWrap;
	var offsetH, h, w;
	var headerH = 53;

	var init = function(){
		cnt = $(contentsID);
		menu1 = $(menu1ID);
		menu2 = $(menu2ID);
		entryWrap = $(entryWrapID);
	};
	//-------------------------------------------------------------
	// インスタンス
	//-------------------------------------------------------------
	return function(resetMinH){
		if(!cnt) init();
		// 幅が設定
		w = ($(window).width() < minW) ? minW : $(window).width();
		cnt.css('width',w+'px');
		w = w - menu1.width() - menu2.width();
		entryWrap.css('width',w+'px');
		// 高さの設定
		if(resetMinH || !minH){
			minH = menu1.height() < menu2.height() ? menu2.height() : menu1.height() ;
			minH = minH < entryWrap.height() ? entryWrap.height() : minH ;
		};
		if(minH < ($(window).height() - headerH)){
			h = $(window).height() - headerH;
			cnt.css('height',h+'px');
		}else{
			cnt.css('height','auto');
		};
	}
}());

//================================================================
// リサイズイベント
//================================================================

var resize = function(){
	var i;
	for(i in resize.list) resize.list[i]();
};
// 登録
resize.list = {};
resize.list.sizeChange = sizeChange;



//================================================================

jd.resize = resize;
jd.setting = setting;

})();

