SmallRivers = (typeof SmallRivers == 'undefined') ? {count: 0} : SmallRivers;
(function() {

	var baseURL = getLoadURL();
	var serviceUrl = baseURL.replace('river', 'dashboard');
	var elementId = getRandomId();

	var CDN_URLS = ['http://assets0.smallrivers.net', 'http://assets1.smallrivers.net'];
	
	var stylesheets = [
		{css: 'ui.core.css', cdn: true},
		{css: 'ui.accordion.css', cdn: true},
		{css: 'ui.datepicker.css', cdn: true},
		{css: 'ui.dialog.css', cdn: true},
		{css: 'ui.slider.css', cdn: true},
		{css: 'ui.timepicker.css', cdn: true},
		{css: 'ui.theme.css', cdn: true},
		{css: 'default.css', cdn: false}
	];
	
	var libraries = [
		{js: 'jquery-1.3.1.js', cdn: true, min: true},
		{js: 'jquery-ext.js', cdn: true},
		{js: 'ui.core.js', cdn: true, min: true},
		{js: 'ui.datepicker.js', cdn: true, min: true},
		{js: 'i18n/ui.datepicker-en.js', cdn: true},
		{js: 'ui.dialog.js', cdn: true, min: true},
		{js: 'ui.dialog-ext.js', cdn: true},
		{js: 'ui.slider.js', cdn: true, min: true},
		{js: 'ui.bubble.js', cdn: true, min: true},
		{js: 'ui.timepicker.js', cdn: true, min: true},
		{js: 'effects.core.js', cdn: true, min: true},
		{js: 'effects.slide.js', cdn: true, min: true},
		{js: 'http://cdn.clearspring.com/launchpad/v2/standalone.js', ext: true},
		{js: 'sm.clearspring.js', cdn: true},
//		{js: 'http://cdn.gigya.com/wildfire/js/wfapiv2.js', ext: true},
//		{js: 'sm.gigya.js', cdn: true},
		{js: 'jquery.bgiframe.js', cdn: true, min: true},
		{js: 'jquery.cookie.js', cdn: true, min: true},
		{js: 'jquery.flip.js', cdn: true, min: true},
		{js: 'jquery.validate.js', cdn: true, min: true},
		{js: 'jquery.form.js', cdn: true, min: true},
		{js: 'jquery.maskedinput.js', cdn: true, min: true},
		{js: 'jquery.maxlength.js', cdn: true, min: true},
		{js: 'jquery.mousewheel.js', cdn: true, min: true},
		{js: 'jquery.timers.js', cdn: true, min: true},
		{js: 'jquery.highlight-3.js', cdn: true, min: true},
//		{js: 'jquery.liscroll.js', cdn: false, min: false},
		{js: 'widget.js'},
		{js: 'i18n/widget-' + getLang() + '.js'},
		{js: 'jquery.noconflict.js', cdn: true}
	];
	
	
	function generateTemplate(index) {
		var pid = getParamValue(index, 'pid');
		var type = getParamValue(index, 'type');
		
		var template = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\
			<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">\
			  <head>\
				<style>body {background: none transparent; padding: 0; margin: 0; border: 0;}</style>\
				<script>\
					var SmallRivers = SmallRivers ? SmallRivers : {};\
					SmallRivers._options = {\
						serviceUrl: "' + serviceUrl + '",\
						placements: [{\
							pid: "' + pid + '",\
							type: "' + type + '",\
							target: "widget"}]\
					};\
				</script>';
		
		// initailze styles
		for (var i = 0; i < stylesheets.length; i++){
			var url = stylesheets[i].css;
			if (stylesheets[i].cdn){
				url = CDN_URLS[i % CDN_URLS.length] + '/stylesheets/' + url;
			}
			else {
				url = baseURL + '/stylesheets/' + url;
			}
			template += '<link href="' + url + '" media="all" rel="Stylesheet" type="text/css"/>\n';
		}
		
		// initialize javascripts
		for (var i = 0; i < libraries.length; i++){
			var src = libraries[i].js;
			if (!libraries[i].ext){
				if (libraries[i].min){
					src = 'minified/' + src.replace(/js$/, 'min.js');
				}
				if (libraries[i].cdn){
					src = CDN_URLS[i % CDN_URLS.length] + '/javascripts/' + src;
				}
				else {
					src = baseURL + '/javascripts/' + src;
				}
			}
			template += '<script type="text/javascript" src="' + src + '"></script>\n';
		}
		
		// finalize template
		template += '</head>\
				<body><div id="widget"></div></body>\
			</html>';
		return template;
	}

	function getLoadURL() {
		var scripts = document.getElementsByTagName('script');
		for (var i = 0; i < scripts.length; i++) {
			var src = scripts[i].src
			if (src) {
				var url = src.match(/^(http:\/\/[^\/]+(\/[^\/]+)*)\/javascripts\/loader.js/i);
				if (url) {
					return url[1];
				}
			}
		}
		return '';
	}
	
	function getParamValue(index, name) {
		var scripts = document.getElementsByTagName('script');
		var loaderUrl = 0;
		for (var i = 0; i < scripts.length; i++) {
			var src = scripts[i].src
			if (src) {
				var url = src.match(/^(http:\/\/[^\/]+)(\/[^\/]+)*\/loader.js\?/i);
				if (url) {
					if (loaderUrl == index) {
						url = src.match(new RegExp(name + '=([a-z0-9]+)', 'i'));
						if (url) {
							return url[1];
						}
						else {
							return null;
						}
						
					}
					loaderUrl++;
				}
			}
		}
		return '';
	}
	
	function getLang() {
		var lang = (navigator.language ? navigator.language /* Mozilla */ : navigator.userLanguage /* IE */);
		if (lang.length > 2) 
			lang = lang.substring(0, 2);
		
		return lang.toLowerCase();
	}
	
	function getRandomId() {
		return 'player_' + Math.floor(Math.random() * Math.pow(10, 8));
	}
	
	function isMozilla(){
		var userAgent = navigator.userAgent.toLowerCase();
		return /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
	}
	
	function createIframe(id, source) {
		var iframe = document.createElement("iframe");
		iframe.width = "425";
		iframe.height = "370";
		iframe.style.border = "none";
		iframe.style.overflow = "hidden";
		iframe.style.margin = "0px auto";
		iframe.style.background = "transparent url(" + CDN_URLS[0] + "/images/spinner-big.gif) no-repeat scroll center center";
		iframe.scrolling = "no";
		iframe.frameBorder = "0";
		iframe.allowTransparency = "true"

		document.getElementById(id).appendChild(iframe);
		// attach to load event so we clear the spinner image
		addEvent(iframe, 'load', function(){
			iframe.style.background = "transparent none";
		});

		var doc = iframe.contentDocument || iframe.contentWindow.document;
		doc.open();
		doc.write(source);
		doc.close();
		
		 // workaround for FF and clearspring
		if (isMozilla()){
				var oldwrite = doc.write;
				doc.write = function(str){
				if (str.match('http://widgets.clearspring.com')){
					doc.write = oldwrite;
				}
				else {
					oldwrite(str);
				}
			};
		}
		// end
		
		// workaround for scribd full size (not working in IE and Opera)
		var resize = function(){
			if (iframe.style.position == 'fixed'){
				iframe.width = '425';
				iframe.height = '370';
				iframe.style.position = 'relative';
				iframe.style.zIndex = null;
				iframe.style.top = null;
				iframe.style.left = null;
			}
			else {
				iframe.width = '100%';
				iframe.height = '100%';
				iframe.style.position = 'fixed';
				iframe.style.zIndex = 10001;
				iframe.style.top = 0;
				iframe.style.left = 0;
			}
		}
		addEvent(doc, 'fullscreenChanged', resize);
		// end
	}
	

	function addEvent(obj, type, fn) {
		if (obj.attachEvent) {
			obj['e' + type + fn] = fn;
			obj[type + fn] = function() {
				obj['e' + type + fn](window.event);
			}
			obj.attachEvent('on' + type, obj[type + fn]);
		}
		else {
			obj.addEventListener(type, fn, false);
		}
	}
	
	function removeEvent(obj, type, fn) {
		if (obj.detachEvent) {
			obj.detachEvent('on' + type, obj[type + fn]);
			obj[type + fn] = null;
		}
		else {
			obj.removeEventListener(type, fn, false);
		}
	}
	
	// let's build the widget
	document.write('<div id="' + elementId + '"></div>'); // iframe wrapper
	createIframe(elementId, generateTemplate(SmallRivers.count));
	SmallRivers.count += 1; // widgets counter
})();
