if(typeof(console) == 'undefined'){ var console = { log : function(){}};}
if(typeof(Flips) == 'undefined'){ var Flips = {}; }
/*
	ページ内ポップアップ画面
	
	表示内容をAJAXで受け取り、ポップアップ内部のHTMLを更新する。
	特定のクラス名の付いたリンク、FORMはポップアップの内側で遷移するように書き換えられる。

	requires : jquery1.3
*/
Flips.Popup = function(){
	this.overlay = null;
	this.obj = null;
	this.body = null;
	this.className = {
		common : 'flips_ui',
		obj  : 'flips_popup',
		body : 'flips_popup_body',
		inner_transition : 'flips_popup_inner_transition',	// このクラスが付いているAタグ,FORMはPopupの内側で遷移する
        ajax_link : 'flips_popup_ajax_link', // このクラスが付いているAタグは、ajax通信を行う
		close_button : 'flips_popup_close'	// このクラスが付いているタグをクリックするとポップアップを閉じる
	};
	this.modal = true;
	this.init.apply(this, arguments);
};
Flips.Popup.prototype = {
	init : function(options){
		// デフォルト値
		var scrollTop  = document.body.scrollTop  || document.documentElement.scrollTop;
		var top = 20;
		var width = 800;
		var height = $(window).height() - 80;
		this.modal = true;

		// optionsで設定を上書き
		if(options){
			top = (typeof(options.top) == 'undefined') ? top : options.top + scrollTop;
			width = (typeof(options.width) == 'undefined') ? width : options.width;
			height = (typeof(options.height) == 'undefined') ? height : options.height;
			this.modal = (typeof(options.modal) == 'undefined') ? this.modal : options.modal;
		}

console.log([top,width,height,this.modal]);
		if(this.modal){
			this.overlay = $('<div></div>').appendTo(document.body).hide().addClass('ui-widget-overlay').css({
				width : this._width(),
				height: this._height()
			});
		}
		this.obj = $('<div />').addClass(this.className.common).addClass(this.className.obj).css({
			width : width + 'px',
			maxHeight : height + 'px',
			left : (($(window).width() - width) / 2 - 20) + 'px',
			top : top + 'px'
		});
		
		// オブジェクトをDOMにバインド
		$.data(this.obj.get(0), 'popup', this);

		this.body = $('<div />').addClass(this.className.body);
console.log(this.body);
		this.obj.append(this.body).hide().appendTo('body');
	},
	// urlもしくはjQueryオブジェクトをロードしつつ開く
	open : function(url_or_object){
		if(this.modal) this.overlay.show();
		this.obj.show();

		if(typeof(url_or_object) == 'string'){
			var url = url_or_object;
			this.get(url);
		}else{
			var obj = url_or_object;
			this.body.append(obj);
		}
	},
	close : function(){
		this.obj.remove();
		if(this.overlay) this.overlay.remove();
	},
	load : function(option){
		var self = this;
 		var method = option.method || 'GET';
		var url = method.toUpperCase() == 'GET' ? this.nocacheUrl(option.url) : option.url;
		$.ajax({
			type : method,
			url  : url,
			data : option.query,
			cache : false,
			dataType : 'html',
			success : function(html){
				self.body.html(html);
				self._replaceLinks();
				self._replaceForms();
                self._setAjaxs();
				self._setCloseButton();
				self.obj.scrollTop(0);
				var win = $(window);
				if(win.scrollTop() > 100) win.scrollTop(0);
			}
		});
	},
	get : function(url, query){
		if(!query) query = '';
		this.load({
			method : 'GET',
			url    : url,
			query  : query
		});
	},
	_replaceLinks : function(){
		var self = this;
		var links = this.body.find('a.' + this.className.inner_transition);
		links.each(function(){
            var link = this;
			var url = $(this).attr('href');
			if(this.onclick) this.onclick();
			$(this).click(function(event){
				event.preventDefault();
                if ($(this).hasClass('flips_popup_move_confirm') ){
                    var message = $(this).attr('message');
                    Flips.confirm(message ? message : "ページを移動しますか？", function(result){
                        if (result) self._loadPage(link, url);
                    });
                } else {
                    self._loadPage(link, url);
                }
            });
        });
    },
    _loadPage : function(link, url) {
        if($.data(link, 'loading')) return;
        $.data(link, 'loading', true);
        var height = 16 < $(link).css("height").replace("px", "") ? $(link).css("height") : "20px";
        var display = $(link).css("display");
        $(link).empty().text("loading...");
		this.get(url);
	},
	_replaceForms : function(){
		var self = this;
		var forms = this.body.find('form.' + this.className.inner_transition);
		forms.each(function(){
			var form = $(this);
            var clickBottonName = null;
            var clickBottonValue = null;
            $('input[type=submit]', form).click(function(){
                clickBottonName = $(this).attr('name');
                clickBottonValue = $(this).val();
                $(this).val('loading...');
            });
			form.submit(function(event){
                event.preventDefault();
                if($.data(form.get(0), 'loading')) return;
                $.data(form.get(0), 'loading', true);
				if(this.onsubmit) this.onsubmit();
				self.load({
					method : form.attr('method'),
					url    : form.attr('action'),
					query  : (clickBottonName && clickBottonValue) ? form.serialize() + '&' + clickBottonName + '=' + clickBottonValue : form.serialize()
				});
			});
		});
	},
    _setAjaxs : function(){
        var self = this;
        var links = this.body.find('a.' + this.className.ajax_link);
        links.each(function(){
            var link = this;
            if(this.onclick) this.onclick();
            $(this).click(function(event){
                event.preventDefault();
                // クラスに紐づく処理を実行する
                $.each(Flips.Blog.Ajax.className, function(k,v){
                    if ($(link).hasClass(v)) {
                        new Flips.Blog.Ajax({content : link});
                    }
                });
            });
        });
    },
	_setCloseButton : function(){
		var self = this;
		var buttons = this.body.find('.' + this.className.close_button);
		buttons.each(function(){
			if(this.onclick) this.onclick();
			$(this).click(function(){
				self.close();
			});
		});
	},
	_height: function() {
		// handle IE 6
		if ($.browser.msie && $.browser.version < 7) {
			var scrollHeight = Math.max(
				document.documentElement.scrollHeight,
				document.body.scrollHeight
			);
			var offsetHeight = Math.max(
				document.documentElement.offsetHeight,
				document.body.offsetHeight
			);

			if (scrollHeight < offsetHeight) {
				return $(window).height() + 'px';
			} else {
				return scrollHeight + 'px';
			}
		// handle "good" browsers
		} else {
			return $(document).height() + 'px';
		}
	},
	_width: function() {
		// handle IE 6
		if ($.browser.msie && $.browser.version < 7) {
			var scrollWidth = Math.max(
				document.documentElement.scrollWidth,
				document.body.scrollWidth
			);
			var offsetWidth = Math.max(
				document.documentElement.offsetWidth,
				document.body.offsetWidth
			);

			if (scrollWidth < offsetWidth) {
				return $(window).width() + 'px';
			} else {
				return scrollWidth + 'px';
			}
		// handle "good" browsers
		} else {
			return $(document).width() + 'px';
		}
	},
	/**
	 * キャッシュされないようにURLに「?_=unixtime」なqueryを加える。
	 * jqueryのajax()でcache=falseにするとフラグメントを無視するのでそれを回避したバージョン
	 */
	nocacheUrl : function(url){
		var fragment = '';
		var reg = /^([^#]+)#(.+)$/;
		var m = url.match(reg);
		if(m){
			url = m[1];
			fragment = '#' + m[2];
		}
		
		/**
		 * code from jquery::ajax()
		 * adds unixtime query
		 */
		var ts = +new Date;
		// try replacing _= if it is there
		var ret = url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
		// if nothing was replaced, add timestamp to the end
		url = ret + ((ret == url) ? (url.match(/\?/) ? "&" : "?") + "_=" + ts : "");
	
		return url + fragment;
	}
};

/*
	一時的に画面を使えなくする
	
	usage:
		var loading = new Flips.loading();
		// 時間のかかる処理
		loading.close();
*/
Flips.loading = function(message){
	var text = message || 'データを読み込んでいます...';
	var content = $('<div style="text-align:center">' + text + '</div>');
	this.popup = new Flips.Popup({width:240, top:$(window).height()/2-100, modal:true});
	this.popup.open(content);
	return this;
}
	Flips.loading.prototype.close = function(){
		this.popup.close();
	}

/*
	alert()代替

	message  : *[string]   表示するメッセージ
	callback :  [function] okを押したときに叩かれる。
	modal    :  [bool]     trueならmodalダイアログ、デフォルトtrue
*/
Flips.alert = function(message, callback, modal){
	if(typeof(modal) == 'undefined') modal = true;
	var popup = new Flips.Popup({width:240, top:$(window).height()/2-100, modal:modal});
	var content = $('<div style="text-align:center;"></div>').append($('<p></p>').text(message));
	var button_close = $('<button>OK</button>').click(function(){
		popup.close();
		if(callback) callback.call();
	});
	popup.open(content.append(button_close));
}
/*
	confirm()代替

	message  : *[string]   表示するメッセージ
	callback :  [function] ok/cancelを押したときに叩かれる。第一引数にOKならtrue, cancelならfalseが渡る
	modal    :  [bool]     trueならmodalダイアログ、デフォルトtrue

	usage:
	Flips.confirm(
		'よろしいですか？',
		function(result){ alert(result ? 'OK' : 'CANCEL');}
	);
*/
Flips.confirm = function(message, callback, modal){
	if(typeof(modal) == 'undefined') modal = true;
	var popup = new Flips.Popup({width:240, top:$(window).height()/2-100, modal:modal});
	var content = $('<div style="text-align:center;"></div>').append($('<p></p>').text(message));
	var button_ok = $('<button>OK</button>').click(function(){
		popup.close();
		if(callback) callback.call(null, true);
	});
	var button_cancel = $('<button>キャンセル</button>').click(function(){
		popup.close();
		if(callback) callback.call(null, false)
	});
	popup.open(content.append(button_ok).append(button_cancel));
}

/*
	リンクを自動置換
	クラス名にflips_command_open_popupが含まれるAタグのonclickをhookする
*/
$(document).ready(function(){
	$('a.flips_command_open_popup').each(function(){
		var a = $(this);
		var url = a.attr('href');
		a.attr('href', 'javascript:void(0);').click(function(){
			var popup = new Flips.Popup();
			popup.open(url);
		});
	});
});
