// JavaScript Document
// It's OK My Will is Good.
// 動作テスト http://dsn.sh/lab/
// (c)The Designium

var Dsn = {
	init : function() {
		this.setSize();
	},
	dominit : function() {
		stateNow = 1;
		Column = {
			singleTags : ["br", "img", "hr", "input", "!--"],
			chopTags : ['<span class="break"></span>', '<br>', '<br/>', '<br />', '<p></p>', '<li></li>', '<ul></ul>', '<ol></ol>'],
			columns : new Array()
		}
		waitAction = 0;
		if(Browser.Platform.mac) {
			$('niceBody').setStyles({'font-family': '"Hiragino Kaku Gothic Pro", "ヒラギノ角ゴ Pro W3", serif', 'color': '#000000', 'line-height': '1.5em' });
			$$('.title').setStyles({'font-family': '"Hiragino Mincho Pro", "ヒラギノ 明朝 Pro W3", serif', 'color': '#000000', 'line-height': '1.5em', 'font-size': '1.5em' });
			$$('p').setStyle('margin-bottom', '1.5em');
			$$('p.info').setStyle('margin-bottom', '0.1em');
			$$('ul').setStyle('margin-bottom', '1.5em');
		}
	},
	setSize : function() {
		var margin = 60, headHeight = 5, footHeight = 60;
		columnSpace = 49;
		paddingSpace = 24;
		winHeight = window.getHeight();
		winWidth = window.getWidth();
		
		//ページで使える幅を測る
		scrollNum = winHeight - headHeight - footHeight;
		pageHeight = winHeight - margin - headHeight - footHeight;
		pageWidth = winWidth - margin + columnSpace;

		//カラム幅とカラム数決定
		if(pageWidth >= 0 && pageWidth < 600) {
			columnCount = 1;
			columnWidth = pageWidth - columnSpace;
		} else	if(pageWidth >= 600 && pageWidth < 900) {
			columnCount = 2;
			columnWidth = (pageWidth/2).toInt() - columnSpace;
		} else	if(pageWidth >= 900 && pageWidth < 1200) {
			columnCount = 3;
			columnWidth = (pageWidth/3).toInt() - columnSpace;
		} else	if(pageWidth >= 1200 && pageWidth < 1600) {
			columnCount = 4;
			columnWidth = (pageWidth/4).toInt() - columnSpace;
		} else	if(pageWidth >= 1600 && pageWidth < 2100) {
			columnCount = 5;
			columnWidth = (pageWidth/5).toInt() - columnSpace;
		} else	if(pageWidth >= 2100) {
			columnCount = 6;
			columnWidth = (pageWidth/6).toInt() - columnSpace;
		}
		
		$('header').setStyle('width', winWidth);
		$('footer').setStyle('width', winWidth);
		$('content').setStyles({ 'height': winHeight, 'width': winWidth });
		$('container').setStyles({ 'height': winHeight*4, 'width': winWidth, 'margin-top': -scrollNum });
		
		if(winHeight > 300) this.setColumn();
	},
	setColumn : function() {
		if (!$("circuit" || !$('container') || !$('stockContent') )) {
			alert('Error');
			return;
		}
		
		var text = $("stockContent").get('html');
		Column.columns = new Array();
		Column.hits = 0;
		var x = "";
	
		for (var i = 0; text != ""; i++) {
		
			Column.columns[i] = this.getFragments(text);
			text = text.slice(Column.columns[i].length);
		
			for (var j = 0; j < Column.chopTags.length; j++) {
				if (text.charAt(0) == "\n") text = text.slice(1);
				x = Column.chopTags[j];
				while (text.indexOf(x) == 0) text = text.slice(x.length);
			}
		
			for (var k = Column.openTags.length - 1; k >= 0; k--) {
				Column.chopTags[i] += "</" + Column.openTags[k].split(" ")[0] + ">";
				if (text != "") text = "<" + Column.openTags[k] + ">" + text;
			}
		
			for (var m = 0; m < Column.chopTags.length; m++) {
				if (text.charAt(0) == "\n") text = text.slice(1);
				x = Column.chopTags[m];
				while (text.indexOf(x) == 0) text = text.slice(x.length);
			}
		}
		
		//console.log('%s', Column.columns.length);
		$$("#content .pageblock").destroy(); 
		$$("#content .columnblock").destroy();
		
		//ページ数
		pageCount = Math.ceil(Column.columns.length/columnCount);
		//ページブロック作成
		for (var i = 0; i <= pageCount; i ++) {
			var id = 'page' + i;
			new Element('div', {
				styles : {
					'height' : winHeight,
					'width' : winWidth
				},
				'id': id,
				'class': 'pageblock'
			}).injectInside($('container'));
			new Element('div', {
				'id' : id + 'margin',
				'class' : 'page-margin'
			}).injectInside($(id));
		}
		var nowPageCount = 0; //カラム化された文章を流し込むページ
		var pageColumnCount = (columnCount * pageCount).toInt();
		for (var i = 0; i < pageColumnCount; i ++) {
			var countPerColumn = i%columnCount;
			var lastPageColumn = columnCount - 1;
			if(countPerColumn == 0) {
				nowPageCount++;
			}
			if(countPerColumn == lastPageColumn) {
				var border = 'none';
			} else {
				var border = '1px solid #E0E0E0';
			}
			var insideId = 'page' + nowPageCount + 'margin';
			var elmnt = new Element('div', {
				styles : {
					'height' : pageHeight,
					'width' : columnWidth,
					'padding-right' :  paddingSpace,
					'padding-left' :  paddingSpace,
					'border-right' : border
				},
				'class': 'columnblock'
			}).injectInside($(insideId));
			if(i < Column.columns.length){
				elmnt.set('html', Column.columns[i]);
			}
		}
		
		this.slideBlock(stateNow);
	},
	getFragments : function(text) {
		var i = 0;
		var limit = 0;
		var add = 0;
		var doloop = false;
		Column.openTags = new Array();

		$("circuit").setStyle('width', columnWidth);
		$("circuit").set('html', text);

		if($("circuit").getHeight() <= pageHeight) {
			i = text.length;
		} else {
			doloop = true;
			limit = text.length;
		}

		while (doloop) {
			add = Math.round((limit - i) / 2);
			if (add <= 1) doloop = false;
			i += add;
			$('circuit').set('html', text.substr(0, i));
		
			if ($('circuit').getHeight() > pageHeight){
				limit = i;
				i -= add;
			}
			Column.hits++;
		}
		
		if (text.substr(0, i) != text) {
			var lastNewline = text.substr(0, i).lastIndexOf("\n")
			var lastGreater = text.substr(0, i).lastIndexOf(">");
			var lastLess = text.substr(0, i).lastIndexOf("<");
			if (lastLess <= lastGreater && lastNewline == i - 1) i = i;
		}

		text = text.substr(0, i).split('<span class="break"></span>')[0];
	
		var doPush = true;
		var tags = text.split("<");
		tags.shift();
	
		for (var j=0; j<tags.length; j++) {
			tags[j] = tags[j].split(">")[0];

			if (tags[j].charAt(tags[j].length-1) == "/") continue;
		
			if (tags[j].charAt(0) != "/") {
				for (var k=0; k<Column.singleTags.length; k++) {
					if (tags[j].split(" ")[0].toLowerCase() == Column.singleTags[k]) doPush = false;
				}
				if (doPush) Column.openTags.push(tags[j]);
				doPush = true;
			}
			else Column.openTags.pop();
		}
		return text;
	},
	slideBlock : function(state) {
		slides = $$("#content .pageblock");
		slideShow = new Fx.Elements(slides, { duration: 500, wait: true, transition: Fx.Transitions.Quart.easeOut });

		this.slideAction(state);
		this.wheelAction(state);
	},
	slideAction : function(state) {
		var o = {};
		if(state > pageCount) {
			state = pageCount;
			stateNow = pageCount;
		}
		var prev = state - 1;
		var next = state + 1;
		
		slides.each(function(slide, i) {
			if(i < prev || i > next ) {
				o[i] = { height: [0] };
			} else {
				o[i] = { height: [scrollNum] };
			}
		});
		slideShow.start(o).chain(function(){
			waitAction = 0;
		});
	},
	wheelAction : function(state) {		
		$('content').addEvent('mousewheel', function(elmnt) {	
			elmnt = new Event(elmnt).stop(); //ホイールの重複動作制御
			if(waitAction != 1) {
				if(elmnt.wheel > 0) {
					state--; //state = state + elmnt.wheel; //ホイール上
				}
				if(elmnt.wheel <= 0) {
					state++; //state = state - elmnt.wheel; //ホイール下
				}
				
				if(state <= 1) state = 1;
				else if(state >= pageCount) state = pageCount;
				stateNow = state;
				waitAction = 1;
			
				Dsn.slideAction(state);
			}
		});
	}
}


window.addEvent('domready', function(){ Dsn.dominit() });
//window.addEvent('load', function(){ Dsn.init() });　描画にずれ？
window.onresize = function() {
	(function() {
		Dsn.setSize();
	}).delay(10);
};
window.onload = function() {
	Dsn.init();
};
