/*
 *  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 968 2007-08-21 14:35:34Z hikarin $
 *
 * @require jquery.js
 */

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

Img0ch.App = (function() {
    var bbs_, bbsURI_, cgiURI_, rendererURI_, staticURI_;
    var isEnabledRedirectRenderer_ = false;
    var plugins_ = [];
    var rendererPath_ = "read.html";
    var rendererSeparator_ = "#";
    var rewritten_ = {};
    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": function() {
         var localServer;
         try {
             localServer
                 = google.gears.factory.create( "beta.localserver", "1.0" );
         } catch(e) {
             return;
         }
         var filesToCapture = [];
         var ns = location.host + ".img0ch." + bbs_;
         var resourceStore = localServer.openStore(ns);
         if (!resourceStore)
             resourceStore = localServer.createStore(ns);
         jQuery("img.image").each(function(){ filesToCapture.push(this.src) });
         jQuery("a.i0_file,a.i0_image,a.i0_thumbnail").click(
             function(event) {
                 var element = this;
                 var fileUrl = element.href;
                 if ( !resourceStore.isCaptured(fileUrl) ) {
                     resourceStore.capture(
                         fileUrl,
                         function( url, success, captureId ) {
                             if (success) location.href = url;
                         }
                     );
                     return false;
                 }
             }
         );
         for ( var i in filesToCapture ) {
             var file = filesToCapture[i];
             if ( !file || resourceStore.isCaptured(file) ) continue;
             resourceStore.capture( file, function(){} );
         }
    },
    "disableRedirectRenderer": function() {
        isEnabledRedirectRenderer_ = false;
        return;
    },
    "enableRedirectRenderer": function() {
        isEnabledRedirectRenderer_ = true;
        return;
    },
    "getBBS": function() { return bbs_ },
    "getBBSURI": function() { return bbsURI_ },
    "getCGIURI": function() { return cgiURI_ },
    "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;
            });
        });
    },
    "redirectRenderer": function( linkElement, query ) {
        var linkTo  = linkElement.href;
        var content = linkElement.innerHTML;
        if ( isEnabledRedirectRenderer_
            && !rewritten_[content + linkTo] ) {
            var qarray  = [];
            var qstring = "";
            if ( query ) {
                for ( var i in query ) {
                    qarray.push(encodeURIComponent(i)
                        + '=' + encodeURIComponent(query[i]));
                }
            }
            if ( plugins_.length ) {
                qarray.push("plugin=" + plugins_.join(','));
            }
            if (qarray.length) qstring += '?' + qarray.join('&');
            linkTo.match(/(.+)\/test\/read\.cgi\/(.+)/);
            var rewrittenURI = RegExp.$1 + "/test/"
                + rendererPath_ + qstring
                + rendererSeparator_ + RegExp.$2;
            linkElement.href = rewrittenURI;
            rewritten_[content + rewrittenURI] = true;
        }
        return true;
    },
    "removeFile": function() {
        if (!this.UFM) {
            jQuery.ajax({
                "async": false,
                "dataType": "script",
                "global": false,
                "url": staticURI_ + "/js/img0ch/app/ufm.js" });
        }
        var a = arguments;
        this.UFM.removeFile( a[0], a[1], a[2] );
        return false;
    },
    "setBBS": function(bbs) {
        bbs_ = bbs;
        return;
    },
    "setBBSURI": function(bbsURI) {
        bbsURI_ = bbsURI;
        return;
    },
    "setCGIURI": function(cgiURI) {
        cgiURI_ = cgiURI;
        return;
    },
    "setRendererURI": function(rendererURI) {
        rendererURI_ = rendererURI;
        return;
    },
    "setRenderer": function( path, separator ) {
        rendererPath_ = path;
        rendererSeparator_ = separator;
        return;
    },
    "setStaticURI": function(staticURI) {
        staticURI_ = staticURI;
        return;
    }
    };
})();
