/*
 *  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.
 *
 *  $Id: zeromin2.js 377 2007-03-18 14:30:14Z hikarin $
 *
 *  @require jquery.js
 *
 */

var Zeromin2 = (function() {
    String.prototype.intval = function() {
        var n = Number(this);
        return isNaN(n) ? 0 : n;
    };
    return {
         "addStyleSheet": function(url) /* : void */ {
             var css = document.createElement("link");
             css.rel = "stylesheet";
             css.type = "text/css";
             css.href = url;
             jQuery("head").append(css);
             return;
         },
         "autoCheckbox": function( element, checkName ) /* : void */ {
            var dist = "input[@name='" + checkName + "']";
            if (Number(element.getAttribute("isChecked"))) {
                jQuery(dist).each(function(){
                    if (this.defaultChecked) return;
                    this.checked = false;
                });
                element.setAttribute( "isChecked", "0" );
            }
            else {
                jQuery(dist).each(function(){
                    if (this.defaultChecked) return;
                    this.checked = true;
                });
                element.setAttribute( "isChecked", "1" );
            }
            return;
        },
        "extend": function(props) /* : object */ {
            var object = jQuery.extend( props, this );
            for ( var i in object ) {
                if ( typeof object[i] == "object" )
                    delete object[i];
            }
            return object;
        },
        "getFormErrorHandler": function(message) /* : void */ {
            return function( error, validate ) {
                var e = jQuery("#notify"
                    ).empty().removeClass().addClass("noticeFailed");
                var ul = document.createElement("ul");
                for ( var i in error ) {
                    var li = document.createElement("li");
                    li.appendChild(document.createTextNode(
                        i + ": " + error[i]));
                    ul.appendChild(li);
                }
                var p = document.createElement("p");
                p.appendChild(document.createTextNode(message));
                p.appendChild(ul);
                e.append(p);
                return;
            }
        },
        "isSelected": function( FORM_ID, degree ) /* : boolean */ {
            var res = jQuery.grep(
                jQuery( "input[@type='checkbox']",
                document.getElementById(FORM_ID) ),
                function( i ) { return i.checked } );
            if (!res.length) {
                this.notifyError(degree + "が選択されていません");
                return false;
            }
            return true;
        },
        "notifyProgress": function(message) /* : void */ {
            jQuery("#notify").css({
                "background": "#eeeeff",
                "border-color": "#9999ff",
                "color": "#0000ff",
                "font-size": "large",
                "padding": "5px" }).html(message).show();
            return;
        },
        "notifySuccess": function(message) /* : void */ {
            jQuery("#notify").css({
                "background": "#eeffee",
                "border-color": "#99ff99",
                "color": "#008000",
                "font-size": "large",
                "padding": "5px" }).html(message).show();
            return;
        },
        "notifyError": function(message) /* : void */ {
            jQuery("#notify").css({
                "background":"#ffeeee",
                "border": "1px solid #ff9999",
                "color":"#ff0000",
                "font-size": "large",
                "padding": "5px" }).html(message).show();
            return;
        },
        "redirect": function(element) /* : void */ {
            var a    = [];
            var root = document.getElementById("hiddenForm");
            var url  = element.href;
            var pos  = url.indexOf('?') + 1;
            if (pos) {
                var qs = url.substring( pos, url.length );
                var params = qs.split('&');
                var f = document.createElement("form");
                f.action = url.substring( 0, pos - 1 );
                f.method = "post";
                root.appendChild(f);
                for ( var i in params ) {
                    var kv = String(params[i]).split('=');
                    var i = document.createElement("input");
                    i.type = "hidden";
                    i.name = decodeURIComponent(kv[0]);
                    i.value = decodeURIComponent(kv[1]);
                    f.appendChild(i);
                }
                f.submit();
            }
            return;
        },
        "removeNotify": function() /* : void */ {
            jQuery("#notify").hide();
            return;
        },
        "selectAllCheckbox": function( element, checkboxName ) /* : void */  {
            var checkmark = element.checked ? true : false;
            jQuery("input[@type='checkbox']").each(function(){
                if ( this.name == checkboxName ) {
                    if (!this.defaultChecked) {
                        this.checked = checkmark;
                    }
                }
            });
            return;
        },
        "sendError": function(e) /* : void */ {
            jQuery("#notify").empty().removeClass().addClass(
                "noticeFailed").append("<p>エラーが発生しました<br />["
                + e.type + "] " + e.description + "</p>");
            return;
        },
        "sendQueryAsync": function( formElement, query, callback ) /* : boolean */ {
            var a = [];
            var o = {};
            var qs = "";
            var getParam = function() { o[this.name] = this.value };
            jQuery( "input[@type='text']", formElement ).each(getParam);
            jQuery( "input[@type='pass']", formElement ).each(getParam);
            jQuery( "input[@type='hidden']", formElement ).each(getParam);
            jQuery( "input[@type='checkbox']", formElement).filter(
                function() { return this.checked } ).each(getParam);
            if (!query) query = {};
            query["js"] = 1;
            for ( var i in query ) {  o[i] = query[i] }
            for ( var i in o ) {
                a.push({ "name": i, "value": o[i] });
            }

            jQuery.ajax({
                "data": a,
                "dataType": "json",
                "global": false,
                "type": "POST",
                "url": formElement.action,
                "success": function(res) {
                    if (!res.ok) {
                        Zeromin2.notifyError(
                            "<p>エラーの結果が返されました"
                            + res.data + "</p>" );
                        return;
                    }
                    if (!res.loginOK) {
                        Zeromin2.notifyError("<p>不正な認証が行われています</p>");
                        return;
                    }
                    var data = res.data;
                    if (data.Code == 1) {
                        Zeromin2.notifyError("<p>実行権限がありません</p>");
                        return;
                    }
                    callback(data);
                    return;
                },
                "error": function( xml, t, e ) {
                    var content = xml.status + ": " + xml.statusText
                        + "&nbsp;[" + ( e.type || e.name ) + "] "
                        + ( e.description || e.message );
                    Zeromin2.notifyError(content);
                } });
            return true;
        },
        "sendQuery": function( formId, query ) /* : boolean */ {
            var srcForm = jQuery(formId);
            var formElement = jQuery("<form>").attr({
                "action": srcForm.attr("action"),
                "method": srcForm.attr("method") });
            var hiddenize = function(){ this.type = "hidden"; return };

            jQuery( "input[@type='text']",
                formId ).clone().each(hiddenize).appendTo(formElement);
            jQuery( "input[@type='password']",
                formId ).clone().each(hiddenize).appendTo(formElement);
            jQuery( "input[@type='hidden']",
                formId ).clone().appendTo(formElement);
            jQuery( "input[@type='checkbox']",
                formId ).filter( function(){ return this.checked }
                ).clone().each(hiddenize).appendTo(formElement);
            jQuery("#hiddenForm").append(formElement);
            for ( var i in query ) {
                jQuery("<input>").attr({
                    "type": "hidden",
                    "name": i,
                    "value": query[i] }).appendTo(formElement);
            }

            formElement.get(0).submit();
            return;
        }
    };
})();
