/* (c) 2008, 2009 Add This, LLC */
/* vim: set expandtab tabstop=4 shiftwidth=4: */
/* --- HOWTO ---
 *
 * creates or updates variables:
 *  _atu
 *  _atd
 *  _atr
 *  _atc
 *  _euc
 *  addthis_*
 *
 * creates public fuctions:
 *
 *  addthis_open
 *  addthis_close
 *  addthis_sendto
 *
 * creates legacy public fuctions:
 *
 *  addthis_onmouseover
 *  addthis_onmouseout
 *  addthis_to
 *
 * on page load, looks for a _csuid cookie on the document.  if it does
 * not exist, loads (or attempts to load) the flash service code. on a
 * successful load, uses flash to establish a definitive user id (in the
 * same namespace as clearspring cookies).  on failure, sets X[rand] as
 * the uid.  When a uid is recovered or set the first time, it's assigned
 * to the page's (domain's) cookie.  The X[rand] uid prevents future flash
 * loads from being attempted.
 *
 * --- TODO ---
 *
 * require pubid for email
 * limit email size to X bytes
 * can we iframe the menu? reduce code size; as of 1/30 stewart doesn't want to
 * templatable or via iframe work for bookmark/feed/other
 */
// event tracking api
if (!window._ate) {
var _atd = 'www.addthis.com/',
	_atr = '//s7.addthis.com/',
    _euc = encodeURIComponent,
    _duc = decodeURIComponent,
    _atu = 'undefined',
    _atc = {
        dr : 0,     // domready
		ver : 250,
        loc : 0,
		enote : '', // pre-filled email note
		cwait : 500, // menu close wait onmouseout in milliseconds
        tamp : 1, // -- test sample rate (-1=off, 1=on)
		samp : 0.01, // -- view sample rate (-1=off, 1=on)
		camp : 0.05, // -- classification sample rate (-1=off, 1=on)
		vamp : 1, // -- view metadata sample rate (-1=off, 1=on)
		addr : -1, // -- ad show rate (-1=off,1=on)
		addt : 1, // -- ad type (0-n)
		xfl : !!window.addthis_disable_flash, // -- disable flash
        abf : !!window.addthis_do_ab // address book frame
            // xtr : 1, // -- disable tracking
		// xck : 1, // -- disable document cookies
	};
	// on dom ready code
	(function(){
    try {
        var l = window.location;
        if (l.protocol.indexOf('file') === 0) _atr = 'http:'+_atr;
        if (l.hostname.indexOf('localhost') != -1) _atc.loc = 1;
    }
    catch (e) {
    }
    // Everything that has to do with properly supporting our document ready event. Brought over from the most awesome jQuery. 
	var ua = navigator.userAgent.toLowerCase(),
		d = document,
		w = window,
		wa = w.addEventListener,
		we = w.attachEvent,
        dl = d.location, 
		// Figure out what browser is being used
		b = {
			//ver: (ua.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
            win: /windows/.test(ua),
			chr: /chrome/.test(ua),
            iph: /iphone/.test(ua),
			saf: (/webkit/.test(ua)) && !(/chrome/.test(ua)),
			opr: /opera/.test(ua),
			msi: (/msie/.test(ua)) && !(/opera/.test(ua)),
            ffx: /firefox/.test(ua),
			//moz: (/mozilla/.test(ua)) && (!/(compatible|webkit)/.test(ua)),
			ie6: /msie 6.0/.test(ua),
            mod: -1 /*compatibility mode*/
		},
        _adr = {
			isBound : false,
			isReady : false,
			readyList : window.addthis_onload || [],
			// browser detect object
			// Handle when the DOM is ready
			onReady : function() {
				// Make sure that the DOM is not already loaded
				if (!_adr.isReady) {
					// Remember that the DOM is ready
					_adr.isReady = true;
					var l = _adr.readyList;
					for (var fn = 0; fn < l.length; fn++) {
						l[fn].call(window);
					}
					_adr.readyList = [];
				}
			},
			// From Simon Willison. A safe way to fire onload w/o screwing up everyone else.
			addLoad : function(func) {
				var oldonload = w.onload;
				if (typeof w.onload != 'function') {
					w.onload = func;
				} else {
					w.onload = function() {
						if (oldonload) {
							oldonload();
						}
						func();
					}
				}
			},
			// does the heavy work of working through the browsers idiosyncracies (let's call them that) to hook onload.
			bindReady : function() {
				if (r.isBound) {
					return;
				}
			
				r.isBound = true;

				// Mozilla, Opera (see further below for it) and webkit nightlies currently support this event
				if (d.addEventListener && !b.opr) {
					// Use the handy event callback
					d.addEventListener("DOMContentLoaded", r.onReady, false);
				}

                var apc = window.addthis_product;
                if (apc && apc.indexOf('f') > -1) { r.onReady(); return; }

				// If IE is used and is not in a frame
				// Continually check to see if the document is ready
				if (b.msi && window == top) (function(){
					if (r.isReady) return;
					try {
						// If IE is used, use the trick by Diego Perini
						// http://javascript.nwbox.com/IEContentLoaded/
						d.documentElement.doScroll("left");
					} catch(error) {
						setTimeout(arguments.callee, 0);
						return;
					}
					// and execute any waiting functions
					r.onReady();
				})();

				if (b.opr) {
					d.addEventListener( "DOMContentLoaded", function () {
						if (r.isReady) return;
						for (var i = 0; i < d.styleSheets.length; i++)
							if (d.styleSheets[i].disabled) {
								setTimeout( arguments.callee, 0 );
								return;
							}
						// and execute any waiting functions
						r.onReady();
					}, false);
				}

				if (b.saf) {
					var numStyles;
					(function(){
						if (r.isReady) return;
						if (d.readyState != "loaded" && d.readyState != "complete") {
							setTimeout( arguments.callee, 0 );
							return;
						}
						if (numStyles === undefined) {
							var links = d.gn("link");
							for (var i=0; i < links.length; i++) {
								if (links[i].getAttribute('rel') == 'stylesheet') {
									numStyles++;
								}
							}
							var styles = d.gn("style");
							numStyles += styles.length;
						}
						if (d.styleSheets.length != numStyles) {
							setTimeout( arguments.callee, 0 );
							return;
						}
					
						// and execute any waiting functions
						r.onReady();
					})();
				}

				// A fallback to window.onload, that will always work
				r.addLoad(r.onReady);
			},
			// This is the public function that people can use to hook up ready.
			append : function(fn, args) {
				// Attach the listeners
				r.bindReady();
			
				// If the DOM is already ready
				if (r.isReady) {
					// Execute the function immediately
					fn.call(window, []);
				} else {
					// Add the function to the wait list
					r.readyList.push( function() { return fn.call(window, []); } );
				}
			}
		},
		r = _adr,
		// addthis event object
		_ate = {
            vst : [],
			rev: '$Rev: 64571 $',
			// browser config
			bro : b,
			// click count sent as custom event
			clck : 1,
			// decremented on first show, limits show event to 1 time
			show : 1,
            // document.location
            dl : dl,
			// sampling rates
			camp : _atc.camp - Math.random(),
			samp : _atc.samp - Math.random(),
			vamp : _atc.vamp - Math.random(),
			tamp : _atc.tamp - Math.random(),
			// AB test name MUST NOT be empty
			ab : '-',
			// service count: number of times services are invoked
			scnt : 1,
			// session tracking sequence counter
			seq : 1,
			// page installs: number of times script is included on page
			inst : 1,
			// delay between first event in queue and transmission
			wait : 500,
			// timeout timer pointer set and cleared 
			tmo : null,
			// custom event queue, cleared on 'wait' interval
			cvt : [],
			// standard event queue, cleared on 'wait' interval
			svt : [],
			// session start time
			sttm : new Date().getTime(),
			// bit mask constant
			max : 0xfffffff,
			// pixel load prefix, changed by service invokations just to keep it real
			pix : 'tev',
			// session id retrieved (an auto-set) through ssid() b/c cuid() function not available until object is complete
			sid : 0,
			// sub-session or library loaded in subsequent iframe
			sub : !!window.at_sub,
			// user id read from flash cookie if available, not used otherwise
			uid : null,
            // opt out time, read from page cookie
            oot : null,
			// flash cookie engine
			swf : '//bin.clearspring.com/at/v/1/button1.6.swf',
			// event root url
			evu : '//e1.clearspring.com/at/',
			// munge a string into a hash
			/* commented out when long tail ad serving off 
			mun : function(s) {
				var mv = 0x123;
                if (s) {
                    for (var i=0; i<s.length; i++) {
                        mv = (mv * (s.charCodeAt(i)+i) + 3) & 0xfffff;
                    }
                }
				return (mv&0xffffff).toString(32);
			},
            */
			// time offset from start of session
			off : function() {
				return Math.floor((new Date().getTime()-_ate.sttm)/100).toString(16);
			},
			// random integer number generator (0-max)
			ran : function() {
				return Math.floor(Math.random()*0xffffffff).toString(36);
			},
            // generate search referer pair
            srd : function () {
                if (_ate.dr) return '&pre='+_euc(_ate.dr);
                else return '';
            },
			// generate comscore tag
			cst : function(c) {
				return 'CXNID=2000001.521545608054043907'+(c || 2)+'NXC';
			},
			// CDN 'tracking' against the cdn
			img : function(i,c) {
				if (!window.at_sub) {
                    var a = _ate, dr = a.dr;
                    if (dr) {
                        dr = (dr.split('?')).shift();
                        dr = (dr.split('http://')).pop();
                        /* @todo if it's off-domain and q= or p= is in the referer, and the UID isn't anonymous or X...., send the full DR */
                        if (dr.length > 25) {
                            dr = dr.substr(0, 25);
                        }
                    }
					new Image().src = _atr+'live/t00/'+i+'.gif?'+(a.uid!==null?'uid='+a.uid+'&':'')+a.ran()+'&'+a.cst(c)+(a.pub()?'&pub='+a.pub():'')+(dr?'&dr='+_euc(dr):'');
				}
			},
			// cuid generator, not in compliance w/ CS yet (so consider it broken)
			cuid : function() {
				return (_ate.sttm&_ate.max).toString(16)+(Math.floor(Math.random()*_ate.max)).toString(16);
			},
			// returns sid (sets it on the first call)
			ssid : function() {
				if (_ate.sid === 0) {
					_ate.sid = _ate.cuid();
				}
				return _ate.sid;
			},
			// schedule sending of standard event
			sev : function(id,close) {
				_ate.pix = 'sev-'+(typeof(id) !== 'number' ? _euc(id) : id);
				_ate.svt.push(id+';'+_ate.off());
				if (close === 1) {
					_ate.xmi(true);
				} else {
					_ate.sxm(true);
				}
			},
			// schedule sending of custom event
			cev : function(k,v) {
				_ate.pix = 'cev-'+_euc(k);
				_ate.cvt.push(_euc(k)+'='+_euc(v)+';'+_ate.off());
				_ate.sxm(true);
			},
			// schedule_xmit: start timer to send event queue
			sxm : function(b) {
				if (_ate.tmo !== null) {
					clearTimeout(_ate.tmo);
				}
				if (b) {
					_ate.tmo = _ate.sto('_ate.xmi(false)',_ate.wait);
				}
			},
			// setTimeout
			sto : function(c,t) {
				return setTimeout(c,t);
			},
			// encode session state for events or to pass to php sub-windows
			sta : function() {
				var a = _ate;
				return 'AT-'+(a.pub() ? a.pub() : 'unknown')+'/-/'+a.ab+'/'+a.ssid()+'/'+(a.seq++)+(a.uid !== null ? '/'+a.uid : '');
			},
			// transmit waiting event queues
			xmi : function(close) {
				var a = _ate,
                    h = a.dl ? a.dl.hostname : '';
				// look for uid set on domain or by flash. if it's missing,
				// assume flash blocked and set cookie to prevent future load attempts
				if (!a.uid) {
					a.dck('X'+a.cuid());
				}
                else {
                    // check opt-out status
                    a.coo();
                }
				// set up transmit url
				if (a.cvt.length + a.svt.length > 0) {
					a.sxm(false);
					if (a.seq === 1) {
						a.cev('pin',a.inst);
					}
					// honor the disable-tracking setting
					if (_atc.xtr) {
						return;
					}
                    if (h.indexOf('.gov') > -1 || h.indexOf('.mil') > -1) {
                        _atc.xck = 1;
                    }
                    var urp = a.pix+'-'+a.ran()+'.png?ev='+_ate.sta()+'&se='+a.svt.join(',')+'&ce='+a.cvt.join(',')+(_atc.xck?'&xck=1':''),
					    url = a.evu+urp;
					a.cvt = [];
					a.svt = [];
					if (close) {
						var d = document, i = d.ce('iframe');
						i.id = '_atf';
						i.src = url;
						_ate.opp(i.style);
						d.body.appendChild(i);
						// busy work forces the browser to find the object it just
						// inserted.  increases chances it loads the url.
						i = d.getElementById('_atf');
					} else {
						(new Image()).src = url;
					}
				}
			},
            // true iff. we're in the local flash security sandbox; needed to prevent scary messages
            // from appearing on less-educated users' machines
            loc : function () {
                return _atc.loc;
            },
			// one pixel position
			opp : function(st) {
				st.width = '1px';
				st.height = '1px';
				st.position = 'absolute';
				st.zIndex = 100000;
			},
			// get addthis publisher id
			pub : function() { return window.addthis_config && addthis_config.username ? _euc(addthis_config.username) : (window.addthis_pub || ''); },
			// post load operation array
			plo : [],
			// plo adder
			lad : function(x) {
				_ate.plo.push(x);
			},
            lng : function (al) {
                var d = document;
                if (al && (al.toLowerCase()).indexOf('en') !== 0 && !_ate.pll) {
                    var o = d.ce('script');
                    o.src = _atr+'static/r07/lang00.js';
                    d.gn('head')[0].appendChild(o);
                    _ate.pll = o;
                } 
            },
			// javascript post loader
			jlo : function() {
				try {
                    var d = document, al = (window.addthis_language || addthis_config.ui_language || (_ate.bro.msi ? navigator.userLanguage : navigator.language));
                    _ate.lng(al);
					if (!_ate.pld) {
						var m = d.ce('script');
						m.src = _atr+'static/r07/menu20.js';
						d.gn('head')[0].appendChild(m);
						_ate.pld = m;
					}
				} catch (e) {
					//console.log('jlo',e)
				}
			},
            // init global vars
            igv : function () {
                  if (!w.addthis_share) 
                      w.addthis_share = {url: w.addthis_url,
                          title: w.addthis_title};
                  if (!w.addthis_config) {
                      w.addthis_config = {username: w.addthis_pub};
                  } else {
                      if (addthis_config.data_use_flash === false) _atc.xfl = 1;
                      if (addthis_config.data_use_cookies === false) _atc.xck = 1;
                  }
            },
			// called on page load (f == force object load (delayed))
			lod : function(arg) {
				try {
                    var w = window, a = _ate, hp = 0, f = ((arg === 1 || w.addthis_load_flash) && !_atc.abf), dr = d.referer||d.referrer||'', du = dl ? dl.href : null, si = du ? du.indexOf('sms_ss') : -1,
                        al = (w.addthis_language || (w.addthis_config ? w.addthis_config.ui_language : null) || (_ate.bro.msi ? navigator.userLanguage : navigator.language)),
                        opts = 'email,favorites,print,delicious,digg,google,myspace,live,facebook,stumbleupon,twitter,more';
                    a.igv();
                    a.dr = dr;
                    /* probabilities for a/b test (#11915) - four cells */
                    //a.ab = w.addthis_ab || (a.tamp > 0 && (al == '' || al.indexOf('en')==0) ? (a.tamp > 0.02 ? (a.tamp > 0.04 ? (a.tamp > 0.06 ? 4 : 3) : 2) : 1) : 0);
                    /* 22 cell a/b test (#12203) */
                    a.ab = (!window.addthis_options || addthis_options == opts) ? w.addthis_ab || Math.round(a.tamp*100 / 4.55) : 0;
                    if (a.ab > 11) {
                        a.ab = "f"+(a.ab-11);
                    } else {
                        a.ab = "t"+a.ab;
                    }
                    if (!f) {
                        if (a.samp >= 0 && !a.sub) {
                            a.sev('20');
                            a.cev('plo',Math.round(1/_atc.samp));
                            if (a.dr) {
                                a.cev('pre',a.dr);
                                hp = 1;
                            }
                            //a.cev('bro',(b.msi?'IE':b.moz?'Firefox':b.saf?'Safari':b.op?'Opera':'Other')+' '+b.ver);
                        }
                                
                        if (a.camp >= 0 && du && dl && dl.protocol && (dr.indexOf('com/search') > -1) && (dl.protocol.indexOf('https') == -1)) {
                            dr = dr.split('?').pop();
                            var t = dr.split('&'), fnd = 0, quo = -1, ts = '';
                            for (var i = 0; i < t.length; i++) {
                                if (t[i].indexOf('q=')==0 || t[i].indexOf('p=')==0) {
                                    t = _duc(t[i].substr(2)).replace(/\+/g,' ');
                                    fnd = 1;
                                    break;
                                }
                            }
                            // if we found search terms, split 'em up
                            if (fnd) {
                                for (var i = 0; i < t.length; i++) {
                                    switch(t[i]) {
                                        case ' ':
                                            if (i > 0 && t[i-1] != ' ' && quo == -1) {
                                                ts += ','; 
                                            }
                                            break;
                                        case '"':
                                                if (quo >= 0) {
                                                    ts += t.substr(quo+1, (i)-(quo+1));
                                                    quo = -1;
                                                } else {
                                                    quo = i;
                                                }
                                            break;
                                        default:
                                            if (quo == -1) 
                                                ts += t[i];
                                    }
                                }
                            }
                            if (!_ate.xck && ts != _atu && ts.length && ts !== ' ' && ts.indexOf(_atu) == -1) {
                                //new Image().src = '//a.collective-media.net/classify?net=cs&url='+_euc(du)+'&terms='+ts;
                                new Image().src = '//cf.addthis.com/redirector?url='+_euc(du)+'&terms='+ts;
                            }
                        }

                        if (si > -1)
                        {
                            var sm = du.substr(si),
                                am = sm.indexOf('&');
                            if (am > -1) sm = sm.substr(0, am);
                            sm = (sm.split('='))[1];
                            if (a.vamp >= 0 && !a.sub && sm.length) {
                                a.cev('plv',Math.round(1/_atc.vamp));
                                a.cev('rsc',sm);
                            }
                        }
                        a.img(_atc.ver+'lo','2');
                    }

                    // load menu if jlo[] array is not empty
                    if (a.plo.length > 0) {
                        a.jlo();
                    }

                    /* if xfl is not on, and we're not in the local sandbox, and we're not in the AB frame,
                       and the uid is null OR not anonymous and it's been a week since we seem to have set 
                       it, load flash. this means that it can take up to a week for your opt-in/out status to change.*/
                    if (a.swf && !_atc.xfl && !(a.loc()) && !_atc.abf &&
                        (f || a.uid === null 
                           || (a.uid !== 'anonymous' && ((new Date()).getTime() - a.oot > 60480000)))) {
                        var addparam = function(o,n,v) {
                            var c = d.createElement('param');
                            c.name = n;
                            c.value = v;
                            o.appendChild(c);
                        };
                        var o = d.createElement('object');
                        a.opp(o.style);
                        o.id = 'atff';
                        if (b.msi) {
                            o.classid = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000';
                            addparam(o,'movie',a.swf);
                        } else {
                            o.data = a.swf;
                            o.quality = 'high';
                            o.type = 'application/x-shockwave-flash';
                        }
                        addparam(o,'wmode','transparent');
                        addparam(o,'allowScriptAccess','always');
                        d.body.insertBefore(o,d.body.firstChild);
                        if (b.msi) {
                            o.outerHTML += ' ';
                        }
                    }
				} catch (e) {
				    //console.log('lod',e)
				}
			},
			// called on page unload
			unl : function() {
				var a = _ate;
				if (a.samp >= 0 && !a.sub && !_atc.abf) {
					a.sev('21',1);
					a.cev('pun',1/_atc.samp);
				}
				return true;
			},
            // kill cookie
            kck : function (k) {
                var d = document;
                if (d.cookie) d.cookie = k+'= ; expires=Tue, 31 Mar 2009 05:47:11 UTC; path=/'
            },
            // read cookie
            rck : function(k) {
                var d = document;
                if (d.cookie) {
                    var ck = d.cookie.split(";");
                    for (var i=0; i<ck.length; i++) {
                        var c = ck[i],
                            x = c.indexOf(k+'=');
                        if (x >= 0) {
                            //console.log("cookie from document : "+c.substring(x+k.length+1));
                            return c.substring(x+(k.length+1));
                        }
                    }
                }
                return;
            },
            // check opt out
            coo : function () {
                if (_ate.uid == 'anonymous' && !_ate.oot) {
                    _ate.xck = 1;
                    _ate.sck('_csoot',(new Date().getTime()));
                } 
            },
            dck : function (c) {
				_ate.uid = c;
                _ate.sck('_csuid',c);
                _ate.coo();
            },
			// set document/domain cookie
			sck : function(u,v,s /* true for session cookie */) {
                var h = _ate.dl ? _ate.dl.hostname : '';
				// set cookie if xck (block cookies) not set
                if (h.indexOf('.gov') > -1 || h.indexOf('.mil') > -1) {
                    _atc.xck = 1;
                    _atc.xfl = 1;
                }
                // some sites were here but no longer need to be on account of .govness:
                // massgov, usagov, dodpubweb, disamil, education, govgab1
				var p = _ate.pub(), x = ['usarmymedia','gobiernousa','govdelivery'];
				for (i in x) {
					if (p == x[i]) {
                        _atc.xck = 1;
                        _atc.xfl = 1;
                        break;
					}
				}
				if (!_atc.xck) {
					d.cookie = u+'='+v+(!s?'; expires=Wed, 04 Oct 2028 03:19:53 GMT':'')+'; path=/';
				}
			},
			// flash chain onload
			fcl : null,
			// called from flash with user id or null if not set yet
			asetup : function(x) {
				var a = _ate;
				//console.log('uid from flash : '+x);
				try {
					if (x !== null && x !== _atu) {
						a.dck(x);
					}
					if (a.fcl) {
						a.fcl();
					}
				} catch (e) {
					//xx('as',e)
				}
				return x;
			},
			// addthis open
			ao : function(elt,pane,iurl,ititle,iconf,ishare) {
				_ate.lad(['open',elt,pane,iurl,ititle,iconf,ishare]);
				_ate.jlo();
				return false;
			},
			// addthis close
			ac : function() {
				//_ate.plo = [];
			},
			// addthis sendto
			as : function(s,cf,sh) {
				_ate.lad(['send',s,cf,sh]);
				_ate.jlo();
			}
		},
		a = _ate;
        // setup global references
        w._ate = a;
        w._adr = r;
        d.ce = d.createElement;
        d.gn = d.getElementsByTagName;
        r.bindReady();
        // setup onload (deprecated for ondomload), onunload
        if (wa) {
            //wa('load', a.lod, false);
            wa('unload', a.unl, false);
        } else if (we) {
            //we('onload', a.lod);
            we('onunload', a.unl);
        } else {
            //w.onload = a.lod;
            w.onunload = a.unl;
        }

        if (!_atc.ost) {
            // create empty conf if it doesn't exist
            if (!w.addthis_conf) {
                w.addthis_conf = { };
            }
            // copy addthis_conf into internal conf object
            for (var i in addthis_conf) {
                _atc[i] = addthis_conf[i];
            }
            _atc.ost = 1;
        }

        r.append(a.lod);
        // read cookie looking for _csuid
        if (d.cookie) {
            var ck = d.cookie.split(";");
            for (var i=0; i<ck.length; i++) {
                var c = ck[i],
                    x = c.indexOf("_csuid="),
                    y = c.indexOf("_csoot=");
                if (x >= 0) {
                    _ate.uid = c.substring(x+7);
                    //console.log("cookie from document : "+_ate.uid);
                } else if (y >= 0) {
                    _ate.oot = c.substring(y+7);
                }
            }
        }
        // insert style sheet (required)
        try {
            // add css stylesheet
            var l = d.ce('link');
            l.rel = 'stylesheet';
            l.type = 'text/css';
            l.href = _atr+'static/r07/widget07.css';     
            l.media = 'all';
            d.gn("head")[0].appendChild(l);
        } catch (e) {
            //xx('pl',e)
        }
        var ss = d.gn('script'),
            s = ss[ss.length - 1],
            q = s.src.replace(/^[^\?]+\??/,''),
            pq = function (q) {
               var p = {};
               if (!q) return p;
               var ps = q.split(/[;&]/);
               for (var i = 0; i < ps.length; i++) {
                  var kv = ps[i].split('=');
                  if (!kv || kv.length != 2) continue;
                  var k = _duc(kv[0]),
                      v = _duc(kv[1]);
                  v = v.replace(/\+/g, ' ');
                  ps[k] = v;
               }
               return ps;
            },
            p = pq(q);
        if (p.pub) {
            w.addthis_pub = _duc(p.pub);
            if (w.addthis_config) w.addthis_config.username = w.addthis_pub;
        } else if (p.username) {
            w.addthis_pub = _duc(p.username);
            if (w.addthis_config) w.addthis_config.username = w.addthis_pub;
        }
        if (p.domready) _atc.dr = 1;

        // code to generate a button (v12 compatibility)
        try {
            if (_atc.ver === 120) {
                var rc = 'atb'+w._ate.cuid();
                d.write('<span id="'+rc+'"></span>');
                w._ate.igv();
                w._ate.lad(['span',rc,addthis_share.url||'[url]',addthis_share.title||'[title]']);
            }
            if (w.addthis_clickout) {
                _ate.lad(['cout']);
            }
        } catch (e) {
        }
	})();


	// public function
	// overridden on hover-load
	function addthis_open(elt, pane, iurl, ititle, iconf, ishare) {
        if (typeof iconf == 'string') iconf = null;
		return _ate.ao(elt,pane,iurl,ititle,iconf,ishare);
	}

	// public function onnmouseout close pop
	// overridden on hover-load
	function addthis_close() {
		_ate.ac();
	}

	// public function
	// overridden on hover-load
	function addthis_sendto(s,cf,sh) {
		_ate.as(s,cf,sh);
		return false;
	}

    if (_atc.dr) _adr.onReady();
} else {
	_ate.inst++;
}

// code to produce munged ad blacklist (comment out for production)
/*
var xl = ['myspace','webs','badongo','ticketmasterus','perfspot','utlol','enkrates','addthis','wwitv','zangoshare','wayn','myflashfetish','foxSports','sayyes943','ewcom','multiply','stanzapub','enchula','snapshots','AlfaTelecom','abcnews','hartster','adopteunmec','kaware3','Videodetective','biggahed','asktiava','slideshare','sfnet','timecom','PlayFirst','mocospace','pmstation','sendspace','mngi','maxgames.com','netaxis','ebsco','longestlist','bulent','phonezoo','IGN','mtvgermany','trent','weblogsinc','ioffer','JeroenW','sicom','rogersradio','Reverso','swapnil_shinde','josechabe','N1PSZUHXZFWVNLB7','wunbuck','grayinteractivemedia','ticketmasteruk','favbook','trafficfortress','wep','dvdzapata','youmint','smashits','fontstock','alexeiramone','vrcorporate','bhgwebmaster','ticketmastermx','mprosellini','4arabnetwork','oswec','tnaflix','mse','cramiller','alfaman','nehemiasxp','nnfog','WeddingChannel','bseker','ticketmasterca','christianglitter','umgnashville','colombo','garse','naukrisalah','Gamebrew','TheKnot','HomeAwayInc','gamesfreak','choodo','w-m.net','techcrunch','azcentral','mihalismmh','ekstrabladet','hazemtorab','jackodog','blogohblog','politico.com','martinl','QQ1EPAI6Z0QTZVGS'];
// TODO added 'politico.com', 'martinl' which is bestbuy.com and 'QQ1EPAI6Z0QTZVGS' which is theatlantic
var xs = [], xo = {};
for (var i in xl) { xo[_ate.mun(xl[i])]=1; }
for (var i in xo) { xs.push("'"+i+"'"); }
console.log('munged exclusion list : '+xs.join(','));
*/

if (_atc.abf)
{
   addthis_open(document.getElementById('ab'), 'emailab', window.addthis_url || '[URL]', window.addthis_title || '[TITLE]'); 
}
/* concatenated to widget.js on v250 code */

// since globals might be defined after script execution, we don't
// provide any functions until after the dom is ready
if (!window.addthis || window.addthis.nodeType !== undefined) {
    window.addthis = {ost: 0,  // set to 1 after initialization
                      cache: {}, // for caching some DOM elements we use a lot
                      plo: [], // queued function calls pre-dom-readiness
                      links: [],
                      button: function () {this.plo.push({call: 'button', args: arguments});},
                      toolbox: function () {this.plo.push({call: 'toolbox', args: arguments});},
                      update: function () {this.plo.push({call: 'update', args: arguments});}
                     };
}
_adr.append((function(){
    if (!window.addthis.ost) {
    var 
        d = document,
        u = undefined,
        w = window,
        globalConfig = w.addthis_config,
        globalShare = w.addthis_share,
        upConfig = {}, // updated config
        upShare = {}, // updated share
        body = d.gn("body").item(0),
        mrg = function (o, n) {
            if (n && o !== n) {
                for (var k in n) {
                    if (o[k] === u) o[k] = n[k];
                }
            } 
        },
        rpl = function (o, n) {
            var r = {};
            for (var k in o) {
                if (n[k]) r[k] = n[k]; else r[k] = o[k];
            }
            return r;
        },
        addthis = window.addthis,
        gebcn = function (oParent, tag, className, allowSuffix) {
            tag = tag.toUpperCase();
            var els = (oParent == body && addthis.cache[tag] ? addthis.cache[tag] : (oParent || body).getElementsByTagName(tag)),
                rv = [],
                o;
            if (oParent == body) addthis.cache[tag] = els;
            className = className.replace(/\-/g, "\\-");
            var rx = new RegExp("(^|\\s)" + className + (allowSuffix ? '\\w*' : '') + "(\\s|$)");
            for(var i=0; i<els.length; i++){
                o = els[i];      
                if(rx.test(o.className)){
                    rv.push(o);
                }   
            }
            return (rv)
        },
        /* todo: move the list entirely into api.js */
        s_list = {
			'aim'         : 'AIM',
			'kirtsy'      : 'kIRTSY',
			'linkagogo'   : 'Link-a-Gogo',
			'meneame'     : 'Men&eacute;ame',
			'misterwong'  : 'Mister Wong',
			'myaol'       : 'myAOL',
			'myspace'     : 'MySpace',
			'yahoobkm'    : 'Y! Bookmarks',
			'typepad'     : 'TypePad',
			'wordpress'   : 'WordPress'
        },
        b_title = {email: 'Email', print: 'Print', favorites: 'Save to Favorites', twitter: 'Tweet This', digg: 'Digg This'},
        json = {services_custom: 1}, /*<<< services that might need to be parsed as json (if they're strings and not objects by the time we get them */
        nosend = {more: 1, email: 1}, /*<<< services that never use sendto */
        nowindow= {email: 1, print: 1, more: 1, favorites: 1}, /*<<< services that never open a new window */
        a_config = [
            'username',
            'services_custom',
            'services_custom_name',
            'services_custom_url',
            'services_custom_title',
            'services_exclude',
            'services_compact',
            'services_expanded',
            'ui_click',
            'ui_hide_embed',
            'ui_delay',
            'ui_hover_direction',
            'ui_language',
            'ui_offset_top',
            'ui_offset_left',
            'ui_header_color',
            'ui_header_background',
            'ui_icons',
            'ui_cobrand',
            'data_use_flash',
            'data_use_cookies',
            'data_track_linkback'],
        a_share = [
            'url',
            'title',
            'templates',
            'content'],
        getElementsByClassName = d.getElementsByClassname || gebcn,
        _svcurl = function (config, share) {
                var sv = config.services instanceof Array ? config.services[0] : config.services || '';
                return 'http://'+_atd+'bookmark.php?v='+_atc.ver+'&pub='+_euc(_ate.pub())+'&s='+sv+(share.url?'&url='+_euc(share.url):'')+(share.title?'&title='+_euc(share.title):'');
        },
        _select = function (what) {
            if (typeof what == 'string') {
                var c = what.substr(0, 1);
                if (c == '#') {
                    what = d.getElementById(what.substr(1));
                } else if (c == '.') {
                    what = getElementsByClassName(body, '*', what.substr(1));
                } else {
                    // don't know how to parse this
                }
            }
            if (!(what instanceof Array)) {
                what = [what];
            }
            return what;
        },
        _parseAttributes = function (el, attrs, overrides, childWins) {
            var rv = {};
            overrides = overrides || {};
            for (var i = 0; i < attrs.length; i++) {
                if (overrides[attrs[i]] && !childWins) {
                    rv[attrs[i]] = overrides[attrs[i]];
                } else if (el) {
                    var p = "addthis:"+attrs[i],
                        v = el.getAttribute ? el.getAttribute(p) || el[p] : el[p];

                    if (v) {
                        rv[attrs[i]] = v;
                    } else if (overrides[attrs[i]]) {
                        rv[attrs[i]] = overrides[attrs[i]];
                    }
                }
                if (rv[attrs[i]] !== undefined && json[attrs[i]] && (typeof rv[attrs[i]] == 'string')) {
                    eval("var e = "+rv[attrs[i]]);
                    rv[attrs[i]] = e;
                }
            }
            return rv;
        }, 
        _getATtributes = function (el, config, share, childWins) {
            var rv = {conf: config || {}, share: share || {}};
            rv.conf = _parseAttributes(el, a_config, config, childWins);
            rv.share = _parseAttributes(el, a_share, share, childWins);
            return rv;
        },
        _render = function (what, conf, attrs) {
            if (what) {
                conf = conf || {};
                attrs = attrs || {};

                var config = conf.conf || globalConfig,
                    share = conf.share || globalShare;

                var onmouseover = attrs.onmouseover, 
                    onmouseout = attrs.onmouseout, 
                    onclick = attrs.onclick, 
                    internal = attrs.internal,      
                    ss = attrs.singleservice;
                if (ss) {
                    config.product = 'tbx-'+_atc.ver;
                    if (onclick === u) onclick = nosend[ss] ? function (el, config, share) { var s = rpl(share, upShare); return addthis_open(el, ss, s.url, s.title, rpl(config, upConfig), s);}
                                                            : nowindow[ss] ? function (el, config, share) { var s = rpl(share, upShare); return addthis_sendto(ss, rpl(config, upConfig), s);} : null;
                } else if (!attrs.noevents) {
                    if (!attrs.nohover && (!config || !config.ui_click)) {
                        if (onmouseover === u) onmouseover = function (el, config, share) {  return addthis_open(el, '', null, null, config, share); };
                        if (onmouseout === u) onmouseout = function (el) { return addthis_close(); };
                        if (onclick === u) onclick = function (el, config, share) { return addthis_sendto('more', config, share);};
                    } else if (!config || !config.ui_click) {
                        if (onclick === u) onclick = function (el, config, share) {  return addthis_open(el, 'more');};
                    } else {
                        if (onclick === u) onclick = function (el, config, share) {  return addthis_open(el, '', null, null, config, share);};
                    }
                }

                what = _select(what);

                for (var i = 0; i < what.length; i++) {
                    var o = what[i],
                        oattr = _getATtributes(o, config, share) || {};

                    mrg(oattr.conf, globalConfig);
                    mrg(oattr.share, globalShare);
                    o.conf = oattr.conf;
                    o.share = oattr.share;

                    if (o.conf.ui_language) {
                        _ate.lng(o.conf.ui_language);                    
                    }

                    if (onmouseover) o.onmouseover = function () { return onmouseover(this, this.conf, this.share) }; 
                    if (onmouseout) o.onmouseout = function () { return onmouseout(this) }; 
                    if (onclick) o.onclick = function () { return onclick(this, this.conf, this.share) }; 

                    if (o.tagName.toLowerCase() == 'a') {
                        if (ss) {
                            o.conf.product = 'tbx-'+_atc.ver;
                            if ((_ate.bro.ffx || _ate.bro.chr) && !nowindow[ss]) {
                                var template = o.share.templates && o.share.templates[ss] ? o.share.templates[ss] : '';
                                o.href = '//'+_atd+'bookmark.php?pub='+_euc(addthis_config.username||o.conf.username||_ate.pub())+'&v='+_atc.ver+'&source=tbx-'+_atc.ver+'&s='+ss+
                                         '&url='+_euc(oattr.share.url||addthis_share.url||'')+'&title='+_euc(oattr.share.title||addthis_share.title||'')+
                                         '&content='+_euc(oattr.share.content||addthis_share.content||'')+(template?'&template='+_euc(template):'')+(o.conf.data_track_linkback?'&sms_ss=1':'')
                                o.target = '_blank';
                                addthis.links.push(o);
                            } else if (!nowindow[ss]) {
                                o.onclick = function () { return addthis_sendto.call(this, ss, rpl(this.conf, upConfig), rpl(this.share, upShare)); }; 
                            } else if (ss == 'email' && _ate.bro.iph) {
                                o.href = w.genieu(this.share);
                                o.email = true;
                                o.target = '_blank';
                                addthis.links.push(o);
                            }
                            if (!o.title) o.title = b_title[ss] ? b_title[ss] : 'Send to ' + (s_list[ss] ? s_list[ss] : ss.substr(0,1).toUpperCase() + ss.substr(1));
                        }
                    }

                    if (internal) {
                        var app = internal;
                        if (!o.hasChildNodes()) {
                            if (internal == 'img') {
                                var img = d.ce("img");
                                img.width = 125; 
                                img.height = 16;
                                img.border = 0;
                                img.alt = 'Share'; 
                                img.src = '//s7.addthis.com/static/btn/lg-share-en.gif';
                                app = img;
                            } 
                            
                            o.appendChild(app);
                        }
                    }
                }
            }
        },
        buttons = gebcn(body, 'A', 'addthis_button_', true), 
        _renderToolbox = function (collection, config, share, reprocess) {
            for (var i = 0; i < collection.length; i++) {
                var b = collection[i];

                if (b == null) continue;
 
                if (reprocess !== false || !b.ost) {
                    var config = config || globalConfig;
                        share = share || globalShare;
                        attr = _getATtributes(b, config, share, true /* b takes precedence */),
                        hc = 0,
                        a = 'at300';
                        c = b.className || '',
                        s = c.match(/addthis_button_(\w+)(?:\s|$)/),
                        opts = u,
                        sv = s && s.length ? s[1] : 0;

                    if (sv) {
                        if (!b.childNodes.length) {
                            var sp = d.ce("span");
                            b.appendChild(sp);
                            sp.className = a+'bs at15t_'+sv;
                        } 
                        else if (b.childNodes.length == 1) {
                            var cn = b.childNodes[0];
                            if (cn.nodeType == 3) // text node
                            {
                                var sp = d.ce("span"),
                                    tv = cn.nodeValue;
                                b.insertBefore(sp,cn);
                                sp.className = a+'bs at15t_'+sv;
                                //sp = d.ce("div");
                                //var tn = d.createTextNode(tv); 
                                //b.appendChild(sp);
                                //sp.appendChild(tn);
                            }
                        } else {
                            hc = 1; 
                        }
                        
                        if (sv === 'compact') {
                            if (!hc && c.indexOf(a) == -1) b.className += ' '+a+'m';
                        } else if (sv === 'expanded') {
                            if (!hc && c.indexOf(a) == -1) b.className += ' '+a+'m';
                            opts = {nohover: true};
                        } else {
                            if (!hc && c.indexOf(a) == -1) b.className += ' '+a+'b';
                            opts = {singleservice: sv};
                        }
                        _render([b], attr, opts);
                        b.ost = 1;
                    }
                }
            }
        };

        addthis.update = function (which, what, value) {
            if (which == 'share') {
                if (!window.addthis_share) window.addthis_share = {};
                window.addthis_share[what] = value;
                upShare[what] = value;

                for (var i in addthis.links) {
                    var o = addthis.links[i],
                        rx = new RegExp("&"+what+"=(.*)&"),
                        ns = '&'+what+'='+_euc(value)+'&';
                    if (o.email) {
                        // special case for iphone) 
                        o.href = w.genieu(addthis_share);
                    } else {
                        o.href = o.href.replace(rx, ns);
                        if (o.href.indexOf(what) == -1) {
                            o.href += ns;
                        }
                    }
                }
            } else if (which == 'config') {
                if (!window.addthis_config) window.addthis_config = {};
                window.addthis_config[what] = value;
                upConfig[what] = value;
            }
        }

        addthis.button = function (what, config, share) { 
            _render(what, {conf: config, share: share}, {internal: 'img'});
        }

        addthis.toolbox = function (what, config, share) {
            var toolboxes = _select(what);
            for (var i = 0; i < toolboxes.length; i++) {
                var tb = toolboxes[i],
                    attr = _getATtributes(tb, config, share),
                    sp = d.ce("div"),
                    c = tb.getElementsByTagName('a');

                if (c) {
                    _renderToolbox(c, attr.conf, attr.share);
                }

                tb.appendChild(sp);
                sp.className = 'atclear';
            }
        }

        /* once the DOM's ready, we process all of our standard classes */
        addthis.ready = function () {
            if (this.ost) return;
            this.ost = 1; 
            var a = '.addthis_';

            /* default actions: render all addthis_toolboxes and addthis_buttons */
            addthis.toolbox(a+'toolbox'); 
            addthis.button(a+'button'); 

            /* there might be buttons floating outside of a toolbox div; we can still render these */
            _renderToolbox(buttons, null, null, false /* don't reprocess buttons we've already processed */);

            /* call post load functions (we queue, e.g., addthis.button() calls
               until after the DOM is ready and we do all this initialization */
            for (var i = 0; i < this.plo.length; i++) {
                addthis[this.plo[i].call].apply(this, this.plo[i].args);
            }
        }

        window.addthis = addthis;
        window.addthis.ready();
    }
}));
