// メニューをhoverしたときの処理
function controlPopupMenu(){
    // ターゲットの取得
    var elems = $('.popup-menu');
    if(elems.length < 1){ return; }
    // データ取得/設定
    var url = '../../ajax/popup';
    $.getJSON(url, function(data){
	if(!data) return false;
	popupDataModel.init(data);
	// イベントハンドラの設定
	elems.hover(
	    function(){ 
		var id = $(this).attr('id');
		selectedPopupModel.init(id);
		var offset = $(this).offset();
		var top  = offset.top + $(this).outerHeight();
		var left = offset.left + 2; 
		selectedPopupModel.setPosition(top,left);
		selectedPopupModel.display(); 
	    },
	    function(){ selectedPopupModel.hide(); }
	);
	
    });
}

// データモデル
var popupDataModel = {

    // popup一覧
    list : [
	// {
	// id : ポップアップ要素
	// title : タイトル
	// content : 本文
	// }, ...
    ],

    init : function(data) { this.list = data; },
    
    // ID検索
    findById: function(id) {
	return $.grep(this.list, function(val){
	    return id == val.id;
	})[0];
    }
};

// 選択しているpopup
var selectedPopupModel = { 

    // 現在表示中のid
    id : '',

    // テンプレート
    tpl : {
	popup : '<div class="popup ui-corner-all" tabindex~"-1"></div>',
	title : '<h3></h3>',
	content: '<p></p>',
	close : '<p class="close">閉じる</p>',
	show  : '<input type="image" src="icon_term.png" alt="(用語解説)"/>'
    },
		
    // キャッシュ
    cache : {
	// id : {
	//   popup : ポップアップ要素
	//   title : タイトル
	//   close : 「閉じる」ボタン
	//   show  : 表示ボタン
	// }, ...
    },

    // 初期化
    init : function(id){
	if(this.cache[id] == undefined || this.cache[id] == null) this.createCache(id);
	this.id = id;
    },

    // キャッシュ作成
    createCache: function(id){
	var selectedData = popupDataModel.findById(id);
	this.cache[id] = {
	    popup   : $(this.tpl.popup),
	    content : $(this.tpl.content).append(selectedData.content)
	};
	this.cache[id].popup.append(this.cache[id].content);
    },

    // 座標の設定
    setPosition: function(top, left){ 
	this.cache[this.id].popup.css({ top: top+'px', left: left + 'px'});
    },

    // 表示
    display: function(){ 
	if(this.cache[this.id] != undefined && this.cache[this.id] != null){
	    $(document.body).append(this.cache[this.id].popup); 
	}
    },
    
    // 非表示
    hide: function(){ 
	if(this.cache[this.id] != undefined && this.cache[this.id] != null){
	    this.cache[this.id].popup.remove(); 
	}
    }

};
