/**
 * jquery.hmk
 * 
 * ハナミズキの死活判定を行い結果により接続する
 * 
 * @example
 *  $('#formID').hmk({"brand": "BRANDNAME"});
 *  $('#formID').hmk({"brand": "BRANDNAME", "url": "http://www.example.com/hmk_server_check.php", "_debugmode": "true"});
 * @author IWASAKI koji <iwasaki@gmo-hs.com>
 * @copyright Copyright &copy; 2009 GMO HOSTING &amp; SECURITY, INC.
 * @version 0.9 2009-06-19
 */
(function($) {
    $.fn.extend({
        hmk: function (opt) {
            url = opt.url || 'http://help.ac-mgr.com/action/hmk_server_check.php';
            brand = opt.brand || false;
            _debugmode = opt._debugmode || false;

            url = (brand)
                ? url + '?b=' + brand + ((_debugmode) ? '&_debugmode=' + _debugmode : '') + '&jsonp=?'
                : false;

            return this.each(function () {
                var targetURL = url;
                if (targetURL != false) {
                    $(this).submit(function () {
                        if (!$(this).hasClass('_hmkPostOK')
                            && !$(this).hasClass('_hmkPostNG')) {
                            // 判定済みクラスがなければ JSON リクエスト
                            targetForm = this;
                            $.getJSON(targetURL, function (json) {
                                // json の返り値によって、action先、classを定義し、再度submitを行う
                                $(targetForm).attr('action', json.url);
                                $(targetForm).addClass((json.status) ? '_hmkPostOK' : '_hmkPostNG');
                                $(targetForm).submit();
                            });
                            return false;
                        }

                        if ($(this).hasClass('_hmkPostOK')) {
                            // OK状態なら、新しいウィンドウを開いてPOST
                            $(this).removeClass('_hmkPostOK _hmkPostNG');

                            var w = (screen.availWidth * 0.7 > 780)
                                ? parseInt(screen.availWidth * 0.8) : 780;
                            var h = (screen.availHeight * 0.7 > 550)
                                ? parseInt(screen.availHeight * 0.8) : 550;

                            window.open('', "windowHMK", "width="
                                + w + ",height=" + h
                                + ",scrollbars=yes,resizable=yes,status=no,menubar=no,toolbar=no,directories=no");

                            return true;
                        } else {
                            // NG状態なら、代替コンテンツにジャンプ
                            $(this).removeClass('_hmkPostOK _hmkPostNG');
                            location.href = $(this).attr('action');
                            return false;
                        }

                    });
                }
            });
        }
    });
})(jQuery);

