//helper function to load css and js resources from https://github.com/rgrove/lazyload
LazyLoad=function(){var f=document,g,b={},e={css:[],js:[]},a;function j(l,k){var m=f.createElement(l),d;for(d in k){if(k.hasOwnProperty(d)){m.setAttribute(d,k[d])}}return m}function h(d){var l=b[d];if(!l){return}var m=l.callback,k=l.urls;k.shift();if(!k.length){if(m){m.call(l.scope||window,l.obj)}b[d]=null;if(e[d].length){i(d)}}}function c(){if(a){return}var k=navigator.userAgent,l=parseFloat,d;a={gecko:0,ie:0,opera:0,webkit:0};d=k.match(/AppleWebKit\/(\S*)/);if(d&&d[1]){a.webkit=l(d[1])}else{d=k.match(/MSIE\s([^;]*)/);if(d&&d[1]){a.ie=l(d[1])}else{if((/Gecko\/(\S*)/).test(k)){a.gecko=1;d=k.match(/rv:([^\s\)]*)/);if(d&&d[1]){a.gecko=l(d[1])}}else{if(d=k.match(/Opera\/(\S*)/)){a.opera=l(d[1])}}}}}function i(r,q,s,m,t){var n,o,l,k,d;c();if(q){q=q.constructor===Array?q:[q];if(r==="css"||a.gecko||a.opera){e[r].push({urls:[].concat(q),callback:s,obj:m,scope:t})}else{for(n=0,o=q.length;n<o;++n){e[r].push({urls:[q[n]],callback:n===o-1?s:null,obj:m,scope:t})}}}if(b[r]||!(k=b[r]=e[r].shift())){return}g=g||f.getElementsByTagName("head")[0];q=k.urls;for(n=0,o=q.length;n<o;++n){d=q[n];if(r==="css"){l=j("link",{href:d,rel:"stylesheet",type:"text/css"})}else{l=j("script",{src:d})}if(a.ie){l.onreadystatechange=function(){var p=this.readyState;if(p==="loaded"||p==="complete"){this.onreadystatechange=null;h(r)}}}else{if(r==="css"&&(a.gecko||a.webkit)){setTimeout(function(){h(r)},50*o)}else{l.onload=l.onerror=function(){h(r)}}}g.appendChild(l)}}return{css:function(l,m,k,d){i("css",l,m,k,d)},js:function(l,m,k,d){i("js",l,m,k,d)}}}();

//get the domain from the script src value
var scripts = document.getElementsByTagName('script'),
	len = scripts.length,
	re = /bar\.js$/,
	src, barSrc;
while (len--) {
	src = scripts[len].src;
	if (src && src.match(re)) {
		barSrc = src;
		var domain = barSrc.match(new RegExp('https?://[^/]*'));
		break;
	}
}

load_init();
//break out of iframes to prevent double bar (embed + promotion iframe)
function load_init(){
	if (top.location != location) {
		top.location.href = document.location.href;
	}
	else {
		//build the bar url

		//if on /demo/
		if (typeof rf_demo_url != "undefined") {
			html_url = "/bar?" + "demo_url=" + rf_demo_url + "&" + rf_demo_url_query_string;
		}
		else {

			//if we have a campaign
			if (typeof rf_campaign_id != "undefined") {
				html_url = domain + "/bar?campaign_id=" + rf_campaign_id;
			} else {
				html_url = domain + "/bar";
			}

			//if using hosted version of the bar
			if (typeof bar_hosted != "undefined") {
				html_url = html_url + "&hosted=true";
			}
			
			//if on the manage page
			if (typeof rf_manage != "undefined") {
				html_url = html_url + "&manage=true";
			} 
			
			//if a share hash exists
			if (location.search.indexOf('rf_shash')>=0) {
				html_url = html_url + "&rf_shash=true";
			}
			
		}

		//load the bar css
		LazyLoad.css(domain+"/_share/css/bar.css");
			
		//load jQuery if needed
		if (typeof jQuery == 'undefined' || jQuery.fn.jquery != '1.4.2') {
			LazyLoad.js("http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js", function () {
				
				//avoid conflicts with other javascript libraries
				jQuery.noConflict();
				
				load_step_2();
			});
		} else {load_step_2();}	
	}
}

//load jQuery tools if needed
function load_step_2(){

	if (typeof jQuery.tools == 'undefined' || jQuery.tools.version != "1.2.5") {
		LazyLoad.js("http://cdn.jquerytools.org/1.2.5/all/jquery.tools.min.js", function () {
			load_bar();
		});
	} else {load_bar();}
}

//do the actual request to fill the bar
function load_bar() {
	LazyLoad.js(html_url, function () {
		jQuery(document).ready(function() {
			//set the promo text if on the manage page
			try{$('.rf-promo').html(getPromoText())} catch(e){}
			
			//load bar.hosted.js if using hosted version of the bar
			if (typeof bar_hosted != "undefined") {
				LazyLoad.js(domain+"/_share/js/bar.hosted.js");
			}
		
			//load tooltip if needed
			if (jQuery("#rf-tooltip").length) {
				//get the tooltip on the page if one exists and remove it
				var text = jQuery("#rf-tooltip").html();
				jQuery("#rf-tooltip").detach();
				
				//insert a new tooltip in the right place
				var html_insert = "<div class='tooltip'>" + text +"</div>"
				jQuery("#rf-bar").after(html_insert);
				
				//activate the tooltip
				jQuery("#rf-bar").tooltip({ position: "bottom right", relative: true, offset: [0, -250], effect: "slide", api: true}).show();
			}
			
			//facebook & twitter user authentication
			network_login('facebook');
			network_login('twitter');

			function network_login(network){
				jQuery("."+network+'-login').click(function(){
					if (network == 'facebook') {
						var url = "https://graph.facebook.com/oauth/authorize?client_id=" + facebook_api + "&redirect_uri=" + redirect_uri + "&display=popup&scope=publish_stream"; }
					else if (network == 'twitter') {
						var url = tauth_login_url + "?popup=true"; }
					signin_window = window.open(url, "SignIn", "width=780,height=410");
					//check in 1 second to see if the sign in window is closed
					setTimeout(function(){check_login_status(network)}, 1000);
					try{signin_window.focus();}catch(e){}
					return false;
				});
			}

			function check_login_status(network) {
				if (signin_window.closed) {
					current_network = network;
					if (network == 'facebook') {
						var check_url = domain+"/facebook_check_logged_in/"; }
					else if (network == 'twitter') {
						var check_url = domain+"/twitter_check_logged_in/"; }
					//jsonp call to see if the user is logged in
					jQuery.getJSON(check_url+"?callback=?");
				}
				else {
					//check every 0.5 seconds to see if the sign in window is closed
					setTimeout(function(){check_login_status(network)}, 500);
				}
			}

			//iframe for use inside the overlays
			var theframe = jQuery('<iframe id="rf-iframe" frameborder="0" scrolling="no"></iframe>');
			
			//setup the share overlays
			setup_overlay('facebook');
			setup_overlay('twitter');

			function setup_overlay(network){
				jQuery("#rf-overlay-holder-"+network).overlay({
					mask: {
						color: '#fff',
						loadSpeed: 200,
						opacity: 0.5
					},
					closeOnClick: false,
					onBeforeLoad: function() {
						var wrap = this.getOverlay().find(".rf-contentWrap");
						var url = domain+"/overlay?type="+network+"&parent=" + escape(location.href);
						if (typeof rf_campaign_id != "undefined")  {
							url = url + "&id=" + rf_campaign_id;
						}
						jQuery(theframe).attr({ src: url, style: 'width:500px; height:155px;' });
						wrap.html(theframe);
					}
				});
			}
			
		});
		
	});
}

//callback from jsonp call
function auth_callback(values){
	if (values["status"] == "1") {
		//open the corresponding overlay when the user has authenticated
		jQuery("#rf-overlay-holder-"+current_network).data("overlay").load();                       
	}
	else {return false;}
}
