
/*  new/common/js/jquery.popupWindow.js  */
(function($){ 		  
	$.fn.popupWindow = function(instanceSettings){
		
		return this.each(function(){
		
		$(this).click(function(){
		
		$.fn.popupWindow.defaultSettings = {
			centerBrowser:0, // center window over browser window? {1 (YES) or 0 (NO)}. overrides top and left
			centerScreen:0, // center window over entire screen? {1 (YES) or 0 (NO)}. overrides top and left
			height:500, // sets the height in pixels of the window.
			left:0, // left position when the window appears.
			location:0, // determines whether the address bar is displayed {1 (YES) or 0 (NO)}.
			menubar:0, // determines whether the menu bar is displayed {1 (YES) or 0 (NO)}.
			resizable:0, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable.
			scrollbars:0, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}.
			status:0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}.
			width:500, // sets the width in pixels of the window.
			windowName:null, // name of window set from the name attribute of the element that invokes the click
			windowURL:null, // url used for the popup
			top:0, // top position when the window appears.
			toolbar:0 // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}.
		};
		
		settings = $.extend({}, $.fn.popupWindow.defaultSettings, instanceSettings || {});
		
		var windowFeatures =    'height=' + settings.height +
								',width=' + settings.width +
								',toolbar=' + settings.toolbar +
								',scrollbars=' + settings.scrollbars +
								',status=' + settings.status + 
								',resizable=' + settings.resizable +
								',location=' + settings.location +
								',menuBar=' + settings.menubar;

				settings.windowName = this.name || settings.windowName;
				settings.windowURL = settings.windowURL?settings.windowURL:this.href;
				var centeredY,centeredX;
			
				if(settings.centerBrowser){
						
					if ($.browser.msie) {//hacked together for IE browsers
						centeredY = (window.screenTop - 120) + ((((document.documentElement.clientHeight + 120)/2) - (settings.height/2)));
						centeredX = window.screenLeft + ((((document.body.offsetWidth + 20)/2) - (settings.width/2)));
					}else{
						centeredY = window.screenY + (((window.outerHeight/2) - (settings.height/2)));
						centeredX = window.screenX + (((window.outerWidth/2) - (settings.width/2)));
					}
					window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
				}else if(settings.centerScreen){
					centeredY = (screen.height - settings.height)/2;
					centeredX = (screen.width - settings.width)/2;
					window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
				}else{
					window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + settings.left +',top=' + settings.top).focus();	
				}
				return false;
			});
			
		});	
	};
})(jQuery);

/*  new/common/js/global_async.js  */
$(document).ready(function(){
    if ('function' === typeof $().popupWindow)
    {
        $('a.tw', '#share-links').popupWindow({
            centerBrowser:1,
            windowURL:'http://twitter.com/intent/follow?region=follow&screen_name=avaaz',
            windowName:'twitter_popup_follow'
        });
    }
});

/*  common/js/ZeroClipboard.js  */
// Simple Set Clipboard System
// Author: Joseph Huckaby

var ZeroClipboard = {

	version: "1.0.7",
	clients: {}, // registered upload clients on page, indexed by id
	moviePath: 'ZeroClipboard.swf', // URL to movie
	nextId: 1, // ID of next movie

	$: function(thingy) {
		// simple DOM lookup utility function
		if (typeof(thingy) == 'string') thingy = document.getElementById(thingy);
		if (!thingy.addClass) {
			// extend element with a few useful methods
			thingy.hide = function() { this.style.display = 'none'; };
			thingy.show = function() { this.style.display = ''; };
			thingy.addClass = function(name) { this.removeClass(name); this.className += ' ' + name; };
			thingy.removeClass = function(name) {
				var classes = this.className.split(/\s+/);
				var idx = -1;
				for (var k = 0; k < classes.length; k++) {
					if (classes[k] == name) { idx = k; k = classes.length; }
				}
				if (idx > -1) {
					classes.splice( idx, 1 );
					this.className = classes.join(' ');
				}
				return this;
			};
			thingy.hasClass = function(name) {
				return !!this.className.match( new RegExp("\\s*" + name + "\\s*") );
			};
		}
		return thingy;
	},

	setMoviePath: function(path) {
		// set path to ZeroClipboard.swf
		this.moviePath = path;
	},

	dispatch: function(id, eventName, args) {
		// receive event from flash movie, send to client
		var client = this.clients[id];
		if (client) {
			client.receiveEvent(eventName, args);
		}
	},

	register: function(id, client) {
		// register new client to receive events
		this.clients[id] = client;
	},

	getDOMObjectPosition: function(obj, stopObj) {
		// get absolute coordinates for dom element
		var info = {
			left: 0,
			top: 0,
			width: obj.width ? obj.width : obj.offsetWidth,
			height: obj.height ? obj.height : obj.offsetHeight
		};

		while (obj && (obj != stopObj)) {
			info.left += obj.offsetLeft;
			info.top += obj.offsetTop;
			obj = obj.offsetParent;
		}
		return info;
	},

	Client: function(elem) {
		// constructor for new simple upload client
		this.handlers = {};

		// unique ID
		this.id = ZeroClipboard.nextId++;
		this.movieId = 'ZeroClipboardMovie_' + this.id;

		// register client with singleton to receive flash events
		ZeroClipboard.register(this.id, this);

		// create movie
		if (elem) this.glue(elem);
	}
};

ZeroClipboard.Client.prototype = {

	id: 0, // unique ID for us
	ready: false, // whether movie is ready to receive events or not
	movie: null, // reference to movie object
	clipText: '', // text to copy to clipboard
	handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor
	cssEffects: true, // enable CSS mouse effects on dom container
	handlers: null, // user event handlers

	glue: function(elem, appendElem, stylesToAdd) {
        var addedStyle;
		// glue to DOM element
		// elem can be ID or actual DOM element object
		this.domElement = ZeroClipboard.$(elem);

		// float just above object, or zIndex 99 if dom element isn't set
		var zIndex = 99;
		if (this.domElement.style.zIndex) {
			zIndex = parseInt(this.domElement.style.zIndex, 10) + 1;
		}

		if (typeof(appendElem) === 'string') {
			appendElem = ZeroClipboard.$(appendElem);
		}
		else if (appendElem === undefined) {
			appendElem = document.getElementsByTagName('body')[0];
		}

        this.appendElem = appendElem;

		// find X/Y position of domElement
		var box = ZeroClipboard.getDOMObjectPosition(this.domElement, appendElem);
		// create floating DIV above element
		this.div = document.createElement('div');
		var style = this.div.style;
		style.position = 'absolute';
		style.left = '' + box.left + 'px';
		style.top = '' + box.top + 'px';
		style.width = '' + box.width + 'px';
		style.height = '' + box.height + 'px';
		style.zIndex = zIndex;

		if (typeof(stylesToAdd) === 'object') {
			for (addedStyle in stylesToAdd) {
				style[addedStyle] = stylesToAdd[addedStyle];
			}
		}

		// style.backgroundColor = '#f00'; // debug

		appendElem.appendChild(this.div);

		this.div.innerHTML = this.getHTML( box.width, box.height );
	},

	getHTML: function(width, height) {
		// return HTML for movie
		var html = '';
		var flashvars = 'id=' + this.id +
			'&width=' + width +
			'&height=' + height;

		if (navigator.userAgent.match(/MSIE/)) {
			// IE gets an OBJECT tag
			var protocol = location.href.match(/^https/i) ? 'https://' : 'http://';
			html += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="'+protocol+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+width+'" height="'+height+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+ZeroClipboard.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/><param name="wmode" value="transparent"/></object>';
		}
		else {
			// all other browsers get an EMBED tag
			html += '<embed id="'+this.movieId+'" src="'+ZeroClipboard.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" wmode="transparent" />';
		}
		return html;
	},

	hide: function() {
		// temporarily hide floater offscreen
		if (this.div) {
			this.div.style.left = '-2000px';
		}
	},

	show: function() {
		// show ourselves after a call to hide()
		this.reposition();
	},

	destroy: function() {
		// destroy control and floater
		if (this.domElement && this.div) {
			this.hide();
			this.div.innerHTML = '';

			var body = document.getElementsByTagName('body')[0];
			try { body.removeChild( this.div ); } catch(e) {;}

			this.domElement = null;
			this.div = null;
		}
	},

	reposition: function(elem) {
		// reposition our floating div, optionally to new container
		// warning: container CANNOT change size, only position
		if (elem) {
			this.domElement = ZeroClipboard.$(elem);
			if (!this.domElement) this.hide();
		}

		if (this.domElement && this.div) {
			var box = ZeroClipboard.getDOMObjectPosition(this.domElement, this.appendElem);
			var style = this.div.style;
			style.left = '' + box.left + 'px';
			style.top = '' + box.top + 'px';
            style.width = '' + box.width + 'px';
            style.height = '' + box.height + 'px';
            this.div.innerHTML = this.getHTML( box.width, box.height );
		}
	},

	setText: function(newText) {
		// set text to be copied to clipboard
		this.clipText = newText;
		if (this.ready) this.movie.setText(newText);
	},

	addEventListener: function(eventName, func) {
		// add user event listener for event
		// event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel
		eventName = eventName.toString().toLowerCase().replace(/^on/, '');
		if (!this.handlers[eventName]) this.handlers[eventName] = [];
		this.handlers[eventName].push(func);
	},

	setHandCursor: function(enabled) {
		// enable hand cursor (true), or default arrow cursor (false)
		this.handCursorEnabled = enabled;
		if (this.ready) this.movie.setHandCursor(enabled);
	},

	setCSSEffects: function(enabled) {
		// enable or disable CSS effects on DOM container
		this.cssEffects = !!enabled;
	},

	receiveEvent: function(eventName, args) {
		// receive event from flash
		eventName = eventName.toString().toLowerCase().replace(/^on/, '');

		// special behavior for certain events
		switch (eventName) {
			case 'load':
				// movie claims it is ready, but in IE this isn't always the case...
				// bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function
				this.movie = document.getElementById(this.movieId);
				if (!this.movie) {
					var self = this;
					setTimeout( function() { self.receiveEvent('load', null); }, 1 );
					return;
				}

				// firefox on pc needs a "kick" in order to set these in certain cases
				if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) {
					var self = this;
					setTimeout( function() { self.receiveEvent('load', null); }, 100 );
					this.ready = true;
					return;
				}

				this.ready = true;
                try {
                    this.movie.setText( this.clipText );
                    this.movie.setHandCursor( this.handCursorEnabled );
                } catch (e) {
                    //silently skip IE8 error
                    // Upgrade ZeroClipboard to latest version
                    // Remove this if the STO Wizard layout + DM does not pass tests
                }


				break;

			case 'mouseover':
				if (this.domElement && this.cssEffects) {
					this.domElement.addClass('hover');
					if (this.recoverActive) this.domElement.addClass('active');
				}
				break;

			case 'mouseout':
				if (this.domElement && this.cssEffects) {
					this.recoverActive = false;
					if (this.domElement.hasClass('active')) {
						this.domElement.removeClass('active');
						this.recoverActive = true;
					}
					this.domElement.removeClass('hover');
				}
				break;

			case 'mousedown':
				if (this.domElement && this.cssEffects) {
					this.domElement.addClass('active');
				}
				break;

			case 'mouseup':
				if (this.domElement && this.cssEffects) {
					this.domElement.removeClass('active');
					this.recoverActive = false;
				}
				break;
		} // switch eventName

		if (this.handlers[eventName]) {
			for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) {
				var func = this.handlers[eventName][idx];

				if (typeof(func) == 'function') {
					// actual function reference
					func(this, args);
				}
				else if ((typeof(func) == 'object') && (func.length == 2)) {
					// PHP style object + method, i.e. [myObject, 'myMethod']
					func[0][ func[1] ](this, args);
				}
				else if (typeof(func) == 'string') {
					// name of function
					window[func](this, args);
				}
			} // foreach event handler defined
		} // user defined handler for event
	}

};

/*  common/js/Share.js  */
if (!window.share_data) {
    window.share_data = {};
}
if (!window.Share) {
    Share = {
        event_id: 0,
        results: {},
        URLdata: [],
        shareCallback: [],
        petition_id: false,
        resetUrls: function () {
            this.urls = {};
            this.urlsA = [];
        },
        addQS: function (d, c) {
            var a = [];
            for (var b in c) if (c[b]) a.push(b.toString() + '=' + encodeURIComponent(c[b]));
            return d + '?' + a.join('&');
        },
        getUrl: function (a) {
            return a.getAttribute('share_url') || window.location.href;
        },
        getType: function (a) {
            return a.getAttribute('type') || 'button_count';
        },
        pretty: function (a) {
            return a >= 1e+07 ? Math.round(a / 1e+06) + 'M' : (a >= 10000 ? Math.round(a / 1000) + 'K' : a);
        },
        updateButton: function (a) {
            var cid = $(a).attr('sharecid');
            var type = $(a).attr('sharetype');
            for (h in this.results[cid]) {
                if (this.results[cid]) {
                    a[type + '_count'] = this.results[cid][type + '_count'];
                } else {
                    a[type + '_count'] = 0;
                }
                this.displayBox(a, 0);
            }

        },
        getWindowInnerSize: function () {
            var width = 0;
            var height = 0;
            var elem = null;
            if ('innerWidth' in window) {
                // For non-IE
                width = window.innerWidth;
                height = window.innerHeight;
            } else {
                // For IE,
                if (('BackCompat' === window.document.compatMode)
                    && ('body' in window.document)) {
                    elem = window.document.body;
                } else if ('documentElement' in window.document) {
                    elem = window.document.documentElement;
                }
                if (elem !== null) {
                    width = elem.offsetWidth;
                    height = elem.offsetHeight;
                }
            }
            return [width, height];
        },
        getParentCoords: function () {
            var width = 0;
            var height = 0;
            if ('screenLeft' in window) {
                // IE-compatible variants
                width = window.screenLeft;
                height = window.screenTop;
            } else if ('screenX' in window) {
                // Firefox-compatible
                width = window.screenX;
                height = window.screenY;
            }
            return [width, height];
        },
        getCenteredCoords: function (width, height) {
            var parentSize = this.getWindowInnerSize();
            var parentPos = this.getParentCoords();
            var xPos = parentPos[0] +
                Math.max(0, Math.floor((parentSize[0] - width) / 2));
            var yPos = parentPos[1] +
                Math.max(0, Math.floor((parentSize[1] - height) / 2));
            return [xPos, yPos];
        },
        displayBox: function (a, d) {
            var type = $(a).attr('sharetype');
            if (typeof(a[type + '_count']) == 'number' && a[type + '_count'] >= d) {
                $('.' + $(a).attr('sharetype') + '_share_counter_' + $(a).attr('sharecid')).each(function () {
                    $(this).html(Share.pretty(a[type + '_count']))
                });
            }
        },
        addEvent: function (href) {
            if ('undefined' !== typeof rsvp_event_id) {
                return href + '&id=' + rsvp_event_id + '';
            }
            return href;
        },
        renderButton: function (c) {
            var bIsMobile = (window.bIsMobile != undefined) ? window.bIsMobile : false;
            var cid = $(c).attr('sharecid');
            var type = $(c).attr('sharetype');
            var lang = $(c).attr('sharelang');
            var href = $(c).attr('href');
            var method = $(c).attr('sharemethod');
            if (!method || bIsMobile) {
                method = 'share';
            }
            /***************************FACEBOOK**************************/
            var global_response = null;

            function is_valid_post_response(response) {
                return (typeof response !== 'undefined' && response !== null && typeof response.post_id !== 'undefined');
            }

            var stream_callback = function (post) {
                if (is_valid_post_response(post)) {
                    // Save share action id
                    $.ajax({
                        url:'/act/ajax_save_fb_share.php',
                        dataType: 'json',
                        type: 'POST',
                        data: {
                            user_hash: getUserHash(true),
                            action_type: 'og.shares',
                            action_id: post.post_id
                        }
                    });
                }
                $(document).facebookReady(function () {
                    FB.getLoginStatus(
                        function (response) {
                            if (response.session) {
                                //login_response(response);
                                var a = document.createElement('script');

                                if (is_valid_post_response(post)) {
                                    var send_data = {
                                        action: 'save_share_counter',
                                        cid: cid,
                                        lang: lang,
                                        random: Math.random(),
                                        value: 'shared',
                                        fb_uid: response.session.uid
                                    };
                                    if (Share.petition_id) {
                                        send_data.petition_id = Share.petition_id;
                                    }
                                    a.src = Share.addQS('/act/facebook.php', send_data);
                                } else {
                                    var send_data = {
                                        action: 'save_share_counter',
                                        cid: cid,
                                        lang: lang,
                                        random: Math.random(),
                                        value: 'closed',
                                        fb_uid: response.session.uid
                                    };
                                    if (Share.petition_id) {
                                        send_data.petition_id = Share.petition_id;
                                    }
                                    a.src = Share.addQS('/act/facebook.php', send_data);
                                }
                                Share.insert(a);
                                if ('undefined' !== typeof post && null !== post && post.post_id) {
                                    Share.updateHiddenCounter(c, 'shared', { fb_uid: response.session.uid });
                                } else {
                                    Share.updateHiddenCounter(c, 'closed', { fb_uid: response.session.uid });
                                }
                            } else {
                                //FB.login(login_response);
                            }
                        }
                    );
                });
            };
            var facebook_click = function (e) {
                var $el = $(this);
                e.preventDefault();
                $('body').trigger('sharing_started');
                Share.updateCounter(c);

                var login_response = function (response) {
                    if (response.session) {
                        Share.updateHiddenCounter(c, 'user_clicked', { fb_uid: response.session.uid });
                        global_response = response;
                    }
                };

                if (method === 'tagging' && (typeof($.fn.FBTagFriendsWidget) == 'function')) {
                    var options = {sMethod: method};
                    if (!window.oFBTagWidget) {
                        if ($el.data('title')) {
                            $('#dialogTagFBFriendsTitle').html($el.data('title'));
                        }
                        if ($el.data('description')) {
                            $('#dialogTagFBFriendsText').html($el.data('description'));
                        }

                        // check if scope was provided let's use it
                        if ($el.data('scope') !== undefined) {
                            options.scope = $el.data('scope');
                        }

                        window.oFBTagWidget = $('div#dialogTagFBFriends').FBTagFriendsWidget(options);
                    }
                    window.oFBTagWidget.process(null, cid);
                } else {
                    $(document).facebookReady(function () {
                        FB.ui({
                            display: 'popup',
                            method: 'share',
                            href: Share.addEvent(share_data[cid].facebook.href)
                        }, stream_callback);
                    });

                    Share.displayBox(this, 1);

                    $('body').trigger('sharing_complete');

                    return false;
                }
            };

            /***********************END OF FACEBOOK***********************/

            /****************************TUMBLR***************************/
            var tumblr_click = function () {
                $('body').trigger('sharing_started');

                Share.updateCounter(c);
                var coordinates = Share.getCenteredCoords(500, 420);
                window.open('http://www.tumblr.com/share/link?url=' + Share.addEvent(share_data[cid].tumblr.href) + '&name=' + share_data[cid].tumblr.text + '&description=' + share_data[cid].tumblr.description, "tweetwindow", "status=1,toolbar=1,height=420,width=500" + ",left=" + coordinates[0] + ",top=" + coordinates[1]);

                $('body').trigger('sharing_complete');
                return false;
            };
            /************************END OF TUMBLR*************************/

            /****************************TWITTER ***************************/
            var twitter_click = function () {
                $('body').trigger('sharing_started');

                Share.updateCounter(c);
                var coordinates = Share.getCenteredCoords(500, 350);
                var sWindowUrl = 'http://twitter.com/share?related=Avaaz&url=' + Share.addEvent(share_data[cid].twitter.href) + '&text=' + encodeURIComponent(share_data[cid].twitter.text) /*decodeURIComponent(j)*/;

                if (typeof(sRetweetUrl) != 'undefined') {
                    sWindowUrl = sRetweetUrl;
                }


                window.open(sWindowUrl, "tweetwindow", "status=1,toolbar=1,height=350,width=500" + ",left=" + coordinates[0] + ",top=" + coordinates[1]);

                $('body').trigger('sharing_complete');
                return false;
            };
            /************************END OF TWITTER*************************/

            /*************************** VK ****************************/
            var vk_click = function () {
                Share.updateCounter(c);
                window.open(decodeURIComponent(Share.addEvent(share_data[cid].vk.href)), "vkwindow", "status=1,toolbar=1,height=650,width=1024");
                return false;
            };
            /************************END OF VK*************************/

            var isValidSelector = function (selector) {
                try {
                    var $element = $(selector);
                } catch(error) {
                    return false;
                }
                return ($element.length > 0);
            };

            /****************************EMAIL ***************************/
            var email_click = function () {

                $('body').trigger('sharing_started');

                Share.updateCounter(c);
                if (!c.email_clicked) {
                    c.email_count += 1;
                    c.email_clicked = true;
                }

                var bStats = true;
                if ($(this).data('stats')) {
                    bStats = !!$(this).data('stats');
                }

                var sSubject = $(this).data('subject');
                if (sSubject !== undefined) {
                    if (isValidSelector(sSubject)) {
                        sSubject = $(sSubject).val();
                    }
                } else {
                    sSubject = '';
                }

                var sBody = $(this).data('body');
                if (sBody !== undefined) {
                    var body = $(sBody).val();
                    if (isValidSelector(sBody) && body !== undefined && body !== '') {
                        sBody = body;
                    }
                } else {
                    sBody = '';
                }


                var domain = GetEmailDomain();
                var mailto = true;
                domain = domain && !$(c).data('mobile') ? domain : 'other';

                sBody = getEdgeData({event: (('undefined' !== typeof rsvp_event_id) ? 'id=' + rsvp_event_id : '')}, (sBody !== '' ? sBody : share_data[cid].email.body));
                sBody = $('<textarea />').html(sBody).text();

                switch (domain) {
                    case 'gmail':
                        mailto = false;
                        href = Share.addQS('https://mail.google.com/mail/', {
                            view: 'cm',
                            fs: 1,
                            to: '',
                            su: sSubject !== '' ? sSubject : share_data[cid].email.subject,
                            body: sBody,
                            ui: 2,
                            shva: 1
                        });
                        break;
                    default:
                        href = Share.addQS('mailto:', {
                            subject: sSubject !== '' ? sSubject : share_data[cid].email.subject,
                            body: sBody
                        });
                        break;
                }

                Share.displayBox(this, 1);
                $('body').trigger('sharing_complete');

                if (!mailto) {
                    window.open(href, "emailwindow", "status=1,toolbar=1,height=650,width=1024");
                } else {
                    $(c).attr('target', '_blank');
                    $(c).attr('href', href);
                    return true;
                }

                return false;
            };
            var email_popup = null;
            var email_click_popup = function () {

                var bStats = true;
                if ($(this).data('stats')) {
                    bStats = !!$(this).data('stats');
                }
                var domain = GetEmailDomain();
                if (!c.email_clicked) {
                    c.email_count += 1;
                    c.email_clicked = true;
                    var send_data = {campaign_id: cid, domain: domain};
                    if (Share.petition_id) {
                        send_data.petition_id = Share.petition_id;
                    }
                    if (bStats) {
                        jQuery.post('/act/ajax_send_stats.php', send_data, function () {
                        });
                    }
                }
                if (email_popup) {
                    email_popup.trigger('click');
                } else {
                    if (!window.colorbox_dialogs) {
                        colorbox_dialogs = {};
                    }
                    colorbox_dialogs.email_popup = $.colorbox(
                        {
                            opacity: 0.5,
                            inline: true,
                            href: "#" + $(c).attr('use_popup'),
                            showClose: ('undefined' !== typeof $(c).data('showclose') ? $(c).data('showclose') : true),
                            onClosed: function () {
                                openid.closeColorbox();
                            },
                            onComplete: function () {
                                $(this).colorbox.resize();
                            }
                        });
                }
                //$(c).attr('href', href);
                Share.displayBox(this, 1);
                return false;
            }
            /************************END OF EMAIL*************************/
            if (type != 'email')
                $(c).click(function () {
                    return false;
                }); // fix for IE redirect
            if (share_data[cid] && share_data[cid][type]) {
                switch (type) {
                    case 'facebook':
                        /****************** ADD FACEBOOK SHARE URL ******************/
                        $(c).attr('href', this.addQS('http://www.avaaz.org/act/facebook_share.php', {
                            cid: cid,
                            lang: lang,
                            src: 'sp'
                        }));
                        $(c).click(facebook_click);
                        /************************************************************/
                        break;
                    case 'tumblr':
                        /****************** ADD TUMBLR SHARE URL ******************/
                        $(c).attr('href', 'http://www.tumblr.com/share/link?url=' + share_data[cid].tumblr.href + '&name=' + share_data[cid].tumblr.text + '&description=' + share_data[cid].tumblr.description);
                        $(c).click(tumblr_click);
                        /************************************************************/
                        break;
                    case 'twitter':
                        /****************** ADD TWITTER SHARE URL ******************/
                        $(c).attr('href', 'http://twitter.com/share?related=Avaaz&url=' + share_data[cid].twitter.href + '&text=' + share_data[cid].twitter.text);
                        $(c).click(twitter_click);
                        /************************************************************/
                        break;
                    case 'email':
                        /****************** ADD EMAIL SHARE URL ******************/
                        $(c).attr('href', 'javascript:void(0);');

                        $(c).click(function (e) {
                            if ($(this).attr('use_popup')) {
                                e.preventDefault();
                                return email_click_popup.apply(this);
                            } else {
                                return email_click.apply(this);
                            }
                        });

                        /************************************************************/
                        break;
                    case 'vk':
                        /****************** ADD VK SHARE URL ******************/
                        $(c).attr('href', share_data[cid].vk.href);
                        $(c).click(vk_click);
                        /************************************************************/
                        break;
                }
            }
            c.fb_rendered = true;
        },
        insert: function (a) {
            (document.getElementsByTagName('HEAD')[0] || document.body).appendChild(a);
        },
        renderAll: function () {
            $('.share').filter(function () {
                return ('undefined' === typeof $(this).attr('sharetype') ? false : true);
            }).each(function (i) {
                Share.URLdata[i] = this;
            });
            var c = Share.URLdata;
            var a = c.length;
            for (var b = 0; b < a; b++) {
                if (!c[b].fb_rendered) {
                    this.renderButton(c[b]);
                }
                if (this.results[$(c[b]).attr('sharecid')]) this.updateButton(c[b]);
            }
        },
        fetchData: function () {
            var data = {};
            for (var h in Share.URLdata) {
                if ('function' === typeof Share.URLdata[h])
                    continue;
                var link = Share.URLdata[h];
                var type = $(link).attr('sharetype');
                var cid = $(link).attr('sharecid');
                if (share_data[cid]) {
                    if ('undefined' === typeof data[cid]) {
                        data[cid] = {};
                    }
                    if ('undefined' === typeof data[cid]['type']) {
                        data[cid]['type'] = {};
                    }
                    data[cid]['type'][type] = 1;
                    /** ADDON FOR PETITIONS ***/
                    if (share_data[cid].petition) {
                        Share.petition_id = share_data[cid].petition;
                    }
                }
            }
            var send_data = {
                v: '1.0',
                action: 'get_share_count',
                format: 'json',
                data: data
            };
            if (Share.petition_id) {
                send_data.petition_id = Share.petition_id;
            }
            this.resetUrls();

            $.ajax(
                {
                    url: '/act/share_stats.php?' + $.param(send_data),
                    type: 'GET',
                    dataType: 'json',
                    success: function (data) {
                        if (data)
                            share_render(data);
                    }
                }
            );
        },
        runShareCallback: function (type) {
            for (var i = 0; i <= Share.shareCallback.length; i++) {
                if ('function' === typeof Share.shareCallback[i]) {
                    Share.shareCallback[i](type);
                }
            }
        },
        updateCounter: function (el) {
            el = $(el);
            if (Share.updateHiddenCounter(el, 'clicked', {})) {
                var elShareButton = el[0];
                var sType = $(elShareButton).attr('sharetype');
                if ($.inArray(sType, ['twitter', 'tumblr', 'email', 'vk']) != -1) {
                    if (!elShareButton[sType + '_clicked']) {
                        elShareButton[sType + '_count'] += 1;
                        elShareButton[sType + '_clicked'] = true;
                    }
                } else {
                    if (sType == 'facebook') {
                        if (!elShareButton['fb_clicked']) {
                            elShareButton['facebook_count'] += 1;
                            elShareButton['fb_clicked'] = true;
                        }
                    }
                }
                Share.displayBox(elShareButton, 1);
                Share.runShareCallback(sType);
            }
        },
        updateHiddenCounter: function (el, sAction, oExtras) {
            var iCid = $(el).attr('sharecid');
            var sType = $(el).attr('sharetype');
            var sLang = $(el).attr('sharelang');
            if (iCid && sType && sLang) {
                if (sType == 'email') {
                    return Share.updateEmailCounter(el);
                } else {
                    var oSendData = {
                        action: 'save_share_counter',
                        cid: iCid,
                        lang: sLang,
                        random: Math.random(),
                        value: sAction
                    };
                }
                if (Share.petition_id) {
                    oSendData.petition_id = Share.petition_id;
                }
                $.extend(oSendData, oExtras);
                var sclick = document.createElement('script');
                var sUpdateScripts = {
                    email: 'ajax_send_stats',
                    facebook: 'facebook',
                    twitter: 'twitter',
                    tumblr: 'tumblr',
                    vk: 'vkontakte'
                };
                if (typeof sUpdateScripts[sType] !== 'undefined') {
                    sclick.src = Share.addQS('/act/' + sUpdateScripts[sType] + '.php', oSendData);
                    Share.insert(sclick);
                    return true;
                }
            }
            return false;
        },
        updateEmailCounter: function (el) {
            var bStats = true;
            if ($(el).data('stats')) {
                bStats = !!$(el).data('stats'); // convert to boolean
            }
            if (bStats) {
                var sDomain = GetEmailDomain();
                sDomain = sDomain && !$(el).data('mobile') ? sDomain : 'other';
                oSendData = {
                    campaign_id: $(el).attr('sharecid'),
                    domain: sDomain
                };
                if (Share.petition_id) {
                    oSendData.petition_id = Share.petition_id;
                }
                $.post('/act/ajax_send_stats.php', oSendData);
                return true;
            }
            return false;
        },
        renderPass: function () {
            Share.renderAll();
            if (Share.URLdata.length > 0) {
                Share.fetchData();
            }
        },
        _onFirst: function () {
            this.resetUrls();
            window.share_render = function (b) {
                for (var h in b) Share.results[h] = b[h];
                Share.renderAll();
            };
            this.renderPass();
        },
        init: function () {
            if (typeof bDoNotRunShare === 'undefined' || !bDoNotRunShare) {
                Share._onFirst();
            }
        }
    };
    $(document).ready(function () {
        Share.init();
    });
}

/*  new/common/js/form-spread.js  */
function loadClipButton() {
    var elm = this,
        $container = $(this).data('container') || '',
        clip,
        clips,
        copy_blurb = this.copy_blurb || window.copy_blurb,
        copied_blurb = this.copied_blurb || window.copied_blurb;
    ZeroClipboard.setMoviePath('/common/js/ZeroClipboard.swf');
    clip = new ZeroClipboard.Client();
    clips = $(elm).data('ZeroClipboard') || [];
    clips.push(clip);
    $(elm).data('ZeroClipboard', clips);
    clip.setText(''); // will be set later on mouseDown
    clip.setHandCursor(true);
    clip.setCSSEffects(true);
    clip.addEventListener('mouseDown', function (client) {
        // set text to copy here
        clip.setText($("#spread_copy_text", $container).val());
        //$("#spread_copy_text").trigger('click').focus();
        // alert("mouse down");
    });
    clip.addEventListener('mouseOver', function (client) {
        // set text to copy here
        $('#spread_copy_button span', $container).eq(0).html(copy_blurb);
        clip.setText($("#spread_copy_text", $container).val());
        //$("#spread_copy_text").trigger('click').focus();
        // alert("mouse down");
    });
    clip.addEventListener('mouseOut', function (client) {
        // set text to copy here
        $('#spread_copy_button span', $container).eq(0).html(copy_blurb);
        clip.setText($("#spread_copy_text", $container).val());
        //$("#spread_copy_text").trigger('click').focus();
        // alert("mouse down");
    });
    clip.addEventListener('mouseUp', function (client) {
        // set text to copy here
        $('#spread_copy_button span', $container).eq(0).html(copied_blurb);
        clip.setText($("#spread_copy_text", $container).val());
        $("#spread_copy_text", $container).trigger('click').focus();
        // alert("mouse down");
    });
    // set the clip text to our innerHTML
    clip.glue(this, $("#label_copy_click", $container).parent()[0]);
}

function loadClipLabel() {
    var $container = $(this).data('container') || '';
    var elm = this;
    ZeroClipboard.setMoviePath('/common/js/ZeroClipboard.swf');
    var clip = new ZeroClipboard.Client();
    clip.setText(''); // will be set later on mouseDown
    clip.setHandCursor(true);
    clip.setCSSEffects(true);
    clip.addEventListener('mouseDown', function (client) {
        // set text to copy here
        clip.setText($("#spread_copy_text", $container).val());
        //$("#spread_copy_text").trigger('click').focus();
        // alert("mouse down");
    });
    clip.addEventListener('mouseOver', function (client) {
        // set text to copy here
        clip.setText($("#spread_copy_text", $container).val());
        //$("#spread_copy_text").trigger('click').focus();
        // alert("mouse down");
    });
    clip.addEventListener('mouseOut', function (client) {
        // set text to copy here
        clip.setText($("#spread_copy_text", $container).val());
        //$("#spread_copy_text").trigger('click').focus();
        // alert("mouse down");
    });
    clip.addEventListener('mouseUp', function (client) {
        // set text to copy here
        clip.setText($("#spread_copy_text", $container).val());
        $("#spread_copy_text", $container).trigger('click').focus();
        // alert("mouse down");
    });
    // set the clip text to our innerHTML
    clip.glue(this, $("#label_copy_click", $container).parent()[0]);
}

function _formSpreadDisplayShareLinks(cid, lang, fb_dialog, bgmail, $container) {
	
    $container = $container || '';
    if (!share_data[cid]) return;

    var domen = GetEmailDomain();
    if (true == bgmail) {
        domen = 'gmail';
    }
    if ('en' !== lang && ('gmail' !== domen)) {
        delete social_data['email'];
    }
    var last = 0;
    var iteration = 0;
    var html = '';
    for (var key in social_data) {
        last++;
    }
    for (var key in social_data) {
        iteration++;
        var first = (0 !== (iteration % 2));
        var social = social_data[key].name;
        var text = social_data[key].text;
        if (first) {
            html += '<div class="social_wc ' + ((1 < (last - iteration)) ? 'border_bottom' : '') + '">';
        }
        html += '<div class="' + social + '_wc ' + ((first && (last !== iteration)) ? 'border_right' : '') + '">';
        html += '<a';
        if (('twitter' === social) && share_data[cid].twitter) {
            html += ' href="https://twitter.com/intent/tweet?related=Avaaz&text=' + share_data[cid].twitter.text +
                '&url=' + encodeURIComponent(share_data[cid].twitter.href) + '" ';
        } else {
            html += ' href="#" ';
        }
        html += 'sharetype="' + social + '"';
        html += 'sharecid="' + cid + '"';
        html += 'sharelang="' + lang + '"';
        html += 'sharemethod="' + fb_dialog + '"';
        html += 'class="share"';
        html += 'title="' + social + '"><span>' + social + '</span></a> <span class=';
        html += '"counter ' + social + '_share_counter_' + cid + '" >0</span> <span class="share label"';
        html += 'sharetype="' + social + '"';
        html += 'sharecid="' + cid + '"';
        html += 'sharemethod="' + fb_dialog + '"';
        html += 'sharelang="' + lang + '"';
        html += '>' + text + '</span>';
        html += '</div><!--' + social + '-->';
        if (0 === (iteration % 2) || (iteration === last)) {
            html += '</div>';
        }
    }

    $('#share-links-wrapper', $container).html(html);

    if (typeof share_data[cid].copy != 'undefined') {
        $('#spread_copy_text', $container).val(share_data[cid].copy.campaign_url);
    }

    if (typeof Share != 'undefined') {
        Share._onFirst();
    }

    if (typeof rsvp_event_id != 'undefined') {
        $('#spread_copy_text', $container).val($('#spread_copy_text', $container).val() + '&id=' + rsvp_event_id);
    }

}

/*  new/common/js/async_done.js  */
function async_load_function() {
    if (typeof(async_load) != 'undefined' && async_load) {
	var func = async_load.pop();
	while (func) {
	    func();
	    func = async_load.pop();
	};
    }
    setTimeout(async_load_function,1000);
};
async_load_function();
