var onigiri = {};

onigiri.Const = {};
onigiri.Const.mainImagePath = "./images/";
onigiri.Const.loadImgFolderPath = "./images/loadimg/";

onigiri.CommonData = function(){
	this.currentItemNo = null;
	this.maxItemNum = null;
	//先読み
	this.loader = new Image();
	this.loader.src = onigiri.Const.mainImagePath + 'loading.gif';
}

onigiri.CommonData.instance = null;

onigiri.CommonData.getInstance = function(){
	if(onigiri.CommonData.instance == null){
		onigiri.CommonData.instance = new onigiri.CommonData();
	}
	return onigiri.CommonData.instance;
}

onigiri.Main = function(){
	this.commonData = onigiri.CommonData.getInstance();
	this.init();
	this.cover = new onigiri.Cover();
};

onigiri.Main.prototype = {
	init:function(){
		/*
		var self = this;
		var myimg = new Image();
		myimg.onload = function(){
		};
		myimg.src = './images/loadimg/sumnail.jpg' + "?" + (new Date()).getTime();
		*/
		//this.outputSumnailHTML();
		//this.outputSumnailCSS();
		
		this.registerEvent();
		$('#nowloading').fadeOut();
	},
	//ソース吐き出し用
	outputSumnailHTML:function(){
		var i,j;
		var addHTML = new Array();
		var currentNum;
		//var threeDegit;
		var fileName;
		var style1;
		var style2;
		for(i = 0; i < 10; i++){
			addHTML.push('<div class="onigiri_sumnail_column">');
			for(j = 0; j < 10; j++){
				currentNum = i * 10 + j + 1;
				//threeDegit = onigiri.Util.getTreeDegit(currentNum);
				if(currentNum <= this.commonData.maxItemNum){
					//addHTML.push('<div id="sum' + currentNum + '" class="onigiri_sumnail" style="background-position: ' + (-64 * j + 1) + 'px ' + (-64 * i - 639) + 'px;"><a href="javascript:void(0);" style="background-position:-' + 64 * j + 'px -' + 64 * i + 'px;">調理写真</a></div>');
					addHTML.push('<div id="sum' + currentNum + '" class="onigiri_sumnail"><a href="javascript:void(0);">調理写真</a></div>');
				}else{
					addHTML.push('<div class="onigiri_sumnail2"></div>');
				}
			}
			addHTML.push('</div>');
		}
		addHTML.push('</div>');
		$('#onigiri_body')
		.html(addHTML.join(''));
	},
	//ソース吐き出し用
	outputSumnailCSS:function(){
		var cssStr = new Array();
		var i,j;
		var currentNum;
		for(i = 0; i< 10; i++){
			for(j = 0; j < 10; j++){
				currentNum = i * 10 + j + 1;
				cssStr.push('#sum' + currentNum + '{background-position:' + (-64 * j + 1) + 'px ' + (-64 * i - 639) +'px;}#sum' + currentNum + ' a{background-position:-' + 64 * j + 'px -' + 64 * i + 'px;}');
			}
		}
		trace(cssStr.join(''));
	},
	registerEvent:function(){
		var i;
		var self = this;
		for(i = 100; i >= 0; i--){
			if(i >= this.commonData.maxItemNum){
				$('#sum' + (i + 1))
				.css('background-image', 'none')
				.html('');
			}else{
				break;
				/*
				$('#sum' + (i + 1))
				.bind("click", {no:(i + 1)}, function(e){
					self.commonData.currentItemNo = e.data.no;
					self.cover.show();
				})
				*/
			}
		}
		$('#onigiri_body').click(function(e){
			var n = e.target.parentNode;
			//サムネ画像だったら
			if(n.id != '' && n.id.indexOf('sum') != -1){
					self.commonData.currentItemNo = parseInt(n.id.substr(('sum').length));
					self.cover.show();
			}
		})
	},
	loadImage:function(imgobj, imgPath, rollOverPath, delayTime, callback){
		var myimg = new Image();
		myimg.onload = function(){ callback(imgobj, imgPath, rollOverPath, delayTime) };
		myimg.src = imgPath;
	}
}

onigiri.Cover = function(){
	this.commonData = onigiri.CommonData.getInstance();
	this.overlay =	new onigiri.LayerUtil('#onigiri_cover_area');
	this.username = $('#onigiri_cover_username');
	this.bodytext = $('#onigiri_cover_bodytext');
	this.image1 = $('#onigiri_cover_img1');
	this.image2 = $('#onigiri_cover_img2');
	this.image1loader = $('onigiri_cover_img1_loader');
	this.image2loader = $('onigiri_cover_img2_loader');
	this.textarea = $('#onigiri_cover_text_area');
	this.prevBtn = $('#onigiri_prev_btn img');
	this.nextBtn = $('#onigiri_next_btn img');
	this.closeBtn = $('#onigiri_close_btn img');
	this.userDatas = onigiri.UserDatas.getInstance();
	this.init();
};

onigiri.Cover.prototype = {
	init:function(){
		this.registerEvent();
	},
	registerEvent:function(){
		var self = this;
		this.prevBtn
		.mouseover(function(){												
				this.src = onigiri.Const.mainImagePath + "cover_prev_f2.gif";
		})
		.mouseout(function(){
				this.src = onigiri.Const.mainImagePath + "cover_prev.gif";
		})
		.click(function(){
				self.commonData.currentItemNo--;
				self.changeContent();
		});
		
		this.nextBtn
		.mouseover(function(){												
				this.src = onigiri.Const.mainImagePath + "cover_next_f2.gif";
		})
		.mouseout(function(){
				this.src = onigiri.Const.mainImagePath + "cover_next.gif";
		})
		.click(function(){
				self.commonData.currentItemNo++;
				self.changeContent();
		});
		
		this.closeBtn
		.mouseover(function(){												
				this.src = onigiri.Const.mainImagePath + "cover_close_f2.gif";
		})
		.mouseout(function(){
				this.src = onigiri.Const.mainImagePath + "cover_close.gif";
		})
		.click(function(){
			self.closeBtnClickHD();					
		});
	},
	closeBtnClickHD:function(){
		this.hide();
	},
	show:function(){
		this.overlay.setLayerVisible(true);
		this.changeContent();
	},
	hide:function(){
		this.overlay.setLayerVisible(false);
		this.username.text('');
		this.bodytext.text('');
	},
	changeContent:function(){
		var self = this;
		var currentItemNo = this.commonData.currentItemNo;
		var userData = this.userDatas.getData(currentItemNo);
		
		var folderPath = onigiri.Const.loadImgFolderPath;
		var path1 = folderPath + userData.degitNo + '_l1.jpg' + "?" + (new Date()).getTime();
		this.loadSizeLImage(path1, this.image1);
		var path2 = folderPath + userData.degitNo + '_l2.jpg' + "?" + (new Date()).getTime();
		this.loadSizeLImage(path2, this.image2);
		this.image1.hide();
		this.image1loader.show();
		this.image2.hide();
		this.image2loader.show();
		
		this.username.html(userData.name + '　さん　<span class="onigiri_font_normal">（' + userData.address + '）</span>');
		this.bodytext.text(userData.text);
		var textAreaHeight = $('#onigiri_cover_text_area_inner').height();
		this.textarea
		.stop()
		.css({'width':'0px'})
		.animate({
			'height':textAreaHeight + 'px'
		 },200, 'swing', function(){
			self.textarea.animate({
				'width':'541px'
			}, 500, 'swing');
		});

		this.setPrevNextVisible();
	},
	loadSizeLImage:function(path, imageObj){
		var myimg = new Image();
		myimg.onload = function(){
			var height = myimg.height;
			var offset = (240 - height) / 2;
			imageObj
			.show()
			.stop()
			.html(myimg)
			.css({
				'padding-top': offset,
				'height':240 -offset,
				'opacity':0
				})
			.fadeTo(500, 1);
		};
		myimg.src = path;
	},
	setPrevNextVisible:function(){
		var currentItemNo = this.commonData.currentItemNo;
		var maxNum = this.commonData.maxItemNum;
		if(maxNum == 1){
			this.prevBtn.hide();
			this.nextBtn.hide();
		}else if(maxNum == currentItemNo){
			this.prevBtn.show();
			this.nextBtn.hide();
		}else if(currentItemNo < maxNum && currentItemNo != 1){
			this.prevBtn.show();
			this.nextBtn.show();
		}else if(currentItemNo < maxNum && currentItemNo == 1){
			this.prevBtn.hide();
			this.nextBtn.show();
		}
	}
};

onigiri.LayerUtil = function(contentID){
	this.contentID = contentID;
	this.content; //表示する中身
	this.bgLayer;
	this.allArea;
	this.isShow = false;
	onigiri.LayerUtil.instance = this;

	this.init();
}

onigiri.LayerUtil.instance = null;

onigiri.LayerUtil.prototype = {
	init:function(){
		this.setOverlay();
		var self = this;
		$(window).resize(function(){						
			if(self.isShow == true){
				self.setLayerPosition();
			}
		});
	},
	getInstance:function(){
		return onigiri.LayerUtil.instance;
	},
	setLayerVisible: function(isVisible){
		var self = this;
		if(isVisible){
			this.allArea.show();
			this.content.fadeTo(200, 1);
			this.isShow = true;
			this.setLayerPosition();
		}else{
			this.content.fadeTo(150, 0, function(){
				self.allArea.hide();
				self.isShow = false;
			});
		}
		
	},
	setOverlay:function(){
		var self = this;
		
		//もとのコンテンツを移動
		$('body').append('<div id="overlay_area"><div id="overlay_bg"></div></div>');
		var coverhtml = $(this.contentID);
		coverhtml.remove();
		$('#overlay_area').append(coverhtml);
		
		//ひもづけ
		this.content = $(this.contentID);
		this.bgLayer = $('#overlay_bg');
		this.allArea = $('#overlay_area');
		this.bgLayer
		.mousedown(function(){
				self.setLayerVisible(false);
		});
		
		//見た目
		this.allArea.hide();
		this.content.fadeTo(0,0);
		this.content.show();
	},
	setLayerPosition: function(){
		this.bgLayer
		.css({
			 width:$('body').width() + 'px',
			 height:$('body').height() + 'px'
		});
		var posx = (this.getBrowserWidth() - this.content.width()) / 2;
		var posy = (this.getBrowserHeight() - 400) / 2 + this.getOffsetY() - 60;
		if(posx < 0){
			posx = 0;
		}
		if(posy < 0){
			posy = 0;
		}
		this.content
		.css({
			'left': posx + 'px',
			'top': posy + 'px'
		});
	},
	getOffsetY: function(){
		if(document.documentElement.scrollTop){
			return document.documentElement.scrollTop;
		}else if(document.body.scrollTop){
			return document.body.scrollTop;
		}else{
			return 0;
		}
	},
	getBrowserWidth: function() {
		if ( window.innerWidth ) {
				return window.innerWidth;
		}
		else if ( document.documentElement && document.documentElement.clientWidth != 0 ) {
				return document.documentElement.clientWidth;
		}
		else if ( document.body ) {
				return document.body.clientWidth;
		}
		return 0;
	},
	getBrowserHeight: function () {
		if ( window.innerHeight ) {
				return window.innerHeight;
		}
		else if ( document.documentElement && document.documentElement.clientHeight != 0 ) {
				return document.documentElement.clientHeight;
		}
		else if ( document.body ) {
				return document.body.clientHeight;
		}
		return 0;
	}
}

onigiri.CSVController = function(loadCompleteHD){
	this.loadCompleteHD = loadCompleteHD;
	this.loadCSV();
}

onigiri.CSVController.prototype = {
		loadCSV: function(){
			var self = this;
			var filename = onigiri.Const.mainImagePath + "onigiri_data.csv" + "?" + (new Date()).getTime();
			$.get(filename, {}, function(data){
				var dataTable = CSVData.parse(data);
				self.parseData(dataTable);
				//完了
				self.loadCompleteHD();
			});
		},
		parseData: function(dataTable){
			dataTable.shift(); //1行目は削除
			var i;
			var len = dataTable.length;
			var firstColumn;
			var rowData;
			var userdatas = onigiri.UserDatas.getInstance();
			var userdata;
			
			var keywordCount = 0;
			for(i = 0; i < len; i++)
			{
				rowData = dataTable[i];
				firstColumn = rowData[0];
				//各行の先頭でエラーチェック
				if(firstColumn == "" || firstColumn == " " || firstColumn == "　" || 
				   firstColumn == "\n" || firstColumn == "\r\n" || firstColumn == "\r"){
					continue;
				}
				userdata = new onigiri.UserData();
				userdata.no = parseInt(rowData[0]);
				userdata.degitNo = onigiri.Util.getTreeDegit(userdata.no);
				userdata.name = rowData[1];
				userdata.address = rowData[2];
				userdata.text = rowData[3];
				userdatas.addData(userdata);
			}
			
			//最大値を代入
			var commonData = onigiri.CommonData.getInstance();
			for(var key in userdatas.datas){
				commonData.maxItemNum++;
			}
		}
}

onigiri.UserDatas = function(){
	this.datas = {};
}

onigiri.UserDatas.instance = null;
onigiri.UserDatas.getInstance = function(){
	if(onigiri.UserDatas.instance == null){
		onigiri.UserDatas.instance = new onigiri.UserDatas();
	}
	return onigiri.UserDatas.instance;
}

onigiri.UserDatas.prototype = {
	addData:function(userdata){
		this.datas[userdata.no] = userdata;
	},
	getData:function(no){
		return this.datas[no];
	}
}

onigiri.UserData = function(){
	this.no;
	this.degitNo;
	this.name;
	this.address;
	this.text;
}

onigiri.Util = {
	//3桁文字を得る
	getTreeDegit:function(num){
		var a = num.toString().split('');
		while(a.length < 3){
			a.unshift('0');
		}
		return a.join('');
	}
}

$(function(){
	//delay plug-in
	$.fn.delay = function(time, callback){
			// Empty function:
			jQuery.fx.step.delay = function(){};
			// Return meaningless animation, (will be added to queue)
			return this.animate({delay:1}, time, callback);
	}

	var loadCompleteHD = function(){
		var Main = onigiri.Main;
		var main = new Main();
	}
	//CSV読み込み
	var csv = new onigiri.CSVController(loadCompleteHD);
});

/* -----------------------------
 utility
----------------------------- */
function trace(s){
	var logstr = '';
	if(typeof(s) == 'object'){
		for(var i in s){
			logstr += i + ' : ' + s[i] + '\r\n';
		}
	}else{
		logstr = s;
	}
	console.log(logstr);
};
