/*
 * Starryworks Simple Lib with jQuery
 * 
 * TODO : 番号のやつ実装する
 * TODO : tooltipにauto時の挙動を追加すること
 * TODO : アコーディオンなおす
 */

var root = this;
var debug = false; //実際に使用するときはfalseに。
var externalCallbacks = {};

//------------------------------------------------------------
// document ready
//------------------------------------------------------------

$(function(){
	var self = $("script[src*='starryworks.simple']").attr('src');
	init(self);
});

//------------------------------------------------------------
// Init
//------------------------------------------------------------

function init(raw)
{
	var config = UTL.queryToArray(raw);
	$.each(config, function(i){
		var prefix = config[i].substr(0, 3);
		if(prefix == 'ie6') {
			if(UTL.isIE6() || debug) {
				root[config[i] + 'Init']();
			}
		} else {
			root[config[i] + 'Init']();
		}
	});
}

//------------------------------------------------------------
// Util
//------------------------------------------------------------

var UTL = {};

UTL.queryToArray = function(raw)
{
	var settings = [];
	var value = raw.split('?')[1];
	var moge = value.split('&');
	$.each(moge, function(){
		var temp = String(this);
		settings.push(temp);
	});
	return settings;
}

//暫定。後ほど個人lib内の判別機構と差し替え
UTL.isIE = function()
{
	IE='\v'=='v';
	if(IE) {
		return true;
	} else {
		return false;
	}
}

//暫定。後ほど個人lib内の判別機構と差し替え
UTL.isIE6 = function()
{
	var md = window.showModelessDialog;
	var ns = document.namespaces;
	var im = document.implementation;
	if(UTL.isIE()){
		if(!window.XMLHttpRequest && (md && ns && im) ) {
			return true;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

//------------------------------------------------------------
// RollOver
//------------------------------------------------------------

function rollOverInit()
{
	var $target = $('.rollover');
	
	$.fn.rollOver = function(options){
		//後の拡張用
		var defaults = {};
		var options = $.extend(defaults, options); 
		
		this.each(function(){
			var $a = $(this);
			var $i = $a.children('img');
			if(!$i.length && $a.attr("src")) $i = $a;
			if(!$i.length) return;
			
			var src = $i.attr("src");
			var over = src.replace(/\.([a-zA-Z0-9]+)$/,"-over.$1");
			$("<img>").attr("src",over);
			
			$i.hover(function(){
			$(this).attr('src', over);
			}, function(){
				$(this).attr('src', src);
			});
		});
	}
	
	$target.rollOver();
}

//------------------------------------------------------------
// FixHeights
//------------------------------------------------------------

function fixHeightInit()
{
	var groups = [];
	var textHeight = 0;
	var $fontSizeDiv;
	var target = $(".fixHeight, .fixHeightNAuto, *[class*=fixHeightN]");
	
	var check = function() {
		if ( $fontSizeDiv.height() == textHeight ) return;
		textHeight = $fontSizeDiv.height();
		$.each(groups,function(){
			var $children = this.children;
			var n = this.n;
			$children.css("height","auto");
			var maxHeight = 0;
			if ( n == 0 ) {
				$children.each(function(){
					if ( $(this).height() > maxHeight ) maxHeight = $(this).height();
				});
				$children.css("height",maxHeight+"px");
			} else if ( n == -1 ) {
				var top = 0, cnt = 0, st = 0, i = 0;
				$children.each(function(){
					if ( top != $(this).position().top ) {
						if ( cnt > st ) for ( i = st; i < cnt; i++ ) $children.eq(i).css("height",maxHeight+"px");
						top = $(this).position().top;
						maxHeight = 0;
						st = cnt;
					}
					if ( $(this).height() > maxHeight ) maxHeight = $(this).height();
					cnt++;
				});
				if ( cnt > st ) for ( i = st; i < cnt; i++ ) $children.eq(i).css("height",maxHeight+"px");
			} else {
				var maxHeights = [];
				$children.each(function(index){
					if ( index != 0 && index % n == 0 ) {
						maxHeights.push(maxHeight);
						maxHeight = 0;
					}
					if ( $(this).height() > maxHeight ) maxHeight = $(this).height();
				});
				maxHeights.push(maxHeight);
				$children.each(function(index){
					$(this).css("height",maxHeights[Math.floor(index/n)]+"px");
				});
			}
		});
	}

	target.each(function(){
		var $this = $(this);
		var $children = $(".fixHeightChild",$this);
		if ( !$children.length ) $children = $this.children();
		if ( !$children.length ) return;
		var n = 0;
		if ( $(this).hasClass("fixHeightNAuto") ) n = -1;
		else if ( String($this.attr("class")).match(/fixHeightN([0-9]+)/) ) n = parseInt(String($this.attr("class")).match(/fixHeightN([0-9]+)/)[1]);
		else if ( !$(this).hasClass("fixHeight") ) return;
		groups.push({ parent:this, children:$children, n:n });
	});
	
	$fontSizeDiv = $(document).append('<div>s</div>');
	setInterval(check,1000);
	$(window).resize(check);
	check();
}

//------------------------------------------------------------
// Image Changer
//------------------------------------------------------------

function imageChangerInit()
{
	var $target = $('.imageChanger');
	$target.each(function(){
		var rpl = $(this).attr("href")
		var dispName =  String(rpl).split("#")[1];
		var $display = $('#' + dispName);
		
		$('<img>').attr('src', rpl);
		
		$(this).click(function(){
			$display.attr('src', rpl);
			return false;
		});
	});
}

//------------------------------------------------------------
// ToolTip
//------------------------------------------------------------

function toolTipInit()
{
	var $target = $("a[class*='toolTip']");
	$.fn.simpleTooltip = function(options) {
		var defaults = {};
		var options = $.extend(defaults, options); 
		
		//var content;
		this.each(function(){
			var title = $(this).attr('title');
			if(!title) return;
			
			var $this = $(this);
			var hoverType = (function(){
					var className = $this.attr('class');
					if(className == 'toolTip') {
						return 'auto';
					} else {
						return className.replace('toolTip-', '');
					}
				})();
				
			console.log(hoverType);
				
			$(this).data('hoverType', hoverType);
			$(this).hover(function(){
				var thisPos = $(this).position();
				var thisScale = { width : $(this).width(), height : $(this).height() };
	
				//とりあえず今は中身に表示できるのはtitleだけにしとく
				//bug : #simpleTooltipにwidthが指定されてないと、高さと幅が正確にとれない！
				//css側で#simpleTooltipにwidthを必ず付与しておくこと。
				var toolTipBody = $('<div id="simpleTooltip">' + title + '</div>').css('display', 'inline-block'); 
				
				$(this).attr("title", "");
				if(title != '') {
					var posHorizontal;
					var posVertical;
					$('body').append(toolTipBody);
					
					if($(this).data('hoverType') == 'auto') {
						//scrollのoffsetとってきてごにょごにょやってhoverTypeを入れ替えるなり
					}
					
					switch($(this).data('hoverType')) {
						case 'left' : 
							posHorizontal = (thisPos.left - toolTipBody.width() - 20);
							posVertical = (thisPos.top - toolTipBody.height() / 2);
							break;
							
						case 'right' :
							posHorizontal = (thisPos.left + thisScale.width + 10);
							posVertical = (thisPos.top - toolTipBody.height() / 2);
							break;
							
						case 'top' : 
							posHorizontal = (thisPos.left + (thisScale.width / 2)) - toolTipBody.width() / 2;
							posVertical = (thisPos.top - 20) - toolTipBody.height();
							break;
							
						case 'bottom' : 
							posHorizontal = (thisPos.left + (thisScale.width / 2)) - toolTipBody.width() / 2;
							posVertical = (thisPos.top + thisScale.height + 10);
							break;
							
						default : 
							return;
							break;
					}
					
					$('#simpleTooltip')
						.css("position","absolute")
						.css("top", posVertical + 'px')
						.css("left", posHorizontal + 'px')
						.css("display", "none")
						.fadeIn('fast');
				}
			}, function(){
				$('#simpleTooltip').remove();
				$(this).attr("title", title);
			});
		});
	}
	
	$target.simpleTooltip();
}

//------------------------------------------------------------
// Accordion
//------------------------------------------------------------

function accrodionInit()
{
	//どのようなマークアップが考えられるか
	//何階層までもつづくのか
	//イージングとかアニメーションのバリエーションの制御をどうするか
	//.handleのhrefに＃を入れた場合は次の兄弟要素
	//それ以外は指定されたidに対してアコーディオンする ex. href="#hogehoge"
	var $handle = $('.handle');
	$handle.click(function(){
		
		//影響範囲をslaveの疑似兄弟要素に限定
		//handleがほかのタグでwrappされている場合の分岐が必要
		//ちょっとここバグ。
		var $siblings = $(this).data('slave').parent().siblings().children('a.handle');
		
		if($(this).data('state') == 'open'){
			$(this).removeClass('selected').data('state', 'close');
			$(this).data('slave').slideUp();
		} else {
			$(this).data('slave').slideDown();
			$siblings.each(function(){
				if($(this).hasClass('selected')){
					$(this).removeClass('selected').data('state', 'close');
					$(this).data('slave').slideUp();
				};
			});
			$(this).addClass('selected').data('state', 'open');
		};

		return false;
	});
	
	$handle.each(function(){
		$(this).data('handles', $handle);
		
		var key = $(this).attr('href');
		var $slave;
		if(key == '#'){
			$slave = $(this).next();
		} else {
			$slave = $(key);
			$(this).data('wrapp', true);
		}

		$(this).data('slave', $slave);
		
		//selectedクラスを同時に持つものは最初は開いとく
		if(!$(this).hasClass("selected")){
			$slave.hide();
			$(this).data('state', 'close');
		} else {
			$(this).data('state', 'open');
		}
	});
}

//------------------------------------------------------------
// Simple Scroll
//------------------------------------------------------------

function simpleScrollInit()
{
	var file = 'js/plugin/jquery.scrollTo.js';
	externalCallbacks.onScrollToLoad = function() {
		var $target = $('.scroll');
		var dest;
		$target.each(function(){
			var key = $(this).attr('href');
			$(this).click(function(){ 
				if(key == "#"){
					dest = 0;
				} else {
					dest = $(key);
				}
				$.scrollTo(dest, 800);
				return false;
			});
		});
	}
	
	$.ajax({
		type: "GET",
		url: file,
		dataType: "script",
		success: externalCallbacks.onScrollToLoad
	});
}

//------------------------------------------------------------
// Tab
//------------------------------------------------------------

function tabInit()
{
	var $tabSet = $('.tabSet');
	$tabSet.each(function(){
		var $tabs = $(this).find('a.tab');
		var $selected = null;
		
		$tabs.click(function(){
			$(this).data("tabs").each(function(){
				$($(this).attr("href")).hide();
				$(this).removeClass("selected");
			});
			
			$($(this).attr("href")).show();
			$(this).addClass("selected");
			return false;
		});
		
		$tabs.each(function(){
			$(this).data("tabs", $tabs);
			if ($(this).hasClass("selected")){
				$selected = $(this);
				$(this).click();
			}
		});
		
		if($selected == null) $selected = $($tabs[0]).click();
	});
}

//------------------------------------------------------------
// AddSpecificClass
//------------------------------------------------------------

function specificClassInit()
{
	//いい名前が思いつかない。
	//あとで同一の親を持つ兄弟要素たちの何番目かを指定して
	//クラスを付与する機能をつける
}

//------------------------------------------------------------
// ie6 PNGFIX
//------------------------------------------------------------

function ie6PngFixInit()
{
	var file = 'js/plugin/DD_belatedPNG_0.0.8a.js';
	externalCallbacks.onPngFixLoad = function() {
		DD_belatedPNG.fix('.pngfix');
	}
	
	$.ajax({
		type: "GET",
		url: file,
		dataType: "script",
		success: externalCallbacks.onPngFixLoad
	});
}

//------------------------------------------------------------
// ie6 PositionFixed
//------------------------------------------------------------

function ie6PositionFixedInit()
{	
	var file = 'js/plugin/jquery.exfixed.1.2.0.js';
	externalCallbacks.onExFixedLoad = function() {
		var target = $('.exFixed');
		target.exFixed();
	}
	
	$.ajax({
		type: "GET",
		url: file,
		dataType: "script",
		success: externalCallbacks.onExFixedLoad
	});
}