/**
 * PhotoCreate jquery Plugin
 * TODO: jQueryのプラグインなので、原則jQueryオブジェクトを返すように書くべき
 */
(function(){
    jQuery.submitForm_timeout = 3;
    /**
     * 関数の雛形
     * jQuery(someobj).test(arg) で、
     * this = someobj, arg = argとして扱える
     */
    jQuery.fn.test = function (arg) {
        alert(arg);
    };

    /**
     * ログの出力
     */
    jQuery.pclog = function(arg, level) {
        if (window.console === undefined) {
            return jQuery;
        }
        if (typeof window.console == 'object') {
            switch (level) {
                case 'debug':
                case 'info':
                case 'error':
                    // ex. console.debug(arg)
                    eval('console.' + level + '(arg)');
                    break;
                case 'alert':
                    window.alert(arg);
                    break;
                default:
                    console.log(arg);
                    break;
            }
        }
        return jQuery;
    };

    /**
     * swapimage
     * aaaa_over.gifのような名前を、aaaa.gifとトグルする
     * もとのオブジェクトに対してmouseover, mouseoutイベントを
     * つけておく
     */
    jQuery.fn.pcswapimage = function() {
        var imgSrc = this.attr("src");
        var imgStatus = (imgSrc.indexOf("_over") != -1);
        if(!imgStatus){
            var ptr = imgSrc.lastIndexOf('.');
            imgSrc = imgSrc.substr(0, ptr) + '_over' + imgSrc.substring(ptr);
        } else {
            imgSrc = imgSrc.replace('_over', '');
        }
        this.attr('src', imgSrc);
    };

    /**
     * formのsubmit
     */
    jQuery.fn.pcsubmit = function(e, submitFormClass) {
        e.preventDefault();
        // リンクを二度押しできないように
        // 後のプロセスでthisが変化するので、ここでコピーを取って残しておく
        function clone(s) {
           function f(){};
           f.prototype = s;
           return new f();
        }
        c = clone(this);

        tagname = $(c).get(0).nodeName.toLowerCase();
        targetUrl = $(c).get(0).href;

        if (tagname === 'a') {
            // 二重押しできないように、hrefにクリック無効化コードを入れる
            $(c).attr('href', 'javascript:void(0);');
        } else {
            return false;
        }
        setTimeout(function(){
            if(tagname==='a') {
                // 一定時間後にURLを書き戻す
                $(c).attr('href', targetUrl);
            }
        }, jQuery.submitForm_timeout * 1000);

        targetForm  = this.pcSearchParentForm(e, submitFormClass);


        if (!this.hasClass('pcnocheck')) {
            // 未入力のチェック
            checks = {};
            checkErrors = new Array();
            // formの子要素から、pcrequireのついている要素を全探索
            $(targetForm).find('.pcrequire').each(function(el) {
                requireTag = this.nodeName.toLowerCase();
                formType = $(this).attr('type');
                formTitle = $(this).attr('title');
                if (formType === 'checkbox' || formType === 'radio') {
                    // チェックボックスの場合は、pcrequireのついているクラスの
                    // nameを取得し、そのnameを持つチェックボックスの
                    // いずれもチェックが入っていない時のみエラー
                    checkName = $(this).attr('name');
                    if (checks[checkName] === undefined) {
                        checks[checkName] = {};
                    }
                    if (!checks[checkName]['value']) {
                        checks[checkName]['value'] = $(this)[0].checked;
                        checks[checkName]['title'] = formTitle;
                    }
                } else if (!$(this).val()) {
                    if (requireTag  === 'select') {
                        type = '選択';
                    } else {
                        type = '入力';
                    }
                    checkErrors.push('<span class="pcerritem">'
                                    + formTitle
                                    + "</span>が"
                                    + type
                                    + "されていません");
                }
            });
            for (check in checks) {
                //$.pclog(check);
                if (!checks[check]['value']) {
                    type = '選択';
                    formTitle = checks[check]['title'];
                    checkErrors.push('<span class="pcerritem">'
                                    + formTitle
                                    + "</span>が"
                                    + type
                                    + "されていません");
                }
            }

            // エラーがある場合にはダイアログを出してsubmitしない
//            $.pclog(checkErrors);
            if (checkErrors.length > 0) {
                $(this).attr('href', targetUrl);
                this.pcerrdialog(checkErrors);
                return;
            }
        }
        $(targetForm).attr('action', targetUrl);
//        $.pclog('submit', 'alert');
//        $.pclog('submit', 'info');
        $(targetForm).submit();
//        $.pclog(targetForm);
//        $.pclog('submitend', 'info');
    };

    /**
     * submit対象のフォームを探索
     */
    jQuery.fn.pcSearchParentForm = function(e, submitFormClass) {
        a = this;
        while(true) {
            parentElem = $(a).parent();
//            $.pclog(parentElem);
            tag = $(parentElem).get(0).nodeName.toLowerCase();
            hasClass = $(parentElem).hasClass(submitFormClass.replace('\.', ''));
            if (tag === 'form' && hasClass) {
                return $(parentElem);
            }
            if (tag === 'html') {
                break;
            }
            a = parentElem;
        }
        return null;
    };

    /**
     * カート内でのプルダウンの変更による反映処理
     */
    jQuery.fn.pcApplyCart = function(e, applyPage) {
        photoCartDetailID = '';
        attrName = $(this).attr('name');
        re = new RegExp("^[a-zA-Z]+_(\\d+)$");
        matches = attrName.match(re);
        if (matches) {
            photoCartDetailId = matches[1];
            $.pclog(matches);
        } else {
            $.pclog(matches);
            return false;
        }

        parentForm = $(this).pcSearchParentForm(e, '.pcform');
        //$(parentForm).append('<input type="hidden" '_
        //                   + 'name="photoCartDetailID" '
        //                   + 'value="'
        //                   + photoCartDetailId
        //                   + '">');
        $(parentForm).attr(
            'action',
            applyPage + '?photoCartDetailID=' + photoCartDetailId
        );
        $(parentForm).submit();
    };

    /**
     * チェックボックスのトグル
     */
    jQuery.fn.pctogglecheck = function(cls) {
//        $.pclog(cls);
        $(cls).attr('checked', $(this).attr('checked'));
    };


    /**
     * ページ送り処理
     */
    jQuery.fn.pcpaging = function(e) {
        obj = this.get(0);
        param_name = obj.name;
        param_val = obj.value;
        search = location.search.replace('?', '');

        // パラメータにparam_nameがあるか
        if (search.indexOf(param_name + "=") >= 0) {
            // param_name の値を取り替える
            re = new RegExp(param_name + "=(\\d*)");
            search = search.replace(re, '');
        }
        // location.searchの先頭に、param_name=param_value&を追加する
        if (search.length > 0 && search[0] !== '&') {
            add = '&' + search;
        } else {
            add = search;
        }
        search = param_name + "=" + param_val + add;

        // 末尾が&の場合消去
        lastAmp = search.lastIndexOf('&');
        if (lastAmp === search.length-1) {
            search = search.substring(0, lastAmp);
        }

        // & が連続する場合に除去
        search = search.replace(/&+/g, '&');

        // #の後ろは常に#cartNum_1とする
// IE6で異常発生するので、ページ内遷移は行わないようにする
        if (!(jQuery.browser.version='6.0' && jQuery.browser.msie)) {
            location.hash = '#cartNum_1';
        }
        location.search = search;
    };

    /**
     * confirm のダイアログを表示する
     */
    jQuery.fn.pcshowconfirm = function(e, submitFormClass, dialogId) {
        e.preventDefault();
        pos = $(e.target).position();
        o = this.get(0);
        $(dialogId).dialog({
            'autoOpen': false,
            'modal': true,
            'buttons': {
                'キャンセル': function() {
                    $(dialogId).dialog('close');
                    // Flashがある場合には再表示
                    $('#flashcontent').show();
                },
                'OK': function() {
                    $(o).pcsubmit(e, submitFormClass);
                }
            },
            'position': pos,
            'open': function(ev, ui) {$('select').toggle()}, 
            'close': function(ev, ui) {$('select').toggle()}
        });
        // Flashがある場合には非表示
        $('#flashcontent').hide();
        $(dialogId).dialog('open');
    };

    /**
     * シンプルなエラーダイアログを表示する
     * contentは配列とする
     */
    jQuery.fn.pcerrdialog = function(content) {
        errorHtml = "";
        $(content).each(function(v) {
            errorHtml = errorHtml + "<li>" + this + "</li>";
        });

        var d = $('<div id="pcerrdialog"/>').html(errorHtml);
        d.dialog({
            'autoOpen': false,
            'modal' : true,
            'title' : '入力にエラーがあります',
            'buttons': {
                'OK': function() {
                    d.dialog('close');
                }
            },
            'open': function(ev, ui) {$('select').toggle()}, 
            'close': function(ev, ui) {$('select').toggle()}
        });
        d.dialog('open');
    };
    /**
     * シンプルなダイアログを表示する
     * contentはHTMLとする
     */
    jQuery.fn.pcdialog = function(content) {
        var d = $('<div id="pcdialog"/>').html(content);
        d.dialog({
            'autoOpen': false,
            'modal' : true,
            'buttons': {
                'OK': function() {
                    d.dialog('close');
                }
            },
            'open': function(ev, ui) {$('select').toggle()}, 
            'close': function(ev, ui) {$('select').toggle()}
        });
        d.dialog('open');
    };

    /**
     * シンプルなタイトル付きダイアログを表示する
     * 内容はdialogIdでHTML内に記入された内容とする
     */
    jQuery.fn.pcdialogWithTitle= function(dialogId) {
        o = this.get(0);
        $(dialogId).dialog({
            'autoOpen': false,
            'modal': true,
            'buttons': {
                'OK': function() {
                    $(dialogId).dialog('close');
                }
            },
            'open': function(ev, ui) {$('select').toggle()}, 
            'close': function(ev, ui) {$('select').toggle()}
        });
        $(dialogId).dialog('open');
    };

    /**
     * 文字列からバイト数を求める
     * tripleBytesがtrue、もしくは、空の場合、
     * 3バイト文字を２バイト換算して返す
     */
    jQuery.getStrBytes = function(str, tripleBytes) {
        l = 0;
        for (var i = 0; i < str.length; i++) {
            var c = str.charCodeAt(i);
            // Shift_JIS: 0x0 ～ 0x80, 0xa0 , 0xa1 ～ 0xdf , 0xfd ～ 0xff
            // Unicode : 0x0 ～ 0x80, 0xf8f0, 0xff61 ～ 0xff9f, 0xf8f1 ～ 0xf8f3
            if ( (c >= 0x0 && c < 0x81) || (c == 0xf8f0)
              || (c >= 0xff61 && c < 0xffa0) || (c >= 0xf8f1 && c < 0xf8f4)) {
                l += 1;
            } else {
                if (tripleBytes === undefined || tripleBytes === true) {
                    l += 2;
                } else {
                    l += 3;
                }
            }
        }
        return l;
    };

    /**
     * SJISかどうかを調べる
     * js/api/chars.php?act=sjisjudgeを呼び出して判定
     * OKの場合、json.status === "OK",
     * NGの場合、json.status === "NG"
     *           かつ、 json.chars にNGの文字を配列で返す
     */
    jQuery.isSjis = function(api_path, str) {
        var json = {};
        jQuery.ajax( {
            url: api_path,
            type: 'GET', dataType: 'json', async: false,
            data: { act: 'sjisjudge', str: str },
            success: function(e) { json = e }
        });
        return json
    }
})(jQuery);
