/* ポップアップ ########################################################
 * 	ポップアップを開きたいタイミングで...
 * 	$(ポップアップで表示する内容).jQpopup(オプション);
 * 	指定の画像のみ表示の時は、$(ポップアップで表示する内容)にはなにかダミー要素を姉弟して、オプションのsrcにパスを入れる
 */

var Popup = function(t,option,id){
	this.t = t;					// ポップアップで表示する内容
	this.t_old = null;
	
	// オプションの初期値
	this.opt = {
			src:null,				// 画像の拡大の時は画像のsrcを入れる
			style:'window',			// ポップアップのスタイル(simple,window)
			title:'',				// ウィンドウのタイトル(style:'window'の時のみ有効)
			close:{					// 閉じるボタン
				disabled:false,			// 非表示にするか
				position:'rt'			// ボタンの位置(lt:左上,lb：左下,rt：右上,rb：右下)
			},
			modal:false,		// モーダル表示にするか
			size:false,			// ポップアップのサイズを強制的に指定したサイズにするか（ウィンドウからはみ出そうが関係なしにする）
			width:'auto',		// ポップアップのサイズ：幅
			height:'auto',		// ポップアップのサイズ：高さ
			// 位置が指定してある場合はpositionをfixedにしないので強制でその位置にする
			left:'',			// ポップアップの左からの位置	
			top:'',				// ポップアップの右からの位置
			create_fn:function(){},		// ポップアップが作成されたら実行（表示・非表示関係なく）
			show_fn:function(){},		// ポップアップが表示されたら実行
			close_fn:function(){}		// ポップアップがとじたら実行
	};
	
	// ポップアップ枠のid
	this.id = id;
	
	// オプションを上書き
	$.extend(this.opt, option);
	
	// 処理実行
	this.init();
}

Popup.prototype = {
	// 実行される処理
	init:function(){
		this.create();	// モーダルやポップアップ枠を作成
		
		var opt = this.opt,
			_this = this,
			t = this.t,				// ポップアップで表示する内容
			m = $('#glay_layer'),	// モーダルレイヤー
			l = $('#loading'),		// ローディング
			f = $('#' + this.id).hide();	// ポップアップ本体
		
		// ポップアップ表示
		if(opt.modal){
			// すでにモーダルではないポップアップが開かれていたらとじる。
			if($("div.popup_frame:visible")) $("div.popup_frame:visible").hide();
			
			// モーダル有りのときはモーダルレイヤーが表示されてからポップアップ表示 
			if(m.is(":visible")){
				_this.popshow();
			}else if(m.is(":hidden")){
				m.fadeTo("1000",0.5,function(){
					_this.popshow();
				});
			}
		}else{
			// 通常はポップアップだけを表示
			_this.popshow();
		}
		
		// 閉じる処理(通常はボタンorモーダルクリック)
		f.find('.close').click(function(){
			jQpopup_close(f,opt.close_fn);
		});
		m.click(function(){
			if($('#' + _this.id).is(":visible")) jQpopup_close(f,opt.close_fn);
		});

		
		$(window).resize(function(){
			if(f.is(":visible")){
				f.find('.popup_content').css({width:opt.width,height:opt.height});
				_this.sizepos(f);
			}
		});
	},
	create:function(){
		// ページ内に一つだけ(モーダル、ローディングレイヤー)
		if(!$('body div').is('#glay_layer')){
			$('body').append('<div id="glay_layer"> </div><div id="loading"> </div>');
		}
		// モーダルとローディングを非表示
		$('#glay_layer').hide();	// モーダル用グレイレイヤー
		$('#loading').hide();		// ローディング表示
		
		// １ポップアップ(id)につき１回
		if(!$('body div').is('#' + this.id)){
			// idのポップアップ枠作成
			$('body').append('<div id="'+this.id+'" class="popup_frame"></div>');
			
			var opt = this.opt,
				t = this.t,		// ポップアップで表示する内容
				m = $('#glay_layer'),	// モーダルレイヤー
				l = $('#loading'),		// ローディング
				f = $('#' + this.id).hide();	// ポップアップ本体
			
			
			// スタイルごとの処理
			switch (opt.style) {
			case "simple":
				f.addClass("popup_simple");
				f.append('<div class="popup_content"></div>');
				break;
			case "window":
				f.addClass("popup_window");
				f.append('<h2 class="title"></h2><div class="popup_content"></div>');
				break;
			default:
				break;
			}
			
			// クローズボタン処理
			if(!opt.close.disabled){
				// オプションの設定に従い、ボタンの位置を決定
				switch (opt.close.position) {
				case "lt":
					f.append('<span class="close lt">&nbsp;</span>');
					break;
				case "lb":
					f.append('<span class="close lb">&nbsp;</span>');
					break;
				case "rt":
					f.append('<span class="close rt">&nbsp;</span>');
					break;
				case "rb":
					f.append('<span class="close rb">&nbsp;</span>');
					break;
		
				default:
					break;
				}
			}
			opt.create_fn();
		}
	},
	popshow:function(){
		var opt = this.opt,
			t = this.t,		// ポップアップで表示する内容
			m = $('#glay_layer'),	// モーダルレイヤー
			l = $('#loading'),		// ローディング
			f = $('#' + this.id).hide();	// ポップアップ本体
		
		// style:window　タイトルを設定する
		if(opt.style == "window") f.find('.title').html(opt.title);
		if (t != this.t_old){
			// srcに値が入っていたらそちらを優先する
			if(opt.src){
				f.find('.popup_content').html('<img src="'+opt.src+'" alt="" />');
			}else{
				f.find('.popup_content').html(t).show();
				t.show();
			}
			this.t_old = t;
		}
		
		f.find('.popup_content').css({width:opt.width,height:opt.height});
		this.sizepos();
		
		if(opt.modal){
			f.show();
		}else{
			f.fadeIn("fast");
		}
		
		opt.show_fn();
	},
	sizepos:function(resize){
		var opt = this.opt,
			f = $('#' + this.id).hide(),	// ポップアップ本体
			left,top,fcw,fch,diff,				// 調整後のポップアップの表示位置、サイズ
			ww = $(window).width(),			// 現在の表示領域（ウィンドウ幅）
			wh = $(window).height(),		// 現在の表示領域（ウィンドウ高さ）
			st = $(document).scrollTop()	// 現在のスクロール位縦置
			fw = f.outerWidth(),			// 現在のポップアップの大きさ（幅）
			fh = f.outerHeight();			// 現在のポップアップの大きさ（高さ）
		
		
		// ＃まずはポップアップのサイズを調整
		// style:windowの時のwindowのサイズが指定のサイズになるように調整しなおす（現段階では中身が指定サイズになっている）
		if(opt.style == "window"){
			fcw = f.find('.popup_content').outerWidth();
			fch = f.find('.popup_content').outerHeight();
			// 幅を修正
			diff = fw-fcw;
			f.find('.popup_content').width(fcw-diff);
			// 高さ修正
			diff = fh-fch;
			f.find('.popup_content').height(fch-diff);
		}
		
		if(opt.size){
			// オプションでサイズを強制にしているとき(強制にしていても、サイズをしていない場合は、ウィンドウ幅に合わせて大きさを変える)
			if(opt.size == "auto"){
				if(fw > ww){
					f.find('.popup_content').width(ww-96);
					if(opt.style =="window"){
						diff = f.outerWidth() - f.find('.popup_content').width();
						f.find('.popup_content').width(f.outerWidth()-diff);
					}
					fw = f.outerWidth();
					fh = f.outerHeight();
				}
			}
			if(opt.height == "auto"){
				if(fh > wh){
					f.find('.popup_content').height(wh-120);
					if(opt.style =="window"){
						diff = f.outerHeight() - f.find('.popup_content').height();
						f.find('.popup_content').height(f.outerHeight()-diff);
					}
					fh = f.outerHeight();
				}
			}
		}else{
			//　幅がウィンドウサイズを超えたとき
			if(fw > ww){
				f.find('.popup_content').width(ww-96);
				if(opt.style =="window"){
					diff = f.outerWidth() - f.find('.popup_content').width();
					f.find('.popup_content').width(f.outerWidth()-diff);
				}
				fw = f.outerWidth();
				fh = f.outerHeight();
			}
			if(fh > wh){
				f.find('.popup_content').height(wh-120);
				if(opt.style =="window"){
					diff = f.outerHeight() - f.find('.popup_content').height();
					f.find('.popup_content').height(f.outerHeight()-diff);
				}
				fh = f.outerHeight();
			}
		}
		
		// ＃位置を調整
		// 通常はウィンドウの真ん中
		left = (ww-fw)/2;
		top = (wh-fh)/2;
		
		// 位置が指定してあるならその位置に変更
		if(opt.left) left = opt.left;
		if(opt.top) top = opt.top;
		
		f.css({
			left:left + "px",
			top:top + "px"
		});
		
		if(!opt.top && !opt.left) f.css("position","fixed");
		
		if(resize) resize.show();
	}
}

// プラグイン化する
$.fn.jQpopup = function(option){
	
	var t = $(this),					// ポップアップで表示する内容
		id = "pop_" + t.attr("id");	// ポップアップの枠用のid
	
	// インスタンス化（jQselectable.jsを参考）
	if(t.length > 1){
		var _instances = [];
		t.each(function(i){
			_instances[i] = new Popup(t,option,id);
		});
		return _instances;
	}else{
		return new Popup(t,option,id);
	}
}

// 閉じる処理はどこからでも呼び出せるように別関数に分けてみた（第1引数に閉じるポップアップを指定）
var jQpopup_close = function(t,close_fn){
	if($('#glay_layer').is(':visible')){
		t.hide();
		$('#glay_layer').fadeOut('fast');
	}else{
		t.fadeOut('fast');
	}
	close_fn();
}
