	function log(_log)
	{
		if(console.log)console.log(_log);
	}
	function ApiUriFormat(_uid) 
	{
		
		_uid = _uid.indexOf(".")!=-1	?	_uid
										: 	_uid + ".tumblr.com";
																
		return "http://api.tumblr.com/v2/blog/"+ _uid +"/";
	}	

	Function.prototype.applyTimeout = function(ms, self, args)
	{
	  	var f = this;
		var args = args || [];
		
		return setTimeout(function () {f.apply(self, args);},ms);
	}
	
	String.prototype.antiXSS = function()
	{
		return this.replace(/<|>|&/g,"");
	}
	
	
	
	var CONST = 
	{
		MOS_ID			:	"Mosaic",
		MOS_ELEM		: 	document.getElementById("Mosaic"),
		BODY			: 	navigator.userAgent.indexOf("Safari") != -1	?	"body"	:	"html",
		KEY				:	"r2s1nCZyRoqfdo0RvgLd61twPioPITgvsJ6ay7cFkqC8N3ttAr",
		BASE_URL		: 	"http://"+location.host+location.pathname,
		TEST			: 	location.host == "tmv.proto.jp"	?	false	: 	true,
		ENABLE_FLASH	: 	swfobject.hasFlashPlayerVersion("10.0")
	}
	
	var cookieManager = 
	{
		hashKey		:	"TmvProtoJp_3",
		dataObj		:	null,
		dataObjClass:	{
							ver			:	1,
							at			:	[""],
							ats			: 	[""],
							atIndex		: 	0,
							name		: 	"",
							id			: 	"",
							size 		: 	100,
							lang		: 	"en",
							highRes		: 	false,
							summary 	: 	[{type:"around",name:"proto-jp"}],
							around		: 	"proto-jp"
						},
		AT			: 	"",
		ATS			: 	"",
		getAT		: 	function(){return this.dataObj.at[this.dataObj.atIndex]},
		getATS		: 	function(){return this.dataObj.ats[this.dataObj.atIndex]},
		setToken	: 	function(_at,_ats)
						{
							this.dataObj.at[this.dataObj.atIndex] = _at;
							this.dataObj.ats[this.dataObj.atIndex] = _ats;
							
							if(!_at)this.dataObj.summary=[{type:"around",name:this.dataObj.around}];
							
							this.saveData();
						},		
		saveData	:	function()
						{
							$.cookie(this.hashKey, JSON.stringify(this.dataObj), {expires:99999});
							
							this.AT = this.getAT();
							this.ATS = this.getATS();
						},
		loadData	:	function()
						{
							this.dataObj = $.cookie(this.hashKey)	?	JSON.parse($.cookie(this.hashKey))
																	:	this.dataObjClass;
							this.AT = this.getAT();
							this.ATS = this.getATS();
							
							
						}
	}
	cookieManager.loadData();	
	
	var OAuthManager =
	{
		available	: 	function(){return document.getElementById('SWF').SetOAuthRequest},
		request		: 	function(_obj)
						{
							if(CONST.ENABLE_FLASH)
								document.getElementById('SWF').SetOAuthRequest(_obj);
						},
		getToken	:	function() 
						{
							
							$.cookie("tumblr_at", null);
							$.cookie("tumblr_ats", null);
							
							window.open('./php/oauth/redirect.php', 'view', 'width=550, height=550');
						},
		setCookie	: 	function()
						{
							
							
							
							if($.cookie("tumblr_at") && $.cookie("tumblr_ats"))
							{
								cookieManager.setToken($.cookie("tumblr_at"),$.cookie("tumblr_ats"))
								$("#loginBtn").hide();
								
								
								$.cookie("tumblr_at", null); 
								$.cookie("tumblr_ats", null); 
								
								
								
								if(CONST.ENABLE_FLASH)
								{
									cookieManager.dataObj.summary = [{type:"dashboard"}];
									PageManager.setPage(cookieManager.dataObj.summary);
									Menu.getUserInfo();									
								}
							}
						}
	}	
	
	var Header = 
	{
		nowName			: 	"",
		form			: 	document.getElementById("HeaderInput"),
		pickup			:	document.getElementById("Pickup"),
		pickupList		: 	new BannerList($("#Pickup .bannerList")[0]),
		showPopup		:	function(_appendContent)
							{
								$("#PickupLayer")
									.append(_appendContent)
									.fadeIn("fast");
									
								$("#Pickup").height($(window).height()-$("#Header").height()*3)
									.css({top:$("#Header").height()});
							},
		hidePopup		:	function()
							{
								$("#PickupLayer").fadeOut("fast",$("#PickupLayer").children().remove);
							},
		selectedStyle	: 	function(_elem)
							{
								$("#HeaderInput,#Home,#About").removeClass("selected");
								$(_elem).addClass("selected");
							},
		action			: 	function () 
							{
								if(!Header.form.tumblrName.value)return;
								Header.nowName = Header.form.tumblrName.value.antiXSS();
								location.href = Thumbnail9.createHref(Header.nowName);
							},
		tmpName			: 	"",
		closeNextClick	: 	function(_fnc)
							{
								$(CONST.BODY).mousedown(function(e)
								{
									var elem = e.target;
									while(!$(elem).hasClass("CloseFalse") && elem.tagName!="BODY")
									{
										elem = elem.parentNode;
									}
																		
									
									if($(elem).hasClass("CloseFalse") && !$(e.target).hasClass("CloseTrue"))return;
									
									_fnc();
									_fnc = null;
									$(CONST.BODY).unbind("mousedown",arguments.callee);
								});
							},
		saveOption		:	function()
							{
								cookieManager.dataObj.size = $("#HeaderNavi input[name=ImageSize]:checked").val();
								cookieManager.dataObj.highRes = !!$("#HeaderNavi input[name=highRes]:checked").val();
								cookieManager.dataObj.lang = $("#HeaderNavi input[name=Language]:checked").val();
								cookieManager.saveData();
							},
		loadOption		:	function()
							{
								$("#HeaderNavi input[name=ImageSize]").val([cookieManager.dataObj.size]);
								$("#HeaderNavi input[name=highRes]").val([cookieManager.dataObj.highRes]);
								$("#HeaderNavi input[name=Language]").val([cookieManager.dataObj.lang]);
								
								!cookieManager.AT	?	$("#LogOut").hide()	:	$("#LogOut").show();
							},
		logOut			: 	function()
							{
								if(window.confirm("Are you sure you want to log out?"))
								{
									cookieManager.setToken("","");
									this.loadOption();
									
									$("#dashboard,#likes").hide();
									
									if(PageManager.nowType == "dashboard" || PageManager.nowType=="likes")
										location.reload();
								};
							},
		init			:	function()
							{
								$("#About").click(function ()
								{
									$("#About + div").fadeIn("fast");
									Header.closeNextClick(function(){$("#About + div").fadeOut("fast");});
								});
								
								$("#Option").click(function ()
								{
									$("#Option + ul").fadeIn("fast");
									$("#Option").addClass("selected");
									Header.closeNextClick(function()
									{
										$("#Option + ul").fadeOut("fast");
										$("#Option").removeClass("selected");
									});
									
									return false;
								});								
								
								
								$("#HeaderInput > input").focus(function()
								{
									if($("#Pickup>.bannerList>.bannerListBlock").length)
									{
										Header.showPopup(Header.pickup,89);
										Header.closeNextClick(function(){Header.hidePopup();});
									}
									
									$("#HeaderInput").addClass("hover");
									
									if("tumblr name.." == Header.form.tumblrName.value)
										Header.form.tumblrName.value ="";
									
								}).blur(function(){
									
									$("#HeaderInput").removeClass("hover");
									
									if("" == Header.form.tumblrName.value)
									{
										$("#HeaderInput>input").css({color:"#999"});
										Header.form.tumblrName.value = "tumblr name..";
									}
								});
								
								
								$("#HeaderInput > #SearchButton")
									.hover(function()
									{
										$(this).css({"background-position": "-120px -96px"});
									},
									function ()
									{
										$(this).css({"background-position": "-96px -96px"});
									});
								
								
								$("#Home").click(function(){$("#HomeLi .listUL").remove();});
								
								
								$("#HomeLi")
									.hover(function()
									{
										if(PageManager.nowPage=="Home" || !$("#list>.listUL>.row").length)return;
										
										ListManager.load();
										ListManager.refreshPullDown();
										
										$("#HomeLi").append($("#list .listUL").clone());
										$("#HomeLi .listUL").fadeIn("fast");
										
										
										var i = 0;
										$("#HomeLi .listUL .row>button").each(function()
										{
											this.setAttribute("onclick","ListManager.openEdit("+i+")");
											i++;
										});
										
										$("#HomeLi .listUL").prepend("<li class='note'>List</li>");
									},
									function ()
									{
											$("#HomeLi .listUL").remove();
									});
									
								
								$("#HeaderNavi input").click(Header.saveOption);
								this.loadOption();
							}
	}
	Header.init();
	
	var Menu = 
	{
		dummyElem		: 	document.createElement("img"),
		targetID		: 	null,
		createAvatarA	: 	function(_name)
							{
								var a = Thumbnail9.createElemA(_name);
								a.style.backgroundImage = "url("+ApiUriFormat(_name)+"avatar/24)";
								
								return a;
							},
		attachAvatars	: 	function(_array)
							{
								var target = $(document.getElementById(this.targetID)).children(".SimilarTumblr");
								if(!target.length)return;
								
								target.children("a").remove();
								
								while(_array.length)
								{
									target.append(this.createAvatarA(_array.shift().name));
									target.children("div").show();									
								}
							},			
		setStyleUser	: 	function(_tumblrName)
							{
								this.targetID = "MenuBlog";
								
								$("#MenuBlog").show();
								$("#MenuHome,#MenuList").hide();
								
								$("#around>a")[0].href =  CONST.BASE_URL+"#!/"+_tumblrName+"/around";
								$("#newest>a")[0].href =  CONST.BASE_URL+"#!/"+_tumblrName;
								$("#random>a")[0].href =  CONST.BASE_URL+"#!/"+_tumblrName+"/random";
								$("#oldest>a")[0].href =  CONST.BASE_URL+"#!/"+_tumblrName+"/oldest";
								
								$("#Avatar128>img")
									.attr({src : "http://assets.tumblr.com/images/default_avatar_128.gif"})
									.attr({src : ApiUriFormat(_tumblrName)+"avatar/128"});
							},
		setStyleHome	: 	function()
							{
								this.targetID = "MenuHome";
								
								$("#MenuBlog,#MenuList").hide();
								$("#MenuHome").show();
								
								if(cookieManager.AT && cookieManager.ATS)
								{
									$("#loginBtn").hide();
									
									if(CONST.ENABLE_FLASH)$("#dashboard,#HomeInfo,#likes").show();
								}
								else
								{
									$("#loginBtn").show();
									$("#dashboard,#HomeInfo,#likes").hide();
								}
							},
		setStyleList	: 	function()
							{
								this.targetID = "MenuList";
								
								$("#MenuBlog,#MenuHome").hide();
								$("#MenuList").show();
							},							
		selectedStyle	: 	function(_elem)
							{
								$(".Navi>li>a").removeClass("selected");
								$(_elem).children("a").addClass("selected");
								this.setHomeInfo();
							},
		setHomeInfo		: 	function()
							{
								if(!this.userInfo)return;
								
								$("#HomeInfo>div").text(this.userInfo.name);
								
								var title = $("#MenuHome>.Navi>li>a.selected").text();
								title = "Dashboard" == title	?	'<a href="http://www.tumblr.com/dashboard" target="_blank">Dashboard</a>'
																: 	"Likes" == title	? 	'<a href="http://www.tumblr.com/likes" target="_blank">Likes</a>'
																						: 	title == "List"	? 	title+" / "+$("#list>ul>li>a.selected").text()
																											: 	title + " / "+cookieManager.dataObj.around;
																											
								$("#HomeInfo>h2").html(title);
							},						
		userInfo		: 	null,
		getUserInfo		: 	function(_json)
							{
								if(_json)
								{
									this.userInfo = _json.response.user;
									$("#HomeInfo>img")[0].src = ApiUriFormat(this.userInfo.name)+"avatar/64";
									this.setHomeInfo();
									
									
									return;
								}
								
								if(cookieManager.AT && cookieManager.ATS)
								{
									OAuthManager.request
									({
										oauthToken		: 	cookieManager.AT,
										oauthTokenSecret: 	cookieManager.ATS,
										type			:　	"GET",
										url				: 	"http://api.tumblr.com/v2/user/info",
										params			: 	{},
										callBack		:	"Menu.getUserInfo",
										test			: 	CONST.TEST
									});									
								}
							},
		getBlogInfo		:　	function(_name)
							{
								$.getJSON
								(
									ApiUriFormat(_name)+"info?jsonp=?"
									,{api_key: CONST.KEY}
									,function(_json)
									{
										
										
										$("#BlogInfo>h1>a")
											.attr("href",_json.response.blog.url)
											.text(_json.response.blog.title).css({width:"auto"});
										
										
										var ds = _json.response.blog.description.replace(/<script/g,"<!--");
										ds = ds.replace(/\/script>/g,"-->");
										$(Menu.dummyElem).html(ds.replace(/script|object|embed|iframe/g,"p"));
										$("#BlogDescription").text($(Menu.dummyElem).text());
										$(Menu.dummyElem).html(null);
									}
								);
							},
		clearPosition	: 	function()
							{
								$("#Menu").css({"position":"relative"});
								$("#Mosaic").css({"position":"relative","top":0});
							},
		clickAround		: 	function()
							{
								cookieManager.dataObj.around = document.getElementById("AroundName").value;
								cookieManager.saveData();
								PageManager.setPage([{type:"around",name:cookieManager.dataObj.around}]);
							},
		clickList		: 	function()
							{
								if(ListManager.dataObj.select>-1)
									PageManager.setPage([{type:'HomeList',index:ListManager.dataObj.select}]);
							},						
		clickTag		: 	function()
							{
								var _tag = document.getElementById("TagInput").value;
								if(!_tag)return;
								
								PageManager.setPage([{name:Header.nowName,tag:_tag}],"Blog");
							},
		clickTagA		: 	function (args) 
							{
								var _tag = this.T9.tag || $(this).text();
								PageManager.setPage([{name:this.T9.name,tag:_tag}],"Blog");
								document.getElementById("TagInput").value = _tag;
								$("#tag>a+div").hide();
								return false;
							},
		popupTip		: 	function(_text)
							{
								if(_text)$("#tip").text(_text);
								
								$("#Home").addClass("tip");
								$("#tip")
									.css({left : $("#Home").offset().left+($("#Home").width()-$("#tip").width())/2-6})
									.show()
									.fadeOut(4000,function(){$("#Home").removeClass("tip")});
							},
		clear			: 	function()
							{
								$(".SimilarTumblr>a").remove();
								$(".SimilarTumblr>div").hide();
							},
		init			: 	function()
							{
								$("#HomeAround").hover(function ()
								{
									document.getElementById("AroundName").value = cookieManager.dataObj.around;
									 $("#HomeAround>a+ul").fadeIn("fast");
								},function ()
								{
								   $("#HomeAround>a+ul").fadeOut("fast");
								});
								
								$("#list").hover(function ()
								{
									
									
									ListManager.load();
									ListManager.refreshPullDown();
									ListManager.selectStyle(ListManager.dataObj.select);
									
									$("#list>a + ul").fadeIn("fast");
								},function ()
								{
									$("#list>a + ul").fadeOut("fast");
								});
								
								$("#tag").hover(function ()
								{
									var l = $("#TagCloud a").length;
									
									if(100>l&&l>10){$("#TagCloud").width(300);}
									else if(l>100){$("#TagCloud").width($(CONST.BODY).width()-640)}
									
									 $("#tag>a+div").fadeIn("fast");
									 $("#TagInput").focus();
								},function (e)
								{
									
									if($("#Thumbnail9").is(":visible"))return;					
									$("#tag>a+div").fadeOut("fast");
								});
								
								(function(_id)
								{
									if(!OAuthManager.available()){_id = setTimeout(arguments.callee, 1000)}
									else
									{
										clearTimeout(_id);
										Menu.getUserInfo();
									};
								})();
							}
	}
	Menu.init();
	
	var mouseX = 0;
	var mouseY = 0;
	$("html").mousemove(function(e){mouseX = e.pageX;mouseY = e.pageY;});	
	
	var Thumbnail9 = 
	{
		createHref	: 	function(_name,_tag)
						{
							
							var _type = _tag	?	"/#"+_tag
												:	PageManager.nowPage!="Blog" || PageManager.nowType=="tag" || PageManager.nowType=="newest"
												?	"" : "/"+PageManager.nowType;
												
							return CONST.BASE_URL+"#!/"+_name+_type;
						},
		createElemA	: 	function(_name,_tag,_callBack)
						{
							 var a = document.createElement("a");
							 a.T9 =	{name:_name,tag:_tag,photos:[],callBack:_callBack};
							 a.href = this.createHref(_name,_tag);
							 
							 $(a).mouseover(Thumbnail9.mouseOver)
								.mousemove(Thumbnail9.mouseMove)
								.mouseout(Thumbnail9.mouseOut);
							
							return a;
						},
		getPhotos	: 	function()
						{
							var self = this;
							
							$("#Thumbnail9>div")
								.text(this.T9.name+(this.T9.tag ? "#"+this.T9.tag:""))
								.css("backgroundImage","url("+ApiUriFormat(this.T9.name)+"avatar/16)");
							
							$.getJSON
							(
								ApiUriFormat(this.T9.name)+"posts/photo?jsonp=?"
								,{api_key: CONST.KEY,limit:9,tag:this.T9.tag}
								,function(_json)
								{
									$("#Thumbnail9>img").remove();
									
									if(!_json.response.posts)
									{
										$(self).remove();
										self = null;
										return;
									}
									
									while(_json.response.posts.length)
									{
										var post = _json.response.posts.shift();
										var as = post.photos[0].alt_sizes;
										
										if(as)
										{
											var img = new Image();
											img.src = as[as.length-1].url;
											
											self.T9.photos.push(img);
											$("#Thumbnail9").append(img);
										}
									}
									
									if(self.T9.callBack)self.T9.callBack(_json,self);
									
									self = null;
								}
							);
						},						
		timeoutId	: 	null,
		mouseState	: 	false,
		mouseOver	: 	function()
						{
							Thumbnail9.mouseState = true;
							
							$("#Thumbnail9>img,#Thumbnail9>div>img").remove();
							$("#Thumbnail9").fadeIn("slow",function()
							{
								if(!Thumbnail9.mouseState)$(this).hide();
							})
							
							if(this.T9.photos.length)
							{
								$("#Thumbnail9>div")
									.text(this.T9.name+(this.T9.tag ? "#"+this.T9.tag:""))
									.css("backgroundImage","url("+ApiUriFormat(this.T9.name)+"avatar/16)");
								
								for(var i=0;i<this.T9.photos.length;i++)
								{
									$("#Thumbnail9").append(this.T9.photos[i]);
								}
								return;
							}
							
							
							Thumbnail9.timeoutId = Thumbnail9.getPhotos.applyTimeout(333,this);
						},
		mouseMove	:	function(e)
						{
							var bw = $("body").width();
							var hw = $("#Thumbnail9").width()/2;
							var _left = mouseX + hw > bw ?	bw - hw*2
														 :	mouseX - hw;
							
							$("#Thumbnail9").css({top:mouseY+20,left:_left});
						},	
		mouseOut	:	function()
						{
							Thumbnail9.mouseState = false;
							
							clearTimeout(Thumbnail9.timeoutId);
							
							$("#Thumbnail9").hide();
						}
	}
	
	var PageManager = 
	{
		nowPage		: 	"Home",
		nowType		: 	"dashboard",
		nowTag		: 	"",
		allClear	: 	function(_rs)
						{
							this.nowPage = 
							this.nowType = 
							this.nowTag = "";
										
							var VM	=	CONST.MOS_ELEM.VM;
							var ILC	=	VM.ILC;
							var ARC =	ILC.ARC;
							
							
							ILC.clear();
							VM.clear();
							ARC.clear();
							Menu.clear();
							
							TagManager.clear(_rs);
						},
		request		: 	function(_summary)
						{
							CONST.MOS_ELEM.VM.ILC.ARC.setRequestSummary(_summary);
						},
		setPage		: 	function(_requestSummary,_pageName,_option)
						{
							$("#Thumbnail9").hide();
							this.allClear(_requestSummary);
							
							switch(_pageName)
							{
								case "Blog"		:
									
									var _rs0 = _requestSummary[0];
									
									_requestSummary = _requestSummary || [{name:Header.nowName}];
									_rs0.name　=  _rs0.name || Header.nowName;
									if(!_rs0.type||_rs0.type=="250px")_rs0.type　=　"newest";
									if(_rs0.tag)
									{
										_rs0.type = "tag";
										this.nowTag = document.getElementById("TagInput").value = _rs0.tag;
										$("#tag>a+div").hide();
									}
									
									Menu.getBlogInfo(_rs0.name);
									Menu.setStyleUser(_rs0.name);
									Menu.selectedStyle(document.getElementById(_rs0.type));
									Header.selectedStyle(document.getElementById("HeaderInput"));
									Header.form.tumblrName.value = _rs0.name;
									
									$("#HeaderInput>input").css({color:"#333"});
									
									this.nowPage = _pageName;
									this.nowType = _rs0.type;
									Header.nowName = _rs0.name;
									
									this.request(_requestSummary);
									
									document.title = _rs0.name + (_rs0.tag ? "/#"+_rs0.tag : "")+" - TUMBLR MOSAIC VIEWER";
									break;
									
								case "PermaList"		:
									
									Menu.setStyleList();
									$("#ListInfo>div>img").remove();
									$("#ListInfo>div").removeClass("size9");
									
									for(var i=0;i<_requestSummary.length&&i<9;i++)
									{
										var img = new Image();
										img.src = 2>_requestSummary.length	?	ApiUriFormat(_requestSummary[i].name)+"avatar/96"
																			:	5>_requestSummary.length	?	ApiUriFormat(_requestSummary[i].name)+"avatar/48"
																											:	ApiUriFormat(_requestSummary[i].name)+"avatar/30";
										$("#ListInfo>div").append(img);
									}
									
									
									if(_requestSummary.length==2){$("#ListInfo>div>img").eq(1).css({position:"absolute",right:0,bottom:0})}
									else if(_requestSummary.length>4){$("#ListInfo>div").addClass("size9")};
									
									this.nowPage = _pageName;
									this.request(_requestSummary);
									
									$("#ListInfo>h1").text(_option || _requestSummary.length + "user List");
									document.title = $("#ListInfo>h1").text()+" - TUMBLR MOSAIC VIEWER / List";
									break;
									
								default 		: 
								
									cookieManager.dataObj.summary = _requestSummary;
									cookieManager.saveData();
																		
									Menu.setStyleHome();
									
									var id = _requestSummary[0].type;
									
									if("around"==id)
									{
										id = "HomeAround";
										$("#HomeAround ul>li").css("backgroundImage","url("+ApiUriFormat(_requestSummary[0].name)+"avatar/24)");
									}
									else if("HomeList"==id)
									{
										id = "list";
										ListManager.selectStyle(_requestSummary[0].index);
										
										_requestSummary = ListManager.dataObj.lists[_requestSummary[0].index].list.slice();
										
										location.hash = "";
									}
									
									
									
									Menu.selectedStyle(document.getElementById(id));
									Header.selectedStyle(document.getElementById("Home"));
									
									if(!_requestSummary.length)return;
									this.nowPage = "Home";
									this.nowType = _requestSummary[0].type;
																		
									this.request(_requestSummary);
									
									document.title = "TUMBLR MOSAIC VIEWER";
									break;
							}
							
							CONST.MOS_ELEM.VM.setLoadingImage();
						}
	}
	
	function Tag(_tagName,_blogName)
	{
		this.name = _tagName;
		this.blogName = _blogName;
	}
	
	var TagManager = 
	{
		oldUserName	: 	"",
		userTags	: 	[],
		getJsonIndex: 	0,
		setUserTag	: 	function(_tagName,_blogName)
						{
							for(var i=0;i<this.userTags.length;i++)
							{
								
								if(this.userTags[i].name==_tagName && this.userTags[i].blogName==_blogName)return;
							}
							
							this.userTags.push(new Tag(_tagName,_blogName));
							
							var a = Thumbnail9.createElemA(_blogName,_tagName,TagManager.T9Callback);
							$(a).append(_tagName);
							$("#TagCloud").append(a).show();
							
							$("#tag>a>span").text(" ("+this.userTags.length+")");
						},
		setTagCount	: 	function()
						{
							var tag = this.userTags[this.getJsonIndex];
							if(!tag || this.getJsonIndex>50)return;
							
							var _selfIndex = this.getJsonIndex;
							this.getJsonIndex++;
							
							if($("#TagCloud a").eq(_selfIndex).hasClass("attached"))return;
							
							$.getJSON
							(
								ApiUriFormat(tag.blogName)+"posts/photo?jsonp=?"
								,{api_key: CONST.KEY,limit:1,tag:tag.name}
								,function(_json)
								{
									TagManager.setTotal($("#TagCloud a").eq(_selfIndex),_json.response.total_posts);
								}
							);
						},
		T9Callback	: 	function(_json,_elem)
						{
							TagManager.setTotal($(_elem),_json.response.total_posts);
						},
		setTotal	: 	function(_target$,_tp)
						{
							if(_target$.hasClass("attached")||!_tp)return;
							
							_target$.append("["+_tp+"]");
								
							if(40>_tp&&_tp>9){_target$.addClass("lv_1 attached")}
							else if(100>_tp){_target$.addClass("lv_2 attached")}
							else if(200>_tp){_target$.addClass("lv_3 attached")}
							else if(500>_tp){_target$.addClass("lv_4 attached")}
							else {_target$.addClass("lv_5 attached")};
						},
		clear		: 	function(_rs)
						{
							if(this.oldUserName==_rs[0].name)return;
							this.oldUserName = _rs[0].name;
							
							this.getJsonIndex = 0;
							this.userTags = null;
							this.userTags = [];
							
							document.getElementById("TagInput").value = "";
							
							$("#TagCloud a").remove();
							$("#TagCloud").width("auto").hide();
							$("#tag>a>span").text("");
						},
		loop		:	function()
						{
							if(PageManager.nowPage=="Blog")TagManager.setTagCount();
							
							setTimeout(arguments.callee, 1450);
						}
	}
	TagManager.loop();
	
	function BannerList(_targetElem,_title,_splitNum,_onClick)
	{
		this.length = 0;			
		
		this.elem = _targetElem;
		this.splitNum = _splitNum || 24;		
		this.title = _title;					
		this.bannerClick = _onClick;			
		
		this.appendTargetElem = this.elem;		
		$(this.elem).addClass("bannerList");	
	}
	
	BannerList.prototype.appendBanner = function(_name)
	{
		if(!_name)return null;
		
		var a = document.createElement("a");
		a.appendChild(document.createTextNode(_name));
		a.style.backgroundImage = "url("+ApiUriFormat(_name)+"avatar/48)";
		a.tumblrName = _name;	
		
		this.bannerClick ? a.onclick = this.bannerClick : null;
		a.href = Thumbnail9.createHref(_name);
		a.onmouseover = this.bannerMouseOver;
		a.onmouseout = this.bannerMouseOut;
		
		if(this.splitNum && 0==this.length%this.splitNum)
		{
			this.appendTargetElem = document.createElement("div");
			$(this.appendTargetElem).addClass("bannerListBlock");
			
			this.elem.appendChild(this.appendTargetElem);
		}
		
		this.appendTargetElem.appendChild(a);
		
		this.length++;
		
		return a;
	}
	BannerList.prototype.bannerMouseOut = function(e)
	{
		if(Header.nowName == Header.form.tumblrName.value)return;
		Header.form.tumblrName.value = Header.tmpName;
	}
	
	BannerList.prototype.bannerMouseOver = function(e)
	{
		
		Header.tmpName = Header.form.tumblrName.value;
		Header.form.tumblrName.value = this.tumblrName;
		
		if(this.childNodes.length>1)return;
		
		var _self = this;
		
		var loading = new Image();
		loading.src = "./images/ajax-loader_16.gif";
		loading.style.top = "4px";
		loading.style.left = "52px";
		_self.appendChild(loading);
		
		$.getJSON
		(
			ApiUriFormat(_self.tumblrName)+"posts/photo?jsonp=?"
			,{
				api_key	: CONST.KEY,
				offset	: 0,
				limit	: 10
			}
			,function(_obj)
			{
				_self.removeChild(loading);
				loading = null;
				
				if(_obj.meta.status!=200)
				{
					_self.parentNode.removeChild(_self);
					img = _obj =_self = null;
					return;
				}
				
				for(var i=0;i<_obj.response.posts.length;i++)
				{
					var alt_sizes = _obj.response.posts[i].photos[0].alt_sizes;
					var img = new Image();
					img.src = alt_sizes[alt_sizes.length-1].url;//一番下の75のサイズ
					img.style.width = 
					img.style.height = "24px";
					img.style.top = 5>i	?	0	:	"24px";
					img.style.left =5>i	? i*24 + 48+ "px"	:	(i-5)*24 + 48 + "px";
					
					_self.appendChild(img);
				}
				_self.title =  _obj.response.blog.title || "";
				
				
				if(!_obj.response.posts.length)
					_self.parentNode.removeChild(_self);
					
				img = _obj =_self = null;
			}
		)
	}
	
	BannerList.prototype.clear = function()
	{
		while(this.elem.childNodes.length)this.elem.removeChild(this.elem.childNodes[0]);
		this.length = 0;
	}
	
	function ApiReadController(_RequestSummary,_BannerList)
	{
		this.min = 160;					
		this.objectList = [];			
		this.BannerList = _BannerList;					
		this.RequestSummary = 			
		this.onlyRequest = 				
		this.multiRequest = 			
		this.getObj = null;				
		this.offset = 0;				
		
		this.allUser = [];				
		this.allUserLengthBefor;		
		this.userPointer = 0;			
		
		if(_RequestSummary)
			this.setRequestSummary(_RequestSummary);
		
		this.loop();
		this.loop2();
	}
	
	ApiReadController.prototype.clear = function()
	{
		this.RequestSummary = 
		this.onlyRequest = 
		this.multiRequest =
		this.getObj = 
		this.allUser = 
		this.objectList = null;
		
		this.objectList = [];
		this.allUser = [];
		this.offset = 
		this.userPointer = 0;
	}
	
	ApiReadController.prototype.getObj = function(){};
	
	ApiReadController.prototype.setRequestSummary = function(_RequestSummary)
	{
		
		
		this.RequestSummary =
		this.onlyRequest = 
		this.multiRequest = null;
		delete this.onlyRequest;
		
		if(_RequestSummary.length==1)
		{
			switch(_RequestSummary[0].type)
			{
				case	"around"	:
					this.RequestSummary = _RequestSummary;
					this.allUser.push({name:_RequestSummary[0].name,value:1});
					this.getObj = this.getAroundObj;	
					
					break;
					
				case	"dashboard"	:
					this.RequestSummary = _RequestSummary;
					this.offset = 0;
					this.getObj = this.getDashboardObj;				
					break;
					
				case	"likes"		:
					this.RequestSummary = _RequestSummary;
					this.offset = 0;
					this.getObj = this.getLikesObj;
					break;
					
				case	"list"		:
					this.setRequestSummary(hoge);
					break;															
				
				default				:
					this.RequestSummary = _RequestSummary;
					
					this.onlyRequest = new ApiReadRequest(_RequestSummary[0],this);
					this.getObj = function(){this.onlyRequest.getNext()};						
					break;
			}
		}
		else
		{
			this.RequestSummary = _RequestSummary;
			this.multiRequest = [];
			this.getObj = this.getMultiObj;	
			
			for(var i=0;i<this.RequestSummary.length;i++)
			{
				this.multiRequest.push(new ApiReadRequest(_RequestSummary[i],this));
			}
			
			return;
			for(var i=0,l=this.multiRequest.length;i<l*3;i++)
			{
				var r0 = Math.floor(Math.random()*l);
				var r1 = Math.floor(Math.random()*l);
				var tmp = this.multiRequest[r0];
				this.multiRequest[r0] = this.multiRequest[r1];
				this.multiRequest[r1] = tmp;
			};
		}
	}
	
	ApiReadController.prototype.setObjectList = function(_json)
	{
		
		
		var posts = _json.response.posts || _json.response.liked_posts;
		
		if(!posts||!posts.length)return;
		
		this.objectList = this.objectList.concat(posts);
	}
	
	ApiReadController.prototype.getDashboardObj = function()
	{
		if(!OAuthManager.available() || this.offset>250)return;
		
		OAuthManager.request
		({
			oauthToken		: 	cookieManager.AT,
			oauthTokenSecret: 	cookieManager.ATS,
			type			:　	"GET",
			url				: 	"http://api.tumblr.com/v2/user/dashboard",
			params			: 	{type:"photo",offset:this.offset},//,notes_info:true
			callBack		:	"CONST.MOS_ELEM.VM.ILC.ARC.setObjectList",
			test			: 	CONST.TEST
		});
		
		this.offset+=20;
	}
	
	ApiReadController.prototype.getLikesObj = function()
	{
		if(!OAuthManager.available() || this.offset>1000)return;
		
		OAuthManager.request
		({
			oauthToken		: 	cookieManager.AT,
			oauthTokenSecret: 	cookieManager.ATS,
			type			:　	"GET",
			url				: 	"http://api.tumblr.com/v2/user/likes",
			params			: 	{type:"photo",offset:this.offset},
			callBack		:	"CONST.MOS_ELEM.VM.ILC.ARC.setObjectList",
			test			: 	CONST.TEST
		});
		
		this.offset+=20;		
	}
	
	ApiReadController.prototype.getAroundObj = function()
	{
		var _name = this.getNextUserId();
		
		if(!_name)return;
		
		$.getJSON
		(
			ApiUriFormat(_name)+"posts/photo?jsonp=?"
			,{
				api_key	: CONST.KEY,
			}
			,function(_json)
			{
				
				CONST.MOS_ELEM.VM.ILC.ARC.setObjectList(_json);
			}
		);
	}
	
	ApiReadController.prototype.getMultiObj = function()
	{
		
		if(!this.multiRequest.length){return;}
		
		var targetRequest = this.multiRequest.shift();//先頭のRequestを取り出す
		targetRequest.getNext();
		
		//まだロードできるなら配列のいちばんうしろへ再度追加
		if(!targetRequest.ListCompleted)this.multiRequest.push(targetRequest);
	}
	
	ApiReadController.prototype.addUser = function(_name)
	{
		if(!_name)return;
		
		
		for(var i=0,l=this.allUser.length;i<l;i++)
		{
			if(this.allUser[i].name==_name)
			{
				this.allUser[i].value++;
				return;
			}
		}
		
		this.allUser.push({name:_name,value:1});
	}
	
	ApiReadController.prototype.getNextUserId = function()
	{
		var r = false;
		if(this.userPointer >= this.allUser.length)return r;	
		
		if(this.allUser[this.userPointer])
		{
			var r = this.allUser[this.userPointer].name;
			this.userPointer++;
		}
		
		return r;
	}
	
	ApiReadController.prototype.attachHighRankUser = function(_array)
	{
		var links = this.BannerList.elem.getElementsByTagName("a");
		var backupImgs = {};
		
		for(var i=0;i<links.length;i++)
		{
			if(links[i].getElementsByTagName("img"))
				backupImgs[links[i].tumblrName] = links[i].innerHTML;
		}
		
		
		this.BannerList.clear();
		
		for(var i=0;i<144&&i<_array.length;i++)
		{
			var name = _array[i].name;
			var newLink = this.BannerList.appendBanner(name);
			
			if(backupImgs[name])
			{
				newLink.innerHTML = backupImgs[name];
				backupImgs[name] = null;
			}
		}
		
		_array = links = backupImgs = null;
	}
	
	ApiReadController.prototype.loop = function()
	{
		if(this.min > this.objectList.length && this.getObj)　this.getObj();
		arguments.callee.applyTimeout(990,this);	
	}
	
	ApiReadController.prototype.loop2 = function()
	{
		if (this.allUserLengthBefor != this.allUser.length) 
		{
			this.allUserLengthBefor = this.allUser.length;
			
			var tmp = this.allUser.slice();
			tmp.sort(function(a, b){return b.value - a.value});
			this.attachHighRankUser(tmp);
			Menu.attachAvatars(tmp.slice(0,30));
			tmp = null;
		}
		
		arguments.callee.applyTimeout(3100,this);
	}
	
	;/★★★どうも、503エラーがあった場合、無限リクエストが発生する可能性がある？再現が難しいので取りあえずtry catch付けた。あとで要調査！！★★★/
	function ApiReadRequest(_Summary,_ApiReadController)
	{
		this.ARC = _ApiReadController;
		this.ListCompleted = false;
		
		this.total = 0;		
		this.offset = _Summary.offset || 0;	
		this.limit = _Summary.limit	|| 20;			
		this.name = _Summary.name;
		this.type = _Summary.type;
		this.tag = _Summary.tag || "";
		
		this.randomStart = null;	
		this.oldestStart = 0;		
		
		
		this.getNext	=	this.type=="random"	?	this.getNextRandomFirst
						:	this.type=="oldest"	?	this.getNextOldestFirst
						:	this.getNextList;
	}
	
	ApiReadRequest.prototype.getNext = function(){};
	
	ApiReadRequest.prototype.getNextList = function()
	{try{
			
		if(this.ListCompleted){}
		if(this.offset+this.limit>=this.total　&& this.total>0)this.ListCompleted = true;
		
		this.request(	this,
						ApiUriFormat(this.name)+"posts/photo?jsonp=?",
						{
							api_key	: CONST.KEY,
							offset	: this.offset,
							limit	: this.limit,
							tag		: this.tag
						});
							
		this.offset += this.limit;
		
		}catch(e){}
	}
	
	ApiReadRequest.prototype.getNextRandomFirst = function()
	{
		var _self = this;
		
		$.getJSON
		(
			ApiUriFormat(_self.name)+"posts/photo?jsonp=?"
			,{
				api_key	: CONST.KEY,
				offset	: 0,
				limit	: 1
			}
			,function(_json)
			{
				_self.total = _json.response.total_posts;
				_self.randomStart = [];
				
				var l = parseInt(_self.total / _self.limit);
				l = l > 1500	?	1500	:	l;
				
				for(var i=0;i<l;i++)_self.randomStart[i] = i*_self.limit;
				
				for(i=0;i<l*3;i++)
				{
					var r0 = Math.floor(Math.random()*l);
					var r1 = Math.floor(Math.random()*l);
					var tmp = _self.randomStart[r0];
					_self.randomStart[r0] = _self.randomStart[r1];
					_self.randomStart[r1] = tmp;
				};
				
				_self.getNext = _self.getNextRandom;
				_self.getNext();					
			}
		)
	}
	
	ApiReadRequest.prototype.getNextRandom = function()
	{
		
		
		if(this.ListCompleted){}
		
		
		
		this.request(	this,
						ApiUriFormat(this.name)+"posts/photo?jsonp=?",
						{
							api_key	: CONST.KEY,
							offset	: this.randomStart.shift(),
							limit	: this.limit
						});
						
		if(!this.randomStart.length)this.ListCompleted = true;						
	}
	
	ApiReadRequest.prototype.getNextOldestFirst = function () 
	{
		
		
		var _self = this;
		
		$.getJSON
		(
			ApiUriFormat(_self.name)+"posts/photo?jsonp=?"
			,{
				api_key	: CONST.KEY,
				offset	: 0,
				limit	: 1
			}
			,function(_json)
			{
				_self.total = _json.response.total_posts;
				_self.oldestStart = _self.total - _self.limit;				
				_self.getNext = _self.getNextOldest;
				_self.getNext();					
			}
		)
	}
	
	ApiReadRequest.prototype.getNextOldest = function()
	{
		
		if(this.ListCompleted){}
		
		this.request(	this,
						ApiUriFormat(this.name)+"posts/photo?jsonp=?",
						{
							api_key	: CONST.KEY,
							offset	: this.oldestStart,
							limit	: this.limit
						});
						
		this.oldestStart-=this.limit;
		
		if(0>=this.oldestStart)this.ListCompleted = true;
	}
	
	ApiReadRequest.prototype.callBack = function(_json)
	{
		try
		{
			
	
			if(!_json.response.posts)return;
			
			this.ARC.setObjectList(_json);
			this.total = _json.response.total_posts;
		
		}catch(e){}
	}	
	
	ApiReadRequest.prototype.request = function(_self,_uri,_params)
	{
		
		
		
		$.getJSON
		(
			_uri
			,_params
			,function(_json){_self.callBack(_json)}
		);
	}
	
	function ApplyObj()
	{
		this.baseImg =
		this.zoomImg = 
		this.doubleSize =  
		this.name = 
		this.post_url = 
		this.id = 
		this.reblog_key = 
		this.tags = 
		this.note_count = 
		this.source_url = 
		this.source_title = null;
	}
	
	function ImageLoadController(_ApiReadController)
	{
		this.min = 80;			
		this.ARC = _ApiReadController;
		this.imagesList = [];
		this.total = 0;			
		this.notesAverage = 10;	
		this.cellSize = parseInt(cookieManager.dataObj.size);
		this.doubleSize = this.cellSize == 100 ? 250 : 500;	
		this.zoomSize = cookieManager.dataObj.highRes	?	1280	:	500;
		
		this.loop();
	}
	
	ImageLoadController.prototype.getTumblrId = function(a)
	{
		if (!a) return;
		
		var arr = a.match(/http:\/\/[\w|-]+\.tumblr\.com/g);
		if (!arr) return;
		
		arr = arr.toString();
		arr = arr.replace(/http:\/\//g, "");
		arr = arr.replace(/.tumblr\.com/g, "");
		arr = arr.replace(/media|data|www/g, "");
		arr = arr.split(",");
		
		return arr;
	}
	
	ImageLoadController.prototype.filterCaption =function(c)
	{
		var tmp = document.createElement("div");
		tmp.innerHTML = c;
		tmp = tmp.getElementsByTagName("a");
		if(!tmp.length){return "no title";}
		tmp = tmp[tmp.length-1];
		if(!tmp.firstChild){return "no title";}
		tmp = tmp.firstChild.nodeValue;
		return tmp;
	}
	
	ImageLoadController.prototype.setImagesList = function(_post,_dsEnable)
	{
		var onceCheck = true;
		
		while(_post.photos.length)
		{
			var applyObj = new ApplyObj();
			var getWidth = this.cellSize;
			var photos = _post.photos.shift();
			var images = photos.alt_sizes;
			images.unshift(photos.original_size);

			if(onceCheck && _dsEnable && _post.note_count > 99)
			{
				getWidth = this.doubleSize;
				
				applyObj.doubleSize = true;
				onceCheck = false;
			}
			
			for(var i=0;i<images.length;i++)
			{
				if(!applyObj.zoomImg && (this.zoomSize==images[i].width || this.zoomSize > images[i].width))
					applyObj.zoomImg = images[i];
				
				if(images[i].width>0 && (getWidth==images[i].width || getWidth > images[i].width))
				{
					applyObj.baseImg = images[i];
					break;
				}
			}
			
			//applyObj.zoomImg = as[0].width>this.zoomImageSize ? as[1] : as[0];
			applyObj.name  = _post.blog_name;
			applyObj.post_url = _post.post_url;
			applyObj.id = _post.id;
			applyObj.reblog_key = _post.reblog_key;
			applyObj.tags = _post.tags;
			applyObj.note_count = _post.note_count;
			applyObj.source_url = _post.source_url;
			applyObj.source_title = _post.source_title;
			applyObj.caption = _post.caption;
			
			var img = new Image();
			img.applyObj = applyObj;
			img.src = applyObj.baseImg.url;
			
			img.ILC = this;
			img.onload = function()
			{
				if(!this.applyObj.zoomImg.height)
				{
					this.applyObj.zoomImg.width = 500;
					this.applyObj.zoomImg.height = this.height * 500 / this.width;
				}
				
				this.ILC.imagesList.push(this);
				
				img = this.ILC = this.onload = arguments.callee = null;
			}
			
			
			if(PageManager.nowPage=="Blog" && 1000>$("#TagCloud>a").length)
			{
				while(_post.tags.length)
				{
					TagManager.setUserTag(_post.tags.shift(),_post.blog_name);
				}
			}
		}
		
		var names = this.getTumblrId(_post.caption + _post.link_url);	
		if(names) while(names.length)this.ARC.addUser(names.shift());	
		
		if(_post.notes)while(_post.notes.length)
			this.ARC.addUser(_post.notes.shift().blog_name);			
		
	}
	
	ImageLoadController.prototype.loadImages = function()
	{
		while(this.min > this.imagesList.length && this.ARC.objectList.length)
		{
			var posts = [];
			var c = 20;
			
			while(c>0 && this.ARC.objectList.length)
			{
				posts.push(this.ARC.objectList.shift());
				c--;
			}
			
			posts.sort(function(a,b)
			{
				a.note_count = a.note_count || 0;
				b.note_count = b.note_count || 0;
				return a.note_count - b.note_count;
			});
			
			while(posts.length)
			{
				var post = posts.shift();
				var dsEnable = !posts.length;
				
				
				if(post.type == "photo")
					this.setImagesList(post,dsEnable);
			}
		}
		
		
		if(c==0 && this.ARC.allUser.length==1 && this.ARC.RequestSummary[0].type =="around")
		{
			
			$.getJSON
			(
				ApiUriFormat(this.ARC.allUser[0].name)+"posts/photo?jsonp=?"
				,{
					api_key	: CONST.KEY,
					limit:10,
					offset:20 + parseInt(Math.random()*100),
					notes_info:true
				}
				,function(_json)
				{
					
					CONST.MOS_ELEM.VM.ILC.ARC.objectList = CONST.MOS_ELEM.VM.ILC.ARC.objectList.concat(_json.response.posts);
				}
			);
		}
	}
	
	ImageLoadController.prototype.clear = function()
	{
		this.imagesList = null;
		this.imagesList = [];
	}
	
	ImageLoadController.prototype.loop = function()
	{
		if(this.min > this.imagesList.length) this.loadImages();
		
		arguments.callee.applyTimeout(2300,this);	
	}
	
	
	var ImageZoomer =
	{
		frameW		: 	6,
		target		: 	null,
		likeThis	: 	function()
						{
							CONST.MOS_ELEM.VM.likeThis(this.target);
						},
		reblogThis	: 	function()
						{
							CONST.MOS_ELEM.VM.reblogThis(this.target);
						},
		open		:	function(_img)
						{
							this.target = _img;
							
							document.getElementById("ThumbImage").src = _img.src;
							
							this.setZoomImg(_img.applyObj.zoomImg);
							
							$("#ZoomInfo>a").remove();
							$("#ZoomInfo").prepend(Thumbnail9.createElemA(_img.applyObj.name))
							$("#ZoomInfo>a")
								.css({backgroundImage:"url("+ApiUriFormat(_img.applyObj.name)+"avatar/30)"})
								.attr({target:"_blank",title:"User mosaic"});
								
							$("#ZoomInfo>div").html(_img.applyObj.caption);
							$("#ZoomMenu>.Notes")
								.text(_img.applyObj.note_count + " notes")
								.attr("href",_img.applyObj.post_url);
							$("#ZoomMenu>.GoogleSearch").attr({href:"http://www.google.com/searchbyimage?image_url="+_img.applyObj.zoomImg.url,target:"_blank"});
							
							
							$("#ZoomImage").hide().attr({src:_img.applyObj.zoomImg.url});
							$("#ZoomLayer").show();
						},
		close		: 	function()
						{
							$("#ZoomLayer").hide();
							$("#ZoomImage").attr({src:"./images/CssSprite.png"});
						},
		setZoomImg	:	function (_zoomImg) 
						{
							
							
							var widthRate = ($(window).width()-20) / _zoomImg.width;
							var heightRate = ($(window).height()-20) / _zoomImg.height;
							var　rate = widthRate > heightRate	?	heightRate	: widthRate;
							rate = 1 > rate	? rate	:	1;
							
							$("#ThumbImage,#ZoomImage").width(_zoomImg.width*rate)
								.height(_zoomImg.height*rate)
								.css("top", ($(window).height() - _zoomImg.height*rate)/2-this.frameW)
								.css("left",($(window).width() - _zoomImg.width*rate)/2-this.frameW);
						},				
		prev		:	function()
						{
							ImageZoomer.open(document.getElementById("i_"+(ImageZoomer.target.applyObj.iCount-1)) || document.getElementById("i_"+(CONST.MOS_ELEM.VM.totalCount-1)));
						},
		next		:	function()
						{				
							ImageZoomer.open(document.getElementById("i_"+(ImageZoomer.target.applyObj.iCount+1)) || document.getElementById("i_0"));
						},
		onload		: 	function()
						{
							$("#ZoomImage").fadeIn();
						},
		resize		:	function()
						{
							document.getElementById("ZoomMenu").style.top = ($(window).height() - $("#ZoomMenu").height())/2 + "px";
						},
		init		:	function() 
						{
							document.getElementById("ZoomImage").onload = ImageZoomer.onload;
							
							
							$("#ThumbImage,#ZoomImage,#ZoomBG").click(this.close);
							
							
							$("#ZoomHover").hover(function ()
							{
								 $("#ZoomMenu").show();
							},function ()
							{
							    $("#ZoomMenu").fadeOut("fast");
							});
							
							this.resize();
						}
	}
	ImageZoomer.init();
	
	
	
	function ViewManager(_targetElem,_imageLoadController)
	{
		
		this.ILC = _imageLoadController;
		
		this.viewTarget = _targetElem;
		this.viewTarget.VM = this;			
		this.totalCount = 0;				
		this.bottomBlank = false;			
		
		this.cellSize = this.ILC.cellSize;				
		this.cellMargin = 1;				
		this.totalCellSize = this.cellSize + this.cellMargin;
		
		
		
		
		this.frameWidth = 6;
		this.htmlDummy = document.createElement("div");
		this.wrapperMenu = document.getElementById("WrapperMenu");
		this.wrapper = document.getElementById("Wrapper");
		this.wrapper.onclick = this.click;
		
		this.avatarIntervalId;
		this.scroll_end = false;
		
		$(this.viewTarget)
			.mouseover(this.wrap)
			.css({position:"relative",width:"100%"});		
				
		this.loop();
		this.loopSetRows();
	}
	
	ViewManager.prototype.loopSetRows = function()
	{		
		20>$(this.viewTarget).width()	?	arguments.callee.applyTimeout(100,this)
										: 	this.setRows();
	}
	
	ViewManager.prototype.wrap = function (e){this.VM.wrapImage(e.target)};
	
	ViewManager.prototype.setRows = function()
	{
		this.bottomCells=	[];
		this.cellPoints	=	[];
		this.putIndex	=	0;
		this.returnNum	=	Math.floor($(this.viewTarget).width()/this.totalCellSize);
		
		$(this.viewTarget).width()%this.totalCellSize/this.totalCellSize>0.8	?	this.returnNum++	:	null;
		
		this.returnNum = 5>this.returnNum ? 5 :this.returnNum;
		
		for(var i=0;i<this.returnNum;i++)
		{
			this.cellPoints[i] = {x:this.totalCellSize*i+this.cellMargin, y:this.cellMargin};
			this.bottomCells[i] = null;
		}
	}
	
	ViewManager.prototype.click = function() 
	{
	  ImageZoomer.open(this.firstChild);
	  
	  return false;
	}
	
	ViewManager.prototype.wrapImage = function(_target)
	{
		
		if(this.wrapper.firstChild == _target || _target.tagName != "IMG")return;
		
		
		if (this.wrapper.firstChild)this.unwrapImage(this.wrapper.firstChild);
		
		
		$(_target).css(
		{
			top				:	parseInt($(_target).css("top")) - this.frameWidth,
			left			:	parseInt($(_target).css("left")) - this.frameWidth,
			zIndex			:	1,
			padding			:	this.frameWidth	- 1,
			border			:	"solid 1px #F00",
			borderBottom	:	"none",
			backgroundImage	:	"url(./images/ichimatsu_f00.gif)"
		});
		
		if(!_target.title)
		{
			var t = $(this.htmlDummy).html(_target.applyObj.caption).text();
			t = t.replace(/\s/g," ");
			t = t.length>100	? 	t.slice(0,100)+"..." : t;
			
			_target.title = "[ "+(_target.applyObj.note_count||"?")+" notes ] "+t;
			$(_target).html(null);
		}
		
		this.wrapper.href = _target.applyObj.zoomImg.url;
		this.wrapper.appendChild(_target);
		
		
		$(this.wrapperMenu).css(
		{
			top		:	parseInt($(_target).css("top"))+ $(_target).height() + (this.frameWidth*2-1),
			left	:	parseInt($(_target).css("left")),
			width	: 	$(_target).width()+10,
			display	:	"block"
		});
		
		$(this.wrapperMenu).children(".SourceLink").attr("href",_target.applyObj.post_url);
		
		this.avatarIntervalId = setInterval(this.attachWrappAvatar,333);
	}
	
	ViewManager.prototype.unwrapImage = function(_target)
	{
		$(_target).css(
		{
			top				:	parseInt($(_target).css("top")) + this.frameWidth,
			left			:	parseInt($(_target).css("left")) + this.frameWidth,
			zIndex			:	0,
			padding			:	0,
			border			:	"none",
			backgroundImage	:	"none"
		});
		
		this.viewTarget.appendChild(_target);
		$(this.wrapperMenu).css({display : "none"});
		$("#WrapperMenu>.SourceLink").css({backgroundImage:"./images/CssSprite.png"});
		
		clearInterval(this.avatarIntervalId);
	}
	
	ViewManager.prototype.reblogThis = function(_target)
	{
		var target = _target || $("#Wrapper>img")[0];
		
		window.open("http://www.tumblr.com/reblog/"+target.applyObj.id+"/"+target.applyObj.reblog_key
		+"?redirect_to=http%3A%2F%2Ftmv.proto.jp%2FreblogClose.html","_blank","width=980,height="
		+$(window).height());
	}
	
	ViewManager.prototype.likeThis = function(_target)
	{
		if(!cookieManager.AT || !cookieManager.ATS)
		{
			OAuthManager.getToken();
			return;
		}
		
		var target = _target ||  $("#Wrapper>img")[0];
		
		$(".LikeThis").addClass("sending");
		
		$.post(	"./php/oauth/likePost.php",
		{
			"id"			: 	target.applyObj.id,
			"rk"			: 	target.applyObj.reblog_key,
			"at"			: 	cookieManager.AT,
			"atc"			: 	cookieManager.ATS,
		},
		CONST.MOS_ELEM.VM.likeResponse);
		
		
		CONST.MOS_ELEM.VM.likeIntervalId = setTimeout(CONST.MOS_ELEM.VM.likeResponse,10000,false);
	}
	ViewManager.prototype.likeIntervalId = null;
	ViewManager.prototype.likeResponse = function(_res)
	{
		clearTimeout(CONST.MOS_ELEM.VM.likeIntervalId);
		$(".LikeThis").removeClass("sending");
		
		if(!_res || JSON.parse(_res).meta.status != 200)
			alert("Like failed. Please try again later.");
	}
	
	ViewManager.prototype.attachWrappAvatar = function () 
	{
		clearInterval(CONST.MOS_ELEM.VM.avatarIntervalId);
		
		if(!$("#Wrapper>img")[0])return;
		
		var avUrl = "url("+ApiUriFormat($("#Wrapper>img")[0].applyObj.name)+"avatar/24)";
		if($("#WrapperMenu>.SourceLink").css("background-image")!=avUrl)
			$("#WrapperMenu>.SourceLink").css({backgroundImage:avUrl});
	}
		
	ViewManager.prototype.getMinPointIndex = function()
	{
		
		var minY = this.cellPoints[0].y;
		var r = 0;
		
		for(var i=1;i<this.cellPoints.length;i++)
		{
			if(minY - this.cellPoints[i].y > 0)
			{
				minY = this.cellPoints[i].y;
				r = i;
			}
		}
		return r;
	}
	
	ViewManager.prototype.getMinPointIndex2 = function () 
	{
	  
	  var diff=999;
	  var point=0;
	  
	  var doubleSizePoint = -1;
	  
	  for(var i=0;i<this.cellPoints.length-1;i++)
	  {
	 	var abs = Math.abs(this.cellPoints[i].y - this.cellPoints[i+1].y);
	 	
	 	if(diff>abs && abs>0)
	 	{
	 		
	 		diff = abs;
	 		point = i;
	 	}
	 	
	 	if(abs==0)doubleSizePoint = i;
	  }
	  
	  
	  if(diff>this.cellSize/2 && doubleSizePoint>-1)
	  	point = doubleSizePoint;
	  	
		return point;
	}
	
	ViewManager.prototype.smoothCellHeight = function (_index) 
	{
		var diff = this.cellPoints[_index].y - this.cellPoints[_index+1].y;
		
		if(!diff)return;
		
		if(0>diff)
		{
			$(this.bottomCells[_index+1]).height(this.bottomCells[_index+1].height + diff);
			
			this.cellPoints[_index+1].y = this.cellPoints[_index+1].y + diff;
			
			
			if(this.bottomCells[_index+1].applyObj.doubleSize)
				this.cellPoints[_index+2].y = this.cellPoints[_index+1].y;
		}
		else
		{
			$(this.bottomCells[_index]).height(this.bottomCells[_index].height - diff);
			this.cellPoints[_index].y = this.cellPoints[_index].y - diff;
			
			
			if(this.bottomCells[_index].applyObj.doubleSize)
				this.cellPoints[_index-1].y = this.cellPoints[_index].y;
		}
	}
	
	ViewManager.prototype.putCell = function(_img)
	{
		var imgWidth,imgHeight;
		
		if(_img.applyObj.doubleSize)
		{
			this.putIndex = this.getMinPointIndex2();
			this.smoothCellHeight(this.putIndex);
			
			imgWidth = this.cellSize*2 + this.cellMargin;
			imgHeight = Math.floor(imgWidth*_img.height/_img.width);
		}
		else
		{
			this.putIndex = this.getMinPointIndex();
			imgWidth = this.cellSize;
			imgHeight = this.cellSize > _img.width	?	Math.floor(imgWidth*_img.height/_img.width)	
													:	_img.height; 	
		}
		
		
		imgHeight = imgHeight > imgWidth*3 ? imgWidth*3 : imgHeight;
		
		$(_img)
		.css("position","absolute")
		.css("left",this.cellPoints[this.putIndex].x)
		.css("top",this.cellPoints[this.putIndex].y)
		.css("width",imgWidth)
		.css("height",imgHeight);
		
		
		if(_img.applyObj.doubleSize)
		{
			this.cellPoints[this.putIndex].y += $(_img).height() + this.cellMargin;
			this.cellPoints[this.putIndex+1].y = this.cellPoints[this.putIndex].y;
			
			this.bottomCells[this.putIndex] = _img;
			this.bottomCells[this.putIndex+1] = _img;
		}
		else
		{
			this.cellPoints[this.putIndex].y += $(_img).height() + this.cellMargin;
			this.bottomCells[this.putIndex] = _img;
		}
		
		
		_img.id = "i_" + this.totalCount;
		_img.applyObj.iCount = this.totalCount;
		this.totalCount++;
		
		$(_img).hide();
		this.viewTarget.appendChild(_img);
		
		$(_img).fadeIn(800);
		
		
		if(this.cellPoints[this.putIndex].y > $(this.viewTarget).height())
			$(this.viewTarget).height(this.cellPoints[this.putIndex].y);
	}
	
	ViewManager.prototype.setLoadingImage = function()
	{
		var offset = $(this.viewTarget).offset();
		
		$("body")
			.css({"backgroundPosition":offset.left+"px "+ offset.top+"px"})
			.delay(7000).animate({"backgroundPosition": 9000},0);
	}
	
	ViewManager.prototype.addBottomBlank = function () 
	{
		if(this.bottomBlank)return;
		this.bottomBlank = true;
		
		$(this.viewTarget).height($(this.viewTarget).height() + $(window).height()*0.5);
	}
	
	ViewManager.prototype.clear = function()
	{
		$(this.viewTarget).children("img").remove();
		$("#Wrapper>img").remove();
		$("#WrapperMenu").css("display","none");
			
		$(this.viewTarget).height(0);
		this.setRows();
		
		
		this.bottomBlank =false;
		Header.hidePopup();
	}
	
	ViewManager.prototype.loop = function()
	{
		if(this.scroll_end && this.ILC.imagesList.length) this.putCell(this.ILC.imagesList.shift());
		
		arguments.callee.applyTimeout(50,this);
	}
	
	var ListManager = 
	{
		encodeListUrl	: 	function(_target)
							{
								var a = [];
								
								for(var i=0;i<_target.list.length;i++)
								{
									var t = _target.list[i].tag	?	"#" + _target.list[i].tag
																:	_target.list[i].type=="random"	? 	"#r"
																									:	_target.list[i].type=="oldest"	? 	"#o"
																																		:	"";
									a.push(_target.list[i].name+t);
								}
								
								var imgSize = parseInt(cookieManager.dataObj.size) == 250	?	"/250px"	:	"";
								
								return CONST.BASE_URL + "#!/perma_list/" + a.join("+") + "/" + _target.title + imgSize;
							},
		refreshPullDown	: 	function()
							{
								var tmp = $("#list .CreateList");
								$("#list>ul>li").remove();
								for(var i=0;i<this.dataObj.lists.length;i++)
								{
									var clone = $("#Template>.row").clone();
									clone.children("a").text(this.dataObj.lists[i].title)
										.attr("href",this.encodeListUrl(this.dataObj.lists[i]));
									clone.children("a")[0].setAttribute("onclick","PageManager.setPage([{type:'HomeList',index:"+i+"}]);return false;");
										
									$("#list>ul").append(clone);
								}
								$("#list>ul").append(tmp);
							},
		selectStyle		: 	function(_index)
							{
								this.dataObj.select = _index;
								this.save();
								
								if(0>_index)return;
								
								$("#list .row a")
									.removeClass("selected")
									.eq(_index).addClass("selected");
							},
		inputTag		: 	function(_target)
							{
								var parent = $(_target).parent();
								var index = $("#ListContent>.ListContentLi").index(parent.parent()); 
								var tag = window.prompt("Input tag","");
								
								if(!tag)
								{
									
									if(!parent.children(".tag").text())parent.children("select")[0].value="newest";
									return;
								}
								parent.children(".tag").text("#"+tag);
							},
		changeName		: 	function(_target)
							{
								var oldName = $(_target).text();
								var name = window.prompt("Input tumblr name",$(_target).text());
								
								if(!name || oldName==name)return;
								
								$(_target).text(name);
								
								var index = $("#ListContent>.ListContentLi").index($(_target).parent().parent());
								this.setEditLiThumb($(_target).parent().parent()[0]);
							},
		changeType		: 	function(_target)
							{
								if(_target.value=="tag")
								{
									this.inputTag(_target);
								}
								else
								{
									var index = $("#ListContent>.ListContentLi").index($(_target).parent().parent());
									$(_target).parent().children(".tag").text("");							
								}
								this.setEditLiThumb($(_target).parent().parent()[0]);
							},
		selectIndex		: 	0,
		setEditLiThumb	: 	function(_elem)
							{
								var control = $(_elem).children(".control");
								var name = $(control).children(".name").text();
								var type = control.children("select")[0].value;
								var tag = control.children(".tag").text().replace("#","");
								$(control).children("img").attr({src : ApiUriFormat(name)+"avatar/32"});
								
								if(type!="oldest")
								{
									$.getJSON
									(
										ApiUriFormat(name)+"posts/photo?jsonp=?"
										,{api_key: CONST.KEY,limit:6,tag:tag}
										,function(_json)
										{
											$(_elem).children(".thumbnail").children("img").remove();
											
											while(_json.response.posts.length)
											{
												var post = _json.response.posts.shift();
												var as = post.photos[0].alt_sizes;
												if(as)
												{
													var img = new Image();
													img.src = as[as.length-1].url;
													$(_elem).children(".thumbnail").append(img);
												}
											}
											_json = _elem = null;
										}
									);
								}
								else
								{
									$.getJSON
									(
										ApiUriFormat(name)+"posts/photo?jsonp=?"
										,{api_key: CONST.KEY,limit:1}
										,function(_json)
										{
											$.getJSON
											(
												ApiUriFormat(name)+"posts/photo?jsonp=?"
												,{api_key: CONST.KEY,offset:_json.response.total_posts-6,limit:6}
												,function(_json)
												{
													$(_elem).children(".thumbnail").children("img").remove();
													while(_json.response.posts.length)
													{
														var post = _json.response.posts.shift();
														var as = post.photos[0].alt_sizes;
														if(as)
														{
															var img = new Image();
															img.src = as[as.length-1].url;
															$(_elem).children(".thumbnail").append(img);
														}
													}
													_json = _elem = null;
												}
											)
										}
									);
								}
							},
		appendLi		: 	function()
							{
								var _name = window.prompt("Input tumblr name","");
								
								if(!_name)return;
								
								this.setEditLi({name:_name});
							},
		removeLi		: 	function(_target)
							{
								if(window.confirm("Delete ["+$(_target).parent().children(".control").children(".name").text()+"] ?"))
								 	$(_target).parent().remove();
							},
		setEditLi		: 	function(_target)
							{
								var target = $("#Template>.ListContentLi").clone();
								target.children(".control").children(".name").text(_target.name);
								target.children(".control").children("select")[0].value=_target.type||"newest";
								target.children(".control").children(".tag").text(_target.tag ? "#"+_target.tag:"");
								$("#ListContent").append(target);
								
								this.setEditLiThumb(target);
							},
		appendListObj	: 	function()
							{
								this.load();
								
								var h = UrlHashManager.getHashToObj();
								this.dataObj.lists.push(new this.listObj(h[3],UrlHashManager.decodeSummary(h[2])));
								this.refresh();
								
								Menu.popupTip();	
							},
		newAppender		: 	function()
							{
								var _title = window.prompt("Input List title","");
								if(!_title)return;
								
								var _type = PageManager.nowType =="around" ? "newest" :	PageManager.nowType;
								
								ListManager.dataObj.lists.push(new ListManager.listObj(_title,[{name:Header.nowName,type:_type,tag:PageManager.nowTag}]));
								ListManager.refresh();
								ListManager.closeListLayer();
								
								Menu.popupTip();
							},
		selectAppender	: 	function(_index)
							{
								var _type = PageManager.nowType =="around" ? "newest" :	PageManager.nowType;
								
								this.load();
								
								this.dataObj.lists[_index].list.push({name:Header.nowName,type:_type,tag:PageManager.nowTag});
								this.refresh();
								this.closeListLayer();
								
								Menu.popupTip();
							},
		openAppender	: 	function()
							{
								this.load();
								this.refreshPullDown();
								
								$("#ListAppender").append($("#list .listUL").clone());
								$("#ListAppender .listUL")
									.css({top:mouseY+10,left:mouseX+10})
									.prepend("<li class='note'>Please select a list to add.</li>");
								
								$("#ListAppender .listUL>.row>button").remove();
								$("#ListAppender .listUL>.row>a")
									.removeClass("selected")
									.each(function(i){this.onclick=null;this.href="javascript:ListManager.selectAppender("+i+");";});
								$("#ListAppender .listUL>.CreateList>button")[0].onclick = this.newAppender;
								
								$("#ListEdit").hide();
								$("#ListAppender .listUL,#ListAppender,#ListLayer").show();
							},
		targetID		: 	null,					
		openEdit		: 	function(_target)
							{
								
								this.selectIndex = isNaN(_target) ? $("#list>ul>li").index($(_target).parent()) : _target;
								
								var target = this.dataObj.lists[this.selectIndex];
								this.targetID = target.id;
								
								$("#ListContent li").remove();
								$("#ListEdit input").val(target.title);
								
								for(var i=0;i<target.list.length;i++)
								{
									ListManager.setEditLi(target.list[i]);
								}
								
								var _top = ($(window).height()-$("#ListEdit").height())/2;
								_top = 0 > _top	?	0	:	_top;
								
								$("#ListAppender").hide();
								$("#ListEdit").css({top:_top}).show();
								$("#ListLayer").show();
								
								$("#ListEdit .permalink")
									.attr({href:encodeURIComponent(this.encodeListUrl(this.dataObj.lists[this.selectIndex]))})
									.hide();
								$("#ListEdit .tweetBtn").hide();
								$("#ListContent").removeClass("LetsClick");
								
								
								$("#ListContent").sortable({items: 'li',opacity: 0.6 });
						        $("#ListContent").disableSelection();
						       	$(".ListContentLi>.control>select").focus(function()
								{
									$("#ListContent").sortable("destroy");
								});
								$(".ListContentLi>.control>select").blur(function()
								{
									$("#ListContent").sortable({opacity: 0.6 });
								});
								
								this.editLoop();
							},
		closeListLayer	: 	function()
							{
								if($("#ListEdit").is(":visible"))ListManager.saveEdit();
								
								
								$("#ListContent").sortable("destroy");
								
								$("#ListAppender>ul").remove();
								$("#ListLayer").hide();
								
								clearTimeout(ListManager.timerID);
							},
		timerID			: 	null,
		editLoop		: 	function()
							{
								if(!$("#ListContent>li").length)
								{
									$("#ListContent").addClass("LetsClick");
									$("#ListEdit .permalink,#ListEdit .tweetBtn").hide();
								}
								else
								{
									$("#ListContent").removeClass("LetsClick");
									$("#ListEdit .permalink")
										.attr({href	: ListManager.encodeListUrl(ListManager.elemToList())})
										.show();
									$("#ListEdit .tweetBtn").show();
								}
								
								ListManager.timerID = setTimeout(arguments.callee, 1000);
							},
		tweet			: 	function()
							{
								var target = this.elemToList();
								var url = this.encodeListUrl(target);
								
								var openUrl = url == encodeURI(url)	?	"http://twitter.com/share?url=" + encodeURIComponent(url) + "&via=proto_jp&text="+encodeURIComponent(target.title)
																	: 	"./tweetBitly.html#" + url;
								
								window.open(openUrl,"_blank","width=550,height=420,scrollbars=1");
							},
		elemToList		:   function()
							{
								return	{
											title	:	$("#ListEdit input").val(),
											list	: 	$.makeArray($("#ListContent .control").map(function()
														{											
															return {name	:	$(this).children(".name").text()
																	,type	: 	$(this).children("select").val()
																	,tag	: 	$(this).children(".tag").text().replace("#","")};											
														})),
											id		: 	ListManager.targetID,
											dt		: 	"",
											tags	: 	[],
											pub		: 	true
										};
							},								
		saveEdit		: 	function()
							{
								this.dataObj.lists[this.selectIndex] = this.elemToList();
								this.refresh();
							},
		appendList		: 	function()
							{
								var _title = window.prompt("Input List title","");
								if(!_title)return;
								this.openEdit(this.dataObj.lists.push(new this.listObj(_title))-1);
								
								if(this.dataObj.lists.length==1)this.dataObj.select = 0;
								
								this.refresh();
							},
		removeList		: 	function()
							{
								
								
								var beforeLength = this.dataObj.lists.length;
								var beforeTitle = this.dataObj.lists[ListManager.selectIndex].title;
								
								if(window.confirm("Are you sure you want to delete this list?"))
								{
									this.load();
									
									if(beforeLength==this.dataObj.lists.length && beforeTitle==this.dataObj.lists[ListManager.selectIndex].title)
									{
										
										
										
										this.dataObj.lists = $.grep(this.dataObj.lists, function (o,i) 
										{
											return i != ListManager.selectIndex; 
										});
										
										
										
										if(!this.dataObj.lists.length)
										{
											cookieManager.dataObj.summary	=  (cookieManager.ATS&&CONST.ENABLE_FLASH)	
																			?	[{type:"dashboard"}]
																			:	[{type:"around",name:cookieManager.dataObj.around}];
																								
																								
											cookieManager.saveData();
											this.dataObj.select = -1;
										}
										else{this.dataObj.select = 0;}
									}
									
									this.refresh();
									$("#ListAppender>ul").remove();
									$("#ListLayer").hide();
									clearTimeout(ListManager.timerID);
								}
							},			
		refresh			: 	function()
							{
								this.save();
								this.load();
								
								this.refreshPullDown();
								this.selectStyle(this.dataObj.select);
							},
		save			:	function()
							{
								localStorage.setItem(this.hashKey, JSON.stringify(this.dataObj));
							},
		load			:	function()
							{
								this.dataObj = JSON.parse(localStorage.getItem(this.hashKey));
							},							
		listObj			: 	function(_title,_list,_dt)
							{
								this.title = _title;
								this.list = _list || [];
								
								this.id = +new Date();
								this.dt = _dt || "";	
								this.tags = [];
								this.pub = true;		
							},
		hashKey			:	"TmvProtoJp_List",
		dataObj			: 	null,
		dataObjClass	: 	{
								ver			: 	1,
								select		: 	-1,
								update		: 	"",
								lists		: 	[]
							},
		oldCheck		:	function()
							{
								if($.cookie("_tmvProtoJp_2") && !this.dataObj.lists.length)
								{
									var oldObj = JSON.parse($.cookie("_tmvProtoJp_2"));
									
									if(!(oldObj.favorite.lists.length==1 && oldObj.favorite.lists[0].list.length==1))
									{
										for (var i=0;i<oldObj.favorite.lists.length;i++)
										{
											var listObj = new this.listObj(oldObj.favorite.lists[i].name);
											
											
											
											for(var j=0;j<oldObj.favorite.lists[i].list.length;j++)
											{
												
												listObj.list.push({name:oldObj.favorite.lists[i].list[j].id,type:""});
											}
											
											this.dataObj.lists.push(listObj);
										}
									}
									
									
									
									this.dataObj.select = 0;
									this.save();
									$.cookie("_tmvProtoJp_2", null);
								}
							},
		init			:	function()
							{
								if(!localStorage)
								{
									$("#list").hide();
									return;
								}
								
								localStorage.getItem(this.hashKey)	?	this.load()
																	: 	this.dataObj = this.dataObjClass;
								this.oldCheck();
								this.refreshPullDown();
								this.selectStyle(this.dataObj.select);
								
								$("#ListLayerBG").click(ListManager.closeListLayer);
								
								
						}
	}
	ListManager.init();
	
	
	var UrlHashManager = 
	{
		setImageSize	: 	function(_size)
							{
								size = _size || parseInt(cookieManager.dataObj.size);
								
								CONST.MOS_ELEM.VM.cellSize = CONST.MOS_ELEM.VM.ILC.cellSize = size;
								CONST.MOS_ELEM.VM.totalCellSize = size + CONST.MOS_ELEM.VM.cellMargin;
								CONST.MOS_ELEM.VM.ILC.cellSize.doubleSize = size == 100 ? 250 : 500;
							},
		oldCheck		:	function()
							{
								var h = location.hash;
								if((h.indexOf("imageSize=250")>-1 || h.indexOf("tagged=")>-1 || h.indexOf("#id=")>-1))
								{
									h = h.replace("#id=","#!/");
									h = h.replace("imageSize=250","250px");
									h = h.replace("tagged=","#");
									
									location.href = CONST.BASE_URL+h;
									location.reload();
								}
							},
		decodeSummary	: 	function(_ListHashObj)
							{
								var a = _ListHashObj.split("+");
								
								for(var i=0;i<a.length;i++)
								{
									a[i] = a[i].split("#");
									
									a[i] = !a[i][1]	?	{name:a[i][0]}
													:	a[i][1]=="r"	? 	{name:a[i][0],type:"random"}
																		:	a[i][1]=="o"	? 	{name:a[i][0],type:"oldest"}
																							:	{name:a[i][0],tag:a[i][1]};
								}
								
								return a;
							},
		getHashToObj	:	function()
							{
								var r = [];
								if (location.hash) 
								{
									r = decodeURIComponent(location.hash).antiXSS().slice(1).split("/");
								}
								return r;
							},
		refreshPage		:	function()
							{

								
								
								this.beforeHash = location.hash;
								this.oldCheck();
								var hashObj = this.getHashToObj();
								
								if("!" == hashObj[0])
								{
									
									hashObj[hashObj.length-1]=="250px"	?	this.setImageSize(250)
																		: 	this.setImageSize();
									if("perma_list"==hashObj[1])
									{
										if(!hashObj[2])location.href = CONST.BASE_URL;
										PageManager.setPage(this.decodeSummary(hashObj[2]),"PermaList",hashObj[3]);
									}
									else
									{
										var _summary={}
										_summary.name = hashObj[1];
										hashObj[2] && hashObj[2].slice(0,1)=="#"	? 	_summary.tag = hashObj[2].slice(1)
																					: 	_summary.type = hashObj[2];
										PageManager.setPage([_summary],"Blog");	
									}
								}
								else
								{
									PageManager.setPage(cookieManager.dataObj.summary);
								}
								
								
							},
		beforeHash		:	location.hash,
		loop			:	function()
							{
								UrlHashManager.beforeHash != location.hash	?	UrlHashManager.refreshPage()	
																			:	UrlHashManager.beforeHash = location.hash;
								setTimeout(arguments.callee, 250);
							}
	}
	UrlHashManager.loop();
	
	new ViewManager(CONST.MOS_ELEM,	new ImageLoadController(new ApiReadController(null, Header.pickupList)));
	
	UrlHashManager.refreshPage();
	
	
	
	
	$(window).resize(ImageZoomer.resize);
	
	(function()
	{
		var scrollBottom = $(CONST.BODY).attr('scrollHeight') - $("html").attr('clientHeight') - $(CONST.BODY).scrollTop();
		
		CONST.MOS_ELEM.VM.scroll_end =	400 > scrollBottom	?	true	:	false;
		
		setTimeout(arguments.callee, 555);
	})();

