/*************************************************************************
    $Id: bbpf.js 3927 2010-03-17 10:24:48Z jcigar $
**************************************************************************/

(function(window) {

    var Bbpf = window.Bbpf = new Object();

    Bbpf.utils = new Object();

    /*************************************************************************
        Helper functions (shortcuts)
    **************************************************************************/

    // Create/initialize a preconfigured editor
    Bbpf.utils.init_tinyMCE = function(params) {

        // VERY IMPORTANT !! document_base_url MUST end with a "/"
        var document_base_url = 'http://' + Bbpf.urls.host + Bbpf.urls.prefix;
        if (document_base_url.charAt(document_base_url.length - 1) != '/') {
            document_base_url += '/';
        }

        var default_values = {
            mode : "specific_textareas",
            skin : "default",
            editor_selector : "mceEditor",
            plugins : 'table, fullscreen, media, pagebreak, bbpf_advimage, bbpf_advlink',
            plugin_insertdate_dateFormat : "%d-%m-%Y",
            plugin_insertdate_timeFormat : "%H:%M:%S",
            pagebreak_separator : "<!-- page break -->",
            theme : "advanced",
            theme_advanced_toolbar_location : "top",
            theme_advanced_toolbar_align : "left",
            theme_advanced_statusbar_location : "bottom",
            theme_advanced_buttons1 : 'bold, italic, underline, formatselect, fontsizeselect, removeformat, forecolor, backcolor, justifyleft, justifycenter, justifyright, justifyfull,  bullist, numlist,  outdent, indent, anchor, link, unlink, image,  fullscreen, media, table, delete_col, delete_row, col_before, row_before, split_cells, code',
            theme_advanced_buttons2 : '',
            theme_advanced_buttons3 : '',
            theme_advanced_resize_horizontal : false,
            theme_advanced_resizing : true,
            cleanup : true,
            document_base_url : document_base_url
        }

        if (params) {
            for (var key in params) {
                default_values[key] = params[key];
            }
        }

        tinyMCE.init(default_values);
    }

    // FIXME
    // Populate an Element (<div>, <table>, ...) with an Ajax request
    Bbpf.utils.AjaxPopulate = function(url, target, params) {
        var q = new Yeti.XMLHttpRequest();

        if (params.spinner) {
            var spinner = params.spinner;
            spinner.style.display = 'inline';
        } else {
            var spinner = undefined;
        }

        q.onreadystatechange = function() {
            if (q.readyState == 4) {
                if (q.status == 200 || q.status == 304) {
                    // FIXME
                    document.getElementById(target).innerHTML = q.responseText;
                    if (params.onSuccess) {
                        params.onSuccess();
                    }
                } else if (q.status == 500 && params.onError) {
                    params.onError();
                }
                if (spinner) spinner.style.display = 'none';
            }
        }

        if (params.parameters) {
            var qs = new Yeti.utils.QueryString(params.parameters);
        } else {
            var qs = null;
        }

        if (!params.method || params.method == 'GET') {
            q.open('GET', url.concat('?').concat(qs));
            q.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            q.send(null);
        } else {
            q.open('POST', url);
            q.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            q.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            q.send(qs.toString());
        }
    }

    // Handle tabs that are used in some forms
    Bbpf.utils.form_tabs = function(container, current) {
        var current = current;
        var container_elem = document.getElementById(container);

        for (var i=0; i<container_elem.childNodes.length; i++) {
            var child = container_elem.childNodes[i];
            if (child.tagName == 'LI') {
                child.onclick = function() {
                    var id = this.id.split('-')[1];
                    document.getElementById('tab-'.concat(current)).className='formTab'
                    document.getElementById('section-'.concat(current)).style.display='none';

                    document.getElementById('tab-'.concat(id)).className='formTab current';
                    document.getElementById('section-'.concat(id)).style.display='block';
                    current = id;
                }
            }
        }
    }


    /*************************************************************************
        Browser
    **************************************************************************/

    Bbpf.Browser = function(params) {
        if (params !== undefined) {
            this.__init__(params);
        }
    }

    Bbpf.Browser.prototype.__init__ = function(params) {
        // Default parameters
        this.parameters = {
            'limit' : 50,
            'offset' : 0,
            'order' : 'desc',
            'sort' : 'weight'
        }

        this.set_params(params);
    }

    Bbpf.Browser.prototype.set_params = function(params) {
        // Additional parameters
        if (params.parameters) {
            for (var prop in params.parameters) {
                this.parameters[prop] = params.parameters[prop];
            }
        }

        // Browser URL (mandatory)
        if (params.url) this.url = params.url;
        if (params.spinner) this.spinner = document.getElementById(params.spinner);
    }

    Bbpf.Browser.prototype.toggle_order = function() {
        this.parameters.order = this.parameters.order == 'desc' ? 'asc' : 'desc';
    }

    Bbpf.Browser.prototype.refresh_spinner = function(action) {
        if (this.spinner && action) {
            this.spinner.style.display = action == 'show' ? 'inline' : 'none';
        }
    }

    Bbpf.Browser.prototype.refresh = function(params) {
        if (params.sort == this.parameters.sort) {
            this.toggle_order()
        }

        for (var key in params) {
            this.parameters[key] = params[key];
        }

        this.reload();
    }

    Bbpf.Browser.prototype.next = function() {
        this.parameters['offset'] += this.parameters['limit'];
        this.reload();
    }

    Bbpf.Browser.prototype.previous = function() {
        this.parameters['offset'] -= this.parameters['limit'];
        this.reload();
    }


    /*************************************************************************
        FolderBrowser
    **************************************************************************/

    Bbpf.FolderBrowser = function(params) {
        if (params !== undefined) {
            this.__init__(params);
        }
    }
    Bbpf.FolderBrowser.prototype = new Bbpf.Browser();
    Bbpf.FolderBrowser.prototype.constructor = Bbpf.FolderBrowser;

    Bbpf.FolderBrowser.prototype.__init__ = function(params) {
        Bbpf.Browser.prototype.__init__.call(this, params);
        this.target = params.body;
    }

    Bbpf.FolderBrowser.prototype.load = function(params) {
        this.refresh_spinner('show');
        Bbpf.utils.AjaxPopulate(this.url, this.target, {
            'parameters' : this.parameters,
            'spinner' : this.spinner
        });
    }

    Bbpf.FolderBrowser.prototype.paste = function(target) {
        if (confirm('Are you sure that you want to move those items ? They will me moved from their original location !')) {
            var self = this;
            Yeti.AjaxRequest(Bbpf.urls.prefix.concat('/folder/paste/').concat(target), {
                'onreadystatechange' : function(req) {
                    if (req.readyState == 4 && req.status == 200) {
                        self.refresh({});
                    }
                }
            })
        }
    }

    Bbpf.FolderBrowser.prototype.reload = Bbpf.FolderBrowser.prototype.load;


    /*************************************************************************
        FolderAdminBrowser
    **************************************************************************/

    Bbpf.FolderAdminBrowser = function(params) {
        if (params !== undefined) {
            this.__init__(params);
        }
    }
    Bbpf.FolderAdminBrowser.prototype = new Bbpf.FolderBrowser();
    Bbpf.FolderAdminBrowser.prototype.constructor = Bbpf.FolderAdminBrowser;

    Bbpf.FolderAdminBrowser.prototype.__init__ = function(params) {
        Bbpf.FolderBrowser.prototype.__init__.call(this, params);
        this.body = document.getElementById(params.body);
        this.pagination = document.getElementById(params.pagination);
        this.select_counter = document.getElementById(params.select_counter);
        this.content = params.content;
    }

    Bbpf.FolderAdminBrowser.prototype.remove_content = function() {
        for (var i=0 ; i<this.body.childNodes.length ; i++) {
            var element = this.body.childNodes[i];
            if (element.nodeName.toLowerCase() == 'tbody') {
                this.body.removeChild(element);
                break;
            }
        }
    }

    Bbpf.FolderAdminBrowser.prototype.populate_content = function(data) {
        for (var i=0 ; i<data.childNodes.length ; i++) {
            var child = data.childNodes[i];
            if (child.nodeName.toLowerCase() == 'tbody') {
                this.body.appendChild(Yeti.DOM.importNode(child, true));
                break;
            }
        }
    }

    Bbpf.FolderAdminBrowser.prototype.populate_pagination = function(data) {
        for (var i=0 ; i < data.childNodes.length ; i++) {
            var child = data.childNodes[i];
            if (child.nodeName.toLowerCase() == 'div') {
                this.pagination.appendChild(Yeti.DOM.importNode(child, true))
            }
        }
    }

    Bbpf.FolderAdminBrowser.prototype.load = function(params) {
        this.refresh_spinner('show');
        var self = this;

        Yeti.AjaxRequest(this.url, {
            'data' : this.parameters,
            'onreadystatechange' : function(req) {
                if (req.readyState == 4 && req.status == 200) {
                    var data = req.responseXML;
                    var content = data.getElementsByTagName('body')[0];
                    var pagination = data.getElementsByTagName('pagination')[0];

                    if (content.hasChildNodes()) {
                        self.remove_content();
                        self.populate_content(content);
                    }

                    if (pagination.hasChildNodes()) {
                        Yeti.DOM.removeChildren(self.pagination);
                        self.populate_pagination(pagination);
                    }

                    self.refresh_spinner('hide');
                }
            }
        })
    }

    Bbpf.FolderAdminBrowser.prototype.reload = Bbpf.FolderAdminBrowser.prototype.load;

    Bbpf.FolderAdminBrowser.prototype.get_selected = function() {
        var selected_ids = [];
        var inputs = this.body.getElementsByTagName('input');
        
        for (var cpt = 0 ; cpt < inputs.length ; cpt ++) {
            var elem = inputs[cpt];
            if (elem.getAttribute('class') == 'select_object' && elem.checked) {
                selected_ids.push(parseInt(elem.parentNode.parentNode.id.split('_')[1]));
            }
        }
        
        return selected_ids;
    }

    Bbpf.FolderAdminBrowser.prototype.check = function(src, content_id) {
        if (parseInt(content_id) > 0) {
            if (this.select_counter) {
                var current_cpt = parseInt(this.select_counter.firstChild.data);
                if (src.checked) {
                    this.select_counter.firstChild.data = current_cpt + 1;
                } else {
                    this.select_counter.firstChild.data = current_cpt - 1;
                }
            }
        }
    }

    Bbpf.FolderAdminBrowser.prototype.reset_select_counter = function() {
        if (this.select_counter) {
            document.getElementById(this.select_counter).firstChild.data = 0;
        }
    }

    Bbpf.FolderAdminBrowser.prototype.delete_selected = function() {
        var selected_ids = this.get_selected();
        if (selected_ids.length && confirm('Are you sure you want to delete those contents ?')) {
            var self = this;
            Yeti.AjaxRequest(Bbpf.urls.prefix.concat('/content/delete_many'), {
                'method' : 'POST',
                'data' : {'id' : selected_ids},
                'onreadystatechange' : function(req) {
                    if (req.readyState == 4 && req.status == 200) {
                        self.refresh({});
                    }
                }
            })
        }
    }

    // FIXME: dirty
    Bbpf.FolderAdminBrowser.prototype.move = function(content_id) {
        var el = document.getElementById('content_' + content_id);
        if (!this.move_content) {
            this.move_content = content_id;
            el.style.backgroundColor = '#78b7c9';
        } else if (content_id != this.move_content) {
            el.style.backgroundColor = '#abc978';
            var weight = parseInt(el.cells[4].firstChild.data);
            var self = this;

            Yeti.AjaxRequest(Bbpf.urls.prefix.concat('/' + this.content.id + '/weight'), {
                'data' : { 'content_id' : self.move_content,
                           'weight' : weight },
                'onreadystatechange' : function(req) {
                    if (req.readyState == 4 && req.status == 200) {
                        self.reload();
                        self.move_content = undefined;
                    }
                }
            });

        }
    }


    /*************************************************************************
        Folder
    **************************************************************************/

    Bbpf.Folder = function() {}

    Bbpf.Folder.show_frame = function(params) {
        var frame = new Yeti.ui.Frame({
            'title' : 'Add content'
        });

        frame.attach({
            'outerFrame' : true
        });

        Yeti.AjaxRequest(params.url, {
            'data' : {'container_id' : params.container_id},
            'onreadystatechange' : function(req) {
                if (req.readyState == 4 && req.status == 200) {
                    frame.body.innerHTML = req.responseText;
                }
            }
        })
    }


    /*************************************************************************
        Content
    **************************************************************************/

    Bbpf.Content = function() {}

    // Remove an object from the database through an Ajax request.
    Bbpf.Content.remove = function(params) {
        if (parseInt(params.id) && confirm('Are you sure you want to delete this content ?')) {
            Yeti.AjaxRequest(Bbpf.urls.prefix.concat('/content/delete/').concat(params.id), {
                'onreadystatechange' : function(req) {
                    if (req.readyState == 4 && req.status == 200 && 
                    params.onSuccess) {
                        params.onSuccess();
                    }
                }
            });
        }
    }

    Bbpf.Content.ids_to_session = function(ids) {
        Yeti.AjaxRequest(Bbpf.urls.prefix.concat('/content/ids_to_session'), {
            'method' : 'POST',
            'data' : {'id' : ids},
            'onreadystatechange' : function(req) {
                if (req.readyState == 4 && req.status == 200) {
                    alert('Selection has been "cut"');
                }
            }
        })
    }
    

    /*************************************************************************
        Event
    **************************************************************************/

    Bbpf.Event = function(params) {
        if (params) {
            for (var p in params) {
                this[p] = params[p];
            }
        }
    }

    Bbpf.Event.prototype.is_georeferenced = function() {
        return this.address_latitude && this.address_longitude;
    }

    Bbpf.Event.prototype.GeocodingHandler = function(src_form, map) {
        var form = src_form;
        
        if (this.is_georeferenced()) {
            var point = new GLatLng(this.address_latitude, 
                                    this.address_longitude);
        } else {
            var point = new GLatLng(50, 0);
        }

        // The global marker which indicates the address
        var marker = new GMarker(point, {
            draggable : true
        })

        // When we move the marker, update the two hidden fields (latitude and
        // longitude)
        GEvent.addListener(marker, "dragend", function() {
            var coords = marker.getLatLng();
            form.address_latitude.value = coords.lat();
            form.address_longitude.value = coords.lng();
        });
     
        var map = new GMap2(document.getElementById(map));
        map.setCenter(point, this.address ? 10 : 4);
        map.addOverlay(marker);
        
        // Test if the event has already a georeferenced address. If
        // yes, add the marker.
        this.is_georeferenced() ? marker.show() : marker.hide();

        var geocoder = new GClientGeocoder();
        form.country_id.onchange = form.address.onblur = function(evt) {
            // " foo     bar     " => "foo bar"
            var q = form.address.value.replace(/(?:^\s+)|(?:\s+$)/g, '').replace(/\s{2,}/g, ' ');
            var zoom = 10;
            
            if (q.length > 0) {
                if (q.charAt(q.length - 1) != ',') {
                    q = q.concat(', ');
                }
            } else {
                zoom = 4;
            }

            // Concat the address with the selected country name
            q = q.concat(form.country_id.options[form.country_id.selectedIndex].text);

            // Now q contains "address, country". If we can find this
            // address, then 1) add its latitude/longitude to the two
            // hidden fields 2) zoom to this address 3) add a marker. If
            // we can't find the address, then set latitude/longitude to
            // null.
            geocoder.getLatLng(q, function(point) {
                if (!point) {
                    marker.hide();
                    form.address_latitude.value = form.address_longitude.value = null;
                } else {
                    marker.setLatLng(point);
                    form.address_latitude.value = point.lat();
                    form.address_longitude.value = point.lng();
                    map.setCenter(point, zoom);
                    
                    if (marker.isHidden()) {
                        marker.show();
                    }
                }
            }); // geocoder.getLatLng
        }
    }
})(window);
