(function(window, document){
    "use strict";
    if(typeof window.workface_resource_loader == 'undefined'){
(function(window,document){
        "use strict";
		window.workface_resource_loader = {
			stylesheets : [],
            scripts : [],
			css_onloads : [],
            css_tests : {
                'font-family': 'fontFamily'
                //TODO: add more css-to-js conversion vals in here for additional style tests we want/need to support
            },
			
            //load_js function takes six arguments:
            //  url:    absolute path of javascritp file to load
            //  load_if_exists: boolean, load even if the script has already been loaded w/ the resource loader
            //  onload_funct: false if no need for onload funcitonality, else valid callback function
            //  onload_data: data to be passed into onload_funct
            //  conditional_load_funct: false if no need to check, else a function that returns boolean to determine if the script should be loaded or not
            //  onload_cb_if_noload:    boolean, if a conditional load funct is provided and returns false, should we call the onload anyway (if one is provided)
            load_js : function(url, load_if_exists, onload_funct, onload_data, conditional_load_funct, onload_cb_if_noload ){
                var found = false;
                if(!load_if_exists){
                    for(var i=0,l=this.scripts.length; i<l; i++){
                        if( url==this.scripts[i] ){
                            found = true; break;
                        }
                    }
                }
                if( found && !onload_cb_if_noload) return;
                
                var load_script = true;
                if( conditional_load_funct !== false && typeof conditional_load_funct == 'function'){
                    load_script = conditional_load_funct();
                    if(!load_script && !onload_cb_if_noload) return;
                }
                if(!found && load_script){
                    this.scripts.push(url);
                    var s = document.createElement('script');
                    s.src = url;
                    s.async = true;
                    s.type = 'text/javascript';
                    if(onload_funct !== false && typeof onload_funct == 'function'){
                        var this_script_onload = function(){ onload_funct( onload_data ) };
                        if(s.readyState){ //IE
                            s.onreadystatechange = function(){
                                if(s.readyState=='loaded' || s.readyState=='complete'){
                                    s.onreadystatechange=null;
                                    this_script_onload();
                                }
                            };
                        }else{
                            s.onload = this_script_onload;
                        }
                    }
                    document.getElementsByTagName('HEAD')[0].appendChild(s);
                }else if(onload_funct !== false && typeof onload_funct == 'function'){
                    onload_funct( onload_data );
                }
            },
            
			//load_css function takes two arguments:
			//	url: absolute path of css file to load
			//	onload_params: false if no need to wait for onload functionality, else an object with ALL of the following:
			//		className:	'class name for span you have defined a testable style for in the stylesheet (example: "test_stylesheet_ready") ',
			//		testStyle:	'css style you want to test a value for (example: "font-family") ',
			//		testValue:	'expected css value that will only be present for span w/ class name on style when stylesheet is loaded (example: "css_is_ready") ',
			//		cb_data:	{data obj passed to callback function, any properties/values you need}, 
			//		cb:			callback_function for when stylesheet is loaded and ready
			load_css : function(url, onload_params){
				//see if the stylesheet has already been included (EXACT url match)
				var found = false;
				for(var i=0,l=this.stylesheets.length; i<l; i++){	
					if( url==this.stylesheets[i]){
						found = true; break;
					}
				}
				if(!found){
					if (document.createStyleSheet){ //IE specific
						document.createStyleSheet(url);
					}else{
						var link = document.createElement('link');
						link.rel = 'stylesheet';
						link.type = 'text/css';
						link.href = url;
						document.getElementsByTagName('body')[0].appendChild(link); //put at bottom of body so page rules that overlap cascalde correctly
					}
					this.stylesheets.push(url);
				}
				if(onload_params !== false){
					this.css_onloads.push(onload_params); //TODO, NOTE: assumes all onload_params are valid and present - check for this?
					this.is_stylesheet_loaded(this.css_onloads.length-1);
				}
			},
            
            //determine if stylesheet is loaded and ready by creating span element w/ specified test class and checking for matched of computed style of test style vs test value
			is_stylesheet_loaded : function(onloads_ind) {
				var opts = workface_resource_loader.css_onloads[onloads_ind];
				var testElem = document.createElement('span');
				testElem.className = opts.className;
				document.getElementsByTagName('body')[0].appendChild(testElem);
                var style_val = workface_resource_loader.get_specific_style_of_elem( testElem, opts.testStyle );
                (typeof style_val != 'undefined' && style_val === opts.testValue) ? opts.cb(opts.cb_data) : setTimeout("window.workface_resource_loader.is_stylesheet_loaded("+onloads_ind+");", 500) ;
				document.getElementsByTagName('body')[0].removeChild(testElem); //cleanup
			},
            
            get_specific_style_of_elem : function( elem, get_style ){
                if(window.getComputedStyle) {   //standards-compliant method
					var value = document.defaultView.getComputedStyle(elem, null).getPropertyValue( get_style );
				}else if(elem.currentStyle){ //IE < 9 specific
                    if( typeof workface_resource_loader.css_tests[get_style] != 'undefined' && workface_resource_loader.css_tests[get_style]  != null){
                        get_style = workface_resource_loader.css_tests[get_style];
                    }
                    var value = elem.currentStyle[ get_style ];
                }
                return value;
            },
            
            //cross-browser dom ready funciton, args are window obj ref and cb function
            DOMready : function(win, fn) {
                var done = false, top = true,
                doc = win.document, root = doc.documentElement,
                add = doc.addEventListener ? 'addEventListener' : 'attachEvent',
                rem = doc.addEventListener ? 'removeEventListener' : 'detachEvent',
                pre = doc.addEventListener ? '' : 'on',
                init = function(e) {
                    if (e.type == 'readystatechange' && doc.readyState != 'complete') return;
                    (e.type == 'load' ? win : doc)[rem](pre + e.type, init, false);
                    if (!done && (done = true)) fn.call(win, e.type || e);
                },
                poll = function() {
                    try { root.doScroll('left'); } catch(e) { setTimeout(poll, 50); return; }
                    init('poll');
                };
                if (doc.readyState == 'complete') fn.call(win, 'lazy');
                else {
                    if (doc.createEventObject && root.doScroll) {
                        try { top = !win.frameElement; } catch(e) { }
                        if (top) poll();
                    }
                    doc[add](pre + 'DOMContentLoaded', init, false);
                    doc[add](pre + 'readystatechange', init, false);
                    win[add](pre + 'load', init, false);
                }

            }
		};
})(window,document);
}    
    if(typeof window.wf_inpage_links == 'undefined'){
        
        window.wf_inpage_links = {
            a_elems : [],                                           //CURRENT in-page anchor elems that are shown
            a_class : 'workface-user-conn-anchor',                  //class applied to anchor tags we change to buttons
            protocol :  'http:',                                    //current protocol being used
            css_path :  'workface.com/inpage/css/inpage_links.css?lastmod=1327584498', //path to needed css file for buttons
            stati_path: 'workface.com/services/status_updater.js?lastmod=1329158669',  //path to needed resource loader js file
            offline_c:  'wf_inpage_status_div_ind',                 //class applied to buttons when user is offline
            online_c :  'wf_inpage_status_div_ind_online',          //class applied to buttons when user is online
            active_rel : 'workface_external_connect',               //rel attribute applied to anchors already drawn & bound
            status_namespace : 'inpage_button_links',               //namespace to use for all status updater indicators / callback subscriptions
            resources_needed : 2,                                   //num resources (css/js) needed for callback to fire start event
            
            //initial setup function, called on DOM ready
            setup : function(){
                if( window.location.protocol === 'https:' ) wf_inpage_links.protocol = 'https:';
                wf_inpage_links.get_inpage_elems();
                if(wf_inpage_links.a_elems.length==0) return;
                wf_inpage_links.get_resources_before_drawing();
            },
            
            //load required stylesheet and JS then when it's ready & active proceed to draw elems
            get_resources_before_drawing: function(){
                if( wf_inpage_links.resources_needed==0 ) return wf_inpage_links.init_button_creation();
                workface_resource_loader.load_css(
                    this.protocol+'//'+this.css_path, {   className: 'workface-inpagea-css-ready', testStyle: 'font-family', testValue: "wf-inpagea-cssready", cb_data:null, cb: window.wf_inpage_links.resource_loaded}
                );
                workface_resource_loader.load_js(
                    this.protocol+'//'+this.stati_path,
                    false,
                    window.wf_inpage_links.resource_loaded,
                    null,
                    function(){ return ('workface_stati_upd' in window) ? false : true; },
                    true
                );
            },
            
            //re-check the page for any new anchor elems & buttons that need drawing & refresh the status indicators listeners
            //should be called anytime page content changes and page needs to be be checked for new user connect links
            update : function(){
                wf_inpage_links.a_elems = []; //clear elem cache
                workface_stati_upd.remove_indicators_for_namespace( wf_inpage_links.status_namespace ); //remove all indicators (NOTE: some may still be present but that's ok, they'll get picked up again)
                wf_inpage_links.get_inpage_elems(); //refresh elem cache from current page content
                if(wf_inpage_links.a_elems.length==0) return;
                wf_inpage_links.get_resources_before_drawing();
            },
            
            draw_and_subscribe_anchor_button : function( node, udomain ){
                //check if this anchor's button already drawn & status set - if so leave as is so we don't see the momenary 'offline' status as elems are redrawn & subscribed as status indicators
                if( node.rel !== wf_inpage_links.active_rel ){
                    var h = '<div class="wf_inpage_status_div_ind"></div>';
                    var d = document.createElement('div');
                    d.className = wf_inpage_links.offline_c;
                    node.innerHTML = '';
                    node.appendChild(d);
                    node.rel = wf_inpage_links.active_rel;
                    node.href = node.href+(node.href.indexOf('?')!==-1 ? '&' : '?')+'f=1'; //append incoming tracking ref
                }
                
                //subscribe this user to the status updater (w/ inpage link namespace & no callback)
                workface_stati_upd.add_indicator({ 
                      type: 'inpage_link',
                      user: udomain,
                      namespace: wf_inpage_links.status_namespace,
                      cb_data: null,
                      cb: false
                });
            },
            
            //css is ready CB
            resource_loaded: function(d){
                wf_inpage_links.resources_needed--;
                if( wf_inpage_links.resources_needed == 0 ) wf_inpage_links.wait_for_statm();
            },
            
            wait_for_statm : function(){
                if( 'workface_stati_upd' in window ) return wf_inpage_links.init_button_creation();
                setTimeout( wf_inpage_links.wait_for_statm, 100 );
            },
            
            init_button_creation : function(){
                //change all anchors to images
                for(var i=0,l=wf_inpage_links.a_elems.length; i<l; i++){
                    //update div content (if not already done)
                    wf_inpage_links.draw_and_subscribe_anchor_button(
                        wf_inpage_links.a_elems[i]['node'],
                        wf_inpage_links.a_elems[i]['user']
                    );
                }
                //now setup the global listener
                workface_stati_upd.subscribe_to_digest_cb( wf_inpage_links.update_statuses, wf_inpage_links.status_namespace );
                workface_stati_upd.check_now();
            },
    
            update_statuses : function( info ){
                for(var i=0,l=wf_inpage_links.a_elems.length; i<l; i++){
                    var e = wf_inpage_links.a_elems[i];
                    if( (e['user'] in info)===false ) continue;
                    var d = e['node'].children[0]; //div elem
                    d.className = info[e['user']] ? wf_inpage_links.online_c : wf_inpage_links.offline_c;
                }
            },
    
            get_inpage_elems : function(){
                if( typeof document.getElementsByClassName == 'function'){
                    var els =  document.getElementsByClassName( wf_inpage_links.a_class );
                }else{
                    var els = [],
                        all = document.getElementsByTagName('*'),
                        pattern = new RegExp("(^|\\s)"+wf_inpage_links.a_class+"(\\s|$)");
                    for( var i=0,l=all.length; i<l; i++){
                        if( pattern.test( all[i].className ) ) els.push( all[i] );
                    }
                }
                for(var j=0,l=els.length; j<l; j++){
                    if(els[j].tagName.toUpperCase()!='A') return; //NOT an anchor tag!
                    wf_inpage_links.a_elems.push( {'node':els[j],'user':els[j].href.split('/').pop().split('?')[0]} );
                    if(typeof els[j].title == 'undefined' || els[j].title == null || els[j].title== '' ) els[j].title='Connect with me!';
                    els[j].target = '_blank';
                }
            }
    
        };
        workface_resource_loader.DOMready( window, function(){ wf_inpage_links.setup(); } );
    }
    
})(window,document);
