
/**
 * 
 * @author rogeriolino
 */
var _4Ps = {

    Node : {

        get : function(id) {
            return document.getElementById(id);
        },
        
        create : function(tag) {
            return document.createElement(tag);
        },

        remove : function(node) {
            if (node != null) {
                var parent = node.parentNode;
                parent.removeChild(node);
            }
        },

        bodyAppend : function(node) {
            var body = document.getElementsByTagName("body")[0];
            body.appendChild(node);
        },

        clone : function(node) {
            return node.cloneNode(true);
        },

        reply : function(node) {
            var clone = _4Ps.Node.clone(node);
            var parent = node.parentNode;
            parent.appendChild(clone);
        }
        
    },

    Form : {
        
        submit : function(form_id, action) {
            var form = _4Ps.Node.get(form_id);
            if (form != undefined) {
                _4Ps.Editor.update();
                var onSubmit = function() { return true; }
                if (typeof(form.onsubmit) == "function") {
                    onSubmit = form.onsubmit;
                }
                if (_4Ps.Form.isValid(form) && onSubmit()) {
                    form.setAttribute("action", action);
                    form.method = "post";
                    
                    //setTimeout("form.submit()",100);
                    form.submit();
                    return true;
                }
            }
            return false;
        },

        isValid : function(form) {
            return _4Ps.Form.showAlert(form, "Os campos abaixo devem ser preenchidos corretamente:");
        },

        showAlert : function(form, title) {
            var message = "";
            with (form) {
                for (i = 0; i < elements.length; i++) {
                    if(elements[i].title != "" && elements[i].value == "") {
                        cp = elements[i].title;
                        message += " - " + cp + "<br/>";
                    }
                }
            }
            if (message.length > 0) {
                _4Ps.Dialog.alert(title + "<br/><br/>" + message);
                return false;
            }
            return true;
        }

    }
    
}

_4Ps.Cookie = {

    set : function(name, value, hours) {
        var date = new Date();
	date.setTime(date.getTime() + 3600 * hours);
	var expires = "; expires=" + date.toGMTString();
	var cookie = name + "=" + value + expires + "; path=;";
	document.cookie = cookie;
    },

    get : function(name) {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            if (cookie[i]) {
                var cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    return decodeURIComponent(cookie.substring(name.length + 1));
                }
            }
        }
        return null;
    },

    remove : function(name) {
        _4Ps.Cookie.set(name, -1);
    }

}

_4Ps.Dialog = {

    createWindow : function(id, title) {
        _4Ps.Node.remove(_4Ps.Node.get(id));
        var win = _4Ps.Node.create("div");
        win.setAttribute("id", id);
        win.setAttribute("title", title);
        _4Ps.Node.bodyAppend(win);
        return win;
    },

    confirm : function(text, action) {
        var id = "template-ui-dialog-confirm";
        var title = "Confirma";
        var win = _4Ps.Dialog.createWindow(id, title);
        var p = _4Ps.Node.create("p");
        p.innerHTML = text;
        win.appendChild(p);
        $(function() {
            $("#" + id).dialog({
                bgiframe: true,
                modal: true,
                buttons: {
                    Ok: function() {
                        action();
                        $(this).dialog('close');
                    },
                    'Cancelar': function() { $(this).dialog('close'); }
                }}
            );
        });
    },

    alert : function(text) {
        var id = "template-ui-dialog-alert";
        var title = "Alerta";
        var win = _4Ps.Dialog.createWindow(id, title);
        var p = _4Ps.Node.create("p");
        p.innerHTML = text;
        win.appendChild(p);
        $(function() {
            $("#" + id).dialog({
                bgiframe: true,
                modal: true,
                buttons: {
                    Ok: function() {
                        $(this).dialog('close');
                    }
                }}
            );
        });
    }

}

_4Ps.Ajax = {

    xmlhttp : (
                window.XMLHttpRequest ?
                new XMLHttpRequest() :
                (
                    window.ActiveXObject ?
                    new ActiveXObject("Msxml2.XMLHTTP") :
                    null
                )
            ),

    queue: Array(),

    Request : function(url, method, parameters, onStart, onComplete, onError) {
        this.constructor = 'Request';
        this.url = url;
        this.method = (method == 'POST') ? method : 'GET';
        this.parameters = parameters;
        this.onStart = (typeof(onStart) == 'function') ? onStart : function() {};
        this.onComplete = (typeof(onComplete) == 'function') ? onComplete : function() {};
        this.onError = (typeof(onError) == 'function') ? onError : function() {};
        this.getEncodedParameters = function() {
            var param = "";
            for (k in this.parameters) {
                param += k + "=" + encodeURI(this.parameters[k]) + "&";
            }
            return param.substring(0, param.length-1);
        }
    },

    toggleLoader : function() {
        var id = "ajax-loader";
        var win = document.getElementById(id);
        if (win == null) {
            win = document.createElement("div");
            win.setAttribute('id', id);
            document.getElementsByTagName('body')[0].appendChild(win);
        } else {
            win.parentNode.removeChild(win);
        }
    },

    reRender : function(id, params) {
        var url = document.location;
        var method = 'GET';
        var parameters = params;
        var onStart = function() { _4Ps.Ajax.toggleLoader(); }
        var onComplete = function(c, xml) {
            var target = document.getElementById(id);
            if (target != null) {
                /*
                 * Bela Gambia por causa do IE e suas
                 * variacoes que so dao trabalho
                 */
                if (document.all) {
                    var pattern = '<body(.|\n)*</body>';
                    var re = new RegExp(pattern, "gi");
                    var m = re.exec(c);
                    if (m != null) {
                        var s = "";
                        for (i = 0; i < m.length; i++) {
                            s = s + m[i] + "\n";
                        }
                        var div = document.createElement("div");
                        div.innerHTML = s;
                        var elems = div.getElementsByTagName(target.nodeName);
                        for (var i = 0; i < elems.length; i++) {
                            var e = elems[i];
                            if (e.id == id) {
                                while (target.childNodes[0]) {
                                    target.removeChild(target.childNodes[0]);
                                }
                                target.appendChild(e);
                                break;
                            }
                        }
                    }
                // Smart Browsers 
                } else {
                    var resp = xml.getElementById(id);
                    if (resp != null) {
                        target.innerHTML = resp.innerHTML;
                    }
                }
            }
            _4Ps.Ajax.toggleLoader();
        }
        var onError = function() { _4Ps.Ajax.toggleLoader(); }
        _4Ps.Ajax.send(new _4Ps.Ajax.Request(url, method, parameters, onStart, onComplete, onError));
        
    },

    loadXMLFromString : function(xml) {
        if (typeof DOMParser != "undefined") {
            return (new DOMParser()).parseFromString(xml, "text/xml");
        }
        else if (typeof ActiveXObject != "undefined") {
            var doc = new ActiveXObject("MSXML2.DOMDocument");
            doc.loadXML(xml);
            return doc;
        }
        else {
            var url = "data:text/xml;charset=utf-8," + escape(xml);
            var request = new XMLHttpRequest();
            request.open("GET", url, false);
            request.send(null);
            return request.responseXML;
        }
    },

    loadXMLFromURL : function(url) {
        var xmlhttp = !window.XMLHttpRequest ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
        xmlhttp.open('GET', url, false);
        xmlhttp.setRequestHeader('Content-Type', 'application/xml');
        xmlhttp.overrideMimeType("application/xml");
        xmlhttp.send('');
        return xmlhttp.responseXML;
    },

    send : function(request) {
        if (request instanceof Object && request.constructor == 'Request') {
            //_4Ps.Ajax.queue.push(request);
            _4Ps.Ajax.exec(request);
        }
    },
    
    exec : function(request) {
        if (_4Ps.Ajax.xmlhttp != undefined) {
            _4Ps.Ajax.xmlhttp.onreadystatechange = function() {
                if (_4Ps.Ajax.xmlhttp.readyState == 4) {
                    if (_4Ps.Ajax.xmlhttp.status == 200) {
                        if (typeof(request.onComplete) == 'function') {
                            request.onComplete(_4Ps.Ajax.xmlhttp.responseText, _4Ps.Ajax.xmlhttp.responseXML);
                        }
                    } else {
                        if (typeof(request.onError) == 'function') {
                            request.onError();
                        }
                    }
//                    if (self.queue.length > 0) {
//                        setTimeout(
//                            function() {
//                                this(_4Ps.Ajax.queue.shift());
//                            },
//                            100
//                        );
//                    }
                }
            }
            if (request.method == "GET") {
                var url = "" + request.url;
                url += (url.indexOf("?") == -1) ? "?" : "&";
                url += request.getEncodedParameters();
                _4Ps.Ajax.xmlhttp.open(request.method, url, true);
                if (_4Ps.Ajax.xmlhttp.overrideMimeType) {
                    _4Ps.Ajax.xmlhttp.overrideMimeType("application/xml");
                }
                _4Ps.Ajax.xmlhttp.send(null);
            }
            else if (request.method == "POST") {
                var p = request.getEncodedParameters();
                _4Ps.Ajax.xmlhttp.open(request.method, request.url, true);
                _4Ps.Ajax.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                _4Ps.Ajax.xmlhttp.setRequestHeader("Content-length", p.length);
                _4Ps.Ajax.xmlhttp.setRequestHeader("Connection", "close");
                _4Ps.Ajax.xmlhttp.send(p);
            }
            request.onStart();
        }
    }
}

_4Ps.UI = {

    Input : {
        
        inputs : new Array(),

        add : function(input, args) {
            _4Ps.UI.Input.inputs[_4Ps.UI.Input.inputs.length] = (input, args);
        },

        listen : function(input, args) {
            for (arg in args) {
                var value = args[arg];
                switch (arg) {
                case 'maxlength':
                    if (input.value.length > value) {
                        input.value = input.value.substr(0, value);
                    }
                case 'format':
                }
            }
        },

        exec : function() {
            for (input in _4Ps.UI.Input.inputs) {
                _4Ps.UI.Input.listen(input[0], input[1]);
            }
        }
    },

    Tabs : {
        
        change : function(tab) {
            var tabs = tab.parentNode.parentNode.parentNode;
            _4Ps.UI.Tabs.disableAll(tabs);
            var id = tab.href.split("#")[1];
            var div = _4Ps.Node.get(id);
            tab.setAttribute("class", "active");
            div.setAttribute("class", "ui-tab-active");
            _4Ps.Cookie.set("ui-tabs", parseInt(id.split('-')[2]) - 1, 8);
        },

        disableAll : function(tabs) {
            for (var i = 0; i < tabs.childNodes.length; i++) {
                var node = tabs.childNodes[i];
                if (node.nodeName.toLowerCase() == 'ul') {
                    for (var j = 0; j < node.childNodes.length; j++) {
                        var li = node.childNodes[j];
                        li.firstChild.setAttribute("class", "");
                    }
                } else if (node.nodeName.toLowerCase() == 'div') {
                    node.setAttribute("class", "ui-tab");
                }
                
            }
        }

    }
    
}

_4Ps.Editor = {

    id : '',
    editors : new Array(),

    create : function(id) {
        _4Ps.Editor.id = id;
        // FCKEditor
        if (_4Ps.Editor.editors[id] == null) {
            var sBasePath = './www/js/fckeditor/';
            var editor = new FCKeditor(_4Ps.Editor.id);
            editor.ToolbarSet = "Default4Ps";
            editor.BasePath = sBasePath;
            editor.Height = '600';
            _4Ps.Editor.editors[id] = editor;
        }
    },

    remove : function(id) {
        if (_4Ps.Editor.editors[id] != null) {
            var textArea = _4Ps.Node.get(id);
            var editor = _4Ps.Node.get(id.concat('___Frame'));
            if (textArea.style.display == 'none') {
                textArea.style.display = 'inline';
                editor.style.display = 'none';
            }
        }
    },

    update : function() {
        if (_4Ps.Editor.id != '') {
        }
    }

}

_4Ps.Gallery = {

    rows : 1,

    addRow : function(rowId) {
        rowId = (rowId != null) ? rowId : "gallery_tr_pattern";
        _4Ps.Node.reply(_4Ps.Node.get(rowId));
        _4Ps.Gallery.rows++;
    },

    replyRows : function() {
        var total = 4;
        for (var i = 0; i < total; i++) {
            _4Ps.Gallery.addRow();
        }
    },

    removeRow : function(node) {
        if (_4Ps.Gallery.rows > 1) {
            var tr = node.parentNode.parentNode.parentNode;
            if (tr.parentNode.childNodes.length > 1) {
                _4Ps.remove(tr);
            }
            _4Ps.Gallery.rows--;
        }
    }

}
