/*
 * Sidebar Widget, version 1.0
 * (c) 2009 SmallRivers
 */


(function(){

    var url = document.URL;
    var userAgent = navigator.userAgent.toLowerCase();

    var browser = {
        version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
        safari: /webkit/.test(userAgent),
        opera: /opera/.test(userAgent),
        msie: (/msie/.test(userAgent)) && (!/opera/.test( userAgent )),
        mozilla: (/mozilla/.test(userAgent)) && (!/(compatible|webkit)/.test(userAgent))
    };    

    var readyBound = false;    
    var isReady = false;
    var readyList = [];
    
    /* event related functions */

    // Handle when the DOM is ready
    function domReady() {
        // Make sure that the DOM is not already loaded
        if(!isReady) {
            // Remember that the DOM is ready
            isReady = true;
        
            if(readyList) {
                for(var fn = 0; fn < readyList.length; fn++) {
                    readyList[fn].call(window, []);
                }
            
                readyList = [];
            }
        }
    };

    // A safe way to fire onload w/o screwing up everyone else.
    function addLoadEvent(func) {
      var oldonload = window.onload;
      if (typeof window.onload != 'function') {
        window.onload = func;
      } else {
        window.onload = function() {
          if (oldonload) {
            oldonload();
          }
          func();
        }
      }
    };

    // does the heavy work of working through the browsers idiosyncracies (let's call them that) to hook onload.
    function bindReady() {
        if(readyBound) {
            return;
        }
    
        readyBound = true;

        // Mozilla, Opera (see further below for it) and webkit nightlies currently support this event
        if (document.addEventListener && !browser.opera) {
            // Use the handy event callback
            document.addEventListener("DOMContentLoaded", domReady, false);
        }

        // If IE is used and is not in a frame
        // Continually check to see if the document is ready
        if (browser.msie && window == top) (function(){
            if (isReady) return;
            try {
                // If IE is used, use the trick by Diego Perini
                // http://javascript.nwbox.com/IEContentLoaded/
                document.documentElement.doScroll("left");
            } catch(error) {
                setTimeout(arguments.callee, 0);
                return;
            }
            // and execute any waiting functions
            domReady();
        })();

        if(browser.opera) {
            document.addEventListener( "DOMContentLoaded", function () {
                if (isReady) return;
                for (var i = 0; i < document.styleSheets.length; i++)
                    if (document.styleSheets[i].disabled) {
                        setTimeout( arguments.callee, 0 );
                        return;
                    }
                // and execute any waiting functions
                domReady();
            }, false);
        }

        if(browser.safari) {
            var numStyles;
            (function(){
                if (isReady) return;
                if (document.readyState != "loaded" && document.readyState != "complete") {
                    setTimeout( arguments.callee, 0 );
                    return;
                }
                if (numStyles === undefined) {
                    var links = document.getElementsByTagName("link");
                    for (var i=0; i < links.length; i++) {
                        if(links[i].getAttribute('rel') == 'stylesheet') {
                            numStyles++;
                        }
                    }
                    var styles = document.getElementsByTagName("style");
                    numStyles += styles.length;
                }
                if (document.styleSheets.length != numStyles) {
                    setTimeout( arguments.callee, 0 );
                    return;
                }
            
                // and execute any waiting functions
                domReady();
            })();
        }

        // A fallback to window.onload, that will always work
        addLoadEvent(domReady);
    };

    function ready(fn, args) {
        // Attach the listeners
        bindReady();
    
        // If the DOM is already ready
        if (isReady) {
            // Execute the function immediately
            fn.call(window, []);
        } else {
            // Add the function to the wait list
            readyList.push( function() { return fn.call(window, []); } );
        }
    };
    
    function listen(elem, evnt, func) {
        if (elem.addEventListener) // W3C DOM
            elem.addEventListener(evnt, func, false);
        else 
            if (elem.attachEvent) { // IE DOM
                var r = elem.attachEvent("on" + evnt, func);
                return r;
            }
    };
    
    function stopEvent(e) {
        if(!e) var e = window.event;
        
        //e.cancelBubble is supported by IE - this will kill the bubbling process.
        e.cancelBubble = true;
        e.returnValue = false;
        
        //e.stopPropagation works only in Firefox.
        if (e.stopPropagation) {
            e.stopPropagation();
            e.preventDefault();
        }
        return false;
    };
    
    /* DOM manipulation functions */
    
    function createElement(e, attrs) {
        var el = document.createElement(e);
        for (var k in attrs) {
            if (k == "text") {
                el.appendChild(document.createTextNode(attrs[k]));
            }
            else if (k == "html") {
                el.innerHTML = attrs[k];
            }
            else {
                setAttribute(el, k, attrs[k]);
            }
        }
        return el;
    };
    
    function createTextElement(text) {
        return document.createTextNode(text);
    };

    function setAttribute(e, k, v) {
        if (k == "class") {
            e.setAttribute("className", v); // set both "class" and "className"
        }
        if (k == "style") {
            e.style.cssText = v; // set cssText for IE
        }
        
        return e.setAttribute(k, v);
    };
    
    function removeElement(e) {
        e.parentNode.removeChild(e);
    };
    
    /* util functions */
        
    function loadScript(_src) {
        var e = createElement('script', {
            'language': 'javascript', 
            'type': 'text/javascript',
            'src': _src
        });
        document.body.appendChild(e);
    };

    function loadImage(_src) {
        var e = createElement('img', {
            'style': 'display: none;',
            'src': _src
        });
        document.body.appendChild(e);
    };
    
    function loadCss(_src) {
        var e = createElement('link', {
            'type': 'text/css', 
            'rel': 'stylesheet',
            'media': 'screen',
            'href': _src
        });
        try {
            document.getElementsByTagName('head')[0].appendChild(e);
        } 
        catch (z) {
            document.body.appendChild(e);
        }
    };
    
    function getSelectedText(){
        if(window.getSelection){
            return window.getSelection();
        }
        else if(document.getSelection){
            return document.getSelection();
        }
        else {
            var selection = document.selection && document.selection.createRange();
            if(selection.text){
                return selection.text;
            }
            return false;
        }
        return false;
    };
    
    /* sidebar functions */
    
    function sidebarOpen(sidebar_info){
        sidebarClose();
        
        loadCss(sidebar_info.sb_url + '/stylesheets/sidebar.css');        
        
        var src = sidebar_info.sb_url + "/index.html?v=2.0.4";
        src += "&p=" + encodeURIComponent(sidebar_info.pid);
        src += "&r=" + encodeURIComponent(sidebar_info.rid);
        src += "&s=" + encodeURIComponent(sidebar_info.svc_url);
        if (sidebar_info.mode){
            src += "&m=" + encodeURIComponent(sidebar_info.mode);
            src += "&u=" + encodeURIComponent(url);
        }
        
        var sidebar = createElement('div', {"id": "_sr_sidebar"}); // main container element
        var content = createElement('div', {"id": "_sr_content"}); // content element
        var closeBtn = createElement('img', { // close link
            "id": "_sr_close",
            "src": "http://assets3.smallrivers.net/images/close.gif",
            "title": "Close sidebar"
        });
        listen(closeBtn, 'click', sidebarClose); // action on close
        
        var iframe = createElement('iframe', { // iframe with sidebar content
            "id": "_sr_iframe",
            "src": src,
            "allowtransparency": "true",
            "frameBorder": "0"
        });
        
        content.appendChild(iframe);
        content.appendChild(closeBtn);
        sidebar.appendChild(content);
        document.body.appendChild(sidebar); // add sidebar
    };

    function sidebarClose() {
        var sidebar = document.getElementById('_sr_sidebar');
        if (sidebar != undefined) {
            removeElement(sidebar);
        }
    };
    
    /* sticker related functions */    
    
    var defCss = {'padding': '0', 'margin': '0', 'line-height': 'normal', 'height': 'auto', 'width': 'auto', 'text-align': 'left', 'font-weight': 'normal', 'text-transform': 'none', 'letter-spacing': 'normal', 'font-size': '11px', 'border': '0 none'};
    
    function merge(destination, source) {
        var res = {}
        for (var property in destination){
            res[property] = destination[property];
        }
        for (var property in source){
            res[property] = source[property];
        }
        return res;
    };
    
    function getStyle(custom) {
        var hash = merge(defCss, custom || {});
        var res = '';
        for (var property in hash){
            res += property + ":" + hash[property] + ";";
        }
        return res;
    };
    
    function getTooltip(sticker_info) {
        return sticker_info.title + ' - ' + sticker_info.count + ' connected sites';
    };
    
    function stickerShow(sidebar_info, sticker_info){
        var clazz = "smallrivers_" + sidebar_info.rid;
        if (sidebar_info.pid != '-'){
            clazz += "_" + sidebar_info.pid;
        }
        var id = clazz + "_" + Math.floor(Math.random()* 1000000); 

        document.write('<div id="' + id + '" class="' + clazz + '" style="padding:0; margin:0;line-height:normal;"></div>');
        ready(function(){
            var element = document.getElementById(id);
            var sticker = null;
            switch(style) {
                case 'image':
                    sticker = stickerCreateImage(sidebar_info, sticker_info);
                    break;
                case 'small':
                    sticker = stickerCreateSmall(sidebar_info, sticker_info);
                    break;
                case 'medium':
                    sticker = stickerCreateMedium(sidebar_info, sticker_info);
                    break;
                default:
                    sticker = stickerCreateFull(sidebar_info, sticker_info);
            }
            
            listen(sticker, 'click', function(e){
                sidebarOpen(sidebar_info);
                stopEvent(e);
            });
            
            element.appendChild(sticker);
            // clearfix
            element.appendChild(createElement('div', {style: 'content:".";display:block;height:0;clear:both;visibility:hidden;'}));
        });
        
        if (sidebar_info.show) {
            sidebarOpen(sidebar_info);
        }
        
        log(sidebar_info, '1283528406.60219', '832105eca75dbdef138f66770639ebfcdb91373d');
    };
    
    function stickerCreateImage(sidebar_info, sticker_info){
        var panel = createElement('img', {src: image, title: getTooltip(sticker_info), style: getStyle({'margin': '0 5px', 'cursor': 'pointer', 'background': 'none', 'float': 'left'})});
        
        return panel;
    };
    
    function stickerCreateSmall(sidebar_info, sticker_info){
        var panel = createElement('div', {title: getTooltip(sticker_info), style: getStyle({'cursor': 'pointer', 'float': 'left', 'position': 'relative', 'font-family': '"lucida grande",tahoma,sans-serif', 'font-size': '10px'})});
        panel.appendChild(createElement('img', {src: image, style: getStyle({'margin': '0 5px', 'background': 'none', 'float': 'left'})}));
        var counter = panel.appendChild(createElement('div', {text: sticker_info.count, style: getStyle({'padding': '3px 7px', 'color': '#1F60A5', 'background-color': color, 'border': '1px solid ' + color, '-moz-border-radius': '5px', '-webkit-border-radius': '5px', 'float': 'left', 'font-weight': 'bold'})}));
        
        listen(panel, 'mouseover', function(e){
            counter.style.backgroundColor = "#fff";
        });
        listen(panel, 'mouseout', function(e){
            counter.style.backgroundColor = color;
        });        
        
        return panel;
    };
    
    function stickerCreateMedium(sidebar_info, sticker_info){
        var panel = createElement('div', {style: getStyle({'padding': '5px', 'cursor': 'pointer', 'background-color': color, 'float': 'left', 'position': 'relative', 'font-family': '"lucida grande",tahoma,sans-serif', '-moz-border-radius': '5px', '-webkit-border-radius': '5px', 'border': '1px solid ' + color})});
        var header = panel.appendChild(createElement('div', {style: getStyle({'margin': '0 0 2px 0', 'color': '#000', 'overflow': 'hidden', 'font-size': '10px'})}));
        header.appendChild(createTextElement(sticker_info.title));

        var footer = panel.appendChild(createElement('div', {style: getStyle()}));
        var content = footer.appendChild(createElement('div', {style: getStyle({'float': 'left'})}));
           content.appendChild(createElement('div', {text: sticker_info.count, style: getStyle({'margin': '0 5px 0 0', 'font-weight': 'bold', 'color': '#1F60A5', 'float': 'left', 'font-size': '10px', 'line-height': '20px'})}));
           content.appendChild(createElement('div', {text: 'connected sites', style: getStyle({'margin': '0 5px 0 0', 'color': '#1F60A5', 'float': 'left', 'font-size': '10px', 'line-height': '20px'})}));
        footer.appendChild(createElement('img', {align: 'bottom', src: image, style: getStyle({'background': 'none', 'float': 'right'})}));

        listen(panel, 'mouseover', function(e){
            panel.style.backgroundColor = "#fff";
        });
        listen(panel, 'mouseout', function(e){
            panel.style.backgroundColor = color;
        });        

        return panel;
    };
    
    function stickerCreateFull(sidebar_info, sticker_info){
        var panel = createElement('div', {style: getStyle({'padding': '5px', 'cursor': 'pointer', 'background-color': color, 'float': 'left', 'position': 'relative', 'font-family': '"lucida grande",tahoma,sans-serif', '-moz-border-radius': '5px', '-webkit-border-radius': '5px', 'width': '220px'})});
        var header = panel.appendChild(createElement('div', {style: getStyle({'line-height': '32px', 'height': '32px', 'font-weight': 'bold', 'color': '#000', 'overflow': 'hidden'})}));
        header.appendChild(createElement('img', {src: image, style: getStyle({'margin': '0 5px', 'background': 'none', 'float': 'left'})}));
        header.appendChild(createTextElement(sticker_info.title));

        if (sticker_info.activity){
            var body = panel.appendChild(createElement('div', {style: getStyle({'padding': '5px', 'margin': '5px 0', 'background-color': '#fff', '-moz-border-radius': '5px', '-webkit-border-radius': '5px'})}));
            var favicon = body.appendChild(createElement('img', {src: sticker_info.activity.favicon, style: getStyle({'margin': '0 5px 0 0', 'max-width': '16px', 'max-height': '16px', 'background': 'none', 'float': 'left', 'display': 'none'})}));

            var content = body.appendChild(createElement('div', {style: getStyle()}));
            var title = content.appendChild(createElement('div', {html: sticker_info.activity.site, style: getStyle({'color': '#000', 'font-weight': 'bold'})}));
            if (sticker_info.activity.comm) {
                title.appendChild(createElement('img', {src: sidebar_info.sb_url + '/images/comment.png', style: getStyle({'margin': '0 0 0 5px', 'background': 'none', 'float': 'right'})}));
            }
            if (sticker_info.activity.asts) {
                title.appendChild(createElement('img', {src: sidebar_info.sb_url + '/images/asset.png', style: getStyle({'margin': '0 0 0 5px', 'background': 'none', 'float': 'right'})}));
            }
            if (sticker_info.activity.title) {
                content.appendChild(createElement('div', {html: sticker_info.activity.title, style: getStyle({'color': '#1F60A5'})}));
            }
            content.appendChild(createElement('div', {text: 'last update', style: getStyle({'color': '#000', 'font-size': '9px'})}));
            
            listen(favicon, 'load', function(e){
                (e.target || e.srcElement).style.display = "block";
                content.style.margin = "0 0 0 21px";
            });
        }

        var footer = panel.appendChild(createElement('div', {style: getStyle()}));
        footer.appendChild(createElement('div', {text: sticker_info.count, style: getStyle({'margin': '0 5px', 'font-weight': 'bold', 'color': '#1F60A5', 'float': 'left', 'font-size': '14px'})}));
        footer.appendChild(createElement('div', {text: 'connected sites', style: getStyle({'line-height': '17px', 'font-weight': 'bold', 'color': '#1F60A5', 'float': 'left'})}));
        footer.appendChild(createElement('div', {text: 'see all', style: getStyle({'margin': '0 5px', 'line-height': '17px', 'font-weight': 'normal', 'color': '#1F60A5', 'float': 'right'})}));
         
        return panel;
    };    
    
    function log(sidebar_info, time, token){
        ready(function(){
            loadImage(sidebar_info.svc_url + '/widget/api/log?r=' + encodeURIComponent(document.referrer) + '&u=' + encodeURIComponent(document.URL) + "&rid=" + sidebar_info.rid + "&pid=" + sidebar_info.pid + "&t=" + time + "&l=" + token);
        });
    };
    
    var style = (typeof sticker_style == 'string') ? sticker_style : 'full';
    var color = (typeof sticker_color == 'string') ? sticker_color : '#AACCEE';
    var image = (typeof sticker_image == 'string') ? sticker_image : ('http://widget.river.li/images/' + ((style == 'image' || style == 'small' || style == 'medium') ? 'splat-small.png' : 'splat.png'));

    
        stickerShow({"sb_url": "http://widget.river.li", "show": false, "rid": "5iy", "svc_url": "http://river.li", "pid": "3SvA"}, {"title": "ASAMCO", "activity": {"comm": false, "title": "ASAMCO.CH - Association ", "asts": false, "site": "asamco.ch", "favicon": "http://www.asamco.ch/favicon.ico"}, "count": 1});
    
    
    sticker_style = null;
    sticker_color = null;
    sticker_image = null;
}());

