/*
 *  Copyright 2007 hkrn <hikarin@users.sourceforge.jp>
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 * Img0ch.App
 * $Id: app.js 1484 2007-10-25 13:03:06Z hikarin $
 *
 * @require jquery.js
 */

var Img0ch;
if ( typeof Img0ch == "undefined" ) Img0ch = {};

Img0ch.App = (function() {
    var bbs_, bbsURI_, cgiURI_, key_, rendererURI_, staticURI_;
    var isEnabledRedirectRenderer_ = false;
    var plugins_ = [];
    var rendererPath_ = "read.html";
    var rendererSeparator_ = "#";
    var rewritten_ = {};
    var syncUploadedFiles_ = function(callback) {
        var object = Img0ch.App.GoogleGears;
        if (!object) {
            this.require(
                [
                    {
                        "Img0ch.App.GoogleGears":
                        staticURI_ + "/js/img0ch/app/googlegears.js"
                    }
                ],
                function(){
                    Img0ch.App.GoogleGears.sync(callback);
                }
            );
        }
        else {
            object.sync(callback);
        }
        return;
    };

    return {
    "addRendererPlugin": function(pluginName) {
        if (!pluginName || !/^\w+$/.test(p)) return;
        plugins_.push(pluginName);
        return;
    },
    "addRendererPlugins": function(plugins) {
        for ( var i in plugins ) {
            var p = plugins[i];
            if (!p || !/^\w+$/.test(p)) continue;
            plugins_.push(p);
        }
        return;
    },
    "cacheUploadedFiles": syncUploadedFiles_,
    "disableRedirectRenderer": function() {
        isEnabledRedirectRenderer_ = false;
        return;
    },
    "enableRedirectRenderer": function() {
        isEnabledRedirectRenderer_ = true;
        return;
    },
    "escapeHTMLEntities": function(html) {
        return String(html).replace(
            /&/g, "&amp;" ).replace(
            /'/g, "&#39;" ).replace(
            /</g, "&lt;" ).replace(
            />/g, "&gt;" );
    },
    "getBBS": function() { return bbs_ },
    "getBBSURI": function() { return bbsURI_ },
    "getCGIURI": function() { return cgiURI_ },
    "getKey": function() { return key_ },
    "getRendererURI": function() { return rendererURI_ },
    "getStaticURI": function() { return staticURI_ },
    "initForm": function( cookiePath, formClass ) {
        if ( !formClass ) formClass = "form.comment";
        jQuery(function () {
            jQuery("input[@name='FROM']").val(
                jQuery.cookie("img0ch_name") || "");
            jQuery("input[@name='mail']").val(
                jQuery.cookie("img0ch_mail") || "");
            jQuery(formClass).submit(function () {
                if ( !jQuery("textarea[@name='MESSAGE']",
                    this).val() && jQuery("input[@type='submit']",
                    this).val() == "書き込む" ) {
                    if ( confirm(
                        "本文がありません。それでも投稿しますか？") == false ) {
                        return false;
                    }
                }
                var option = { "expires": 30,
                    "path": cookiePath };
                jQuery.cookie( "img0ch_name", jQuery(
                    "input[@name='FROM']", this ).val(), option );
                jQuery.cookie( "img0ch_mail", jQuery(
                    "input[@name='mail']", this ).val(), option );
                jQuery("input[@type='submit']").attr({ "disabled": true });
                return true;
            });
        });
    },
    "intval": function(num) {
        var n = Number(num);
        return isNaN(n) ? 0 : n;
    },
    "parseQueryString": function(aURL) {
        var param = {};
        var url   = aURL || document.URL;
        var pos   = url.indexOf('?') + 1;
        if (pos) {
            var qs = url.substring( pos, url.length ).replace(/#.+/, "");
            var params = qs.split('&');
            for ( var i in params ) {
                var kv = String(params[i]).split('=');
                var key = decodeURIComponent(kv[0]);
                var val = this.escapeHTMLEntities(decodeURIComponent(kv[1]));
                var k   = param[key];
                if (k) {
                    typeof k == "Array"
                        ? k.push(val)
                        : param[key] = [ k, val ];
                }
                else {
                    param[key] = val;
                }
            }
        }
        return param;
    },
    "redirectRenderer": function( linkElement, query ) {
        var linkTo  = linkElement.href;
        var content = linkElement.innerHTML;
        if ( isEnabledRedirectRenderer_
            && !rewritten_[content + linkTo] ) {
            var qarray  = [];
            if ( query ) {
                for ( var i in query ) {
                    qarray.push(encodeURIComponent(i)
                        + '=' + encodeURIComponent(query[i]));
                }
            }
            if ( plugins_.length ) {
                qarray.unshift("plugin=" + plugins_.join(','));
            }
            linkTo.match(/^(.+)\/test\/read\.cgi\/([^\/]+)\/([^\/]+)\/?(.*)/);
            qarray.unshift( "option=" + ( RegExp.$4 || "" ) );
            qarray.unshift( "key=" + ( key_ || RegExp.$3 ) );
            qarray.unshift( "bbs=" + ( bbs_ || RegExp.$2 ) );
            var rewrittenURI =  RegExp.$1 + "/test/"
                + rendererPath_ + '?' + qarray.join('&');
            linkElement.href = rewrittenURI;
            rewritten_[content + rewrittenURI] = true;
        }
        return true;
    },
    "removeFile": function() {
        var a      = arguments;
        var object = Img0ch.App.UFM;
        if (!object) {
            this.require(
                [
                    {
                        "Img0ch.App.UFM":
                        staticURI_ + "/js/img0ch/app/ufm.js"
                    }
                ],
                function() {
                    Img0ch.App.UFM.removeFile( a[0], a[1], a[2] );
                }
            );
        }
        else {
            object.removeFile( a[0], a[1], a[2] );
        }
        return false;
    },
    "require": function() {
       /*
        * code from
        * http://coderepos.org/share/browser/lang/javascript/misc/loader.js.inc
        * and this code is modified version for working Safari(Konqueror) etc.
        */
        var args = [];
        args.push.apply( args, arguments );
        var entries  = args.shift();
        var callback = args.shift();

        function defined(prop) {
            try{
                return eval( "typeof " + prop ) != "undefined";
            } catch(e) {
            }
            return false;
        }
        function loadScript(src) {
            var script     = document.createElement("script");
            script.charset = "UTF-8";
            script.src     = src;
            script.type    = "text/javascript";
            document.getElementsByTagName("head")[0].appendChild(script);
        }
        function doNextEntry() {
            var entry = entries.shift();
            if (!entry) {
                return callback.apply( callback, args );
            }
            if (typeof entry == "string" || entry instanceof String) {
                entry = { "window": entry };
            }
            for (var prop in entry) {
                if (prop == "window" || !defined(prop)) {
                    loadScript(entry[prop]);
                }
            }
            var timer = setInterval(function() {
                for (var prop in entry) {
                    if (!defined(prop)) {
                        return;
                    }
                }
                clearInterval(timer);
                doNextEntry();
            }, 99);
        }
        doNextEntry();
    },
    "setBBS": function(bbs) {
        bbs_ = bbs;
        return;
    },
    "setBBSURI": function(bbsURI) {
        bbsURI_ = bbsURI;
        return;
    },
    "setCGIURI": function(cgiURI) {
        cgiURI_ = cgiURI;
        return;
    },
    "setKey": function(key) {
        key_ = key;
        return;
    },
    "setRendererURI": function(rendererURI) {
        rendererURI_ = rendererURI;
        return;
    },
    "setRenderer": function( path, separator ) {
        rendererPath_ = path;
        rendererSeparator_ = separator;
        return;
    },
    "setStaticURI": function(staticURI) {
        staticURI_ = staticURI;
        return;
    },
    "syncUploadedFiles": syncUploadedFiles_
    };
})();
