/*(function() {*/
var skobj = {
    constant : {
        researchAppUrl : function() {
            if (location.hostname.match(new RegExp('(?:^(?:www|labs).stickam.jp$)|staging'))) {
                return 'http://labs.stickam.jp';
            } else {
                return 'http://' + location.hostname;
            }
        }
    },
    host : {
        user_id : 0
    },
    viewer : {
        user_id   : 0,
        user_name :''
    },
    page : '',
    research : {
        question_id : 0,
        answer_num  : 0,
        remain      : 0
    },
    confinement : {
        flg : true,
        list_enable_id : [100000010527, 173728274, 173760001, 173752541, 100000040769, 174905573]
    }
};

var skcommon = {
    /*
     *  elementの生成
     */
    create_element : function(obj) {
        var ele = document.createElement(obj.tag);

        for (var key in obj.attribute) {
            ele.setAttribute(key, obj.attribute[key]);
        }

        obj.element.appendChild(ele);
    },

    /*
     *  パラメータの取得
     */
    get_query_param : function(key){
        var pattern = '[?&]' + key + '=(.*?)(?:&|$)';
        var param = location.search.match(new RegExp(pattern));

        return param && param[1] ? param[1] : 'undefined';
    }
};

var skresearch = {
    init : function() {
        document.cookie.match(/token=(.*?)%3A(.*?)%3A/);
        skobj.viewer.user_name = RegExp.$1 || 'undefined';
        skobj.viewer.user_id   = RegExp.$2 || 0;
        skobj.host.user_id     = skcommon.get_query_param('uid');

        if (location.pathname.match(/(\/sample|\/largechat|\/large_chat)/gim)) {
            skobj.page = 'chat';
        } else if (location.pathname.match(/\/app\/research\/form.html/gim)) {
            skobj.page = 'form';
        } else {
            skobj.page = 'undefined';
        }

        /*
         if (skobj.viewer.user_name == 'undefined' || !skobj.viewer.user_id || skobj.host.user_id == 'undefined' || skobj.page == 'undefined') {
         } else {
         skresearch.check_question();
         }
         */

        /*
         *  アンケート情報の取得
         *  [ホストチャット画面または回答フォーム画面]かつ[ホストのuidが取得できた]場合
         */
        if (skobj.page != 'undefined' && skobj.host.user_id != 'undefined') {
            if (skobj.page == 'chat') {
                $.timer(100, function(timer){
                            if (skobj.research.question_id) {
                                timer.reset(60 * 1000);
                            } else {
                                skresearch.check_question();

                                timer.reset(10 * 1000);
                            }
                        });
            } else if (skobj.page == 'form') {
                $.timer(100, function(timer){
                            skresearch.check_question();

                            timer.reset(10 * 1000);
                        });
            }
        }
    },
    get_question : function(question_json) {
        /*
         *  新しいアンケートが出題された場合のみ処理を進める
         *  取得済みのskobj.research.question_idと取得したquestion_json.question_idを比較する
         */
        if (!question_json.question_id) {
            if (skobj.research.question_id != -1) {
                skobj.research.question_id = -1;
                skresearch.gen_noquestion();
            }
        } else {
            if (question_json.question_id != skobj.research.question_id) {
                skobj.research.question_id = question_json.question_id;

                if (skobj.page == 'chat') {
                    /*
                     *  チャット画面に回答フォームへのリンク生成
                     */
                    skresearch.append_formopen();
                } else if (skobj.page == 'form') {
                    /*
                     *  ホストのユーザ情報を取得
                     */
                    if (!skobj.host.api) {
                        $.ajax({
                                   url      : 'http://api.stickam.jp/api/user/' + question_json.user_name + '/profile',
                                   dataType : 'jsonp',
                                   data     : {
                                       mime : 'json'
                                   },
                                   success : function(userapi_json) {
                                       skobj.host.api = userapi_json;

                                       /*
                                        *  回答フォームの生成
                                        */
                                       skresearch.gen_questionform(question_json);
                                   }
                               });
                    } else {
                        /*
                         *  回答フォームの生成
                         */
                        skresearch.gen_questionform(question_json);
                    }
                }
            }
        }
    },
    gen_noquestion : function() {
        if ($('#loader').css('display') == 'none') {
            $('#content').fadeOut(300, function(){
                                      $('#loader').fadeIn(300).fadeTo(1000, 1.0, function(){
                                                                          gen_html();
                                                                      });
                                  });
        } else {
            gen_html();
        }

        function gen_html(){
            var temp_html = '<h1>スティッカム ライブリサーチ</h1><p class="noquestion">現在、アンケートは実施されていません。</p>';

            $('#loader').fadeOut(300, function(){
                                     $('#content').html(temp_html).fadeIn(300);
                                 });
        }
    },
    check_question : function() {
        $.ajax({
                   url      : skobj.constant.researchAppUrl() + '/app/research/json/' + skobj.host.user_id + '.json',
                   dataType : 'jsonp',
                   data     : {
                       hostchat_id : skobj.host.user_id
                   }
               });
    },
    append_formopen : function() {
        clearTimeout(ads_timer);

        var open_window = function() {
            window.open(tempHref, 'researchForm', 'width=500, height=300, menubar=no, toolbar=no, scrollbars=no');
        };

        var tempHref = skobj.constant.researchAppUrl() + '/app/research/form.html?uid=' + skobj.host.user_id;

        $('#adsContent').fadeOut(500, function(){
                                     $('#adsContent').html('');
                                     $('<a href="' + tempHref + '"><strong>[スティッカムリサーチ] アンケート画面を開くにはこちらをクリックしてください</strong></a>').appendTo('#adsContent').click(function(){
                                                                                                                                                                                                        open_window();
                                                                                                                                                                                                        return false;
                                                                                                                                                                                                    });
                                     $(this).fadeIn(200).fadeOut(200).fadeIn(200);
                                 });

    },
    gen_questionform : function(question_json) {
        function change_disabled() {
            //$('input[@type^=radio]').each(function(){
            //  $(this).attr({disabled : 'disabled'})
            //});

            $('#answerSubmit').attr({disabled : 'disabled'});
        }

        function gen_answer_note(remain) {
            var temp_text = '以下の回答案の中から選択して送信ボタンを押してください。';

            if (typeof remain != 'undefined' && remain != 'nolimit') {
                if (remain > 0) {
                    temp_text = 'あなたはあと' + remain + '回まで回答が可能です。<br />' + temp_text;
                } else {
                    temp_text = 'あなたはこの質問をすでに回答済みです。';
                }
            }

            return temp_text;
        }

        if ($('#loader').css('display') == 'none') {
            $('#content').fadeOut(300, function(){
                                      $('#loader').fadeIn(300).fadeTo(1000, 1.0, function(){
                                                                          gen_html();
                                                                      });
                                  });
        } else {
            gen_html();
        }

        function gen_html() {
            var temp_html = '<div id="question">'
                + '<h1>スティッカム ライブリサーチ</h1>'
                + '<p>' + skobj.host.api.screen_name + 'さんからの質問です。</p>'
                + '<dl>'
                + '<dt>質問 :</dt>'
                + '<dd>' + question_json.question + '</dd>'
                + '</dl>'
                + '<p class="note">' + (function(){
                                            if (question_json.max_count == 'nolimit') {
                                                return 'この質問は回答数の制限はありません。';
                                            } else {
                                                return 'この質問は' + question_json.max_count + '回の回答制限があります。';
                                            }
                                        })() + '</p>'
                + '</div>'
                + '<div id="answer">'
                + '<dl>'
                + '<dt>回答 :</dt>'
                + '<dd>'
                + '<p class="note" id="answerNote">' + gen_answer_note() + '</p>'
                + '<ol id="answerSelect">'
                + '</ol>'
                + '<div id="answerBlock">'
                + '<p id="answerStatus"></p>'
                + '<div id="answerSubmitBlock">'
                + '<button id="answerSubmit">回答を送信</button>'
                + '</div>'
                + '</div>'
                + '</dd>'
                + '</dl>'
                + '</div>'
            ;

            $('#loader').fadeOut(300, function(){
                                     $('#content').html(temp_html).fadeIn(300);

                                     var temp_checked = question_json.select.length == 1 ? 'checked="checked"' : '';
                                     for (var i = 0; i < question_json.select.length; i++) {
                                         var count = i + 1;
                                         $('#answerSelect').append(
                                             $('<li></li>').append('<input type="radio" name="answer" value="' + count + '" id="answer' + count + '" ' + temp_checked + ' />')
                                                 .append('<label for="answer' + count + '">' + question_json.select[i] + '</label></li>')
                                         );
                                     }

                                     if (question_json.remain == 0) change_disabled();

                                     $('#answerSubmit').click(function(){
                                                                  if (!$('input:checked').val()) {
                                                                      alert('回答が選択されていません。\n選択後、もう一度「回答を送信」ボタンを押してください。');
                                                                  } else {
                                                                      $('#answerStatus').text('回答を送信しています...').fadeIn(100);
                                                                      skobj.research.answer_num = $('input:checked').val();

                                                                      $.ajax({
                                                                                 url : skobj.constant.researchAppUrl() + '/app/research/answer',
                                                                                 dataType : 'jsonp',
                                                                                 data : {
                                                                                     question_id : skobj.research.question_id,
                                                                                     hostchat_id : skobj.host.user_id,
                                                                                     answer_num  : skobj.research.answer_num
                                                                                 },
                                                                                 success : function(json) {
                                                                                     if (json.remain == 0) change_disabled();

                                                                                     if (json.status == 'OK') {
                                                                                         $('#answerStatus').text('回答が完了しました。').fadeTo(2000, 1.0).fadeOut(1000);
                                                                                     } else {
                                                                                         if (json.description == 'answered') {
                                                                                             $('#answerStatus').text('あなたはこの質問をすでに回答済みです。').fadeTo(2000, 1.0).fadeOut(1000);
                                                                                         } else {
                                                                                             $('#answerStatus').text('エラーが発生しました。').fadeTo(2000, 1.0).fadeOut(1000);
                                                                                         }
                                                                                     }

                                                                                     $('#answerNote').html(gen_answer_note(json.remain));
                                                                                 },
                                                                                 error :function(){
                                                                                     $('#answerStatus').text('送信に失敗しました。').fadeOut(1000);
                                                                                 }
                                                                             });
                                                                  }
                                                              });
                                 });
        }
    }
};

/*
 *    jQueryのチェック
 */
if (!skobj.confinement.flg || skobj.confinement.list_enable_id.join(',').match(new RegExp('\\b' + skcommon.get_query_param('uid') + '\\b'))) {
    var timerCheckJquery = setInterval(function(){
                                           if (typeof jQuery == 'function') {
                                               clearInterval(timerCheckJquery);

                                               var timerCheckJqueryPlugin = setInterval(function(){
                                                                                            if (typeof jQuery.timer == 'function') {
                                                                                                clearInterval(timerCheckJqueryPlugin);
                                                                                                skresearch.init();

                                                                                            } else if (!document.getElementById('jqueryTimer')) {
                                                                                                skcommon.create_element(
                                                                                                    {
                                                                                                        tag : 'script',
                                                                                                        attribute : {
                                                                                                            id       : 'jqueryTimer',
                                                                                                            encoding : 'UTF-8',
                                                                                                            src      : skobj.constant.researchAppUrl() + '/lib/plugin/jquery.timer.js',
                                                                                                            type     : 'text/javascript'
                                                                                                        },
                                                                                                        element : document.getElementsByTagName('head')[0]
                                                                                                    }
                                                                                                );
                                                                                            }
                                                                                        }, 200);
                                           } else if (!document.getElementById('jquery')) {
                                               skcommon.create_element(
                                                   {
                                                       tag : 'script',
                                                       attribute : {
                                                           id       : 'jquery',
                                                           encoding : 'UTF-8',
                                                           src      : 'http://jquery-ui.googlecode.com/svn/tags/1.8.1/jquery-1.4.2.js',
                                                           type     : 'text/javascript'
                                                       },
                                                       element : document.getElementsByTagName('head')[0]
                                                   }
                                               );
                                           }
                                       }, 200);
}
/*})();*/

