
/*  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/popuplib.js  */
//  Copyright 2009 Google Inc.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.


//  PopupManager is a library to facilitate integration with OpenID
//  identity providers (OP)s that support a pop-up authentication interface.
//  To create a popup window, you first construct a popupOpener customized
//  for your site and a particular identity provider, E.g.:
//
//  var googleOpener = popupManager.createOpener(openidParams);
//
//  where 'openidParams' are customized for Google in this instance.
//  (typically you just change the openidpoint, the version number
//  (the openid.ns parameter) and the extensions based on what
//  the OP supports.
//  OpenID libraries can often discover these properties
//  automatically from the location of an XRD document.
//
//  Then, you can either directly call
//  googleOpener.popup(width, height), where 'width' and 'height' are your choices
//  for popup size, or you can display a button 'Sign in with Google' and set the
//..'onclick' handler of the button to googleOpener.popup()

var popupManager = {};

// Library constants

popupManager.constants = {
  'darkCover' : 'popupManager_darkCover_div',
  'darkCoverStyle' : ['position:absolute;',
                      'top:0px;',
                      'left:0px;',
                      'padding-right:0px;',
                      'padding-bottom:0px;',
                      'background-color:#000000;',
                      'opacity:0.5;', //standard-compliant browsers
                      '-moz-opacity:0.5;',           // old Mozilla 
                      'filter:alpha(opacity=50);',  // IE
                      'z-index:999999;',
                      'width:100%;',
                      'height:100%;'
                      ].join(''),
  'openidSpec' : {
     'identifier_select' : 'http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select',
     'namespace2' : 'http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0'
  } };

// Computes the size of the window contents. Returns a pair of
// coordinates [width, height] which can be [0, 0] if it was not possible
// to compute the values.
popupManager.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];
};

// Computes the coordinates of the parent window.
// Gets the coordinates of the parent frame
popupManager.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];
};

// Computes the coordinates of the new window, so as to center it
// over the parent frame
popupManager.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];
};

//  A utility class, implements an onOpenHandler that darkens the screen
//  by overlaying it with a semi-transparent black layer. To use, ensure that
//  no screen element has a z-index at or above 10000.
//  This layer will be suppressed automatically after the screen closes.
//
//  Note: If you want to perform other operations before opening the popup, but
//  also would like the screen to darken, you can define a custom handler
//  as such:
//  var myOnOpenHandler = function(inputs) {
//    .. do something
//    popupManager.darkenScreen();
//    .. something else
//  };
//  Then you pass myOnOpenHandler as input to the opener, as in:
//  var openidParams = {};
//  openidParams.onOpenHandler = myOnOpenHandler;
//  ... other customizations
//  var myOpener = popupManager.createOpener(openidParams);
popupManager.darkenScreen = function() {
  var darkCover = window.document.getElementById(window.popupManager.constants['darkCover']);
  if (!darkCover) {
    darkCover = window.document.createElement('div');
    darkCover['id'] = window.popupManager.constants['darkCover'];
    darkCover.setAttribute('style', window.popupManager.constants['darkCoverStyle']);
    window.document.body.appendChild(darkCover);
    jQuery(darkCover).height($(document).height());
    $('body').append('<div id="TB_window"><img src="/images/ajax-loader2.gif" /></div>');
    $('#TB_window').attr('style', [
        'position: fixed;',
        'text-align:left;',
        'top:50%;',
        'left:50%;',
		'display:block;',
        'z-index:999999;'
    ].join(''));
  }
  
  darkCover.style.visibility = 'visible';
  $("#TB_window").css({marginLeft: '-' + parseInt((300 / 2),10) + 'px', width: 210 + 'px'});
    if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
        $("#TB_window").css({marginTop: '-' + parseInt((300 / 2),10) + 'px'});
    }
  $("#TB_window").hide();
};

//  Returns a an object that can open a popup window customized for an OP & RP.
//  to use you call var opener = popupManager.cretePopupOpener(openidParams);
//  and then you can assign the 'onclick' handler of a button to
//  opener.popup(width, height), where width and height are the values of the popup size;
//
//  To use it, you would typically have code such as:
//  var myLoginCheckFunction = ...  some AJAXy call or page refresh operation
//  that will cause the user to see the logged-in experience in the current page.
//  var openidParams = { realm : 'openid.realm', returnToUrl : 'openid.return_to',
//  opEndpoint : 'openid.op_endpoint', onCloseHandler : myLoginCheckFunction,
//  shouldEncodeUrls : 'true' (default) or 'false', extensions : myOpenIDExtensions };
//
//  Here extensions include any OpenID extensions that you support. For instance,
//  if you support Attribute Exchange v.1.0, you can say:
//  (Example for attribute exchange request for email and name,
//  assuming that shouldEncodeUrls = 'true':)
//  var myOpenIDExtensions = {
//      'openid.ax.ns' : 'http://openid.net/srv/ax/1.0',
//      'openid.ax.type.email' : 'http://axschema.org/contact/email',
//      'openid.ax.type.name1' : 'http://axschema.org/namePerson/first',
//      'openid.ax.type.name2' : 'http://axschema.org/namePerson/last',
//      'openid.ax.required' : 'email,name1,name2' };
//  Note that the 'ui' namespace is reserved by this library for the OpenID
//  UI extension, and that the mode 'popup' is automatically applied.
//  If you wish to make use of the 'language' feature of the OpenID UI extension
//  simply add the following entry (example assumes the language requested
//  is Swiss French:
//  var my OpenIDExtensions = {
//    ... // other extension parameters
//    'openid.ui.language' : 'fr_CH',
//    ... };
popupManager.createPopupOpener = (function(openidParams) {
  var interval_ = null;
  var popupWindow_ = null;
  var that = this;
  var shouldEscape_ = ('shouldEncodeUrls' in openidParams) ? openidParams.shouldEncodeUrls : true;
  var encodeIfRequested_ = function(url) {
    return (shouldEscape_ ? encodeURIComponent(url) : url);
  };
  var identifier_ = ('identifier' in openidParams) ? encodeIfRequested_(openidParams.identifier) :
      this.constants.openidSpec.identifier_select;
  var identity_ = ('identity' in openidParams) ? encodeIfRequested_(openidParams.identity) :
      this.constants.openidSpec.identifier_select;
  var openidNs_ = ('namespace' in openidParams) ? encodeIfRequested_(openidParams.namespace) :
      this.constants.openidSpec.namespace2;
  var onOpenHandler_ = (('onOpenHandler' in openidParams) &&
      ('function' === typeof(openidParams.onOpenHandler))) ?
          openidParams.onOpenHandler : this.darkenScreen;
  var onCloseHandler_ = (('onCloseHandler' in openidParams) &&
      ('function' === typeof(openidParams.onCloseHandler))) ?
          openidParams.onCloseHandler : null;
  var returnToUrl_ = ('returnToUrl' in openidParams) ? openidParams.returnToUrl : null;
  var realm_ = ('realm' in openidParams) ? openidParams.realm : null;
  var endpoint_ = ('opEndpoint' in openidParams) ? openidParams.opEndpoint : null;
  var extensions_ = ('extensions' in openidParams) ? openidParams.extensions : null;

  // processes key value pairs, escaping any input;
  var keyValueConcat_ = function(keyValuePairs) {
    var result = "";
    for (key in keyValuePairs) {
      result += ['&', key, '=', encodeIfRequested_(keyValuePairs[key])].join('');
    }
    return result;
  };

  //Assembles the OpenID request from customizable parameters
  var buildUrlToOpen_ = function() {
    var connector = '&';
    var encodedUrl = null;
    var urlToOpen = null;
    if ((null === endpoint_) || (null === returnToUrl_)) {
      return;
    }
    if (endpoint_.indexOf('?') === -1) {
      connector = '?';
    }
    encodedUrl = encodeIfRequested_(returnToUrl_);
    urlToOpen = [ endpoint_, connector,
        'openid.ns=', openidNs_,
        '&openid.mode=checkid_setup',
        '&openid.claimed_id=', identifier_,
        '&openid.identity=', identity_,
        '&openid.return_to=', encodedUrl ].join('');
    if (realm_ !== null) {
      urlToOpen += "&openid.realm=" + encodeIfRequested_(realm_);
    }
    if (extensions_ !== null) {
      urlToOpen += keyValueConcat_(extensions_);
    }
    urlToOpen += '&openid.ns.ui=' + encodeURIComponent(
        'http://specs.openid.net/extensions/ui/1.0');
    urlToOpen += '&openid.ui.mode=popup';
    return urlToOpen;
  };

  // Tests that the popup window has closed
  var isPopupClosed_ = function() {
    return (!popupWindow_ || popupWindow_.closed || window['provider_popup_window']);
  };

  // Check to perform at each execution of the timed loop. It also triggers
  // the action that follows the closing of the popup
  var waitForPopupClose_ = function() {
    
    if (isPopupClosed_()) {
      
      popupWindow_ = null;
      var close = function() {
      
            var darkCover = window.document.getElementById(window.popupManager.constants['darkCover']);
            if (darkCover) {        
                $("#TB_window").hide();
                darkCover.style.visibility = 'hidden';
            }
      }
      if (onCloseHandler_ !== null) {
        
        document.getElementById('TB_window').style.display = 'block';
        setTimeout(function(){
            onCloseHandler_();
            close();
        }, 1000);
      } else {
        close();
      }
      if ((null !== interval_)) {
        window.clearInterval(interval_);
        interval_ = null;
      }
    }
  };

  return {
    // Function that opens the window.
    popup: function(width, height) {
      var urlToOpen = buildUrlToOpen_();
      if (onOpenHandler_ !== null) {
        onOpenHandler_();
      }
      
      window['provider_popup_window'] = false;
      var coordinates = that.getCenteredCoords(width, height);
      popupWindow_ = window.open(urlToOpen, "",
          "width=" + width + ",height=" + height +
          ",status=1,location=1,resizable=yes" +
          ",left=" + coordinates[0] +",top=" + coordinates[1]);
      interval_ = window.setInterval(waitForPopupClose_, 80);
      return true;
    }
  };
});
/*  new/common/js/jquery.openid.js  */
/*
	Simple OpenID Plugin
	http://code.google.com/p/openid-selector/
	
	This code is licensed under the New BSD License.
*/

var providers;
var openid;
(function ($) {
openid = {
	version : '1.3-beta1', // version constant
	demo : false,
    eheight: 28,
	demo_text : null,
	cookie_expires : 6 * 30, // 6 months.
	cookie_name : 'openid_provider',
	cookie_path : '/',

	img_path : '/new/images/blue/sprite/',
	locale : null, // is set in openid-<locale>.js
	sprite : null, // usually equals to locale, is set in
	// openid-<locale>.js
	signin_text : null, // text on submit button on the form
	all_small : false, // output large providers w/ small icons
	no_sprite : false, // don't use sprite image
	image_title : '{provider}', // for image title

	input_id : null,
	provider_url : null,
	provider_id : null,
    
    load_limit: 20,
    
    load_from:0,
    
    load_finished: true,
	/**
	 * Class constructor
	 * 
	 * @return {Void}
	 */
	init : function(input_id) {
		providers = $.extend({}, providers_large, providers_small);
        var img = new Image(300, 300);
        img.src = "/images/ajax-loader2.gif";
		var openid_btns = $('#openid_btns');
		this.input_id = input_id;
		$('#openid_choice').show();
		$('#openid_input_area').empty();
		var i = 0;
		// add box for each provider
		for (id in providers_large) {
			box = this.getBoxHTML(id, providers_large[id], (this.all_small ? 'small' : 'large'), i++);
			openid_btns.append(box);
		}
		if (providers_small) {
			openid_btns.append('<br/>');
			for (id in providers_small) {
				box = this.getBoxHTML(id, providers_small[id], 'small', i++);
				openid_btns.append(box);
			}
		}
        $("#imported_contact").delegate("input", "click", function(){
            var input = $('#emails');
            var str=this.value+", ";
            if(this.checked) {
                input.val(input.val()+ str);
                window.loaded_contacts[$(this).attr('index')]['checked'] = true;
            } else {
                input.val(input.val().replace(str,""));
                window.loaded_contacts[$(this).attr('index')]['checked'] = false;
            }
            input.focus();
            input.trigger('keydown.infieldlabel');
            input.blur();
            input.focus();
            
            return;
        });
        $("#imported_contact").scroll(function(){
            //if (openid.load_finished) return;
            //var max_height = this.scrollHeight - $(this).innerHeight();
            //if ($(this).scrollTop() > (max_height / 2)) {
                openid.load_contacts();
            //}
        });
		$('#openid_form').submit(this.submit);
		/*var box_id = this.readCookie();
		if (box_id) {
			this.signin(box_id, true);
		}*/
	},

	/**
	 * @return {String}
	 */
	getBoxHTML : function(box_id, provider, box_size, index) {
		if (this.no_sprite) {
			var image_ext = box_size == 'small' ? '.ico.gif' : '.gif';
			return '<a title="' + this.image_title.replace('{provider}', provider["name"]) + '" href="javascript:openid.signin(\'' + box_id + '\');"'
					+ ' style="background: #FFF url(' + this.img_path + '../images.' + box_size + '/' + box_id + image_ext + ') no-repeat center center" '
					+ 'class="' + box_id + ' openid_' + box_size + '_btn ' + (provider.className?provider.className:'') + '"></a>';
		}
		var x = box_size == 'small' ? -index * 24 : -index * 100;
		var y = box_size == 'small' ? -60 : 0;
		if (provider.background){
			if (null !== provider.background.x)
			{
				x = provider.background.x;
			}
			if (null !== provider.background.y)
			{
				y = provider.background.y;
			}
		}
		return '<a title="' + this.image_title.replace('{provider}', provider["name"]) + '" href="javascript:openid.signin(\'' + box_id + '\');"'
				+ ' style="background: #FFF url(' + this.img_path + 'email_sprite2.png) no-repeat; background-position: ' + x + 'px ' + y + 'px" '
				+ 'class="' + box_id + ' openid_' + box_size + '_btn ' + (provider.className?provider.className:'') + '"></a>';
	},
    keyValueConcat_: function(keyValuePairs) {
        var result = "";
        for (key in keyValuePairs) {
          result += ['&', key, '=', encodeURIComponent(keyValuePairs[key])].join('');
        }
        return result;
    },
    buildUrlToOpen_: function(endpoint_, extensions_) {
        var connector = '&';
        var encodedUrl = null;
        var urlToOpen = null;
        if (endpoint_.indexOf('?') === -1) {
          connector = '?';
        }
        urlToOpen = [ endpoint_, connector].join('');
        if (extensions_ !== null) {
          urlToOpen += this.keyValueConcat_(extensions_);
        }
        return urlToOpen;
  },
	/**
	 * Provider image click
	 * 
	 * @return {Void}
	 */
    load_contacts: function(){
        
        if (!contacts) return;
        var html = '';
        var added = 0;
        var f_position = 10;
        var f_position_ready = false;
        var top = $("#imported_contact").scrollTop();
        var currpos = parseInt(top / openid.eheight);
        var pos_diff = top - (currpos * openid.eheight);
        if ((currpos - f_position) > 0) {
            currpos = currpos - f_position;
            f_position_ready = true;
        } else {
            currpos = 0;
            f_position = 0;
        }
        var limit = this.load_limit + currpos + f_position;
        var limited = true;
        for(var i = currpos; i <= limit; i++) {
            if (!window.loaded_contacts[i]){ this.load_finished = true; break;}
            added++;
            this.load_from = i + 1;
            var name = window.loaded_contacts[i]['name'];
            var email = window.loaded_contacts[i]['email'];
            //if ($('[name="imported_emails\['+email+'\]"]').get(0)) continue;
            html += '<div class="one-contact" index="'+ i +'">';
            html += '    <div class="contact-boxes">';
            html += '        <input type="checkbox" index="'+ i +'" ' + (window.loaded_contacts[i].checked?'checked="checked"':'')+' name="imported_emails['+email+']" value="'+email+'"/>';
            html += '    </div>';
            html += '    <div class="contact-names">';
            html += '        <span class="contact-name" title="'+name+'">' +((name.length > 25)?name.substring(0, 23)+ '...':name)+ '</span>';
            html += '        <span class="contact-email" title="'+email+'">' +((email.length > 40)?email.substring(0, 38)+ '...':email)+ '</span>';
            html += '    </div>';
            html += '</div>';
            html += '<div class="contact-border"></div>';
        }
        if ('' !== html) {
            document.getElementById('contacts_scroll').innerHTML = '<div id="contacts_resizer" style="height:'+((f_position_ready)?top - (openid.eheight * f_position) - pos_diff:0)+'px;"></div>' + html;
            //$('#contacts_scroll').html('<div id="contacts_resizer" style="height:'+top+'px;"></div>' + html);
        }
    },
	signin : function(box_id, onload) {
		var provider = providers[box_id];
		if (!provider) {
			return;
		}
		this.highlight(box_id);
		this.setCookie(box_id);
		this.provider_id = box_id;
		this.provider_url = provider['url'];
		// prompt user for input?
		if (provider['label']) {
			this.useInputBox(provider);
		} else {
			$('#openid_input_area').empty();
			if (!onload) {
                var upgradeToken = function() {
                    
                    // maybe need move this function to diff place
                    if (!window.imported_contacts) return false;
                    if (!window.loaded_contacts) window.loaded_contacts = [];
                    if (!window.contacts) window.contacts = {};
                    //for (var provider in window.imported_contacts.contacts) {
                    //var p_contacts = window.imported_contacts.contacts[provider];
                    var p_contacts = window.imported_contacts.contacts[box_id];
                        for (var email in p_contacts) {
                            if (!window.contacts[email]){
                                openid.load_finished = false;
                                var name = p_contacts[email];
                                window.contacts[email] = {name: name, email: email, checked: false};
                                window.loaded_contacts.push(window.contacts[email]);
                            }
                        }
                    window.loaded_contacts.sort(function(a, b){
                     var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase()
                     if (nameA < nameB) //sort string ascending
                      return -1 
                     if (nameA > nameB)
                      return 1
                     return 0 //default return value (no sorting)
                    });
                    //}
                    //window.imported_contacts.contacts = {};
                    if (0 < window.loaded_contacts.length) {
                        $('#imported_contact').html('<div id="contacts_scroll"></div>');
                        $('#contacts_scroll').height((window.loaded_contacts.length) * openid.eheight);
                    }
                    openid.load_contacts();
                    var your_name = $('#your-name');
                    //if ('' === your_name.val()) {
                        your_name.val(window.imported_contacts.owner[box_id].fullname);
                        your_name.focus();
                        your_name.trigger('keydown.infieldlabel');
                        your_name.blur();
                        your_name.focus();
                    //}
                    var your_email = $('#your-email');
                    //if ('' === your_email.val()) {
                        your_email.val(window.imported_contacts.owner[box_id].email);
                        your_email.focus();
                        your_email.trigger('keydown.infieldlabel');
                        your_email.blur();
                        your_email.focus();
                    //}                    
                    if ('' === $('#imported_contact').html()) {
                        //$('#imported_contact').html('<b>Contacts not found</b>');
                    } else {
                        $('#select_email').show();
                        $('#imported_contact').show();
                    }
                    
                    colorbox_dialogs.email_popup.colorbox.resize();
              
                    
                };
                    if (window.imported_contacts && window.imported_contacts.contacts && window.imported_contacts.contacts[box_id]) {
                        upgradeToken();
                    } else {
                    var extensions = {
                        'provider'          : box_id,
                        'openid_mode'       : 'checkid_setup',
                        'redirect_host'     : window.location.host,
                        'redirect_protocol' : window.location.protocol,
                        'rand' : Math.random() + (new Date())
                    };
                    var googleOpener = popupManager.createPopupOpener({
                        //'realm' : 'https://code.avaaz.org',
                        'opEndpoint' : openid.authurl,//'https://www.google.com/accounts/o8/ud',
                        'returnToUrl' : 'true',
                        'onCloseHandler' : upgradeToken,
                        'shouldEncodeUrls' : true,
                        'extensions' : extensions
                    });
                    googleOpener.popup(500, 500);
            }
        }
        }
    },
    setImportedContacts: function (provider, owner, contacts) {
        
        
        if (!window.imported_contacts) {
                window.imported_contacts = {};
                window.imported_contacts.contacts = {};
                window.imported_contacts.owner = {};
                /*window.imported_contacts.owner.fullname = '';
                window.imported_contacts.owner.email = '';*/
        }
        window.imported_contacts.contacts[provider] = $.extend({}, contacts);
        window.imported_contacts.owner[provider] = $.extend({email: '', fullname: ''}, owner);
        
        
    },
    closeColorbox: function() {
        //if (window.imported_contacts) window.imported_contacts.contacts = {};
        window.contacts = {};
        window.loaded_contacts = [];
        this.load_from = 0;
        $('#imported_contact').html('');
        $('#imported_contact').hide();
        $('#select_email').hide();
        $('#emails').val('').trigger('blur');
        $('#your-name').val('').trigger('blur');
        $('#your-email').val('').trigger('blur');
        $($('#your-email').get(0).form).trigger('closedialog');
        var highlight = $('#openid_highlight');
		if (highlight) {
			highlight.replaceWith($('#openid_highlight a')[0]);
		}
    },
	/**
	 * Sign-in button click
	 * 
	 * @return {Boolean}
	 */
	submit : function() {
		var url = openid.provider_url;
		if (url) {
			url = url.replace('{username}', $('#openid_username').val());
			openid.setOpenIdUrl(url);
		}
		if (openid.demo) {
			alert(openid.demo_text + "\r\n" + document.getElementById(openid.input_id).value);
			return false;
		}
		if (url.indexOf("javascript:") == 0) {
			url = url.substr("javascript:".length);
			eval(url);
			return false;
		}
		return true;
	},

	/**
	 * @return {Void}
	 */
	setOpenIdUrl : function(url) {
		var hidden = document.getElementById(this.input_id);
		if (hidden != null) {
			hidden.value = url;
		} else {
			$('#openid_form').append('<input type="hidden" id="' + this.input_id + '" name="' + this.input_id + '" value="' + url + '"/>');
		}
	},

	/**
	 * @return {Void}
	 */
	highlight : function(box_id) {
		// remove previous highlight.
		var highlight = $('#openid_highlight');
		if (highlight) {
			highlight.replaceWith($('#openid_highlight a')[0]);
		}
		// add new highlight.
		$('.' + box_id).wrap('<div id="openid_highlight"></div>');
	},

	setCookie : function(value) {
		var date = new Date();
		date.setTime(date.getTime() + (this.cookie_expires * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
		document.cookie = this.cookie_name + "=" + value + expires + "; path=" + this.cookie_path;
	},

	readCookie : function() {
		var nameEQ = this.cookie_name + "=";
		var ca = document.cookie.split(';');
		for ( var i = 0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ')
				c = c.substring(1, c.length);
			if (c.indexOf(nameEQ) == 0)
				return c.substring(nameEQ.length, c.length);
		}
		return null;
	},

	/**
	 * @return {Void}
	 */
	useInputBox : function(provider) {
		var input_area = $('#openid_input_area');
		var html = '';
		var id = 'openid_username';
		var value = '';
		var label = provider['label'];
		var style = '';
		if (label) {
			html = '<p>' + label + '</p>';
		}
		if (provider['name'] == 'OpenID') {
			id = this.input_id;
			value = 'http://';
			style = 'background: #FFF url(' + this.img_path + 'openid-inputicon.gif) no-repeat scroll 0 50%; padding-left:18px;';
		}
		html += '<input id="' + id + '" type="text" style="' + style + '" name="' + id + '" value="' + value + '" />'
				+ '<input id="openid_submit" type="submit" value="' + this.signin_text + '"/>';
		input_area.empty();
		input_area.append(html);
		$('#' + id).focus();
	},

	setDemoMode : function(demoMode) {
		this.demo = demoMode;
	}
};
})(jQuery);

/*  new/common/js/openid.providers.js  */
/*
	Simple OpenID Plugin
	http://code.google.com/p/openid-selector/
	
	This code is licensed under the New BSD License.
*/

var providers_large = {
	yahoo : {
		name : 'Yahoo',
		url : 'http://me.yahoo.com/',
        popup_url: 'https://open.login.yahooapis.com/openid/op/auth',
		background: {x:-261, y:null},
        className: 'provider-border'
        
	},
	google : {
		name : 'Google',
		url : 'https://www.google.com/accounts/o8/id',
        popup_url: 'https://www.google.com/accounts/o8/ud',
        background: {x:25, y:null}
	}
	
};

var providers_small = {
};

openid.locale = 'en';
openid.sprite = 'en'; // reused in german& japan localization
openid.demo_text = 'In client demo mode. Normally would have submitted OpenID:';
openid.signin_text = 'Sign-In';
openid.image_title = 'log in with {provider}';
openid.authurl = 'https://secure.avaaz.org/act/auth';

/*  new/common/js/do_blue/dialog-email-share.js  */
window.validate_object_spread = {
    highlight: function(element) {
        $(element).addClass('pinkwraper');
    },
    unhighlight: function(element) {
        $(element).removeClass('pinkwraper');
    },
    showErrors: function(errorMap, errorList) {
        var iErrors = this.numberOfInvalids();
        if (iErrors) {
            var sMessgae = window.translation['RequiredFields'];
            var sHerror = '';

            if (!this.errorList[0]){
                $(this.currentForm).valid();
            }

            for (var h in this.errorList) {
                var merror = this.errorList[h];
                if (merror.message && !sHerror) {
                    sHerror = merror.message;
                    break;
                }
            }

            if (!sHerror) {
                sHerror = sMessgae;
            }

            $("#spread_error_place").html(sHerror).show();
        } else {
            $("#spread_error_place").hide();
        }

        $.colorbox.resize();
        this.defaultShowErrors();
    },
    onkeyup: false,
    errorPlacement: function(error, element) {},
    submitHandler: function(form) {
        var oData = $('#form-tell').serializeArray();

        $.ajax({
            url:'/act/?r=tell&type=ajax',
            dataType: 'json',
            type: 'POST',
            data: oData,
            success: function (response) {
                if (response && response.error == 'invalid_emails') {
                    $('#emails').addClass('pinkwraper');
                    $("#spread_error_place").html(window.translation['TafErrorSenderName']);
                    $("#spread_error_place").show();
                    $.colorbox.resize();
                } else {
                    $.colorbox({
                        opacity:0.5,
                        inline:true,
                        href:"#tell_a_friend_popup_postaction",
                        showClose: false,
                        onClosed: function() {
                            openid.closeColorbox();
                        },
                        onComplete: function(){
                            $.colorbox.resize();
                            setTimeout(function(){
                                $(this).colorbox.close();
                            }, 3000);
                        }
                    });
                }
            }
        });

        return false;
    }
};

(function($){
    $.fn.serializeJSON = function() {
        var json = {};
        jQuery.map($(this).serializeArray(), function(n, i){
            json[n['name']] = n['value'];
        });
        return json;
    };
})(jQuery);

$('#form-tell').bind('closedialog', function(){
    $(this).data('validator').resetForm();
    $('*', this).removeClass('pinkwraper');
    $("#spread_error_place").hide();
});

$('a', '.contact-text-postaction').filter(function(){
    return $(this).get(0).href.indexOf('/spread') > 0;
}).click(function(){
    openid.closeColorbox();
    colorbox_dialogs.email_popup.trigger('click');
    return false;
});
