function change_getLeft(Elem)
{
	obj = document.getElementById(Elem);
	var posLeft = 0;
	while (obj.offsetParent) {posLeft += obj.offsetLeft; obj = obj.offsetParent;}
	return posLeft;
}

function change_getTop(Elem)
{
	obj = document.getElementById(Elem);
	var posTop = 0;
	while (obj.offsetParent) {posTop += obj.offsetTop; obj = obj.offsetParent;}
	return posTop;
}

var _adContainer;
var _loadingContainer;
var _flashContainer;
var _flash;
var _bottomBar;
var _roundedBar;
var _poweredLink;
var _grabLink;
var _startLink;
var _petitionsUrl = 'http://www.change.org/petitions';
var _startUrl = 'http://www.change.org/petition';
var _flashObject;
var _swfFile = 'SinglePetition.swf';
var _baseUrl = 'http://www.change.org/widget_flash/SinglePetition/';
var _imageUrl = _baseUrl + 'images/';
var _embedFile = _baseUrl + 'change_embed.js';
var _partner_id = '-1';
var _widgetId = null;
var _hidden = null;
var _align = '';
var _expanded = false;
var _color = '#1A3563';
var _cornerRadius = 5;
var _linkBar;
var _minZindex = '1';
var _maxZindex = '100';

if(document.getElementById('change_temp')) { var temp = document.getElementById('change_temp');  temp.parentNode.removeChild(temp); }
document.write("<link rel='stylesheet' type='text/css' href='" + _baseUrl + "change_style.css'/><script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js'></script><script type='text/javascript' src='"+_baseUrl+"DD_roundies.js'></script>");

var _adWidth;
var _adHeight = '250';

//SETUP
function configure_widget(paramName, value)
{
	eval("_" + paramName + " = '" + value.replace(/'/, "\\\'") + "'");
}
function change_setup(adWidth, petitionId, color, partner_id)
{
	//assign vars
	_widgetId = Math.floor(Math.random()*1001);
	if(adWidth > 300) adWidth = 300;
	if(adWidth < 150) adWidth = 150;
	_adWidth = adWidth;
	_petitionId = petitionId;
	
	if(color && color != '-1') _color = color;
	if(partner_id) {
	  if(typeof(partner_id) != 'string') partner_id += '';
	  if(partner_id != '-1') _partner_id = partner_id;
	} 
	
	_adContainer = document.getElementById('change_AdContainer');
	if(_adContainer == null) {
	  document.write("<div id='change_AdContainer'></div>");
	  _adContainer = document.getElementById('change_AdContainer');
	}
	_adContainer.style.width = _adWidth + 'px';
	_adContainer.style.height = _adHeight + 'px';
	
	//wait for domReady
	ChangeDomReady.ready(function(){change_init();});
}

//On DomReady
function change_init()
{
	//Add html structure
	////Flash Container
	_flashContainer = document.createElement('div');
	_flashContainer.setAttribute('id', 'change_FlashContainer');
	_flashContainer.style.width = _adWidth + 'px';
	_flashContainer.style.height = (_adHeight - 22) + 'px';
	_flashContainer.style.display = 'block';
	_flashContainer.style.top = '-100000px';
	if(_minZindex != '1') {_flashContainer.style.zIndex = _minZindex;}

	document.body.appendChild(_flashContainer);

	////to be replaced by swfobject
	_flash = document.createElement('span');
	_flash.setAttribute('id', 'change_Flash'+_widgetId);
	_flashContainer.appendChild(_flash);
	
	/// display "Loading..." text before flash is placed on top
	_loadingContainer = document.createElement('div');
	_loadingContainer.setAttribute('id', 'change_Loading');
	_loadingContainer.style.height = (_adHeight - 22) + 'px';
	_adContainer.appendChild(_loadingContainer);

	// check if the Bottom Bar already exists, or needs to be created
	if(document.getElementById('change_BottomBar')) {
	  _bottomBar = document.getElementById('change_BottomBar');
	} else {
	  _bottomBar = document.createElement('div');
	  _bottomBar.setAttribute('id', 'change_BottomBar');
	}
	
	////Bottom Bar
	_bottomBar.style.background = _color;
	_bottomBar.style.display = 'block';
	_bottomBar.style.height = '22px';
	_bottomBar.style.width = _adWidth + 'px';
	_bottomBar.style.margin = '0px';
	_adContainer.appendChild(_bottomBar);
	DD_roundies.addRule('#change_BottomBar', '0 0 5px 5px', 'true');
	
	_startLink = document.getElementById('change_Start');
	if(!_startLink) {
	  ////Start Link
	  _startLink = document.createElement('span');
	  _startLink.setAttribute('id', 'change_Start');
	  if(_adWidth >= 220)
	    _startLink.innerHTML = 'Start a <a href="'+_startUrl+'" target="_blank">Petition</a> &raquo;';
	  else
	    _startLink.innerHTML = 'Start <a href="'+_startUrl+'" target="_blank">Petition</a>';
	  _bottomBar.appendChild(_startLink);
	}
	
	_poweredLink = document.getElementById('change_Powered');
	if(_adWidth >= 220 && !_poweredLink) {
	  ////Powered By Link
	  _poweredLink = document.createElement('span');
	  _poweredLink.setAttribute('id', 'change_Powered');
	  if(_adWidth >= 250)
	    _poweredLink.innerHTML = '<a href="' + _petitionsUrl + '" target="_blank">Petitions</a> by Change.org';
	  else if(_adWidth >= 220) {
	    _poweredLink.innerHTML = 'Change.org <a href="' + _petitionsUrl + '" target="_blank">Petitions</a>';
	  } else {
	  	_poweredLink.innerHTML = 'Change.org';
	  }
	  _bottomBar.insertBefore(_poweredLink, _startLink);
	  
	  ////Separator
	  var separator1 = document.createElement('a');
	  separator1.innerHTML = '|';
	  _bottomBar.insertBefore(separator1, _startLink);
	}
	
	_grabLink = document.getElementById('change_Grab');
	if(_adWidth >= 300 && !_grabLink) {
	  ////Grab Widget Link
	  _grabLink = document.createElement('span');
	  _grabLink.setAttribute('id', 'change_Grab');
	  _grabLink.innerHTML = '<a href="#" onclick="change_grab(); return false;">Get Widget</a>';
	  _bottomBar.insertBefore(_grabLink, _startLink);
	  
	  ////Separator
	  var separator2 = document.createElement('a');
	  separator2.innerHTML = '|';
	  _bottomBar.insertBefore(separator2, _startLink);
	}
	
	swfobject.embedSWF(_baseUrl + _swfFile, "change_Flash"+_widgetId, "100%", "100%", "9.0.0","", {adWidth:_adWidth, imageUrl:_imageUrl, embedFile:_embedFile, align:_align, partnerId:_partner_id, color:_color, petitionId:_petitionId}, {wmode:"transparent",AllowScriptAccess:"always"});
	
	ChangeDomReady.onLoad(initialWidgetPlacement);
}

function initialWidgetPlacement()
{
	if (_hidden != 'true' && _adContainer && _adContainer.clientHeight > 0) {
		_loadingContainer.style.background = "none";
		_loadingContainer.style.border = "none";
		positionFlashContainer();
	}
	
	//ON WINDOW RESIZE
	window.onresize = positionFlashContainer;
}

function positionFlashContainer()
{
	if (_adContainer && _adContainer.clientHeight > 0) {
		// changes to fix on any overflow / positions of the widget
		var change_top_elem = change_getTop('change_AdContainer');
		var change_left_elem = change_getLeft('change_AdContainer');
		var change_body_width = document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth || document.body && document.body.parentNode && document.body.parentNode.clientWidth || 0;
		
		_flashContainer = document.getElementById('change_FlashContainer');
		_flashContainer.style.top = change_top_elem + 'px';
		_flashContainer.style.right = (change_body_width - change_left_elem - _adWidth) + 'px';
		
		fn = 'check_align(' + change_left_elem + ', ' + change_body_width + ')';
		window.setTimeout(fn, 1000);
	}
}

function check_align(change_left_elem, change_body_width)
{
	var prev_align = _align;
	
	if(change_left_elem+_adWidth/2 < change_body_width/2) _align = 'left';
	else _align = 'right';
	
	var flashMovie = getFlashMovieObject('change_Flash'+_widgetId);
	flashMovie.setAlign(_align);
}

function change_grab()
{
	var flashMovie = getFlashMovieObject('change_Flash'+_widgetId);
	flashMovie.grabWidget();
}


function expandPanel()
{
	positionFlashContainer()
	
	_flashContainer.style.width = '600px';
	_flashContainer.style.height = '520px';
	_flashContainer.style.zIndex = _maxZindex;
	
	if(_align == 'left') {
		var change_left_elem = change_getLeft('change_AdContainer');
		var change_body_width = document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth || document.body && document.body.parentNode && document.body.parentNode.clientWidth || 0;
		_flashContainer.style.right = (change_body_width - change_left_elem - 600) + 'px';
	}
	
	_bottomBar.style.display = 'none';
	_expanded = true;
}

function collapsePanel()
{
	_bottomBar.style.display = 'block';
	_bottomBar.style.width = _adWidth + 'px';

	_flashContainer.style.width = _adWidth + 'px';
	_flashContainer.style.height = (_adHeight - 22) + 'px';
	_flashContainer.style.zIndex = _minZindex;
	_expanded = false;

	_adContainer.style.width = _adWidth + 'px';
	_adContainer.style.height = _adHeight + 'px';
	
	if(_align == 'left')
	{
		var change_left_elem = change_getLeft('change_AdContainer');
		var change_body_width = document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth || document.body && document.body.parentNode && document.body.parentNode.clientWidth || 0;
		_flashContainer.style.right = (change_body_width-change_left_elem-_adWidth) + 'px';
	}
	
	positionFlashContainer();
}

function change_hostDomain()
{
	return document.domain;
}

function getFlashMovieObject(movieName)
{
	if (window.document[movieName])
	{
		return window.document[movieName];
	}
	if (navigator.appName.indexOf("Microsoft Internet")==-1)
	{
		if (document.embeds && document.embeds[movieName])
		return document.embeds[movieName];
	}
	else
	{
		return document.getElementById(movieName);
	}
}

(function(){
	var ChangeDomReady = window.ChangeDomReady = {};

	// 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 user
    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);
	};

	// This is the public function that people can use to hook up ready.
	ChangeDomReady.ready = function(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, []); } );
	    }
	};

    ChangeDomReady.onLoad = function(fn, args){
		if(browser.msie)
		  eval("addLoadEvent("+fn+"())");
		else
		  addLoadEvent(fn);
	}

	bindReady();

})();

// if the configuration info for the widget has already been defined, then go ahead and call the load function
if(typeof(changeWidgetParams) !== 'undefined') {
  if(changeWidgetParams['configParams']) {
  	configParams = changeWidgetParams['configParams'];
	for(var i in configParams) {
	  if(configParams.hasOwnProperty(i))
	    configure_widget(i, configParams[i]);
	}
  }
  change_setup(changeWidgetParams['width'], changeWidgetParams['petitionID'], changeWidgetParams['color']);
}
