var Background = Class.create({
    initialize: function(body) {
        this.body = body;
        this.initElement();
        this.loadingImg = LoadingImage.getInstance();
        this.init();
    },
    initElement: function() {
        this.backgroundElement                   =  document.createElement("div");
        this.backgroundElement.id                =  "popup01";
        this.backgroundElement.className         =  "popup01BG";
    },
    show: function() {
        this.body.appendChild(this.backgroundElement);
        jQuery(this.backgroundElement).fadeIn();
        this.loadingImg.show();
    },
    finish: function() {
        try {
            this.body.removeChild(this.backgroundElement);
        } catch(e) {}
    },
    init: function() {
    }
});

var CloseButton = Class.create({
    initialize: function (popup) {
        this.popup = popup;
        this.btns = $A(document.getElementsByClassName('close'));
        this.checkboxs = $A(document.getElementsByClassName(popup.checkboxClassName));
    },

    initMouseEvent: function() {
        this.btns.each(function(btn) {
            btn.observe('click', function() {
                this.doClose();
                this.finish();
                this.doorSelectbox.show();
            }.bind(this));
        }.bind(this.popup));
        this.checkboxs.each(function(chkbox) {
            chkbox.observe('click', this.checkLimit.bind(this));
        }.bind(this.popup));
    }
});

var DoorPopup = Class.create(Background, {
    initDialog: function(href) {
        this.href = href;
        var screenHeight = document.documentElement.clientHeight;
        var scrollHeight = document.body.scrollTop || document.documentElement.scrollTop;
        this.show();
        this.dialog                   =  document.createElement("div");
        this.dialog.id                =  this.name + "Dialog";
        this.dialog.style.width       =  "700px";
        this.dialog.style.zIndex      =  100;
        this.dialog.style.left        =  (document.body.clientWidth-700)/2 + 'px';
        this.dialog.style.position    =  "absolute";
        this.dialog.style.top         =  ((screenHeight/2 + scrollHeight) - 300) + "px";
        this.body.appendChild(this.dialog);
        jQuery(this.dialog).fadeIn();
        this.loadingImg.hide();
        this.doorSelectbox = DoorSelectbox.getInstance();
        this.doorSelectbox.hide();
    },
    isBaseArea: function() {
        return this.name == 'pref';
    },
    isDependingOnBaseArea: function() {
        return this.isCityOrLine();
    },
    isCityOrLine: function() {
        return this.name == 'city' || this.name == 'line' || this.name == 'town';
    },
    closeDialog: function() {
        try {
            this.doorSelectbox.show();
            this.body.removeChild(this.dialog);
        } catch (e) {}
    },
    updateContents: function(pars) {
        new Ajax.Updater(
            this.name + 'Dialog',
            '/dialog/' + this.name,
            {
                method: 'GET',
                parameters: pars,
                asynchronous: false
            }
        );
    },
    close: function() {
        this.body.removeChild(this);
        this.body.removeChild(this.element);
    },
    initMouseEvent: function() {
        new CloseButton(this).initMouseEvent();
        this.initSearchBtnEvent();
        this.initLinkEvent();
        this.initBackBtnEvent();
        this.initCheckAllEvent();
        this.initLinkAllEvent();
    },
    checkLimit: function() {
        if (this.limit == undefined || this.limit == null) {
            return ;
        }
        var checkboxs = $A(document.getElementsByClassName(this.checkboxClassName));
        numChecked = checkboxs.inject(0, function(acc, chkbox) {return chkbox.checked? acc+1 : acc;});
        
        $$('div.searchSubmit input').each(function(searchBtn) {searchBtn.disabled = (numChecked == 0);});
        if (numChecked >= this.limit) {
            checkboxs.each(function(chkbox) {chkbox.disabled = !chkbox.checked;});
        } else {
            checkboxs.each(function(chkbox) {chkbox.disabled = false;});
        }
    },
    initSearchBtnEvent: function() {
        $A(document.getElementsByClassName('btnAdSearch')).each(function(searchBtn) {
            searchBtn.observe('click', function() {
                for (var key in updaterMap) {
                    if ((this.name + 'Update').match(new RegExp(key, 'i'))) {
                        updater = updaterMap[key];
                        break;
                    }
                }
                updater.update();
                this.closeDialog();
                this.finish();
                if (this.executeNextPopup) {
                    this.executeNextPopup();
                }
            }.bind(this));
        }.bind(this));
    },
    initLinkEvent: function() {
        $A(document.getElementsByClassName(this.name + 'Link')).each(function(link) {
            link.observe('click', function() {
                for (var key in updaterMap) {
                    if ((this.name + 'Update').match(new RegExp(key, 'i'))) {
                        updater = updaterMap[key];
                        break;
                    }
                }
                if (!updater.isExisted(link.id.replace(/[^0-9]/g, ''))) {
                    updater.update(link);
                }
                this.closeDialog();
                this.finish();
            }.bind(this));
        }.bind(this));
    },
    initBackBtnEvent: function() {
        $A(document.getElementsByClassName('prevPage')).each(function(backBtn) {
            backBtn.observe('click', function() {
                for (var key in popupMap) {
                    if (backBtn.name.match(new RegExp(key, 'i'))) {
                        popupMap[key].goPrevPage();
                        break;
                    }
                }
            }.bind(this));
        }.bind(this));
    },
    initCheckAllEvent: function() {
        $A(document.getElementsByClassName('popupCheckAll')).each(function(chk) {
            chk.observe('click', function() {
                $A(document.getElementsByClassName(chk.id)).each(function(subChk) {
                    //subChk.click();
                    subChk.checked = chk.checked;
                });
            });
        });
        if (this.synStatus) {
            this.synStatus();
        }
    },
    initLinkAllEvent: function() {
        $A(document.getElementsByClassName('linkAll')).each(function(link) {
            link.observe('click', function() {
                if (this.name == 'station') {
                    var innerHTML = '<span><label><input name="line[' + link.id.replace(/[^0-9]/g, '') + ']" value="' + link.id.replace(/[^0-9]/g, '') + '" class="lineIds" checked="checked" type="checkbox">' + link.innerHTML.replace(/（.*?）/, '') + '</label></span>';
                    $('line').innerHTML = innerHTML;
                    $('lineRow').style.display = "block";
                }
                this.doClose();
                this.finish();
            }.bind(this));
        }.bind(this));
    },
    doClose: function () {
        this.closeDialog();
    },
    getLimit: function () {
        return this.limit;
    }
});

var PrefPopup = Class.create(DoorPopup, {
    name: 'pref',
    checkboxClassName: 'prefList',
    limit: 3,
    nextPopup: null,
    getParameters: function() {
        return getParameters(this.name);
    },
    getLimit: function () {
        return this.limit;
    },
    setNextPopup: function(nextPopup) {
        this.nextPopup = nextPopup;
    },
    executeNextPopup: function() {
        if (this.nextPopup != null) {
            this.nextPopup.initDialog();
            this.nextPopup.updateContents(this.nextPopup.getParameters());
            this.nextPopup.initMouseEvent();
        }
    }
});

var CityPopup = Class.create(DoorPopup, {
    name: 'city',
    checkboxClassName: 'cityList',
    getParameters: function() {
        return getParameters(prefPopupObj.name) + getParameters(this.name);
    },
    closeDialog: function() {
        this.body.removeChild(this.dialog);
        if (!popupMap['townUpdate'].isActive()) {
            this.doorSelectbox.show();
            return;
        }
        popupMap['townUpdate'].initDialog();
        popupMap['townUpdate'].updateContents(popupMap['townUpdate'].getParameters());
        popupMap['townUpdate'].initMouseEvent();
        if (popupMap['townUpdate'].synStatus) {
            popupMap['townUpdate'].synStatus();
        }
        this.clear();
    },
    synStatus: function() {
        $A($$('input[type=checkbox]')).each(function(subChk) {
            if (!subChk.hasClassName('popupCheckAll')) {
                Event.observe(subChk, 'click', function() {
                    sectionChks = $A(document.getElementsByClassName(subChk.className));
                    num = sectionChks.inject(0, function(acc, ck) {return ck.checked ? acc + 1 : acc;});
                    $(subChk.className.replace('cityList ', '')).checked = num == sectionChks.length;
                }.bind(this));
            }
        }.bind(this));
    },
    closeAll: function() {
        try {
            this.body.removeChild(this.dialog);
            this.finish();
        } catch (e) {}
    },
    doClose: function () {
        this.closeAll();
    },
    clear: function() {
        $('city').innerHTML = '';
        $('cityOption').style.display = 'none';
    }
});

var TownPopup = Class.create(DoorPopup, {
    name: 'town',
    checkboxClassName: 'townList',
    getParameters: function() {
        try {
            pars = getParameters(cityPopupObj.name) + getParameters(this.name);
        } catch (e) {}
        return pars;
    },
    isActive: function() {
        return $('townOption').style.display == 'block';
    },
    goPrevPage: function() {
        this.body.removeChild(this.dialog);
        this.body.removeChild(this.backgroundElement);
        for (var key in popupMap) {
            if ('cityUpdate'.match(new RegExp(key, 'i'))) {
                popupMap[key].initDialog();
                popupMap[key].updateContents(popupMap[key].getParameters());
                popupMap[key].initMouseEvent();
            }
        }
    },
    synStatus: function () {
        this.checkboxs = $A($('searchTownBox').getElementsByTagName('input'));
        this.checkboxs.each(function(chk) {
            if (chk.type == 'checkbox' && chk.className.match(new RegExp('townList', 'i'))) {
                Event.observe(chk, 'click', function() {
                    var chkedNum = this.checkboxs.inject(0, function(acc, chkbox) {return this.isTownChk(chkbox) && chkbox.checked && chkbox.className == chk.className ? acc+1 : acc;}.bind(this));
                    subCheckboxNum = this.checkboxs.inject(0, function(acc, chkbox) {return this.isTownChk(chkbox) && chkbox.className == chk.className ? acc+1 : acc}.bind(this));
                    $(chk.className).checked = subCheckboxNum == chkedNum;
                }.bind(this))
            }
        }.bind(this));
    },
    isTownChk: function(chk) {
        return chk.type == 'checkbox' && chk.className.match(new RegExp('townList', 'i'));
    }
});

var StationPopup = Class.create(DoorPopup, {
    name: 'station',
    checkboxClassName: 'stationList',
    getParameters: function() {
        try {
            pars = getParameters(prefPopupObj.name) + getParameters(linePopupObj.name) + getParameters(this.name);
        } catch (e) {}
        return pars;
    },
    goPrevPage: function() {
        this.body.removeChild(this.dialog);
        this.body.removeChild(this.backgroundElement);
        for (var key in popupMap) {
            if ('lineUpdate'.match(new RegExp(key, 'i'))) {
                popupMap[key].initDialog();
                popupMap[key].updateContents(popupMap[key].getParameters());
                popupMap[key].initMouseEvent();
            }
        }
    },
    synStatus: function() {
        this.checkboxs = $A($('searchStationBox').getElementsByTagName('input'));
        this.checkboxs.each(function(chk) {
            Event.observe(chk, 'click', function() {
                if (this.isStationChk(chk)) {
                    this.checkboxs.each(function(otherChk) {
                        if (otherChk.value == chk.value) {
                            otherChk.checked = chk.checked;
                        }
                    });
                    var chkedNum = this.checkboxs.inject(0, function(acc, chkbox) {return this.isStationChk(chkbox) && chkbox.checked && chkbox.className == chk.className ? acc+1 : acc;}.bind(this));
                    subCheckboxNum = this.checkboxs.inject(0, function(acc, chkbox) {return this.isStationChk(chkbox) && chkbox.className == chk.className ? acc+1 : acc}.bind(this));
                    $(chk.className).checked = subCheckboxNum == chkedNum;
                }
            }.bind(this));
        }.bind(this));
    },
    isStationChk: function(chkbox) {
        return chkbox.type == 'checkbox' && chkbox.className.match(new RegExp('station', 'i'));
    }
});

var NminsLinePopup = Class.create(DoorPopup, {
    name: 'nminsLine',
    checkboxClassName: 'nminsLineList',
    getParameters: function() {
        return Form.serialize($('form'));
    }
});

var NminsStationPopup = Class.create(DoorPopup, {
    name: 'nminsStation',
    checkboxClassName: 'nminsLineList',
    getParameters: function() {
        minuteBounds = this.href.replace(/^.*#/, '');
        return Form.serialize($('form')) + '&minuteBounds=' + minuteBounds;
    }
});

var LinePopup = Class.create(DoorPopup, {
    name: 'line',
    checkboxClassName: 'lineList',
    limit: 3,
    getParameters: function() {
        return getParameters(prefPopupObj.name) + getParameters(this.name);
    },
    closeDialog: function() {
        this.body.removeChild(this.dialog);
        popupMap['stationUpdate'].initDialog();
        popupMap['stationUpdate'].updateContents(popupMap['stationUpdate'].getParameters());
        popupMap['stationUpdate'].initMouseEvent();
        if (popupMap['stationUpdate'].synStatus) {
            popupMap['stationUpdate'].synStatus();
        }
        this.clear();
    },
    closeAll: function() {
        try {
            this.body.removeChild(this.dialog);
            this.finish();
        } catch (e) {}
    },
    doClose: function () {
        this.closeAll();
    },
    clear: function() {
        $('line').innerHTML = '';
        $('lineRow').style.display = 'none';
    }
});

var FeaturePopup = Class.create(DoorPopup, {
    name: 'feature',
    checkboxClassName: 'featureList',
    limit: 15,
    getParameters: function() {
        return getParameters('feature');
    }
});

var LoadingImage = Class.create({
    src: '/img/front/search_result/loading.gif',
    initialize: function() {
        var screenHeight = document.documentElement.clientHeight;
        var scrollHeight = document.body.scrollTop || document.documentElement.scrollTop;
        
        this.image = document.createElement('div');
        this.image.innerHTML = '<img src=\'' + this.src +  '\' alt=\'読み込み中\' style=\'opacity:0.5\'>';
        this.image.style.marginLeft = document.body.clientWidth/2 + 'px';
        this.image.style.marginTop = ((screenHeight/2 + scrollHeight) - 200) + "px";
    },
    show: function() {
        $('popup01').appendChild(this.image);
    },
    hide: function() {
        $('popup01').removeChild(this.image);
    }
});

LoadingImage.instance = null;

LoadingImage.getInstance = function() {
    if (this.instance == null) {
        this.instance = new LoadingImage();
    }
    return this.instance;
}

function getParameters(name)
{
    var pars = '';
    $A(document.getElementsByClassName(name + 'Ids')).each(function(e) {
        if (e.type != 'checkbox' || e.checked) {
            pars = pars + name + '[]=' + e.value + '&';
        }
    });
    return pars;
}


