/* 
 *  Copyright 2012 Institut de recherche et d'innovation 
 *  contributor(s) : Yves-Marie Haussonne, Raphael Velt, Samuel Huron
 *   
 *  contact@iri.centrepompidou.fr
 *  http://www.iri.centrepompidou.fr 
 *   
 *  This software is a computer program whose purpose is to show and add annotations on a video .
 *  This software is governed by the CeCILL-C license under French law and
 *  abiding by the rules of distribution of free software. You can  use, 
 *  modify and/ or redistribute the software under the terms of the CeCILL-C
 *  license as circulated by CEA, CNRS and INRIA at the following URL
 *  "http://www.cecill.info". 
 *  
 *  The fact that you are presently reading this means that you have had
 *  knowledge of the CeCILL-C license and that you accept its terms.
*/

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

if (typeof Rkns !== "object") {
    Rkns = {}
}

Rkns.$ = jQuery;

Rkns._ = _;

Rkns.VERSION = '0.2';

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._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","#")
            .addClass("Rk-Bin-Close")
            .html('&times;')
            .appendTo(this.$)
            .click(function() {
                _this.destroy();
                return false;
            });
        Rkns.$('<a>')
            .attr("href","#")
            .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)
        }
    }
}

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

/* Point of entry */

Rkns.Renkan = function(_opts) {
    var _this = this;
    
    if (typeof _opts.language !== "string" || typeof Rkns.i18n[_opts.language] == "undefined") {
        _opts.language = (navigator.language || navigator.userLanguage || "en");
    }
    if (typeof _opts.container !== "string") {
        _opts.container = "renkan";
    }
    if (typeof _opts.search !== "object" || !_opts.search) {
        _opts.search = [];
    }
    if (typeof _opts.bins !== "object" || !_opts.bins) {
        _opts.bins = [];
    }
    if (typeof _opts.static_url !== "string") {
        _opts.static_url = "";
    }
    if (typeof _opts.show_bins !== "boolean") {
        _opts.show_bins = !!_opts.search.length || !!_opts.bins.length;
    }
    if (typeof _opts.read_only !== "boolean") {
        _opts.read_only = false;
    }
    if (typeof _opts.properties !== "object") {
    	_opts.properties = [];
    }
    if (typeof _opts.property_files === "object") {
    	Rkns._(_opts.property_files).each(function(f) {
    		Rkns.$.getJSON(f, function(data) {
    			_this.properties = _this.properties.concat(data);
    		});
    	});
    }
    if (typeof _opts.clip_images === "undefined") {
    	_opts.clip_images = true;
    }
    this.project = new Rkns.Models.Project();
    this.language = _opts.language;
    this.static_url = _opts.static_url;
    this.show_bins = _opts.show_bins;
    this.read_only = _opts.read_only;
    this.properties = _opts.properties;
    this.clip_images = _opts.clip_images;
    
    this.translate = function(_text) {
    	return (Rkns.i18n[_opts.language] || Rkns.i18n[_opts.language.substr(0,2)] || {})[_text] || _text;
    }
    if (typeof _opts.user_id !== "undefined") {
        this.current_user = _opts.user_id;
    }
    this.$ = Rkns.$("#" + _opts.container);
    this.$
        .addClass("Rk-Main")
        .html(this.template(this));
    this.renderer = new Rkns.Renderer.Scene(this);
    this.tabs = [];
    this.search_engines = [];

    this.current_user_list = new Rkns.Models.UsersList();
    
    if (!_opts.search.length) {
        this.$.find(".Rk-Web-Search-Form").detach();
    } else {
        var _tmpl = Rkns._.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");
        Rkns._(_opts.search).each(function(_search, _key) {
        	console.log(_search, Rkns[_search.type]);
        	if (Rkns[_search.type] && Rkns[_search.type].Search) {
        		_this.search_engines.push(new Rkns[_search.type].Search(_this, _search));
        	}
        });
        console.log(_this.search_engines);
        _select.html(
            Rkns._(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);
    }
    Rkns._(_opts.bins).each(function(_bin) {
    	if (Rkns[_bin.type] && Rkns[_bin.type].Bin) {
    		_this.tabs.push(new Rkns[_bin.type].Bin(_this, _bin));
    	}
    });
    
    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();
            }
        }).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")
                });
                Rkns._(_models).each(function(_model) {
                    _this.renderer.highlightModel(_model);
                });
            }
        }).mouseout(function() {
            _this.renderer.unhighlightAll();
        }).on("dragstart", ".Rk-Bin-Item", function(e) {
            var _t = Rkns.$(this);
        	e.originalEvent.dataTransfer.setData("text/x-iri-title",$(_t).attr("data-title"));
        	e.originalEvent.dataTransfer.setData("text/x-iri-description",$(_t).attr("data-description"));
        	e.originalEvent.dataTransfer.setData("text/x-iri-uri",$(_t).attr("data-uri"));
        	e.originalEvent.dataTransfer.setData("text/x-iri-image",$(_t).attr("data-image"));
        });
    Rkns.$(window).resize(function() {
        _this.resizeBins();
    });
    
    this.$.find(".Rk-Bins-Search-Input").on("change keyup paste input", function() {
       var val = Rkns.$(this).val();
       Rkns._(_this.tabs).each(function(tab) {
           tab.render(val);
       });
    });
    this.$.find(".Rk-Bins-Search-Form").submit(function() {
        return false
    });
}

Rkns.Renkan.prototype.template = Rkns._.template(
    '<% if (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" /></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" /></form></div>'
    + '<ul class="Rk-Bin-List"></ul></div><% } %><div class="Rk-Render Rk-Render-<% if (show_bins) { %>Panel<% } else { %>Full<% } %>"></div>'
);


Rkns.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());
}

Rkns.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 = {
    _ID_AUTO_INCREMENT : 0,
    _ID_BASE : (function(_d) {
        function pad(n){return n<10 ? '0'+n : n}
        function fillrand(n) {
            var _res = ''
            for (var i=0; i<n; i++) {
                _res += Math.floor(16*Math.random()).toString(16);
            }
            return _res;
        }
        return _d.getUTCFullYear() + '-'  
            + pad(_d.getUTCMonth()+1) + '-'  
            + pad(_d.getUTCDate()) + '-'
            + fillrand(16);
    })(new Date()),
    getUID : function(_base) {
        var _n = (++this._ID_AUTO_INCREMENT).toString(16),
            _base = (typeof _base === "undefined" ? "" : _base + "-" );
        while (_n.length < 4) {
            _n = '0' + _n
        }
        return _base + this._ID_BASE + '-' + _n;
    },
    inherit : function(_baseClass, _callbefore) {
        var _class = function() {
            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._init.apply(this, Array.prototype.slice.call(arguments, 0));
            }
        }
        _class.prototype = new _baseClass();
        return _class;
    }
}