if (typeof(QLife) == 'undefined') {
    var QLife = {};
}

QLife.Detail2009 = {
    /**
     * 
     */
    init : function() {
        this._initMap();
        this.updatePagersOnclick();
        this._initHistory();
    },
    /**
     * Yahoo地図を初期化
     */
    _initMap : function() {
//        var mapLat = $F('map-lat');
//        var mapLong = $F('map-long');
//        var map = new YahooMapsCtrl('map-mini', mapLat + ',' + mapLong, 3, YMapMode.Map, YDatumType.WGS84);
//        map.setVisibleCentermark(false);
//        map.setEnableWheelOperation(false);
//        map.addCategory('qlife_mappin', '/pet/images/icon_mappin.png', {'width' : 23, 'height' : 25});
//        map.addIcon('hospital', mapLat + ',' + mapLong, '', 'qlife_mappin');
//        map.setVisibleSliderbar(false);
    },
    /**
     * ブラウザ履歴処理の初期化
     */
    _initHistory : function () {
        // 
        dhtmlHistory.initialize();
        dhtmlHistory.addListener(this.restoreHistory);
    },
    
    // {{{ ブラウザ履歴

    /**
     * ブラウザ履歴の追加
     */
    addHistory : function(pathname) {
        if (! pathname.match(/^\/(?:hospital_detail_|2009_controller\.php).+$/)) {
            return false;
        }
        dhtmlHistory.add(pathname, null);
//        alert('addHistory');
    },
    /**
     * ブラウザ履歴の復帰
     */
    restoreHistory : function(newLocation, historyData) {
        if ($('hospital_kuchikomi') == null) {
            return false;
        }
        // 復帰用URLがないとき
        if (newLocation == null || newLocation.length == 0) {
            newLocation = String(window.location.href).replace(/^https*:\/\/[^\/]+(\/hospital_detail_[^#]+).*$/, '$1');
        }
        
//        if (newLocation.match(/^\/hospital_detail_.+$/)) {
        // 復帰処理では履歴を追加しない
        QLife.Detail2009.updateKuchikomi(null, newLocation, false);
//        }
    },
    /**
     * ページャーのonclickイベントを更新
     */
    updatePagersOnclick : function(){
        var anchors = $$('div.hospital_pager a');
        anchors.each(function(anc, index) {
            anc.onclick = function() {
                QLife.Detail2009.updateKuchikomi(this, null, true);
                return false; // hrefによるページ遷移禁止
            };
        });
    },
    /**
     * 口コミ一覧の更新処理
     */
    updateKuchikomi : function(anchor, pathname, addHistory) {
        if (anchor != null) {
            pathname = QLife.Common.getPathname(anchor);
        }
        if (pathname == null || pathname.length == 0) {
            return false;
        }
        // GooglwAnalyticsコール
//        alert('updateKuchikomi');
        QLife.Common.gaTrack(pathname);
        // 待機画像
        $('hospital_kuchikomi').innerHTML = QLife.Common.IMG_LOADING;

        new Ajax.Request('2009qlife_views/hospital_itemlist_update.php', {
            method : 'get',
            parameters : {pathname : pathname},
            onSuccess : function(transport) {
                $('hospital_kuchikomi').innerHTML = transport.responseText;
                QLife.Detail2009.updatePagersOnclick();
            }
        });
        // 履歴を追加
        if (addHistory) {
            QLife.Detail2009.addHistory(pathname);
        }
    },
    
    // }}}

    // {{{ スターレイティング

    /**
     * すでに評価送信済みか
     */
    rated : false,
    /**
     * スターレイティング送信
     */
    starRate : function(itemid, currentRate, isPositive) {
        if (this.rated) {
            return;
        }
        this.rated = true;

        new Ajax.Request('2009qlife_views/starrating.php', {
            method : 'get',
            parameters : {itemid : itemid, is_positive : (isPositive ? '1' : '0')},
            onSuccess : function(transport) {
                if (transport.responseText == '1') {
                    // 成功
                    $('starrating_success').setStyle({display : 'block'});
                } else {
                    // 失敗
                    $('starrating_failed').setStyle({display : 'block'});
                }
                // 画像変更
                if ((isPositive && currentRate < 5) || (! isPositive && currentRate > 0)) {
                    var result = currentRate + (isPositive ? 1 : -1) * 0.5;
                    $('rateimage').src = '2009qlife_images/star/' + (result * 10) + '.png';
                }
            }
        });
    },
    // }}}
    
    // {{{ 口コミ投稿フォーム

    /**
    * 口コミ投稿: フォーム開く
    */
   open : function(divId){
       if ($(divId) == null) {
           alert('id=' + divId + ' is not exist.');
           return;
       }

       this.counter = 0;
       this.ev = new PeriodicalExecuter(function(){ QLife.Detail2009._animateOpening(divId); }, 0.05);
   },
   /**
    * 口コミ投稿: フォーム閉じる
    */
   close : function(divId){
       this.divBg.setStyle({display : 'none'});
       $(divId).setStyle({display : 'none'});
   },
   /**
    * 背景div
    */
   divBg : null,
   /**
    * フォーム開く処理カウンタ
    */
   counter : 0,
   /**
    * フォーム開く処理オブジェクト (PeriodicalExecuter)
    */
   ev : null,
   /**
    * ページ領域の大きさ(ピクセル単位)を返す
    */
   _getPageSize : function(){
       var width = 0, height = 0;
       if (window.innerWidth && window.scrollMaxX) {
           // Firefox
           width  = window.innerWidth + window.scrollMaxX;
           height = window.innerHeight + window.scrollMaxY;
       } else if (document.body.scrollHeight) {
           // IE, Opera, Safari
           width  = document.body.scrollWidth;
           height = document.body.scrollHeight;
       }
       return {width : width, height : height};
   },
   _getFormLeft : function(divId){
       var div = $(divId);
       var size = this._getPageSize();
       var left = 0;
       if (size.width - 60 > div.getWidth()) {
           left = Math.floor((size.width - div.getWidth()) / 2);
       } else {
           left = 60;
       }
       return left;
   },
   /**
    * 
    */
   _animateOpening : function(divId){
       // 背景領域を表示(透明)
       if (this.divBg == null) {
           this.divBg = $(document.createElement('div'));
           this.divBg.id = 'toukou_bg';
           // 背景領域スタイル
           var pageSize = this._getPageSize();
           this.divBg.setStyle({
               opacity : '0',
               position : 'absolute',
               top : '0',
               left : '0',
               width : pageSize.width + 'px',
               height : pageSize.height + 'px',
               zIndex : '900'
           });
           $$('body')[0].appendChild(this.divBg);
//           window.location = '#' + this.divBg.id;
       }
       var div = $(divId);
       if (this.counter == 0) {
           // アニメーション開始: フォームを透明表示
           var left = this._getFormLeft(divId);
           div.setStyle({
               opacity : '0',
               display : 'block',
               top : '100px',
               left : String(left) + 'px'
               });
       } else if (this.counter == 10) {
           // アニメーション終了: ループ終了、
           if (this.ev != null) {
               this.ev.stop();
               this.ev = null;
           }
           div.setStyle({opacity : '1'});
       } else {
           // アニメーション中: フォームを徐々に不透明に
           var opacityStep = 1.0 / 10 * this.counter;
           div.setStyle({opacity : String(opacityStep)});
       }
       this.counter++;
   },
   /**
    * gaイベント追跡
    */
   trackEvent : function(category, action, label, value)
   {
//       alert('category=' + category + ' action=' + action + ' label=' + label + ' value=' + value);
//       return true;
       try {
           if (pageTracker._trackEvent) {
               pageTracker._trackEvent(category, action, label, value);
               setTimeout('document.location = "' + link.href + '"', 100);
           }
       } catch (e) {
           if (console.log) {
               console.log(e);
           }
       }
       return true;
   }
}

Event.observe(window, 'load', function(){ QLife.Detail2009.init(); });

