/**
 * @classDescription prototype.js
 */
if(!Control) var Control = {};
Control.cypopupTzoneSelects = [];
Control.CypopupTzoneSelect = Class.create({
    /**
     *
     * @param {string}              field ターゲットフィールド　ID
     * @param {string} nextfield    Next TabIndex Field         ID
     * @param {string} ymdfield     対象yyyy/mm/dd格納Field     ID
     * @param {string} ajaxUri      Open時Ajaxリクエスト
     */
    initialize : function(field, nextfield, ymdfield, ajaxUri, exam_code){
        var tzoneSelect = this;
        Control.cypopupTzoneSelects.push(tzoneSelect);
        this.myField    = $(field);
        this.nextfield  = $(nextfield);
        this.ymdfield   = $(ymdfield);
        this.fieldName = this.myField.id;
        if(exam_code == ""){
            this.exam_code = 0;
        }
        else{
            this.exam_code = exam_code - 0;
        }
        this.ajaxUri    = ajaxUri;
        this.oldYmd     = "";
        this.isOpen     = false;
        this.isClick    = false;
        this.eventSeted = false;
        this.doubleBooking = false;
        this.r_items = [];
        this.radioItems = [];
 //-----------------------------2009/09/24
        this.checkedCount = -1;
        this.radioItemCount = -1;
        this.rowHeight = 0;
        this.tableHeight = 0;
 //-----------------------------
        if(!Control.CypopupTzoneSelect.CONTROL) {
            Control.CypopupTzoneSelect.CONTROL = {};
            if(!$("cypopuptzoneselect")) {
                var control = Builder.node('div', {id:'cypopuptzoneselect'});
                control.innerHtml = 'dumm';
                document.body.appendChild(control);
            }
            Control.CypopupTzoneSelect.CONTROL = {
                popUp : $("cypopuptzoneselect")
            };
            Element.hide($("cypopuptzoneselect"));
        }
        this.control = Control.CypopupTzoneSelect.CONTROL;

        this.fieldOnFocusListener = this.open.bindAsEventListener(this);
        this.fieldKeydownListener = this.fieldKeydown.bindAsEventListener(this);
        this.popupOnClickListener = this.marginClick.bindAsEventListener(this);
        this.docOnClickListener   = this.docClick.bindAsEventListener(this);
/*
        this.ctrlscrollListener   = this.ctrlScroll.bindAsEventListener(this);
        Event.observe(this.control.popUp,"scroll", this.ctrlscrollListener);
*/

        Event.observe(this.myField, "focus", this.fieldOnFocusListener);
        Event.observe(this.myField, "keydown", this.fieldKeydownListener);
        Event.observe(this.control.popUp, "click", this.popupOnClickListener);
        Event.observe(document, 'click', this.docOnClickListener);
    },



    /**
     * トリガー:myField が focus
     * yyyy/mm/dd が以前から変更があったら
     * サーバーへradoi エレメント生成要素を
     * 返すようにリクエスト
     * 変更がない場合は旧来のinerHtmlを表示
     * @param {Object} event
     */
    open : function(event) {
        if(this.ymdfield.value == ""){
            this.close(event);
            event.stop();
           this.ymdfield.focus();

            return;
        }
        Control.cypopupTzoneSelects.each(function(ele){
            if(ele != this) {
                ele.close();
            }
        });
        Control.CypopupTzoneSelect.activeTzoneSelect = this;

        Event.stopObserving(this.myField, 'focus');
        if(this.ymdfield.value == this.oldYmd) {
            this.render();
        }
        else{
            this.getR_itemsListener = this.getR_items.bindAsEventListener(this);
            var YMD = this.ymdfield.value.split("/");
            var data = 'yy='+YMD[0]+'&mm='+YMD[1]+'&dd='+YMD[2];
            if(this.exam_code > 0){
                data = data + '&exam_code=' + this.exam_code;
            }
            var options = {
                method:'post',
                onSuccess:this.getR_itemsListener,
                parameters:data
            };
            new Ajax.Request(this.ajaxUri, options);
        }
    },
    getR_items : function(httpObject){
        if(Control.CypopupTzoneSelect.activeTzoneSelect != this)
            return;
        if(this.r_items){
            this.r_items.clear();
        }
        var res = httpObject.responseJSON;
        if (res == "") {
            Event.observe(this.myField, "focus", this.fieldOnFocusListener);
            this.oldYmd     = "";
            var ymd = this.ymdfield.value.split("/");
            this.ymdfield.value = ymd[0] + '/' + ymd[1] + '/' + '00';
            this.close();
            this.ymdfield.focus();
        }
        else {
            this.r_items = res.toArray();
            this.render();
        }
    },

    eraseEvents : function() {

        for(var i = 0; i < this.radioItems.length; i++){
            Event.stopObserving($(this.radioItems[i]), 'click');
        }
        this.eventSeted = false;
    },

    radioBtnClick : function(event){
        Event.stop(event);
        var ele = Event.element(event);
        this.myField.value = ele.value;
        this.close(event);
        this.nextfield.focus();
    },

    setEvents : function(){
        this.radioBtnClickListener = this.radioBtnClick.bindAsEventListener(this);

        for (var i = 0; i < this.radioItems.length; i++) {
            Event.observe($(this.radioItems[i]), 'click', this.radioBtnClickListener);
        }
        this.eventSeted = true;

    },

    /**
     * btn or non, sy_min, en_min
     */

    makeHTML : function(){
        this.radioItems.clear();
        this.checkedCount = -1;
        var html = "";
        var idVal = "";
        var hh, mm, st, en, vv;
        var checked = false;
        var items = [];
        var j = 0;
        for(var i = 0; i < this.r_items.length; i++){
            items = this.r_items[i].split(",")
            items[1] -= 0;
            items[2] -= 0;
            hh = Math.floor(items[1]  / 60);
            mm = items[1] % 60;
            if(hh < 10)
                hh = '0' + hh;
            if(mm < 10)
                mm = '0' + mm;
            st = hh + ':' + mm;

            hh = Math.floor(items[2]  / 60);
            mm = items[2] % 60;
            if(hh < 10)
                hh = '0' + hh;
            if(mm < 10)
                mm = '0' + mm;
            en = hh + ':' + mm;
            vv = st + ' ～ ' + en;
            if (items[0] == 'btn') {
                idVal = this.fieldName + '-' + items[1] + '-' + items[2];
                this.radioItems.push(idVal);
                html += '<input type="radio" name="' + this.fieldName + '-ritem" id="' + idVal + '" ';
                html += 'class="cycPop-radio-items" value="' + vv + '" ';

                if (vv == this.myField.value) {
                    html += 'checked="checked" />';
                    checked = true;
                    this.checkedCount = j;
                }
                else {
                    html += ' />';
                }
                html += '<label for="' + this.fieldName + '-' + items[1] + '-' + items[2] + '">';
                html += '&nbsp;' + vv + '</label><br />'+"\n";
                j++

            }
            else{
                html += '<span class="cannot"><input type="radio" disabled="true" />' + '<span class="cyc-through">' + '&nbsp;' + vv + '</span></span><br />'+"\n";
            }

        }
        this.radioItemCount = j;
        if(this.myField.value != "" && !checked) {
            this.myField.value = "";
        }
        return html;
    },
    render : function(){
        if(this.eventSeted){
            this.eraseEvents();
        }

        Element.update(this.control.popUp, this.makeHTML());
        var h = this.control.popUp.getHeight();
        if(h > 200){
            this.control.popUp.setStyle('height:200px;');
        }
        Element.show(this.control.popUp);
        this.setEvents();
        var pos = Position.cumulativeOffset(this.myField);
        pos[1] = pos[1] + this.myField.getHeight();

        this.isOpen = true;
        this.control.popUp.style.left = (pos[0]) + "px";
        this.control.popUp.style.top = (pos[1]) + "px";
        this.oldYmd = this.ymdfield.value;

        this.rowHeight = $(this.radioItems[0]).getHeight();
        this.tableHeight = this.control.popUp.getHeight();
        if(this.checkedCount >= 0){
            var pos = $(this.radioItems[this.checkedCount]).offsetTop + this.rowHeight - this.control.popUp.scrollTop;
            if (pos > this.tableHeight) {
                this.control.popUp.scrollTop += pos - this.tableHeight;
            }
        }

        this.myField.focus();
    },

    close :function(event) {
        if(!this.isOpen)
            return;
        this.isOpen = false;
        this.control.popUp.style.height = null;
        if (Control.CypopupTzoneSelect.activeTzoneSelect == this) {
            Control.CypopupTzoneSelect.activeTzoneSelect = null;
        }
        Element.hide(this.control.popUp);
        Event.observe(this.myField, "focus", this.fieldOnFocusListener);
        if(this.eventSeted)
            this.eraseEvents();
        if(this.myField.value != ""){
            if(!this.myField.value.match(/([01][0-9]|2[0-3]):[0-5][0-9]\s～\s([01][0-9]|2[0-3]):[0-5][0-9]$/)){
                this.myField.value = "";
            }
        }

    },
    keyDown : function(){
        var i = this.checkedCount + 1;
        if( i < this.radioItemCount){
            this.checkedCount = i;
            $(this.radioItems[this.checkedCount]).checked = true;
            var pos = $(this.radioItems[this.checkedCount]).offsetTop + this.rowHeight - this.control.popUp.scrollTop;
            if (pos > this.tableHeight) {
                this.control.popUp.scrollTop += pos - this.tableHeight + this.rowHeight ;
            }

        }
    },
    keyUp : function(){
        var i = this.checkedCount - 1;
        if(i >= 0){
            this.checkedCount = i;
            $(this.radioItems[this.checkedCount]).checked = true;
            var pos = $(this.radioItems[this.checkedCount]).offsetTop - this.control.popUp.scrollTop;
            if (pos < 0) {
                this.control.popUp.scrollTop += pos;
            }

        }
    },
    keyEnter: function(event){
        Event.stop(event);
        if(this.checkedCount >= 0){
            this.myField.value = $(this.radioItems[this.checkedCount]).value;
            this.close(event);
            this.nextfield.focus();
        }
    },
    keyTab : function(event){
        if (this.checkedCount >= 0) {
            this.myField.value = $(this.radioItems[this.checkedCount]).value;
        }
        this.close(event);
    },
    pageUp :function(){
        var cnt = Math.ceil(this.radioItemCount / 4);
        this.checkedCount -= cnt;
        if(this.checkedCount < 0)
            this.checkedCount = 0;
        $(this.radioItems[this.checkedCount]).checked = true;
        var pos = $(this.radioItems[this.checkedCount]).offsetTop - this.control.popUp.scrollTop;
        if (pos < 0) {
            this.control.popUp.scrollTop += pos;
        }

    },
    pageDown :function(){
        var cnt = Math.ceil(this.radioItemCount / 4);
        this.checkedCount += cnt;
        if(this.checkedCount >= this.radioItemCount)
            this.checkedCount = this.radioItemCount - 1;
        $(this.radioItems[this.checkedCount]).checked = true;
        var pos = $(this.radioItems[this.checkedCount]).offsetTop + this.rowHeight - this.control.popUp.scrollTop;
        if (pos > this.tableHeight) {
            this.control.popUp.scrollTop += pos - this.tableHeight + this.rowHeight ;
        }

    },


    /**
     * Tabキーでクローズ
     * @param {Object} event
     */
    fieldKeydown : function(event) {
        var code = event.keyCode;
        switch (code) {
            case 9:
                this.keyTab(event);
                break;
            case 13:
                this.keyEnter(event);
                break;
            case 33:
                this.pageUp();
                Event.stop(event);
                break;
            case 34:
                this.pageDown();
                Event.stop(event);
                break;

            case 38:
                this.keyUp();
                Event.stop(event);
                break;
            case 40:
                this.keyDown();
                Event.stop(event);
                break;
            default:
                Event.stop(event);
        }

    },
    docClick : function(event) {
        var ele = Event.element(event);
        if (ele != this.myField && ele != this.control.popUp) {
            if(Control.CypopupTzoneSelect.activeTzoneSelect == this){
                this.close();
            }
        }
    },


/*
    ctrlScroll:function(event){
        Event.stop(event);
        var ele = Event.element(event);
        var x = 0;
    },
*/



    /**
     * popUpのragio以外をクリック
     * @param {Object} event
     */
    marginClick:function(event){
        Event.stop(event);
    }

});


Control.CypopupTzoneSelect.activeTzoneSelect;
Control.CypopupTzoneSelect.CONTROL;



Control.CyMasterpopupTzoneSelect = Class.create(Control.CypopupTzoneSelect, {
    open : function(event) {
        if(this.ymdfield.value == ""){
            this.close(event);
            event.stop();
           this.ymdfield.focus();

            return;
        }
        Control.cypopupTzoneSelects.each(function(ele){
            if(ele != this) {
                ele.close();
            }
        });
        Control.CypopupTzoneSelect.activeTzoneSelect = this;

        Event.stopObserving(this.myField, 'focus');
        if(this.ymdfield.value == this.oldYmd) {
            this.render();
        }
        else{
            this.getR_itemsListener = this.getR_items.bindAsEventListener(this);
            var YMD = this.ymdfield.value.split("/");
            var data = 'yy='+YMD[0]+'&mm='+YMD[1]+'&dd='+YMD[2]+'&master=1';
            if(this.exam_code > 0){
                data = data + '&exam_code=' + this.exam_code;
            }
            var options = {
                method:'post',
                onSuccess:this.getR_itemsListener,
                parameters:data
            };
            new Ajax.Request(this.ajaxUri, options);
        }
    }

});


Control.CyTscopedpopupTzoneSelect = Class.create(Control.CypopupTzoneSelect, {
    initialize : function(field, nextfield, ymdfield, tscope, ajaxUri, exam_code){
        var tzoneSelect = this;
        Control.cypopupTzoneSelects.push(tzoneSelect);
        this.myField    = $(field);
        this.nextfield  = $(nextfield);
        this.ymdfield   = $(ymdfield);
        this.fieldName = this.myField.id;
        if(exam_code == ""){
            this.exam_code = 0;
        }
        else{
            this.exam_code = exam_code - 0;
        }
        this.ajaxUri    = ajaxUri;
        this.tScope     = $(tscope);

        this.oldTScopeValue = this.tScope.value;
        this.oldYmd     = "";
        this.isOpen     = false;
        this.isClick    = false;
        this.eventSeted = false;
        this.doubleBooking = false;
        this.r_items = [];
        this.radioItems = [];
 //-----------------------------2009/09/24
        this.checkedCount = -1;
        this.radioItemCount = -1;
        this.rowHeight = 0;
        this.tableHeight = 0;

 //-----------------------------
        if(!Control.CypopupTzoneSelect.CONTROL) {
            Control.CypopupTzoneSelect.CONTROL = {};
            if(!$("cypopuptzoneselect")) {
                var control = Builder.node('div', {id:'cypopuptzoneselect'});
                control.innerHtml = 'dumm';
                document.body.appendChild(control);
            }
            Control.CypopupTzoneSelect.CONTROL = {
                popUp : $("cypopuptzoneselect")
            };
            Element.hide($("cypopuptzoneselect"));
        }
        this.control = Control.CypopupTzoneSelect.CONTROL;

        this.fieldOnFocusListener = this.open.bindAsEventListener(this);
        this.fieldKeydownListener = this.fieldKeydown.bindAsEventListener(this);
        this.popupOnClickListener = this.marginClick.bindAsEventListener(this);
        this.docOnClickListener   = this.docClick.bindAsEventListener(this);

        Event.observe(this.myField, "focus", this.fieldOnFocusListener);
        Event.observe(this.myField, "keydown", this.fieldKeydownListener);
        Event.observe(this.control.popUp, "click", this.popupOnClickListener);
        Event.observe(document, 'click', this.docOnClickListener);
    },
    open: function(event){
        if(this.ymdfield.value == ""){
            this.close(event);
            event.stop();
           this.ymdfield.focus();

            return;
        }
        Control.cypopupTzoneSelects.each(function(ele){
            if(ele != this) {
                ele.close();
            }
        });
        Control.CypopupTzoneSelect.activeTzoneSelect = this;

        Event.stopObserving(this.myField, 'focus');
        if((this.ymdfield.value == this.oldYmd)  &&
           (this.oldTScopeValue == this.tScope.value)){
            this.render();
        }
        else{
            this.oldTScopeValue = this.tScope.value;
            this.getR_itemsListener = this.getR_items.bindAsEventListener(this);
            var YMD = this.ymdfield.value.split("/");
            var tscope = this.tScope.value.split(",");
            var data = 'yy='+YMD[0]+'&mm='+YMD[1]+'&dd='+YMD[2]
                     + '&from=' + tscope[0] + '&to=' + tscope[1];
            if(this.exam_code > 0){
                data = data + '&exam_code=' + this.exam_code;
            }
            var options = {
                method:'post',
                onSuccess:this.getR_itemsListener,
                parameters:data
            };
            new Ajax.Request(this.ajaxUri, options);
        }
    },
    render : function($super){
        if(this.r_items.length == 1){
            var items = this.r_items[0].split(',');
            var str = (((items[1] - 0) / 60).floor()).toPaddedString(2)
                    + ':'
                    + ((items[1] - 0) % 60).toPaddedString(2)
                    + ' ～ '
                    + (((items[2] - 0) / 60).floor()).toPaddedString(2)
                    + ':'
                    + ((items[2] - 0) % 60).toPaddedString(2);
            this.myField.value = str;
            this.oldYmd = this.ymdfield.value;
            Event.observe(this.myField, "focus", this.fieldOnFocusListener);
            this.nextfield.focus();
        }
        else{
            $super();
        }

    }

});

