// v1.0

SmallRiversInitializer = (typeof SmallRiversInitializer != 'undefined') ?  SmallRiversInitializer : function(){

    // Everything that has to do with properly supporting our document ready event. Brought over from the most awesome jQuery. 

    var userAgent = navigator.userAgent.toLowerCase();

    // Figure out what browser is being used
    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 = [];

    // 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 = [];
            }
        }
    };

    // From Simon Willison. 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 createElement(e, attrs) {
        var el = document.createElement(e);
        for (var k in attrs) {
            if (k == "text") {
                el.appendChild(document.createTextNode(attrs[k]));
            }
            else {
                setAttribute(el, k, attrs[k]);
            }
        }
        return el;
    };

    function setAttribute(e, k, v) {
        if (k == "class") {
            e.setAttribute("className", v); // set both "class" and "className"
        }
        return e.setAttribute(k, v);
    };
        
    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 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 getElementsByClass(searchClass,node,tag) {
        var classElements = new Array();
        if ( node == null )
            node = document;
        if ( tag == null )
            tag = '*';
        var els = node.getElementsByTagName(tag);
        var elsLen = els.length;
        var pattern = new RegExp('(^|\\\\s)'+searchClass+'(\\\\s|$)');
        for (i = 0, j = 0; i < elsLen; i++) {
            if ( pattern.test(els[i].className) ) {
                classElements[j] = els[i];
                j++;
            }
        }
        return classElements;
    };
    
    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;
    }    
    
    bindReady();
    
    return {
        init: function(base_url, rid, pid, serviceUrl){
            ready(function(){
                var clazz = "smallrivers_" + rid;
                if (pid != '-'){
                    clazz += "_" + pid;
                }
                var elements = getElementsByClass(clazz, null, 'a');
                for (i = 0; i < elements.length; i++) {
                    listen(elements[i], 'click', function(e){
                        SmallRiversInitializer.open(base_url, rid, pid, serviceUrl);
                        stopEvent(e);
                    });
                }
            });
        },
        
        open: function(base_url, rid, pid, serviceUrl){
            ready(function(){
                window.sr_data = {pid: pid, rid: rid, url: base_url, surl: serviceUrl};
                loadCss(base_url + '/stylesheets/sidebar.css');
                loadScript(base_url + '/javascripts/sidebar.js?v=2.0.4');
            });
        },
        
        log: function(base_url, rid, pid, time, token){
            ready(function(){
                loadImage(base_url + '/widget/api/log?r=' + encodeURIComponent(document.referrer) + '&u=' + encodeURIComponent(document.URL) + "&rid=" + rid + "&pid=" + pid + "&t=" + time + "&l=" + token);
            });
        }
    }
}();

SmallRiversInitializer.init('http://river.smallrivers.com', 'KD', 'W7e', 'http://www.smallrivers.com');
SmallRiversInitializer.log('http://www.smallrivers.com', 'KD', 'W7e', '1268203676.92551', '0481241ba85b7b0e4654e560438540d80846d61a');

