
/* Declaring the Renkan Namespace Rkns and Default values */

(function(root) {

"use strict";

if (typeof root.Rkns !== "object") {
    root.Rkns = {};
}

var Rkns = root.Rkns;
var $ = Rkns.$ = root.jQuery;
var _ = Rkns._ = root._;

Rkns.VERSION = '0.2.3';

Rkns.pickerColors = ["#8f1919", "#a80000", "#d82626", "#ff0000", "#e87c7c", "#ff6565", "#f7d3d3", "#fecccc",
    "#8f5419", "#a85400", "#d87f26", "#ff7f00", "#e8b27c", "#ffb265", "#f7e5d3", "#fee5cc",
    "#8f8f19", "#a8a800", "#d8d826", "#feff00", "#e8e87c", "#feff65", "#f7f7d3", "#fefecc",
    "#198f19", "#00a800", "#26d826", "#00ff00", "#7ce87c", "#65ff65", "#d3f7d3", "#ccfecc",
    "#198f8f", "#00a8a8", "#26d8d8", "#00feff", "#7ce8e8", "#65feff", "#d3f7f7", "#ccfefe",
    "#19198f", "#0000a8", "#2626d8", "#0000ff", "#7c7ce8", "#6565ff", "#d3d3f7", "#ccccfe",
    "#8f198f", "#a800a8", "#d826d8", "#ff00fe", "#e87ce8", "#ff65fe", "#f7d3f7", "#feccfe",
    "#000000", "#242424", "#484848", "#6d6d6d", "#919191", "#b6b6b6", "#dadada", "#ffffff"];

Rkns.__renkans = [];

var _BaseBin = Rkns._BaseBin = function(_renkan, _opts) {
    if (typeof _renkan !== "undefined") {
        this.renkan = _renkan;
        this.renkan.$.find(".Rk-Bin-Main").hide();
        this.$ = Rkns.$('<li>')
            .addClass("Rk-Bin")
            .appendTo(_renkan.$.find(".Rk-Bin-List"));
        this.title_icon_$ = Rkns.$('<span>')
            .addClass("Rk-Bin-Title-Icon")
            .appendTo(this.$);
            
        var _this = this;
        
        Rkns.$('<a>')
            .attr({
                href: "#",
                title: _renkan.translate("Close bin")
            })
            .addClass("Rk-Bin-Close")
            .html('&times;')
            .appendTo(this.$)
            .click(function() {
                _this.destroy();
                if (!_renkan.$.find(".Rk-Bin-Main:visible").length) {
                    _renkan.$.find(".Rk-Bin-Main:last").slideDown();
                }
                _renkan.resizeBins();
                return false;
            });
        Rkns.$('<a>')
            .attr({
                href: "#",
                title: _renkan.translate("Refresh bin")
            })
            .addClass("Rk-Bin-Refresh")
            .appendTo(this.$)
            .click(function() {
                _this.refresh();
                return false;
            });
        this.count_$ = Rkns.$('<div>')
            .addClass("Rk-Bin-Count")
            .appendTo(this.$);
        this.title_$ = Rkns.$('<h2>')
            .addClass("Rk-Bin-Title")
            .appendTo(this.$);
        this.main_$ = Rkns.$('<div>')
            .addClass("Rk-Bin-Main")
            .appendTo(this.$)
            .html('<h4 class="Rk-Bin-Loading">' + _renkan.translate("Loading, please wait") + '</h4>');
        this.title_$.html(_opts.title || '(new bin)');
        this.renkan.resizeBins();
        
        if (_opts.auto_refresh) {
            window.setInterval(function() {
                _this.refresh();
            },_opts.auto_refresh);
        }
    }
};

_BaseBin.prototype.destroy = function() {
    this.$.detach();
    this.renkan.resizeBins();
};

/* Point of entry */

var Renkan = Rkns.Renkan = function(_opts) {
    var _this = this;
    
    Rkns.__renkans.push(this);
    
    this.options = _.defaults(_opts, Rkns.defaults);
        
    _(this.options.property_files).each(function(f) {
        Rkns.$.getJSON(f, function(data) {
            _this.options.properties = _this.options.properties.concat(data);
        });
    });
    
    this.read_only = this.options.read_only || !this.options.editor_mode;

    this.project = new Rkns.Models.Project();
    
    if (typeof this.options.user_id !== "undefined") {
        this.current_user = this.options.user_id;
    }
    this.$ = Rkns.$("#" + this.options.container);
    this.$
        .addClass("Rk-Main")
        .html(this.template(this));
    
    this.tabs = [];
    this.search_engines = [];

    this.current_user_list = new Rkns.Models.UsersList();
    
    this.current_user_list.on("add remove", function() {
        if (this.renderer) {
            this.renderer.redrawUsers();
        }
    });
    
    this.colorPicker = (function() {
        var _tmpl = _.template('<li data-color="<%=c%>" style="background: <%=c%>"></li>');
        return '<ul class="Rk-Edit-ColorPicker">' + Rkns.pickerColors.map(function(c) { return _tmpl({c:c})}).join("") + '</ul>'
    })();
    
    if (this.options.show_editor) {
        this.renderer = new Rkns.Renderer.Scene(this);
    }
    
    if (!this.options.search.length) {
        this.$.find(".Rk-Web-Search-Form").detach();
    } else {
        var _tmpl = _.template('<li class="<%= className %>" data-key="<%= key %>"><%= title %></li>'),
            _select = this.$.find(".Rk-Search-List"),
            _input = this.$.find(".Rk-Web-Search-Input"),
            _form = this.$.find(".Rk-Web-Search-Form");
        _(this.options.search).each(function(_search, _key) {
            if (Rkns[_search.type] && Rkns[_search.type].Search) {
                _this.search_engines.push(new Rkns[_search.type].Search(_this, _search));
            }
        });
        _select.html(
            _(this.search_engines).map(function(_search, _key) {
                return _tmpl({
                    key: _key,
                    title: _search.getSearchTitle(),
                    className: _search.getBgClass()
                });
            }).join("")
        );
        _select.find("li").click(function() {
            var _el = Rkns.$(this);
            _this.setSearchEngine(_el.attr("data-key"));
            _form.submit();
        });
        _form.submit(function() {
            if (_input.val()) {
                var _search = _this.search_engine;
                _search.search(_input.val());
            }
            return false;
        });
        this.$.find(".Rk-Search-Current").mouseenter(
            function() { _select.slideDown(); }
        );
        this.$.find(".Rk-Search-Select").mouseleave(
            function() { _select.hide(); }
        );
        this.setSearchEngine(0);
    }
    _(this.options.bins).each(function(_bin) {
        if (Rkns[_bin.type] && Rkns[_bin.type].Bin) {
            _this.tabs.push(new Rkns[_bin.type].Bin(_this, _bin));
        }
    });
    
    var elementDropped = false;
    
    this.$.find(".Rk-Bins")
        .on("click",".Rk-Bin-Title,.Rk-Bin-Title-Icon", function() {
            var _mainDiv = Rkns.$(this).siblings(".Rk-Bin-Main");
            if (_mainDiv.is(":hidden")) {
                _this.$.find(".Rk-Bin-Main").slideUp();
                _mainDiv.slideDown();
            }
        });
    
    if (this.options.show_editor) {
        
        this.$.find(".Rk-Bins").on("mouseover", ".Rk-Bin-Item", function(_e) {
            var _t = Rkns.$(this);
            if (_t && $(_t).attr("data-uri")) {
                var _models = _this.project.get("nodes").where({
                    uri: $(_t).attr("data-uri")
                });
                _(_models).each(function(_model) {
                    _this.renderer.highlightModel(_model);
                });
            }
        }).mouseout(function() {
            _this.renderer.unhighlightAll();
        }).on("mousemove", ".Rk-Bin-Item", function(e) {
            try {
                this.dragDrop();
            }
            catch(err) {}
        }).on("touchstart", ".Rk-Bin-Item", function(e) {
            elementDropped = false;
        }).on("touchmove", ".Rk-Bin-Item", function(e) {
            e.preventDefault();
            var touch = e.originalEvent.changedTouches[0],
                off = _this.renderer.canvas_$.offset(),
                w = _this.renderer.canvas_$.width(),
                h = _this.renderer.canvas_$.height();
            if (touch.pageX >= off.left && touch.pageX < (off.left + w) && touch.pageY >= off.top && touch.pageY < (off.top + h)) {
                if (elementDropped) {
                    _this.renderer.onMouseMove(touch, true);
                } else {
                    elementDropped = true;
                    var div = document.createElement('div');
                    div.appendChild(this.cloneNode(true));
                    _this.renderer.dropData({"text/html": div.innerHTML}, touch);
                    _this.renderer.onMouseDown(touch, true);
                }
            }
        }).on("touchend", ".Rk-Bin-Item", function(e) {
            if (elementDropped) {
                _this.renderer.onMouseUp(e.originalEvent.changedTouches[0], true);
            }
            elementDropped = false;
        }).on("dragstart", ".Rk-Bin-Item", function(e) {
            var div = document.createElement('div');
            div.appendChild(this.cloneNode(true));
            try {
                e.originalEvent.dataTransfer.setData("text/html",div.innerHTML);
            }
            catch(err) {
                e.originalEvent.dataTransfer.setData("text",div.innerHTML);
            }
        });
        
    }
    
    Rkns.$(window).resize(function() {
        _this.resizeBins();
    });
    
    var lastsearch = false, lastval = '';
    
    this.$.find(".Rk-Bins-Search-Input").on("change keyup paste input", function() {
        var val = Rkns.$(this).val();
        if (val === lastval) {
            return;
        }
        var search = Rkns.Utils.regexpFromTextOrArray(val.length > 1 ? val: null);
        if (search.source === lastsearch) {
            return;
        }
        lastsearch = search.source;
        _(_this.tabs).each(function(tab) {
            tab.render(search);
        });
        
    });
    this.$.find(".Rk-Bins-Search-Form").submit(function() {
        return false;
    });
    
};

Renkan.prototype.template = _.template(
    '<% if (options.show_bins) { %><div class="Rk-Bins"><div class="Rk-Bins-Head"><h2 class="Rk-Bins-Title"><%- translate("Select contents:")%></h2>'
    + '<form class="Rk-Web-Search-Form Rk-Search-Form"><input class="Rk-Web-Search-Input Rk-Search-Input" type="search" placeholder="<%- translate("Search the Web") %>" />'
    + '<div class="Rk-Search-Select"><div class="Rk-Search-Current"></div><ul class="Rk-Search-List"></ul></div>'
    + '<input type="submit" value="" class="Rk-Web-Search-Submit Rk-Search-Submit" title="<%- translate("Search the Web") %>" /></form>'
    + '<form class="Rk-Bins-Search-Form Rk-Search-Form"><input class="Rk-Bins-Search-Input Rk-Search-Input" type="search" placeholder="<%- translate("Search in Bins") %>" />'
    + '<input type="submit" value="" class="Rk-Bins-Search-Submit Rk-Search-Submit" title="<%- translate("Search in Bins") %>" /></form></div>'
    + '<ul class="Rk-Bin-List"></ul></div><% } %>'
    + '<% if (options.show_editor) { %><div class="Rk-Render Rk-Render-<% if (options.show_bins) { %>Panel<% } else { %>Full<% } %>"></div><% } %>'
);

Renkan.prototype.translate = function(_text) {
    if (Rkns.i18n[this.options.language] && Rkns.i18n[this.options.language][_text]) {
        return Rkns.i18n[this.options.language][_text];
    }
    if (this.options.language.length > 2 && Rkns.i18n[this.options.language.substr(0,2)] && Rkns.i18n[this.options.language.substr(0,2)][_text]) {
        return Rkns.i18n[this.options.language.substr(0,2)][_text];
    }
    return _text;
};

Renkan.prototype.onStatusChange = function() {
    this.renderer.onStatusChange();
};

Renkan.prototype.setSearchEngine = function(_key) {
    this.search_engine = this.search_engines[_key];
    this.$.find(".Rk-Search-Current").attr("class","Rk-Search-Current " + this.search_engine.getBgClass());
};

Renkan.prototype.resizeBins = function() {
    var _d = + this.$.find(".Rk-Bins-Head").outerHeight();
    this.$.find(".Rk-Bin-Title:visible").each(function() {
        _d += Rkns.$(this).outerHeight();
    });
    this.$.find(".Rk-Bin-Main").css({
        height: this.$.find(".Rk-Bins").height() - _d
    });
};

/* Utility functions */

Rkns.Utils = {
    getUID : (function() {
        function pad(n){
            return n<10 ? '0'+n : n;
        }
        function fillrand() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
                return v.toString(16);
            });
        }
        var _d = new Date(),
            ID_AUTO_INCREMENT = 0,
            ID_BASE = _d.getUTCFullYear() + '-'  
            + pad(_d.getUTCMonth()+1) + '-'  
            + pad(_d.getUTCDate()) + '-'
            + fillrand();
        return function(_base) {
            var _n = (++ID_AUTO_INCREMENT).toString(16),
                _base = (typeof _base === "undefined" ? "" : _base + "-" );
            while (_n.length < 4) { _n = '0' + _n; }
            return _base + ID_BASE + '-' + _n;
        }
    })(),
    getFullURL : function(url) {
        
        if(typeof(url) == 'undefined' || url == null ) {
            return "";
        }
        if(/https?:\/\//.test(url)) {
            return url;
        }
        var img = new Image();
        img.src = url;
        var res = img.src;
        img.src = null;
        return res;
        
    },
    inherit : function(_baseClass, _callbefore) {
        
        var _class = function(_arg) {
            if (typeof _callbefore === "function") {
                _callbefore.apply(this, Array.prototype.slice.call(arguments, 0));
            }
            _baseClass.apply(this, Array.prototype.slice.call(arguments, 0));
            if (typeof this._init == "function" && !this._initialized) {
                this._init.apply(this, Array.prototype.slice.call(arguments, 0));
                this._initialized = true;
            }
        };
        _(_class.prototype).extend(_baseClass.prototype);
        return _class;
        
    },
    regexpFromTextOrArray: (function() {
        var charsub = [
                '[aáàâä]',
                '[cç]',
                '[eéèêë]',
                '[iíìîï]',
                '[oóòôö]',
                '[uùûü]'
            ],
            removeChars = [
                String.fromCharCode(768), String.fromCharCode(769), String.fromCharCode(770), String.fromCharCode(771), String.fromCharCode(807),
                "｛", "｝", "（", "）", "［", "］", "【", "】", "、", "・", "‥", "。", "「", "」", "『", "』", "〜", "：", "！", "？", "　",
                ",", " ", ";", "(", ")", ".", "*", "+", "\\", "?", "|", "{", "}", "[", "]", "^", "#", "/"
            ],
            remsrc = "[\\" + removeChars.join("\\") + "]",
            remrx = new RegExp(remsrc, "gm"),
            charsrx = _(charsub).map(function(c) {
                return new RegExp(c);
            });
        
        function replaceText(_text) {
            var txt = _text.toLowerCase().replace(remrx,""), src = "";
            for (var j = 0; j < txt.length; j++) {
                if (j) {
                    src += remsrc + "*";
                }
                var l = txt[j];
                _(charsub).each(function(v, k) {
                    l = l.replace(charsrx[k], v);
                });
                src += l;
            }
            return src;
        }
        
        function getSource(inp) {
            switch (typeof inp) {
                case "string":
                    return replaceText(inp);
                case "object":
                    var src = '';
                    _(inp).each(function(v) {
                        var res = getSource(v);
                        if (res) {
                            if (src) {
                                src += '|';
                            }
                            src += res;
                        }
                    });
                    return src;
            }
            return '';
        }
        
        return function(_textOrArray) {
            var source = getSource(_textOrArray);
            if (source) {
                var testrx = new RegExp( source, "im"),
                    replacerx = new RegExp( '(' + source + ')', "igm")
                return {
                    isempty: false,
                    source: source,
                    test: function(_t) { return testrx.test(_t) },
                    replace: function(_text, _replace) { return _text.replace(replacerx, _replace); }
                }
            } else {
                return {
                    isempty: true,
                    source: '',
                    test: function() { return true },
                    replace: function(_text) { return text }
                }
            }
        }
    })()
};
})(window);

/* END main.js */
