if (typeof gigya == 'undefined') {gigya = new Object();}
if (typeof gigya.services == 'undefined') {	gigya.services= new Object(); }

if (typeof gigya.fbConnectEnabled == 'undefined') {	gigya.fbConnectEnabled=false; }
gigya.fbcInitialized=function() {
    if (typeof gigya.fbcInitializedTime=='undefined') return null;
    return (gigya.fbcInitializedTime>0)
}
gigya.refreshFbcSession=function() {
    var fncCallback=function(response) {
        gigya.fbcInitializedTime = (new Date()).getTime();
        gigya.services.socialize._dispatchGlobalEvent({isEvent:true, eventName:'FBCRefreshed'});     
    }
    if (gigya.fbAppID) {
        FB.getLoginStatus(fncCallback, true);
    } else {
        FB.Connect.forceSessionRefresh(function() {
            FB.Connect.get_status().waitUntilReady(fncCallback);
        });
    }
}

/*
Gigya.Socialize.Cache.swf
var cacheID:String = internals['cacheID'];
   switch (methodName) {
    case 'clearCache': Cache.clearCache(conf['APIKey']); break;
    case 'clearExpired': Cache.clearExpired(); break;
    case 'setCached': cache.setCached(cacheID, internals['cacheResult'], internals['TTL']); break;
    case 'getCached': cache.getCached(cacheID); break;
    case 'deleteCached': cache.deleteCached(cacheID); break;
    case 'setPendingCache': cache.setPendingCache(cacheID); break;
   }
*/

gigya._cache = {
	clearCache:function(c,p) {
		p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });  
		var containerID=p['containerID'];  	
		var isPopup = (containerID=='' || p['isPopup']);    
		if ( isPopup ) {                
			p = gigya.global.normalizeParams(p,false, { width:{def:1}, height:{def:1} });
		}
		gigya.services.socialize._AddRequest('clearCache','Gigya.Socialize.Cache','',containerID,p['width'],p['height'],true,false,c,p,{});
	}
}

gigya.services.socialize= {

_GlobalEventHandlers : {
    onLogin:{idx:0},     
    onConnect:{idx:0},     
    onDisconnect:{idx:0},
    onLogout:{idx:0},
    onFBCLoaded:{idx:0},
    onFBCRefreshed:{idx:0},
    onHideUIRequested:{idx:0}
} ,
 
_PopupContainers:{},
pseudoContainers:{},

CenteredComponentDivID:'WFComponentDiv_'+(new Date()).getTime(),
GetCenteredComponentDivID:function(popupName){
	return this.CenteredComponentDivID+'_'+popupName;
},
loadFB2:function() {
    gigya.fbcInitializedTime=-1;
    window.fbAsyncInit = function() {
        // It's better to get login status manually so that we could dispatch the FBCLoaded event only after we have the FB session params.
        FB.init({
            appId  : gigya.fbAppID,
            //status : true,
            cookie : true,
            xfbml  : true
        });
        FB.getLoginStatus(function(){
            gigya.fbcInitializedTime = (new Date()).getTime();
            gigya.services.socialize._dispatchGlobalEvent({isEvent:true, eventName:'FBCLoaded'/*, connected:(status==FB.ConnectState.connected)*/});
            gigya.services.socialize.addEventHandlers({},{
                listenerDescription:'listener for updating Facebook Connect session',
                onLogin: function() {gigya.refreshFbcSession()},
                onConnect: function() {gigya.refreshFbcSession()},
                onLogout: function(e){if (e && e.providers && e.providers.toLowerCase().indexOf('facebook')!=-1) FB.logout()}
            });                               
        }, true);
    };    
    var divFbRoot=document.createElement('div');
    divFbRoot.id='fb-root';
    document.body.appendChild(divFbRoot);
    var e = document.createElement('script');
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    e.async = true;
    divFbRoot.appendChild(e);
},
loadFBC:function() {
    gigya.fbcInitializedTime=-1;
    //this fixes JS error caused sometimes by FB
    var fbdiv=document.createElement('div');
    fbdiv.id='FB_HiddenContainer';
    fbdiv.style.display='none';
    fbdiv.style.position='absolute';
    fbdiv.style.width='0px';
    fbdiv.style.height='0px';
    fbdiv.style.left='-100px';
    fbdiv.style.top='-100px';
    document.body.appendChild(fbdiv);
    
    function fbInit() {
        FB_RequireFeatures(["Connect"], function() { 
            //FB.FBDebug.logLevel = 9;
            //FB.FBDebug.isEnabled = true;
            
            FB.Facebook.init(gigya.fbcAPIKey, gig_xdReceiverUrl);
        });
        FB.ensureInit(function() {
            FB.Facebook.set_baseDomain(gigya.fbcDomain);
            FB.Connect.get_status().waitUntilReady(function(status) {
                gigya.fbcInitializedTime = (new Date()).getTime();
                gigya.services.socialize._dispatchGlobalEvent({isEvent:true, eventName:'FBCLoaded'/*, connected:(status==FB.ConnectState.connected)*/});
                gigya.services.socialize.addEventHandlers({},{
                    listenerDescription:'listener for updating Facebook Connect session',
                    onLogin: function() {gigya.refreshFbcSession()},
                    onConnect: function() {gigya.refreshFbcSession()},
                    onLogout: function(e){if (e.providers.toLowerCase().indexOf('facebook')!=-1) FB.Connect.logout()}
                });
            });
        });
    }

    // Load feature loader asynchronously

    var head = document.getElementsByTagName("head")[0],
        script = document.createElement("script"),
        done = false;
        if (gigya._vars.lastScriptProtocol=='https') {
            script.src = 'https://ssl.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php';
        } else {
            script.src = 'http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US';
        }
    script.onload = script.onreadystatechange = function(){
            if ( !done && (!this.readyState ||
                            this.readyState == "loaded" || this.readyState == "complete") ) {
                    done = true;
                    fbInit();
            }
    };

    head.appendChild(script);
},
//Gets info, then adds the user object to the event object and dispatches it.
_getInfoForEvent:function(rid, evt) {
    var oRID=gigya.services.socialize._parseRID(rid);
	var conf=oRID.req.c;
    gigya.services.socialize.getUserInfo(conf, {callback: gigya.services.socialize._afterGetInfoForEvent, context: {evt:evt}});
},
_afterGetInfoForEvent:function(e) {
    var evt=e.context.evt;
    evt.user=e.user;
    evt.isEvent=true;
    gigya.services.socialize._dispatchGlobalEvent(evt);     
},
waitForService:function(c,p) {

    if (p && p['service'] && p['service'].toLowerCase()=='fbconnect') {
        var callback = p['callback'];
        if (!gigya.fbcInitializedTime || gigya.fbcInitializedTime<0) {
            gigya.services.socialize.addEventHandlers({},{onFBCLoaded:callback, context: p['context']});
        } else {
            //alert('not adding');
            callback({context:p['context']});
        }
    }
},
GrayOut:function(vis, options, extra) {
	  var options = options || {};
	  var zindex = options.zindex || 50;
	  var opacity = options.opacity || 70;
	  var opaque = (opacity / 100);
	  var bgcolor = options.bgcolor || '#000000';
	  var dark=document.getElementById('darkenScreenObject');
	  var tbody = document.body;
	  if (!dark) {
	    var isCompMode=(window.attachEvent && (gigya.flash.isIE6 || document.compatMode=='BackCompat'));
        var scrollTop=document.documentElement.scrollTop;
        if (scrollTop==0) scrollTop=document.body.scrollTop;	  
		var tnode = document.createElement('div');
		    if (isCompMode) {
			    tnode.style.position='absolute';
			    tnode.style.top=''+scrollTop+'px';
		    } else {
			    tnode.style.position='fixed';
			    tnode.style.top='0px'; 
		    }
		    tnode.style.overflow='hidden';	
			tnode.style.left='0px';
			tnode.style.display='none';
			tnode.id='darkenScreenObject';
			tnode.innerHTML='&nbsp;';
		tbody.appendChild(tnode);
		dark=document.getElementById('darkenScreenObject');
	    if (!gigya.attachedFixGray) {
	        gigya.attachedFixGray = true;		
            if (window.addEventListener) {                
                window.addEventListener('resize',gigya.services.socialize._fixGraySize,false);
            }
            if (window.attachEvent) {                
                window.attachEvent('onresize', gigya.services.socialize._fixGraySize);
            }
            if (isCompMode) {
                window.attachEvent('onscroll', gigya.services.socialize._fixGrayPosition);
            }
        }
	  }
	  if (vis) {
		var vph;
		var vpw;
		if (window.innerHeight) {
			vph=window.innerHeight;
			vpw=window.innerWidth;
		}
		if (typeof vph=='undefined') {
			var de=document.documentElement;
			vph=de.clientHeight;
			vpw=de.clientWidth;
		}
		if (vpw==0) vpw=tbody.clientWidth;   
		if (vph==0) vph=tbody.clientHeight;   
		dark.style.opacity=opaque;
		dark.style.MozOpacity=opaque;
		dark.style.width= '' + vpw + 'px';
		dark.style.height= '' + vph + 'px';		
		dark.style.filter='alpha(opacity='+opacity+')';
		dark.style.zIndex=zindex;
		dark.style.backgroundColor=bgcolor;
		dark.style.display='block';	
	  } else {
		 tbody.removeChild(dark);
	  }    
},
_fixGrayPosition:function(){
    var dark=document.getElementById('darkenScreenObject');
    if (dark) {
        var de=document.documentElement;
        var db=document.body;
        var scrollTop=de.scrollTop;
        if (scrollTop==0) scrollTop=db.scrollTop;
        var scrollLeft=de.scrollLeft;
        if (scrollLeft==0) scrollLeft=db.scrollLeft;        
        var clientHeight=de.clientHeight;
        if (clientHeight==0) clientHeight=db.clientHeight;    
        var clientWidth=de.clientWidth;
        if (clientWidth==0) clientWidth=db.clientWidth;    
        if (gigya.flash.isIE6) clientWidth-=1;
        dark.style.top=scrollTop;
        dark.style.left=scrollLeft;
    }
},
_fixGraySize:function() {
    var dark=document.getElementById('darkenScreenObject');
    if (dark) {
        var de=document.documentElement;
        var db=document.body;
        var clientHeight=de.clientHeight;
        if (clientHeight==0) clientHeight=db.clientHeight;    
        var clientWidth=de.clientWidth;
        if (clientWidth==0) clientWidth=db.clientWidth;    
        if (gigya.flash.isIE6) clientWidth-=1;
        
        dark.style.width=''+clientWidth+'px';
        dark.style.height=''+clientHeight+'px';  
    }
},
_DescribeObjectRec:function(o,on,levels,a){
	if (typeof o=='function') return;
	a.push(on+'={'+typeof o+'}:' + o);
	if ((levels>0) && (typeof o=='object') && (a.length<100)) {
		var c;
		c=0;
		for (var p in o) {
			c++;
			if ((c<15) && p!='container') {
				if (/^[0-9]+$/.test(p)) {
					gigya.services.socialize._DescribeObjectRec(o[p],on+'['+p+']',levels-1,a);
				}
				else {
					gigya.services.socialize._DescribeObjectRec(o[p],on+'.'+p,levels-1,a);
				}
			}
		}
		//if (o.constructor==Date) {
			//a.push(
		//}
	}
},

describeObject :function(o,oname,desc,levels){
	var a=new Array();
	a.push(desc);
	gigya.services.socialize._DescribeObjectRec(o,oname,levels,a);
	return a.join('\n');
},

//fn gets o and i and may modify o[i] - returns true if further drilldown is allowed
_TraverseObject : function(o,fnBefore,fnAfter){
	var t; var drill;
	for (var i in o) {
		t=typeof o[i];
		drill=true;	
		if (fnBefore) drill=fnBefore(o,i,t);
		if (drill && ((t=='object') || (t=='Array'))) {
				gigya.services.socialize._HandleObjectRepresentation(o[i],fnBefore,fnAfter);
		}
		if (fnAfter) {fnAfter(o,i,typeof o[i])} // not using t becasue it could have changed
	}
},

_HandleObjectRepresentation : function(o){
	gigya.services.socialize._TraverseObject(o,
		function(o,i,t) { 
			if ((t=='object') && (null!=o[i] && o[i].EmptyString==true)){
				o[i]='';
				return false;
			}
			return true;
		},
		function(o,i,t) { 
			if ((t=='object') && (null!=o[i] && o[i].JSON!=null)){
				try{
					o[i]=eval('('+o[i].JSON+')');
				}
				catch (e) {
					if (gigya.services.socialize.verbose) alert('Failed to evaluate ' + o[i].JSON + ' using  default ');
					if (o[i].Defval) {o[i].Defval}
					else {o[i]={parseError:true,JSONString:o[i].JSON}}
				}
			}
			return true;
		}
	)
},

_LoadSWF:function(rid){
	var oRID=gigya.services.socialize._parseRID(rid);
	var req=oRID.req;
	var w=req.w;
	var h=req.h;
	
	var swfName=req.servicedBy;
	
	
	
	var confObj=req.c;
	
	var wmode='transparent';
	if (req.p['isPopup']==true) {
		wmode='opaque';
	}
	
	var swfurl=gigya._vars.lastScriptURLBase +'/Wildfire/swf/'	+ swfName + '.swf';	
	var container=oRID.container;
	
	var ContainerIDAndSWFName=container.id+'_'+swfName;
	var ContainerIDAndSWFNameEscaped=container.id+'|'+swfName;
	var html='';	
	html += gigya.flash.AC_FL_GetContent(
	'id', ContainerIDAndSWFName,
	'wmode', wmode, 
	'name', ContainerIDAndSWFName,
	'width', w,
	'height', h,
	'movie', swfurl,
	'quality', 'high',  
	'align', 'middle',
	'play', 'true',
	'loop', 'true',
	'scale', 'showall',
	
	
	'devicefont', 'false',
//	'bgcolor', '#ffffff',
	'menu', 'true',
	'allowFullScreen', 'false',
	'allowScriptAccess','always',
	'salign', '',
	'flashvars','ContainerAndSWF='+ContainerIDAndSWFNameEscaped+'&SWFModuleID='+ContainerIDAndSWFNameEscaped+'&now='+(new Date()).getTime(),
	'swLiveConnect','true'
	);
	//if (typeof gigya.services.socialize._swfs  == 'undefined') gigya.services.socialize._swfs={};
	//gigya.services.socialize._swfs[container.id+'_'+swfName]={container:container};
	//if (gigya.services.socialize.verbose) alert('setting innerHTML of container ' + container.id + ' to:\n' + html);
	
	//Without Timeout
	//container.childNodes[1].innerHTML=html;
	
	//alert(window[ContainerIDAndSWFName].id);
	window[ContainerIDAndSWFName]={
	    id:ContainerIDAndSWFName,
	    SetReturnValue:function(){
	        window[this.id] = document.getElementById(this.id);
	        window[this.id].SetReturnValue('<undefined/>');
	    }
	}
	var ifrel=document.getElementById('gigya_ifr_'+container.id);
	if (ifrel!=null) {ifrel.style.visibility=''; }
	container.style.visibility = '';
	container.innerHTML=html;
	//alert('in swfLoad \n'+html);
	//window[ContainerIDAndSWFName] = document.getElementById(ContainerIDAndSWFName);
	
	return;
	//With Timeout
	var expr= 'document.getElementById(\'' + container.id + '\').innerHTML=\''+html.replace('\'','\\\'')+'\'';
	//var expr2= 'gigya.services.socialize._SetContainerHTML(\'' + container.id + '\',\''+html.replace('\'','\\\'')+'\')';
	
	//expr=prompt('expr',expr);
	container.innerHTML = '&nbsp;';// '5 msec to override content for ' + container.id;
	window.setTimeout(expr,1);
	//I am using this because a write without timeout did not work and
	//a direct write via timeout cause a "click to activate"
	//*/
},


_escapeXML:function(s) {
	return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
},

_SerializePropertyToBuffer:function(o,p,a){ a.push('<property id="' + p + '">'); gigya.services.socialize._SerializeToBuffer(o[p],a); a.push('</property>');} ,
_SerializeObjectToBuffer:function(o,a) {a.push('<object>'); for (var prop in o) { gigya.services.socialize._SerializePropertyToBuffer(o,prop,a); } ;	a.push('</object>');},
_SerializeArrayToBuffer:function(arr,a){a.push('<array>');	for (var i=0; i<arr.length; i++) { gigya.services.socialize._SerializePropertyToBuffer(arr,i,a); }; a.push('</array>');},

_SerializeToBuffer:function(v,a){
	    var value=v;
		var type = typeof(v);
		if (type == 'string') {	
			if (value=='') {
				return gigya.services.socialize._SerializeObjectToBuffer({EmptyString:true},a);
			}
			else {
				a.push('<string>'+gigya.services.socialize._escapeXML(value) + '</string>'); 
			}
		}
		else if (type == 'undefined') {a.push('<undefined/>');}
		else if (type == 'number') {a.push('<number>' + value + '</number>');}
		else if (value == null) {a.push('<null/>');}
		else if (type == 'boolean') {a.push(value ? '<true/>' : '<false/>');}
		else if (value instanceof Date) {a.push('<date>' + value.getTime() + '</date>');}
		else if (value instanceof Array) {gigya.services.socialize._SerializeArrayToBuffer(value,a);}
		else if (type == "object") {return gigya.services.socialize._SerializeObjectToBuffer(value,a);} 
		else {return "<null/>";}
},

_SerializeArgs:function(args){
	var a=new Array();
	a.push('<arguments>');
	for (var i=0; i<args.length; i++) {	gigya.services.socialize._SerializeToBuffer(args[i],a); }			
	a.push('</arguments>');
	return a.join('');
},

_RegisterSWF:function(ContainerAndSWF,isComponent){	
    var lastUnderscorePos = ContainerAndSWF.lastIndexOf('|');
    ContainerAndSWF=ContainerAndSWF.replace('|','_');
	var ri='gigya.services.socialize._ReissueRequests(\'' + ContainerAndSWF + '\');';
	var swf=document.getElementById(ContainerAndSWF);	

	if (swf!=null) { swf.swfLoaded = true; }
      
    
    var swfName = ContainerAndSWF.substring(lastUnderscorePos+1);
    var divName = ContainerAndSWF.substring(0,lastUnderscorePos);            
    var internals = { isEvent:true } ;

    if (divName.indexOf('WFComponentDiv_') == 0) {
        gigya.services.socialize._PopupContainers[divName] = document.getElementById(divName);
    }
    
    
    // the parameters for addEventHandlers - for registering the componencts event handlers.
    var p={listenerType:'component', ContainerAndSWF:ContainerAndSWF};
    
    // create a set of event handlers for this component
	for ( var knowEvtHandlerName in this._GlobalEventHandlers ) {
        p[knowEvtHandlerName]=new Function('evtObj',
            'var oRID=gigya.services.socialize._parseRID(\'0@'+ swfName + '@' + divName + '\');\n' +
            'if (oRID.swf!=null) { \n' +
	        '    gigya.services.socialize._AddRequest(\''+knowEvtHandlerName+'\',\''+swfName+'\',\'\','+'\''+divName+'\',1,1,false,false,{},{},{ isEvent:true, e:evtObj });\n' +
	        '}'
	    );	    	    
	}   	
	gigya.services.socialize.addEventHandlers({},p);	   
	window.setTimeout(ri,1);
},

_ReissueRequests:function(ContainerAndSWF){
	var req;
	var swf=document.getElementById(ContainerAndSWF);
	if (swf==null) return;// might happan when pages change
	
	var container;
	if (swf.parentElement) {
		container=swf.parentElement;
	}
	else {
		container=swf.parentNode;
	}
	
	var Reqs=container.Reqs; // Array	
	var GS=gigya.services.socialize;

	//Used to re-run the last show request so that when the component is re-initialize 
	// like when display is set to none and then reset on FF
	var blnExecutedAShowRequest=false;
	var lastShowRequestIndex=-1;
	var blnIsShowRequest;
	for (var r=0;null!=(req=Reqs[r]);r++) {
		blnIsShowRequest=(req.operation.indexOf('show')==0);
		if (blnIsShowRequest) lastShowRequestIndex=r;
		if (req.Loaded!=true) {
			req.Loaded=true;
			if ( (req.moreArgs==null) || (req.moreArgs['isEvent']!=true)  ) {
				if (blnIsShowRequest) blnExecutedAShowRequest=true;
			    GS._DoRequest(req.rid);
			}
		}
	}
	if ((!blnExecutedAShowRequest) && (lastShowRequestIndex!=-1)) {
		GS._DoRequest(Reqs[lastShowRequestIndex].rid);
	}

},

_parseRID:function(rid){
		var ridp=rid.split('@');
		var swf=document.getElementById(ridp[2]+'_'+ridp[1]);
		var containerID=ridp[2];
		var container;
		
		if (null==(container=gigya.services.socialize.pseudoContainers[containerID])) {
//		if (containerID=='coreDiv') {
//			container=gigya.services.socialize.coreDivContainer;
//		}
//		else {
			container=document.getElementById(ridp[2]);
		}
		
		var Reqs=null;
		if (container!=null) Reqs=container.Reqs;
		var req=null;
		if (Reqs!=null) req=Reqs[parseInt(ridp[0])];
		
		return {rid:rid,container:container,Reqs:Reqs,req:req,swf:swf};
},

_DoRequest:function(rid){
	try {
		var oRID=gigya.services.socialize._parseRID(rid);
		var req=oRID.req;
		var swf=oRID.swf;	
		
		if ((typeof swf.CallFunction !='function') && (typeof swf.CallFunction !='unknown')) return;

		req.container.style.visibility='';
		if (oRID.container.id=='coreDiv'){
			// calls to Core should not go via a timeout or Popup Killers might be invoked.
			gigya.services.socialize.__DoRequest(rid);
		}
		else {
			window.setTimeout('gigya.services.socialize.__DoRequest(\''+rid+'\')',1);
		}
	}
	catch(e){
		if (gigya.services.socialize.verbose) {
			var s='An Error has occurred :\n';
			for(var v in e) {
				s+=v+' -> ' + e[v] + '\n';
			}
			alert('Exception While trying to _DoRequest ' + rid + '\n' +  s);
		}
	}
},	



__DoRequest:function(rid){
	try {
		
		if (gigya.services.socialize.verbose) {
			alert( 'gigya.services.socialize.__DoRequest ' + rid);
		}
		var oRID=gigya.services.socialize._parseRID(rid);
		var req=oRID.req;
		var swf=oRID.swf;

		if (!swf.swfLoaded) return;
		if (gigya.services.socialize.verbose) {			
			alert('Calling .exec for rid=' + req.rid );
		}
		ret=swf.exec(req.rid, req.c, req.p, req.internals);	
	}
	catch(e){
		if (gigya.services.socialize.verbose) {
			var s='An Error has occurred :\n';
			for(var v in e) {
				s+=v+' -> ' + e[v] + '\n';
			}
			alert('Exception While trying to __DoRequest ' + rid + '\n' +  s);
		}
	}
},

_getScrollXY:function() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
},

// will return the container if its a pseudo container or null otherwise.
_getPseudoContainer:function(id) {
	if (gigya.services.socialize.pseudoContainers==null) gigya.services.socialize.pseudoContainers={};
	if (id=='coreDiv' || id.toLowerCase().indexOf('pseudoContainer_')==0) {
		if (gigya.services.socialize.pseudoContainers[id]==null) {
			gigya.services.socialize.pseudoContainers[id]={};
		}
		return gigya.services.socialize.pseudoContainers[id];
	}
	return null;
},

// will return real or pseudo container
_GetContainer:function(id){
	if (id=='') return null;
	var container=gigya.services.socialize._getPseudoContainer(id);
	if (container!=null) return container;
	
	var el=document.getElementById(id);
	if (typeof(el)=='Array') {
		alert('Gigya Social Warning:\nYou seem to have have multiple elements on your page with ID ' + id + '\nplease make sure you have only one such element.');
		return el[el.length];
	}		
	return el;
},

_CreateContainer:function(id) {
	var ifrel;
	if ((gigya.browser.isIE && gigya.flash.isWin) || gigya.browser.isChrome) {
		ifrel = document.createElement('IFRAME');
		ifrel.id='gigya_ifr_'+id;
		ifrel.frameborder="0";
		ifrel.frameBorder="0";
        ifrel.allowtransparency=true;
		ifrel.style.position='absolute';
		if (gigya.browser.isChrome) {
		    ifrel.style.width='30px';
		    ifrel.style.height='1px';
		}
		else {
		    ifrel.style.width='1px';
		    ifrel.style.height='1px';
		}
		//ifrel.style.display = 'none';
		if (ifrel.style.zIndex!=null) {
			ifrel.style.zIndex=gigya.global._NextZIndex++;
		}
		if (gigya.flash.isIE6) {
		    //ifrel.src='IgnoreThis404ItsOK.htm'; ///prevent mix content (will cause 404 , but its ok!).
		    ifrel.src=gigya._vars.lastScriptURLBase + '/wildfire/DO_NOT_DELETE.htm';
		}
	}

	var el = document.createElement('div');
	el.style.position='absolute';
	if (el.style.zIndex!=null) {
		el.style.zIndex=gigya.global._NextZIndex++;
	}
	var html='';
	//html+='<iframe frameborder="1" onclick="alert(\'iframe\');" style="background-color:red;width:200px;"  ></iframe>'
	//html+='<div style="position:absolute;top:0;left:0;" onclick="alert(\'innerdiv\');" id="' + id + '_div' + '">'
	html+='newly Created container: ' + id 
	//html+='</div>';
	el.innerHTML = html;
	el.id=id;
	gigya.services.socialize._DodgeEmbedsAndIframes(el,1,1);
	el.swfLoaded = false;
	if (document.body) {
		if(document.body.insertBefore) {
			if (document.body.firstChild) {
				if (ifrel!=null) document.body.insertBefore(ifrel, document.body.firstChild);
				document.body.insertBefore(el, document.body.firstChild);
			} else if (document.body.appendChild) {
			    if (ifrel!=null) document.body.appendChild(ifrel);
			    document.body.appendChild(el);
			} else alert('gigya.services.socialize.js:document.body.firstChild is null - can not create container ' + id);
//			if (document.body) {
//				alert('ccc');
//				document.body.insertBefore(ifrel,document.getElementById('last'));
//				document.body.insertBefore(el,document.getElementById('last'));
//			}
			
			//document.body.appendChild(el);
			
		} 
		else {
			alert('gigya.services.socialize.js:document.body.insertBefore is null - can not insert container ' + id);
		}
	}
	else {
		alert('gigya.services.socialize.js:document.body is null - can not Create container ' + id);
	}
	//el.onclick=function(){this.firstChild.style.display='none'};
	return el;
},

_SetContainerSizeAndPosition:function(container,w,h,blnCenter){
/*	alert(['gigya.services.socialize._SetContainerSizeAndPosition ' ,
	      'container = ' + container.id,
	      'w = ' + w,
	      'h = ' + h,
	      'blnCenter = ' + blnCenter].join('\n'));
*/	      
	if (container==null || container.style==null) {
		//this is a fake container for coreDiv
		return;
	}
	
    if ((container.style.width!=''+w+'px') || (container.style.height!=''+h+'px')) {
        //debugger;
	    container.style.width=''+w+'px';
	    container.style.height=''+h+'px';			    
    }	
	if ( blnCenter ) { 
	    if (container.style.zIndex==null || blnCenter) {
		    container.style.zIndex=gigya.global._NextZIndex++;
	    }
    	
    	 
    
		
		var vph;
		var vpw
		
		
		//based on info from http://www.quirksmode.org/dom/w3c_cssom.html
		if (window.innerHeight) { //should work in FF 2 FF 3b3 Safari 3.0 Win Opera 9.5b Konqueror 3.5.7 
			vph=window.innerHeight;
			vpw=window.innerWidth;
		}

		if (typeof vph=='undefined') {
			var de=document.documentElement;
			vph=de.clientHeight;      //This is too hight in FF (its the height of the document not the viewport
			vpw=de.clientWidth;
		}
		// on ie7 de.clientHeight returns 0 so we go to the next option
		if (((typeof vph=='undefined') || (vph==0)) && (document.body) && document.body.clientHeight) { // returns wrong height in IE7 (do
			vph=document.body.clientHeight;
			vpw=document.body.clientWidth;
		}


        // IE 
        var children = container.children;        
        if ( null== children ) {        
            // FF
            children = container.childNodes;
        }
                  
        if ( null != children && w!=0) {         
            var child1 = children[0];
            if ( null != child1 ) {
                if ( w!=child1.width || h!=child1.height) {                
                    child1.height = ''+h;
                    child1.width = ''+w;
                }
            }
        }

		
		var scrl=gigya.services.socialize._getScrollXY();
		
		var vpt=scrl[1];
		var vpl=scrl[0];

		container.style.top=''+(Math.max(0,vpt+Math.floor((vph-h)/2)))+'px';
		container.style.left=''+(Math.max(0,vpl+Math.floor((vpw-w)/2)))+'px';
		container.style.visibility='';
	}
},

_LoadRequiredFor:function(rid){
	var oRID=gigya.services.socialize._parseRID(rid);
	return (oRID.swf==null);
},

_DodgeEmbedsAndIframes:function(container,w,h){

	//alert('_DodgeEmbedsAndIframes');
	//debugger;
	if (!gigya.flash.isFF)  return;
	if (container.id!='coreDiv') return; // only the coreDiv is allowed to skiparound
	
	var blnHide=true;
	var cpos=gigya.global._GetElementPos(container);
	var ctop=cpos.top;
	var cleft=cpos.left;
	var cright=cleft+w;
	var cbottom=ctop+h;
	
	var tags;
	tags=['object','embed','iframe'];
	
	var viewport = gigya.global._ClientViewport.get(); 
	
	var obstaclePositions=new Array();
	var optionalPositions=new Array();
	optionalPositions.push({t:viewport.scrollTop,l:viewport.scrollLeft});
	
	var elements = [];
	for (var itag=0;itag<tags.length;itag++) {
		tagname=tags[itag];
		elements=document.getElementsByTagName(tagname);
		for (var i=0;i<elements.length;i++){
			var el=elements[i];
			
			if (el.id!='coreDiv_Gigya.Socialize.Core' && el.style.visibility!='hidden' && container.childNodes[0]!=el) {
			
				var epos=gigya.global._GetElementPos(el);
				var etop=epos.top;
				var eleft=epos.left;
				
				var elcs=(document.defaultView)?document.defaultView.getComputedStyle(el, ""):el.currentStyle;
				var eright=eleft+parseInt(elcs.getPropertyValue?elcs.getPropertyValue('width'):elcs.width)-1;
				var ebottom=etop+parseInt(elcs.getPropertyValue?elcs.getPropertyValue('height'):elcs.height)-1;
				
				obstaclePositions.push({t:etop,l:eleft,r:eright,b:ebottom});
				if (viewport.contains(eright+1,etop)) {
					optionalPositions.push({t:etop,l:eright+1});
				}
				if ((viewport.contains(eleft,ebottom+1))) {
					optionalPositions.push({t:ebottom+1,l:eleft});
				}
			}
		}	
	}
	
	var opt;
	var obs;
	var blnOverlap;
	blnOverlap = true;
	for (var iopt=0; (iopt<optionalPositions.length) && (blnOverlap == true) ; iopt++) {
		opt = optionalPositions[iopt];
		blnOverlap = false;
		for (var iobs=0; iobs < obstaclePositions.length ; iobs++) {
			obs = obstaclePositions[iobs];
			if (!((opt.t>obs.b) || (opt.t<obs.t) || (opt.l >obs.r) || (opt.l<obs.l))) {
			    blnOverlap=true;
			    break;
			}
		}
		
		if (blnOverlap==false) {
			if (container.style.left !=''+ opt.l+'px') container.style.left=''+ opt.l+'px';
			if (container.style.top !=''+ opt.t+'px') container.style.top=''+ opt.t+'px';
			//alert ('Moved ' + container.id + ' to ' + opt.l + ',' + opt.t);
			return;
		}
		
	}
	// consider calling callback with an error.	
},


_HandleEmbedAndObjectsBelow:function(container,w,h){
	//if (!gigya.flash.isFF)  return;

	var blnHide=true;
	var cpos=gigya.global._GetElementPos(container);
	var ctop=cpos.top;
	var cleft=cpos.left;
	var cright=cleft+w;
	var cbottom=ctop+h;
	var tags;
	if (gigya.flash.isIE)  {
		tags=['iframe'];
	}
	else {
		tags=['embed','iframe']; //object seems to be unrequired.
	}
	for (var itag=0;itag<tags.length;itag++) {
		tagname=tags[itag];
		elements=document.getElementsByTagName(tagname);
		//alert ('There are ' + elements.length + ' of tag ' + tagname);
		for (var i=0;i<elements.length;i++){
			var el=elements[i];
			if (el.id!='coreDiv_Gigya.Socialize.Core' && el.style.visibility!='hidden' && container.childNodes[0]!=el) {
			    // obj.offsetParent is null in safari/chrome, because obj.parentNode is '<object>'. styles won't be applied to embed in chrome.
			    if (el.parentNode.tagName.toLowerCase() == 'object') {
                    el = el.parentNode;
                }			
				var epos=gigya.global._GetElementPos(el);
				var etop=epos.top;
				var eleft=epos.left;
				
				var elcs=(document.defaultView)?document.defaultView.getComputedStyle(el, ""):el.currentStyle;
				var eright=eleft+parseInt(elcs.getPropertyValue?elcs.getPropertyValue('width'):elcs.width);
				var ebottom=etop+parseInt(elcs.getPropertyValue?elcs.getPropertyValue('height'):elcs.height);
				
				if (!((etop>cbottom) || (ebottom<ctop) || (eleft >cright) || (eright<cleft))) {
					//alert([el.src,'\n',etop,'>',cbottom,' ',(etop>cbottom) ,'\n',ebottom,'<',ctop,' ',(ebottom<ctop),'\n', eleft,'>',cright,' ',(eleft >cright),'\n',eright,'<',cleft,' ', (eright<cleft)].join(','));
					//debugger;	
					//alert(' ' + i + ' wmode=' + el.wmode)
					var isNonGigyaIframe=(tagname=='iframe') && ((el.id+'          ').substr(0,10)!='gigya_ifr_');
					if (
						  ( (tagname=='embed' ) && 
							( (el.getAttribute('wmode')==null) || 
							  (el.getAttribute('wmode')=='') || 
							  (el.getAttribute('wmode')=='window') 
							)
						   ) 
						|| isNonGigyaIframe)  {
	
						if (blnHide && (container.id != 'coreDiv')) {
								//alert('in honor of ' + container.id + ' hiding ' + el.id + ' ' + (container.Reqs!=null)+ ' ' + el.style.visibility);
								
								el.style.visibility='hidden';
								if (container.elementsToShowOnClose == null) container.elementsToShowOnClose=[];
								container.elementsToShowOnClose.push(el);

						}
					}
				}
			}
		}
	}
},

_noSuchDivID:function(containerID,p,methodName){	
    // Popup is not required, but the containerID does not exist - Failure !!!
    var onErrorFn = p['onError'];         
    if ( typeof onErrorFn =='function' ) {        
        var evt = {
            eventName:'Error',
            context:p['context'],
            status:'FAIL', 
            statusMessage:'Invalid_containerID',
            errorCode: 400103,
            errorMessage: 'Invalid_containerID'
        };              
        
        onErrorFn(evt);
    }
    else {
        // onError is either undefined or not a function, use call back if exists
        var callback = p['callback'];         
        if ( typeof callback !='undefined' ) {        
            var resp = {
                eventName:'Error',
                context:p['context'],
                status:'FAIL', 
                statusMessage:'Invalid_containerID',
                errorCode: 400103,
                errorMessage: 'Invalid_containerID'
            }; 
            
            callback(resp);
        }        
    }                
},

_RetryPending:function() {
	//debugger;
    var pr=gigya.services.socialize.pendingRequests;
    if (!document.body) {
        window.setTimeout('gigya.services.socialize._RetryPending()',200);
    } else {
        for (var i=0; i<pr.length; i++) {
            var r=pr[i];
            if (r.length==12) {
				gigya.services.socialize._AddRequest(r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11]);
			}
			else if (r.length==6) {
				gigya.services.socialize._AddJSRequest(r[0],r[1],r[2],r[3],r[4],r[5]);
			}
        }
    }
},
_handlePendingJSCalls:function(serviceName) {
    var reqs=gigya.services.socialize.pendingJSRequests[serviceName];
    for (var i=0;i<reqs.length;i++) {
        var req=reqs[i];
        eval(req.methodName+"(req.c,req.p,req.i)");
    }
},
getStyleString:function(oStyle, blnIsLink) {
    var s='';
    s+='line-height: normal;';
    if (blnIsLink) s+='cursor:pointer;';
    if (oStyle.underline) s+='text-decoration:underline;';
    if (oStyle.font) s+='font-family:'+oStyle.font+';';
    if (oStyle.size) s+='font-size:'+oStyle.size+'px;';
    if (oStyle.color) s+='color:'+oStyle.color+';';
    if (oStyle.bold) s+='font-weight:bold;';
    if (oStyle['frame-thickness']) s+='border-style:solid; border-width:'+oStyle['frame-thickness']+'px;';
    if (oStyle['frame-color']) s+='border-color:'+oStyle['frame-color']+';';
    if (oStyle['background-color']) s+='background-color:'+oStyle['background-color']+';';
    return s;
},
_closeComponent:function(rid,dispatchCloseEvent) {
    gigya.services.socialize._HandleResponse(rid, {Action:'Hide'});
    if (dispatchCloseEvent) {
        gigya.services.socialize._broadcastEvent(rid, {eventName:'close'});
    }
},
_createJSPopup:function(rid, resolver, captionText, noCaption) {
	var oRID=gigya.services.socialize._parseRID(rid);
	
	var req=oRID.req;
	var params = req.p;
	var conf = req.c;
	if (gigya.global.valueIsExplicitFalse(params['showCaption'])) noCaption=true;
	
    var GS=gigya.services.socialize;    
    var container=document.getElementById(params['containerID']);
    req.container=container;
    
    var oBgStyle=resolver.Resolve('+/config/body/background');
    var oCaptionStyle=resolver.Resolve('+/config/body/captions');
    
    var s='<table style="'+GS.getStyleString(oBgStyle)+';empty-cells:show;width:'+params['width']+';height:'+params['height']+'" cellpadding="0" cellspacing="0" >';
    if (!noCaption) {
        s+='<tr style="'+GS.getStyleString(oCaptionStyle)+'"><td><table width="100%" cellpadding="0" cellspacing="0"><tr id="'+params['containerID']+'_caption"><td style="vertical-align:middle"><div style="'+GS.getStyleString(oCaptionStyle)+';padding:7px">'+captionText+'</div></td><td style="vertical-align:middle">';
        s+='<div align="right" style="padding-right: 7px; cursor: pointer"><img onclick="gigya.services.socialize._closeComponent(\''+rid+'\', true);"  src="http://cdn.gigya.com/gs/i/HTMLLogin/closeIcon.gif"></div></td></tr></table></td></tr><tr><td colspan="2">';
    } else {
        s+='<tr><td>';
    }
    s+='<div id="'+params['containerID']+'_container"></div></td></tr></table>';
    container.innerHTML=s;
    var p={};
    var c={};
    for (var param in params) {
        p[param]=params[param];
    }
    
    for (var param in conf) {
        c[param]=conf[param];
    }
    
    var caption=document.getElementById(p['containerID']+'_caption');

    p['height']=p['height']-(oBgStyle['frame-thickness']*2);
    if (!noCaption) p['height']-=caption.offsetHeight;
    p['width']=p['width']-(oBgStyle['frame-thickness']*2);
    
    p['containerID']=p['containerID']+'_container';
    
    document.getElementById(p['containerID']).style.width=''+p['width']+'px';
    document.getElementById(p['containerID']).style.height=''+p['height']+'px';
    
    gigya.services.socialize._PopupContainers[p['containerID']]=container
    
    return {c:c,p:p}
},
_createJSPopup2:function(rid, resolver) {
	var oRID=gigya.services.socialize._parseRID(rid);
	
	var req=oRID.req;
	var params = req.p;
	var conf = req.c;
	
    var GS=gigya.services.socialize;    
    var container=document.getElementById(params['containerID']);
    req.container=container;
    
    var base=gigya._vars.lastScriptURLBase +'/gs/i/Dialog/DialogBg_';
    var s='<table style="padding:0px;margin:0px;vertical-align:middle;font-size:1px;line-height:1px;empty-cells:show;width:'+params['width']+';height:'+params['height']+'" cellpadding="0" cellspacing="0" >';
    s+='<tr><td><img src="'+base+'TopLeft.png"></td><td style="background-image:url(\''+base+'filler.png\');bakground-repeat:repeat"></td><td><img src="'+base+'TopRight.png"></td></tr>';
    s+='<tr><td style="background-image:url(\''+base+'filler.png\');background-repeat:repeat"></td><td><div id="'+params['containerID']+'_container"></div><td style="background-image:url(\''+base+'filler.png\');background-repeat:repeat"></td></td></tr>';
    s+='<tr><td><img src="'+base+'BottomLeft.png"></td><td style="background-image:url(\''+base+'filler.png\');bakground-repeat:repeat"></td><td><img src="'+base+'BottomRight.png"></td></tr></table>';
    container.innerHTML=s;
    var p={};
    var c={};
    for (var param in params) {
        p[param]=params[param];
    }
    
    for (var param in conf) {
        c[param]=conf[param];
    }

    p['containerID']=p['containerID']+'_container';
    
    gigya.services.socialize._PopupContainers[p['containerID']]=container
    p['height']=p['height']-20;
    p['width']=p['width']-20;
    
    return {c:c,p:p}
},

_AddJSRequest:function(servicedBy,methodName,containerID,conf,params,i){	

    if (!document.body) {
		var needTimeout=false;
        var pr=gigya.services.socialize.pendingRequests;
        if (typeof pr=='undefined') {
            pr=gigya.services.socialize.pendingRequests=[];
            needTimeout=true
        }    
        pr.push([servicedBy,methodName,containerID,conf,params,i]);
        window.setTimeout('gigya.services.socialize._RetryPending()',200);
        return;
    }


    var blnCenter=false;
    var p={};
    var c={};
    for (var param in params) {
        p[param]=params[param];
    }
    for (var param in conf) {
        c[param]=conf[param];
    }
    var GS=gigya.services.socialize;
    var isPopup=(params['isPopup']==true);
    
    var container;
    
    if (i['grayOut'] && containerID=='') {
	    gigya.services.socialize.GrayOut(true, {'zindex':gigya.global._NextZIndex++, 'opacity':'25'});
    }        
    
    if (containerID=='coreDiv' || containerID.toLowerCase().indexOf('pseudocontainer_')==0 ) {
        if (gigya.services.socialize.pseudoContainers[containerID]==null) {
			gigya.services.socialize.pseudoContainers[containerID]={};
        }
		container=gigya.services.socialize.pseudoContainers[containerID]; //so it will be able to hold .Reqs on it.
    }
    else if (typeof containerID=='undefined' || containerID=='') {
        blnCenter=true;
        containerID=GS.GetCenteredComponentDivID(methodName);
        isPopup=true;
        
        container = document.getElementById(containerID);
        
        if (container==null) {
            container = GS._CreateContainer(containerID);
        }
    } 
    else {
        container=document.getElementById(containerID);
    }
    
    p['containerID']=containerID;
    if (container.style) {
		container.style.visibility='';
		container.innerHTML='';
		var ifrel= document.getElementById('gigya_ifr_'+containerID);
		
		if (!i['isEvent']) {
			if (ifrel!=null) {
				GS._SetContainerSizeAndPosition(ifrel,p.width,p.height,blnCenter);
				if (gigya.browser.isIE) { ifrel.style.visibility='visible';	} 
			}
		    GS._SetContainerSizeAndPosition(container,p.width,p.height,blnCenter);
			
		}
	    
	}
	
	    
	var Reqs=(container.Reqs?container.Reqs:(container.Reqs=[]));	
	var rid=Reqs.length+'@'+servicedBy+'@'+containerID;
	i.rid=rid;
	i.callback='gigya.services.socialize._HandleResponse'
	i.isPopup=isPopup;
	var req=Reqs[Reqs.length]={
		rid:rid,			
		servicedBy:servicedBy,
		container:container,
		method:methodName,
		context:p['context'],
		c:c,
        p:p,
        i:i,
        operation:methodName,
        isHTML:true
	};
	
    var methodNameParts=methodName.split('.');
    var node=eval(methodNameParts[0]);
    var pfxi=1;
    while (null!=(node=node[methodNameParts[pfxi]])  && (++pfxi<methodNameParts.length)) {
        //alert(pfxi);
    };
    var func = node;
    
//    try {func = eval(methodName)} catch(e){}
    
    if (typeof func!='undefined') {
        eval(methodName+'(c,p,i)');
    } else {
        var pr=GS.pendingJSRequests;
        var loadScript=false;
        
        if (typeof pr=='undefined') {
            pr=GS.pendingJSRequests=[];
        }  
        if (typeof pr[servicedBy]=='undefined') {
            pr[servicedBy]=[];
            loadScript=true;
        }
        pr=pr[servicedBy];
        pr.push({serviceName:servicedBy,methodName:methodName,c:c,p:p,i:i});
       
        if (loadScript) {
			gigya.global.loadScript(gigya._vars.lastScriptURLBase +'/js/' + servicedBy + '.js');
            //var script=document.createElement('SCRIPT');
            //script.src=gigya._vars.lastScriptURLBase +'/js/' + servicedBy + '.js?dbg=1';
            //document.body.appendChild(script);
        }
    }
},
parseLang:function(c,p) {
	var lang;
	if (p && p['lang'] != null) {
		lang = p['lang'];
	}
	else if (c && c['lang'] != null) {
		lang = c['lang'];
	}
	else {
		lang = "en";
	}
	
	lang=lang.toLowerCase();
	if (lang=='auto' || lang=='') {
		lang='en';
	}
	return lang;
},

_AddRequest:function(operation,servicedBy,methodName,containerID,w,h,blnCenter,blnShowClose,c,p,moreArgs){	
    if (!document.body) {
		var needTimeout=false;
        var pr=gigya.services.socialize.pendingRequests;
        if (typeof pr=='undefined') {
            pr=gigya.services.socialize.pendingRequests=[];
            needTimeout=true
            
        }    
        pr.push([operation,servicedBy,methodName,containerID,w,h,blnCenter,blnShowClose,c,p,moreArgs]);
        window.setTimeout('gigya.services.socialize._RetryPending()',200);
        return;
    }
    servicedBy = servicedBy.replace('%lang',gigya.services.socialize.parseLang(c,p));
    
    if (moreArgs['grayOut'] && containerID=='') {
	    gigya.services.socialize.GrayOut(true, {'zindex':gigya.global._NextZIndex++, 'opacity':'25'});
    }    
	w=parseInt(w,10);
	h=parseInt(h,10);	
	if ( w == 1 && h == 1 ) {	
		if ( gigya.flash.isIE ) { 		
			w=0;
			h=0;
		}			
	}
	if (!gigya.fbConnectEnabled && p['useFacebookConnect']!=null) {
	    p['useFacebookConnect'] = false;
	}	
	
	var GS=gigya.services.socialize;
		
	// operation is the name from the API
	// methodName is for the swf 
	if (methodName=='') methodName=operation;
	
	// internals are params sent from the js to the flash ( to core for example ) 
	var internals = { methodName:methodName , windowName:moreArgs['windowName'], listenerID: moreArgs['listenerID']};	

	if (containerID=='' || containerID==null || p['isPopup']) {	
		blnCenter=true;
		blnShowClose=true;
		
		if (containerID=='' || containerID==null ) { 		    
		    containerID=GS.GetCenteredComponentDivID(methodName);
		}
		
		// A popup is required
        internals['isPopup']=true; 
	}
	
	if ( moreArgs['isEvent'] ) {
	    internals['isEvent']=true;
	    internals['e'] = moreArgs['e'] 
	}
		
		
   // debugger;		
	var container=GS._GetContainer(containerID);
	
	if (container==null) {	    
	    if ( ('gigyaEventsListenerDiv'!=containerID) && containerID!=null && containerID!='' 
	                                                 && typeof internals['isPopup'] =='undefined' && typeof p['isPopup'] =='undefined' ) { 	        
            return gigya.services.socialize._noSuchDivID(containerID,p,methodName);
	    }
		container=GS._CreateContainer(containerID);
	} else{ 
		
	}
	
	
	var ifrel= document.getElementById('gigya_ifr_'+containerID);
	
	if (!internals['isEvent']) {
	    if (ifrel!=null) {
			if (w==1 && h==1 && gigya.browser.isChrome) {
			    
				GS._SetContainerSizeAndPosition(ifrel,30,1,blnCenter); //fix for bug #10525
			}
			else {
				GS._SetContainerSizeAndPosition(ifrel,w,h,blnCenter);
			}
	    }
	    GS._SetContainerSizeAndPosition(container,w,h,blnCenter);
	}
	if (internals['isPopup']) GS._HandleEmbedAndObjectsBelow(container,w,h);
    if ( containerID =='coreDiv' ) {
        gigya.services.socialize._DodgeEmbedsAndIframes(container,w,h);	
	    if ( ifrel!=null ) {	        
	       ifrel.style.zIndex = 99998; 
	    }
	    container.style.zIndex = 99999;
	}	
	
	var Reqs=(container.Reqs?container.Reqs:(container.Reqs=[]));	
	var rid=Reqs.length+'@'+servicedBy+'@'+container.id;
    //alert('rid=' +rid + '\nc='+c+'\ncallback='+p['callback']) ;		
	
	// params that are passed to the swf
	var args=[rid,c,p,internals];
	
	var callback = p['callback'];
	
	var context = p['context']; // so we wont try to serialize this as part of the args.
    delete p['context'];
	
	var req=Reqs[Reqs.length]={
			rid:rid,			
			servicedBy:servicedBy,
			container:container,
			method:methodName,
			serializedArgs:GS._SerializeArgs(args),
			c:c,
            p:p,					
			context:context,
			moreArgs:moreArgs,
			w:w,
			h:h,
			internals:internals,
			operation:operation
			//,request:{operation:operation,args:args,status:'',callback:callback,context:moreArgs}
	};
			
	gigya.services.socialize._TryExecute(rid);
},

_TryExecute:function(rid){
	var GS=gigya.services.socialize;
	if (GS._LoadRequiredFor(rid)) { 
		//alert('b4 _LoadSWF');
		GS._LoadSWF(rid);
	}
	else {		
		//alert('b4 _DoRequest');
		GS._DoRequest(rid);
	}

},


_AdjustResponseStatus:function(response){
	switch ((''+response.status).toUpperCase()) {
		case 'FAIL':response.status='ERROR';break;
		case 'NEW_USER':
		case 'NO_AUTH_SITE':response.status='NOT_LOGGED_IN';break;
		case 'INVALID_URL':
		case 'INVALID_SITE':response.status='INVALID_KEY';break;
		case 'NO_AUTH_LEVEL':response.status='UNAUTHORIZED';break;
	}
},

_HandleResponse:function(rid,response){	
    if ( typeof rid == null ) return;
    
    if (response.statusMessage==undefined) {
        response.statusMessage = '';
    }

	if (gigya.services.socialize._Responses==null) {
	    gigya.services.socialize._Responses={};
	    gigya.services.socialize._uidx=0;
	}
	var uidx=gigya.services.socialize._uidx++;
	gigya.services.socialize._Responses[rid+'_'+uidx]=response;
	var expr='gigya.services.socialize.__HandleResponse(\'' + rid + '\',\'' + rid +'_'+uidx + '\');';	
	window.setTimeout(expr,1);
	return true;
},

__HandleResponse:function(rid,key){	    

    var response=gigya.services.socialize._Responses[key];
	delete gigya.services.socialize._Responses[key];

	var oRID=gigya.services.socialize._parseRID(rid);
	
	var req=oRID.req;
	
	response.requestParams = req.p;
	
	if (typeof req.p.context!='undefined') response.context = req.p.context;
	gigya.services.socialize._AdjustResponseStatus(response);
	if ( response.status=='INVALID_KEY' ) {
	    var errText = 'The Gigya Socialize key set on this page does not match this domain.\nPlease make sure to set up this domain and get the proper key in the URL bellow:\n  http://www.gigya.com/site/partners/wfsocapi.aspx#&&userstate=SiteSetup';
	    //alert(errText);
	}

    if (!req.isHTML) gigya.services.socialize._HandleObjectRepresentation(response);
    	
	if (gigya.services.socialize.verbose || (req.c!=null && req.c.verbose)) {
		alert(gigya.services.socialize.describeObject(response,'response','JS response after empty string fix for operation ' + req.operation + ' for rid='+rid,4)+'\n=============\n'+gigya.services.socialize.describeObject(req,'req','req for operation ' + req.operation + ' for rid='+rid,10));
	}
	
	/// CONTEXT RESTORATION !!!!
	response.context=req.context;
	response.operation=req.operation; 
	var lastDotIndex;
	if (-1<(lastDotIndex=response.operation.lastIndexOf('.'))) {
		response.operation=response.operation.substr(lastDotIndex+1);
	}
	//if (response.context == null) response.context = {};
	
	gigya.services.socialize._HandleSpecialFields(response);
	
	
	if (response.Action && (response.Action!='') && (response.Action!=null)) {
		if (response.Action=='Hide') {
		    gigya.services.socialize.GrayOut(false);
			//req.container.style.display='none';
			var ifr=document.getElementById('gigya_ifr_'+req.container.id)
			if (ifr!=null) ifr.style.visibility='hidden';
			
			var elementsToShowOnClose=req.container.elementsToShowOnClose
			if (elementsToShowOnClose!=null) {
				for (var i=0;i<elementsToShowOnClose.length;i++) {
					elementsToShowOnClose[i].style.visibility='';
				}
			}
			var cd=document.getElementById('coreDiv_WSSCore');
			
			if (cd!=null) {
				
				if ((gigya.flash.isIE && gigya.flash.isWin) || gigya.flash.isChrome) {
					var cdifr=document.getElementById('gigya_ifr_coreDiv');
					cd.style.visibility='hidden';
					cd.style.display='none';
					cdifr.style.visibility='hidden';
					cdifr.style.display='none';
				}
				else if (gigya.flash.isFF) {
					cd.width=0; // this prevents a white dot from apearing where 'coreDiv_WSSCore' is.
				}
			}
			
			req.container.innerHTML='&nbsp;';
			req.container.style.visibility='hidden';
			req.Loaded=true;
			
//			req.container.Reqs = [];
			
		}
		
	}
	else {
	    //	alert('response.Action was empty');
	}
		
	if (gigya.services.socialize.verbose || (req.c!=null && req.c.verbose)) alert('before callback \n' + gigya.services.socialize.describeObject(response,'response','response to be passed to callback for ' + req.operation + ' for rid='+rid,4)+'\n=============\n'+gigya.services.socialize.describeObject(req.p['callback'],'req.p[\'callback\']','req.p[\'callback\'] for operation ' + req.operation + ' for rid='+rid,4));

	if (response.Action!='Hide') {
	    delete response.Action;
	    
	    if (typeof req.p['callback']=='function' && response!=null) {
	        
		    req.p['callback'](response);
	    }
	    else {
		    //if (gigya.services.socialize.verbose || (req.c!=null && req.c.verbose)) {alert ('No callbeck found to call on ');}
		    if ( null!=req.p['callback'] ) {		    
		        var wrongCallbackMsg ='The callback for ' + req.operation +' function ( "'+req.p['callback']+ '" ) is not a function.';
		        wrongCallbackMsg +='\nPlease provide a callback function and not a string.';
		        alert(wrongCallbackMsg);
		    }
	    }
    }
    else {
        delete response.Action;
    }
},

_HandleSpecialFields:function(o) {
    if (o.photos) {
        o.photos=new gigya.services.socialize.Collection(o.photos, '');
    }
    if (o.albums) {
        o.albums=new gigya.services.socialize.Collection(o.albums, '');
    }    
	if (o.user)   {o.user=new gigya.services.socialize.User(o.user);}
	if (o.friends){
	    var arUIDs=[];
	    for (var i=0; i<o.friends.length; i++) {
	        arUIDs.push(o.friends[i].UID);
	    }
	    o.UIDs=arUIDs.join(',');
	    o.friends=new gigya.services.socialize.Collection(gigya.services.socialize._ConvertToTypedObjects(o.friends,gigya.services.socialize.Friend),'UID');
	}
	if (o.contacts){
	    o.contacts=new gigya.services.socialize.Collection(gigya.services.socialize._ConvertToTypedObjects(o.contacts,gigya.services.socialize.Contact),'email');
	}
	if (o.friend) {o.friend=new gigya.services.socialize.Collection(gigya.services.socialize._ConvertToTypedObjects(o.friend,gigya.services.socialize.Friend),'UID');}	
	if (o.actions){o.actions=new gigya.services.socialize.Collection(gigya.services.socialize._ConvertToTypedObjects(o.actions,gigya.services.socialize.UserAction),'UID');}
	
},

addEventHandlers:function(c,p) {    
    var eventHandlerName = '';
    var status = 'OK';
    var statusMessage = '';
    var errorCode = 0;
    var errorMessage = '';
    for ( var knowEvtHandlerName in this._GlobalEventHandlers ) { 
        if (typeof p[knowEvtHandlerName]=='function') {
            eventHandlerName=knowEvtHandlerName;         
            var eventHandlers=this._GlobalEventHandlers[eventHandlerName];  
			var currHandlerIndex;
			if (null!=p['ContainerAndSWF']) {
				currHandlerIndex=p['ContainerAndSWF'];
			}
			else {
				currHandlerIndex=(eventHandlers.idx++);
			}
			
            eventHandlers['HC'+currHandlerIndex]={
                context:p['context'],
                handler:p[eventHandlerName],
                listenerType:(typeof p['listenerType']=='undefined')?'other':p['listenerType'],
                listenerDescription:(typeof p['listenerDescription']=='undefined')?'':p['listenerDescription'],
                ContainerAndSWF:p['ContainerAndSWF']
            };  
        }
        else {
            if ( p[knowEvtHandlerName]!=null ) { 
                alert('gigya.services.socialize.addEventHandlers:\nThe event handler \''+knowEvtHandlerName+'\' is not a function');
                status = 'FAIL';
                errorCode = 400102;
                statusMessage = 'Invalid_event_handler';
                errorMessage = 'Invalid_event_handler';
            }
        }
    } 
            
    if ( typeof p['callback'] == 'function' ) {
        var response = { status:status, statusMessage: statusMessage, errorCode:errorCode,errorMessage:errorMessage, operation: 'addEventHandlers', context: p['context'] };        
        p['callback'](response);
    }   

} , 



_dispatchGlobalEvent:function(eventObj,ignoreRID) {
    gigya.services.socialize._HandleObjectRepresentation(eventObj);
    var eventHandlerName = 'on'+eventObj['eventName'].substring(0,1).toUpperCase()+eventObj['eventName'].substring(1);
    var eventHandlers=gigya.services.socialize._GlobalEventHandlers[eventHandlerName];
    var eventHandlerKeysSnaphhot={}; // used to prevent a situation where more handlers are added and called during and as a result of the event dispatch.
    for (var hcKey in eventHandlers ) { 
		eventHandlerKeysSnaphhot[hcKey]=true;
    };
    var eventObjCopy;
    var needToInvoke;
    var ListenerTypes=['component','other'];
	for (var iListenerType=0;iListenerType<ListenerTypes.length;iListenerType++) {
		var listenerType=ListenerTypes[iListenerType];
		for (hcKey in eventHandlerKeysSnaphhot ) {
			if (hcKey.substring(0,2)!='HC') continue;
			if (eventHandlers[hcKey].listenerType==listenerType) {
			    eventObjCopy = new Object();
			    for (var prop in eventObj ) {
				    eventObjCopy[prop] = eventObj[prop];            
			    }
			    eventObjCopy['context'] = eventHandlers[hcKey]['context'];        
			    if (listenerType!='component') {
				    // Make sure returned fields such as friends are returned as collections.
				    gigya.services.socialize._HandleSpecialFields(eventObjCopy);
			    }
			    needToInvoke = true;
                if (ignoreRID != null) {
                    var oRID=gigya.services.socialize._parseRID(ignoreRID);
                    var container=oRID.container;
                    var req=oRID.req;
                    if ( null!=req ) { 
	                    var swfName=req.servicedBy;                    
	                    var ContainerIDAndSWFName=container.id+'_'+swfName;
	                    var cas = eventHandlers[hcKey]['ContainerAndSWF'];
	                    if ( typeof cas !='undefined' ) {				    
		                    if ( ContainerIDAndSWFName == cas ) {
			                    needToInvoke = false;				            
		                    }
	                    }
                    }
                }
			    if ( needToInvoke ) {
					if ( gigya.services.socialize.plugins && gigya.services.socialize.plugins.debug && gigya.services.socialize.plugins.debug.conf && gigya.services.socialize.plugins.debug.conf.dbg>0  ) { 	
						var debug=gigya.services.socialize.plugins.debug;
						if ((debug.conf.dbg>1) || ((debug.conf.dbg>0) && (listenerType=='other'))) {
							gigya.services.socialize._callPartnerHandlerForGlobalEvent(eventHandlers[hcKey]['handler'],eventObjCopy)
						}
					}
					else {
						eventHandlers[hcKey]['handler'](eventObjCopy);
			        }
			    }
		    }
	    }
    }
} , 

_callPartnerHandlerForGlobalEvent:function(handler,eventObj){
	handler(eventObj); // calling your event handler (use step-into to enter your own code)
},

_fireComponentEvent:function(rid,eventObj) {  
  gigya.services.socialize._AdjustResponseStatus(eventObj);    
  if ( 'error'==eventObj['eventName'] && 'INVALID_KEY'==eventObj['status'] ) {
        var errTxt = 'The Gigya Socialize key set on this page does not match this domain.\nPlease make sure to set up this domain and get the proper key in the URL bellow:\n  http://www.gigya.com/site/partners/wfsocapi.aspx#&&userstate=SiteSetup';
	    //alert(errTxt);
  }
    
  gigya.services.socialize._HandleObjectRepresentation(eventObj);
  var oRID=gigya.services.socialize._parseRID(rid);
  var req=oRID.req;
  if ( null == req ) return;
  var eventHandlerName = 'on'+eventObj['eventName'].substring(0,1).toUpperCase()+eventObj['eventName'].substring(1);  
  if ( typeof req.p[eventHandlerName] == 'function' ) {
	eventObj.context=req.context;

	// Make sure returned fields such as friends are returned as collections.
	gigya.services.socialize._HandleSpecialFields(eventObj);
    
    req.p[eventHandlerName](eventObj);
  }  
},
_addDefaultResponseProperties:function(response, target) {
	var r = response;
	if (r.response) r = r.response;
	if (target == null) target = { };
	var status = 'FAIL';
	var statusMessage = 'General Server Error';
	var errorCode = 500001;
	var errorMessage = 'General Server Error';
	if (r != null) {
		if (r.status != null) status = r.status;
		if (r.statusMessage != null) statusMessage = r.statusMessage;
		if (r.errorCode != null) errorCode = r.errorCode;
		if (r.errorMessage != null) errorMessage = r.errorMessage;
	}
	target.status = status;
	target.statusMessage = statusMessage;
	target.errorCode = errorCode;
	target.errorMessage = errorMessage;
	return target;
},
_broadcastError:function(rid, response, additionalProperties) {
	var evt = { eventName:'error' };
	gigya.services.socialize._addDefaultResponseProperties(response, evt);
	if (additionalProperties != null) {
		for (var p in additionalProperties) {
			evt[p] = additionalProperties[p];
		}
	}
	gigya.services.socialize._broadcastEvent(rid, evt);
},
_broadcastEvent:function(rid,eventObj,global,sendToSelf) {
	if (global) {
		if (sendToSelf) {
			this._dispatchGlobalEvent(eventObj);
		} else {
			this._dispatchGlobalEvent(eventObj, rid);
		}
	} else {
		this._fireComponentEvent(rid, eventObj);
	}
},
_addCoreJSRequest:function(c,p,i,operation){
	gigya.services.socialize._AddJSRequest('gigya.services.socialize.plugins.core','gigya.services.socialize.plugins.core.'+operation,'coreDiv',c,p,i);
},

setStatus:function(c,p){	
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	//var moreArgs = {};
	//gigya.services.socialize._AddRequest('setStatus','Gigya.Socialize.Core','','coreDiv',1,1,true,false,c,p,moreArgs); 	
	//gigya.services.socialize._AddJSRequest('gigya.services.socialize.plugins.core','gigya.services.socialize.plugins.core.setStatus','coreDiv',c,p);
	gigya.services.socialize._addCoreJSRequest(c,p,{},'setStatus');
},	
getPhotos:function(c,p){
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	//var moreArgs = {};
	//gigya.services.socialize._AddRequest('getPhotos','Gigya.Socialize.Core','','coreDiv',1,1,true,false,c,p,moreArgs); 	    
	//gigya.services.socialize._AddJSRequest('gigya.services.socialize.plugins.core','gigya.services.socialize.plugins.core.getPhotos','coreDiv',c,p);
	gigya.services.socialize._addCoreJSRequest(c,p,{},'getPhotos');
},
getAlbums:function(c,p){
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	//var moreArgs = {};
	//gigya.services.socialize._AddRequest('getAlbums','Gigya.Socialize.Core','','coreDiv',1,1,true,false,c,p,moreArgs); 	    
	//gigya.services.socialize._AddJSRequest('gigya.services.socialize.plugins.core','gigya.services.socialize.plugins.core.getAlbums','coreDiv',c,p);
	gigya.services.socialize._addCoreJSRequest(c,p,{},'getAlbums');
},

notifyLogin:function(c,p){	
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	gigya.services.socialize._addCoreJSRequest(c,p,{},'notifyLogin');

},	
	
isLoggedIn:function(c,p){	
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	//var moreArgs = {};
	//gigya.services.socialize._AddRequest('isLoggedIn','Gigya.Socialize.Core','','coreDiv',1,1,true,false,c,p,moreArgs); 	
	//gigya.services.socialize._AddJSRequest('gigya.services.socialize.plugins.core','gigya.services.socialize.plugins.core.isLoggedIn','coreDiv',c,p);
	gigya.services.socialize._addCoreJSRequest(c,p,{},'isLoggedIn');
},	
	
getSessionInfo:function(c,p){	
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	//var moreArgs = {};
	//gigya.services.socialize._AddRequest('getSessionInfo','Gigya.Socialize.Core','','coreDiv',1,1,true,false,c,p,moreArgs); 	
	//gigya.services.socialize._AddJSRequest('gigya.services.socialize.plugins.core','gigya.services.socialize.plugins.core.getSessionInfo','coreDiv',c,p);
	gigya.services.socialize._addCoreJSRequest(c,p,{},'getSessionInfo');
},	

getRawData:function(c,p){		
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	//var moreArgs = {};
	//gigya.services.socialize._AddRequest('getRawData','Gigya.Socialize.Core','','coreDiv',1,1,true,false,c,p,moreArgs);
	gigya.services.socialize._addCoreJSRequest(c,p,{},'getRawData');
},
	
getAvailableProviders:function(c,p){		
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	//var moreArgs = {};
	//gigya.services.socialize._AddRequest('getAvailableProviders','Gigya.Socialize.Core','','coreDiv',1,1,true,false,c,p,moreArgs); 	
	gigya.services.socialize._addCoreJSRequest(c,p,{},'getAvailableProviders');
},
_convertAction:function(c,p){
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });	
	gigya.services.socialize._addCoreJSRequest(c,p,{},'convertAction');    
},
_getProviderByName:function(provider,providersEnum) {
    if (null==providersEnum) providersEnum=gigya.services.socialize._arProviders;
    for (var i=0; i<providersEnum.length; i++) {
        if (providersEnum[i].name.toLowerCase()==provider.toLowerCase()) return providersEnum[i];
    }
},
_getProviderByID:function(providerID,providersEnum) {
    if (null==providersEnum) providersEnum=gigya.services.socialize._arProviders;
    for (var i=0; i<providersEnum.length; i++) {
        if (providersEnum[i].ID==providerID) return providersEnum[i];
    }
},
_SNLink:function(onSNLink,c,p,SNLinkMethod,rid,lid,permissions,getPermissionsOnly,neverUseIframe,sendUserAction,operation){
	var enabledProviders=(c['enabledProviders']?c['enabledProviders']:'*');
	var disabledProviders=(c['disabledProviders']?c['disabledProviders']:'');
	var lang;
	if (p && p['lang'] != null) {
		lang = p['lang'];
	}
	else if (c && c['lang'] != null) {
		lang = c['lang'];
	}
	else {
		lang = "en";
	}
	
	lang=lang.toLowerCase();
	if (lang=='auto' || lang=='') {
		lang='en';
	}
	
	var provider;
	if (p && p['provider']) provider=gigya.services.socialize._getProviderByName(p['provider'].toLowerCase());
	var callback = p['callback']; 
	if (typeof provider=='undefined' && typeof callback!='undefined') {
        var resp = {
            operation: operation, 
            context: p['context'],
            status:'FAIL', 
            statusMessage:'Invalid_provider',
            errorCode: 400099,
            errorMessage: 'Invalid_provider'
        };
        
        callback(resp);	    
	    return;
	}
	
    gigya.global.addCookieEventListener(rid+'_'+lid,p.context,onSNLink);
	if (!(gigya.browser.isMobile) && !(gigya.browser.supportsPostMessage)) {
		gigya.services.socialize._AddRequest('setOnLoginCompleteCallback','eventsBroadcaster','','gigyaEventsListenerDiv',1,1,true,false,{},{onLoginCompleteFunctionName:'gigya.global.onLoginEventFromFlashListener' , listenerID: lid},{}); 	
	}
	
	
	rid=rid+'~'+lid;
	var forceIframe=false;
	var snid=provider.ID;
	var windowOptions='menubar=0,toolbar=0,resizable=1,scrollbars=1,width=' + provider.width + ',height=' + provider.height;
	var domain=gigya.global.URLEncode(document.location.href.split('://')[1].split('?')[0].split('#')[0]);
	var ap={
	    enabledProviders: enabledProviders,
	    disabledProviders: disabledProviders,
	    lang: lang
	}
	var useIframe = (gigya.fbConnectEnabled && (p['useFacebookConnect']==true || p['useFacebookConnect']=='true'));
	var sessionExpiration=p['sessionExpiration'];
	var pd = c['cid'];
	if (typeof p['cid']!='undefined') pd = p['cid'];
	var su = c['shortURLs'];
	if (typeof p['shortURLs']!='undefined') su = p['shortURLs'];

	var pr=c['pendingRegistration']
	if (typeof p['pendingRegistration']!='undefined') pr = p['pendingRegistration'];
	
	
	if (typeof sessionExpiration!='undefined') ap['sessionExpiration'] = sessionExpiration;
	if (typeof pd!='undefined') ap['pd'] = pd;
	if (typeof su!='undefined') ap['su'] = su;
	if ((typeof pr!='undefined') &&  gigya.global.valueIsExplicitTrue(pendingRegistration)) ap['pr'] = true; //false is the default 
	
	if (typeof permissions!='undefined') {
		ap['perms'] = permissions;
		if (getPermissionsOnly) {
			ap['getPerms'] = true;
			if (!neverUseIframe) {
				useIframe = true;
				forceIframe = true;					
			}
		}
	}	
	var ad=gigya.global.URLEncode(gigya.services.socialize._createObjectQueryString(ap));
	var adIframe=ad;
	//safari doesn't allow third party cookies by default, so we never use iframe in safari
    if (useIframe && provider.nativeLoginStr) adIframe += gigya.global.URLEncode(provider.nativeLoginStr);
	var url=gigya._vars.lastScriptProtocol+'://socialize.gigya.com/GS/SNLink.aspx?rid='+rid+'&m='+SNLinkMethod+'&d='+domain+'&ak='+c['APIKey']+'&sn='+snid+'&js=1';

	
	if (sendUserAction) {
		//trying to send userAction for facebook fallback (fb share screen). 400 is an average SNLink URL size.
		var ua = gigya.global.JSONSerialize(p['userAction']);
		if (gigya.global.URLEncode(ua).length < (2083 - 400)) {
			url+='&ua='+gigya.global.URLEncode(ua);
		} else {
			var linkback = p['userAction'].linkBack;
			if (linkback==null || linkback=='') {
				try {
					linkback = '' + document.location.href;
				} catch (e) { }
			}
			if (linkback!=null) url+='&lb='+linkback;
		}
	}

    if (gigya.browser.isMobile || gigya.browser.supportsPostMessage) {
        url += '&mobile=1';
    }	
	
	var iframeUrl=url;
	url+='&ad='+ad;
	iframeUrl+='&ad='+adIframe;
	    
    var invite = p.invite;
	if (typeof invite == 'object') {
		if (invite.title) url+='&ivTl='+gigya.global.URLEncode(invite.title);
		if (invite.text) url+='&ivT='+gigya.global.URLEncode(invite.text);
		if (invite.name) url+='&ivN='+gigya.global.URLEncode(invite.name);
		if (invite.actionText) url+='&ivAT='+gigya.global.URLEncode(invite.actionText);
		if (invite.actionURL) url+='&ivAU='+gigya.global.URLEncode(invite.actionURL);
		if (invite.repeatFreq) url+='&ivIF='+gigya.global.URLEncode(invite.repeatFreq);
		if (invite.repeatCap) url+='&ivIC='+gigya.global.URLEncode(invite.repeatCap);
		if (invite.reinviteFreq) url+='&ivRF='+gigya.global.URLEncode(invite.reinviteFreq);
		if (invite.reinviteCap) url+='&ivRC='+gigya.global.URLEncode(invite.reinviteCap);
		if (p['provider'].toLowerCase()=='facebook') windowOptions = 'menubar=0,toolbar=0,resizable=1,width=650,height=520,scrollbars=1';
	}
	var e='login';
	if (SNLinkMethod == 'cn') e = 'connect'
    var pixelURL=gigya._vars.lastScriptProtocol+'://socialize.gigya.com/gs/api.ashx?f=re&e='+e+'&ak='+c['APIKey']+'&sn='+snid;	
    if (typeof pd!='undefined') {
        pixelURL+='&pd='+gigya.global.URLEncode(pd);
    }

    var imgPixel=new Image();
    imgPixel.src=pixelURL;
    
	//window.open(url, 'GS_login_'+p['provider'], windowOptions);
	if (!useIframe || neverUseIframe) iframeUrl=null;
	
	gigya.global._OpenTarget(url, 'GS_login_'+p['provider'], windowOptions, false, iframeUrl, provider.iframeWidth, provider.iframeHeight, forceIframe)
	return true;
},
_createObjectQueryString:function(params) {
	var arParams = [];
	for (var pName in params) {
		arParams.push(pName + '=' + gigya.global.URLEncode(params[pName]));
	}
	return arParams.join('&');    
},
_listenerID:(new Date()).getTime(),

requestPermissions:function(c,p){

	var i={};
	var shouldOpenWindow=true;
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''}, provider:{nullAs:''}});

	if (p['provider']=='') {
		i.presetResponse =  {
			status:'FAIL', 
			statusMessage:'Missing_required_provider_parameter',
			errorCode: 400060,
			errorMessage: 'Missing_required_provider_parameter'
		}
		shouldOpenWindow=false;
	}
	else {
		var provider = gigya.services.socialize._getProviderByName(p['provider']);
		if (provider == null) {
			i.presetResponse =  {
				status:'FAIL', 
				statusMessage:'Invalid_provider',
				errorCode: 400099,
				errorMessage: 'Invalid_provider'
			}
			shouldOpenWindow=false;
		}	
    }
	var ReqsLength=0;

	if (gigya.services.socialize.coreDivContainer==null) {
			gigya.services.socialize.coreDivContainer={};
	}

	var corediv=gigya.services.socialize.coreDivContainer;
	if (corediv!=null && corediv.Reqs!=null) {
	    ReqsLength=corediv.Reqs.length;
	}
	var lid=gigya.services.socialize._listenerID;
	var rid=(ReqsLength+1)+'@Gigya.Socialize.Core@coreDiv';
	
	if (shouldOpenWindow==true) {
		gigya.services.socialize._SNLink(
		    function(event,context){
			    gigya.services.socialize._addCoreJSRequest(c,p,{snlinkEvent:event},'requestPermissions');
		    },
		    c,p,'cn',rid,lid,p['permissions'],true,(!p.useIframe),false,'requestPermissions'
	    );
	}
	else {
		//Will return the presetResponse
		gigya.services.socialize._addCoreJSRequest(c,p,i,'requestPermissions');
	}
},

login:function(c,p){ // Window opeing (i.e. call to snlink can not be done from the plugin as it will loose user click context and be blocked */

    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''}, provider:{nullAs:''}});
	var moreArgs = {};	
	var ReqsLength=0;

	if (gigya.services.socialize.coreDivContainer==null) {
			gigya.services.socialize.coreDivContainer={};
	}

	var corediv=gigya.services.socialize.coreDivContainer;
	if (corediv!=null && corediv.Reqs!=null) {
	    ReqsLength=corediv.Reqs.length;
	}
	var lid=gigya.services.socialize._listenerID;
	var rid=(ReqsLength+1)+'@Gigya.Socialize.Core@coreDiv';
	gigya.services.socialize._SNLink(
	    function(event,context){
		    gigya.services.socialize._addCoreJSRequest(c,p,{snlinkEvent:event},'login');
	    },	
	    c,p,'au',rid,lid,p['_permissions'],false,false,false,'login');
},


logout:function(c,p){	
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	//var moreArgs = {};
	//gigya.services.socialize._AddRequest('logout','Gigya.Socialize.Core','','coreDiv',1,1,true,false,c,p,moreArgs);
	gigya.services.socialize._addCoreJSRequest(c,p,{},'logout');
},	
	
connect:function(c,p){
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''}, provider:{nullAs:''}});
	var moreArgs = {};	
	var ReqsLength=0;

	if (gigya.services.socialize.coreDivContainer==null) {
			gigya.services.socialize.coreDivContainer={};
	}

	var corediv=gigya.services.socialize.coreDivContainer;
	if (corediv!=null && corediv.Reqs!=null) {
	    ReqsLength=corediv.Reqs.length;
	}
	var lid=gigya.services.socialize._listenerID;
	var rid=(ReqsLength+1)+'@Gigya.Socialize.Core@coreDiv';
	
	gigya.services.socialize._SNLink(
	    function(event,context){
		    gigya.services.socialize._addCoreJSRequest(c,p,{snlinkEvent:event},'connect');
	    },
	    c,p,'cn',rid,lid,p['_permissions'],false,false,false,'connect');

/*
	if (gigya.services.socialize._SNLink(c,p,'cn','connect', ReqsLength+'@Gigya.Socialize.Core@coreDiv',lid)) {
	    moreArgs['listenerID']=lid;
	    gigya.services.socialize._AddRequest('connect','Gigya.Socialize.Core','','coreDiv',1,1,true,false,c,p,moreArgs);
	}
*/
	
},	
	
disconnect:function(c,p){	
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	gigya.services.socialize._addCoreJSRequest(c,p,{},'disconnect');
},			

getUserInfo:function(c,p){
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	gigya.services.socialize._addCoreJSRequest(c,p,{},'getUserInfo');
},

linkAccounts:function(c,p){
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	gigya.services.socialize._addCoreJSRequest(c,p,{},'linkAccounts');
},


notifyRegistration:function(c,p){
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	gigya.services.socialize._addCoreJSRequest(c,p,{},'notifyRegistration');
},

deleteAccount:function(c,p){
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	gigya.services.socialize._addCoreJSRequest(c,p,{},'deleteAccount');
},


unlinkAccounts:function(c,p){
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	gigya.services.socialize._addCoreJSRequest(c,p,{},'unlinkAccounts');
},

getFriendsInfo:function(c,p){	
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''}, UIDs:{def:''} });
    if (typeof p['friends']!='undefined') {
		var friendUIDs=gigya.services.socialize._ExtractListOfGIGUIDs(p['friends']);
		if (p['UIDs'].length>0) {
			p['UIDs']+=',';
		}
		p['UIDs']+=friendUIDs;
	}
	gigya.services.socialize._addCoreJSRequest(c,p,{},'getFriendsInfo');
},
	
getContacts:function(c,p){	
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	gigya.services.socialize._addCoreJSRequest(c,p,{},'getContacts');
},	
	
sendNotification:function(c,p){	
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });    
    p['recipients']=gigya.services.socialize._ExtractListOfGIGUIDs(p['recipients']);    
	gigya.services.socialize._addCoreJSRequest(c,p,{},'sendNotification');
},	
	

publishUserAction:function(c,p){  
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} }); 

	if (gigya.global.ParamsFailValidation(c,p,{userAction:{req:true}})) return;
    
	//var moreArgs = { };	
	//gigya.services.socialize._AddRequest('publishUserAction','Gigya.Socialize.Core','','coreDiv',1,1,true,false,c,p,moreArgs);	
	gigya.services.socialize._addCoreJSRequest(c,p,{},'publishUserAction');
} ,
	
	
getActions:function(c,p){
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''},siteActionOnly:{nullAs:true} }); 	
	var moreArgs = { };
	gigya.services.socialize._AddRequest('getActions','Gigya.Socialize.Core','','coreDiv',1,1,true,false,c,p,moreArgs);	
},	

	
showFriendSelectorUI:function(c,p){
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	var containerID=p['containerID'];	        
	p = gigya.global.normalizeParams(p,false, { width:{def:400}, height:{def:360} });	 
	var moreArgs = { };			

	gigya.global._ClearContainer(containerID);
	gigya.services.socialize._AddRequest('showFriendSelectorUI','Gigya.Socialize.FriendSelector_%lang','',containerID,p['width'],p['height'],true,false,c,p,moreArgs);
},	
	
showShareUI:function(c,p){
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	var containerID=p['containerID'];	
	
	
	if (gigya.global.ParamsFailValidation(c,p,{userAction:{req:true}})) return;
	
	
	gigya.global._ClearContainer(containerID);
    
    if (gigya.browser.isMobile || gigya.global.valueIsExplicitTrue(p['useHTML'])) {
        gigya.services.socialize._showHTMLShareUI(c,p);
        return;    
    }    
    
    var moreArgs = { };		
    moreArgs['grayOut']=true;
    p = gigya.global.normalizeParams(p,false, {width:{def:520},height:{def:320}});
	gigya.services.socialize._AddRequest('showShareUI','Gigya.Socialize.Share_%lang','',containerID,p['width'],p['height'],true,false,c,p,moreArgs);
},				

_showHTMLShareUI:function(c,p){
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	var containerID=p['containerID'];	
	p = gigya.global.normalizeParams(p,false, {width:{def:595},height:{def:324}});
	

	if (gigya.global.ParamsFailValidation(c,p,{userAction:{req:true}})) return;
	
	var moreArgs = { };		
	gigya.global._ClearContainer(containerID);
	
	if (p['containerID']!='') {
        if (gigya.browser.isMobile) {
            p['containerID']='';
        } else {
            p['useHTML']=false;
            gigya.services.socialize.showShareUI(c,p);
            return;  
        }
    }
    
	if (p['containerID']=='') {
	    //force width/height
        p['width']=595;
        p['height']=324;	
    }
	gigya.services.socialize._AddJSRequest('gigya.services.socialize.plugins.share','gigya.services.socialize.plugins.share.showShareUI',p['containerID'],c,p,{});
	
},				

_showHTMLBookmarkUI:function(c,p){
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	var containerID=p['containerID'];	
	var isPopup = containerID=='' || p['isPopup'];    
    if ( isPopup ) {      	
	    p = gigya.global.normalizeParams(p,false, { width:{def:310}, height:{def:310} });	   
	}
	else {
		gigya.global._ClearContainer(containerID);
        p = gigya.global.normalizeParams(p,false, { width:{def:310}, height:{def:250} });	   	
	}
	gigya.services.socialize._AddJSRequest('gigya.services.socialize.plugins.bookmark','gigya.services.socialize.plugins.bookmark.showBookmarkUI',p['containerID'],c,p,{});
},				


_showHTMLLoginUI:function(c,p){
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
    p = gigya.global.normalizeParams(p,false, { width:{def:120}, height:{def:110} });	    
	gigya.services.socialize._AddJSRequest('gigya.services.socialize.plugins.login','gigya.services.socialize.plugins.login.showLoginUI',p['containerID'],c,p,{});
},
showFeedUI:function(c,p){
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
    if (p.containerID=='') return;
    p = gigya.global.normalizeParams(p,false, { width:{def:304}, height:{def:265} });	    
	gigya.services.socialize._AddJSRequest('gigya.services.socialize.plugins.newsfeed','gigya.services.socialize.plugins.newsfeed.showFeedUI',p['containerID'],c,p,{});
},
showLoginUI:function(c,p){  
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });  
	var containerID=p['containerID'];  	
    var isPopup = (containerID=='' || p['isPopup']);    
    if ( isPopup ) {                
	    p = gigya.global.normalizeParams(p,false, { width:{def:280}, height:{def:220} });
    }
    else {            
		gigya.global._ClearContainer(containerID);
	    p = gigya.global.normalizeParams(p,false, { width:{def:120}, height:{def:110} });	 	    
    }
    if (gigya.browser.isMobile || gigya.global.valueIsExplicitTrue(p['useHTML'])) {
        gigya.services.socialize._showHTMLLoginUI(c,p);
        return;    
    }        
	var moreArgs = { };	
    gigya.services.socialize._AddRequest('showLoginUI','Gigya.Socialize.Login_%lang','',containerID,p['width'],p['height'],true,false,c,p,moreArgs);
    
},	


showConnectUI:function(c,p){
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });      
	var containerID=p['containerID'];                
    var isPopup = (containerID=='' || p['isPopup']);   
    
    if ( isPopup ) {                  
        p = gigya.global.normalizeParams(p,false, { width:{def:250}, height:{def:200} });	 	    
    }
    else {      
		gigya.global._ClearContainer(containerID);
	    p = gigya.global.normalizeParams(p,false, { width:{def:110}, height:{def:65} });	 	    
    }
    if (gigya.browser.isMobile || gigya.global.valueIsExplicitTrue(p['useHTML'])) {
        gigya.services.socialize._showHTMLConnectUI(c,p);
        return;    
    }       
	var moreArgs = { };	
    gigya.services.socialize._AddRequest('showConnectUI','Gigya.Socialize.Login_%lang','',containerID,p['width'],p['height'],true,false,c,p,moreArgs);
},	

_showHTMLConnectUI:function(c,p){
	gigya.services.socialize._AddJSRequest('gigya.services.socialize.plugins.login','gigya.services.socialize.plugins.login.showConnectUI',p['containerID'],c,p,{});
    
	//var moreArgs = { };	
    //gigya.services.socialize._AddRequest('showConnectUI','Gigya.Socialize.Login_%lang','',containerID,p['width'],p['height'],true,false,c,p,moreArgs);
},	

showEditConnectionsUI:function(c,p){

    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	var containerID=p['containerID']; 
	var isPopup = containerID=='' || p['isPopup'];    
    if ( isPopup ) {      	
	    p = gigya.global.normalizeParams(p,false, { width:{def:310}, height:{def:310} });	   
	}
	else {
		gigya.global._ClearContainer(containerID);
        p = gigya.global.normalizeParams(p,false, { width:{def:310}, height:{def:250} });	   	
	}
    if (gigya.browser.isMobile || gigya.global.valueIsExplicitTrue(p['useHTML'])) {
        gigya.services.socialize._showHTMLEditConnectionsUI(c,p);
        return;    
    }   			                 
	var moreArgs = { };	
    gigya.services.socialize._AddRequest('showEditConnectionsUI','Gigya.Socialize.EditConnections_%lang','',containerID,p['width'],p['height'],true,false,c,p,moreArgs);
    
},	

_showHTMLEditConnectionsUI:function(c,p){
	gigya.services.socialize._AddJSRequest('gigya.services.socialize.plugins.edit','gigya.services.socialize.plugins.edit.showEditConnectionsUI',p['containerID'],c,p,{});
},	
_getFacebookParams:function(oTarget) {

    if (oTarget==null) oTarget={};
    if (gigya.fbAppID) { //facebook new API
        if (typeof FB!='undefined') {
            var session=FB.getSession();
            if (session) {
                if (session.uid!=null) oTarget.fb_UID=session.uid;
                if (session.access_token!=null) oTarget.fb_at=session.access_token;
                if (session.secret!=null) oTarget.fb_ss=session.secret;
                if (session.expires!=null) oTarget.fb_exp=session.expires;
            }
         }
    } else {
        var gfk=gigya.services.socialize._getFacebookCookie;
        var user=gfk('user');
        var expires=gfk('expires');
        var ss=gfk('ss');
        var session_key=gfk('session_key');
        if (user!=null) oTarget.fb_UID=user;
        if (expires!=null) oTarget.fb_exp=expires;
        if (ss!=null) oTarget.fb_ss=ss;
        if (session_key!=null) oTarget.fb_sk=session_key;
    }
    return oTarget;
},
_getFacebookCookie:function(name) {
   var nameEQ = gigya.fbcAPIKey + '_' + 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;       
},
hideUI:function(c,p) {
    gigya.services.socialize.GrayOut(false);
    for (var containerID in gigya.services.socialize._PopupContainers) {
        var container=gigya.services.socialize._PopupContainers[containerID];
        container.innerHTML = '';
        container.parentNode.removeChild(container);
        var ifrel=document.getElementById('gigya_ifr_'+containerID);
        if ( null!=ifrel ) { 
            ifrel.parentNode.removeChild(ifrel);
            //ifrel.style.visibility = 'hidden';     

        }
    }
    gigya.services.socialize._dispatchGlobalEvent({isEvent:true, eventName:'HideUIRequested'});
    if (p!=null && typeof p.callback == 'function') {
        var oResponse = {
            status: 'OK',
            statusMessage: '',
            operation: 'hideUI',
            context: p.context,
            errorMessage: '',
            errorCode: 0
        };
        p.callback(oResponse);
    }
},	


_ExtractListOfGIGUIDs:function(source) {
	switch (typeof source) {
		case 'string': return source;
		case 'object':
			if (typeof source.UID != 'undefined') { return source.UID; }
			if (source instanceof gigya.services.socialize.Collection) {
				var a=[];
				source.each(
					function(o,i) {
						var UID=gigya.services.socialize._ExtractListOfGIGUIDs(o);
						if ((UID!=null) && (UID!='')) {a.push(UID);}
					}
				);
				return a.join(',');
			}
	}
},
/*
// add can be an [{key:v1},{key:v2}...] or [v1,v2,v3]
buildKeyedDictionary:function(arr,keyField,caseSensitive){
	var dict={};
	if (caseSensitive==null) caseSensitive=false;
	for (var i=0;i<arr.length;i++){
		var key=arr[i];
		if (null!=keyField)key=key[keyField];
		if (!caseSensitive) key=key.toLowerCase();
		dict[key]=arr[i];
	}
	dict.prototype={
		containsKey:function(key){return (typeof this[key.toLowerCase()]!='undefined')}
	};
	return dict;
},

//keys is eiter ['key1','key2', '*','key3',...] or "key1,key2,*,key3,.."

replaceWildcard:function(keys,arAllObjects,keyField) { 
	if (null==arAllObjects) arAllObjects=gigya.services.socialize._arProviders;
	if (null==keyField) keyField='name';
	var arKeys=(typeof keys=='string')?keys.split(','):keys;
		
    var arNewKeys = [];
    var dict=null;
    
    for (var i = 0; i < arKeys.length; i++) {
        if (arKeys[i] == '*') {
			if (null==dict) dict=gigya.services.socialize.buildKeyedDictionary(arObjects,keyField,false);
            for (var iObj=0; iObj < arObjectSet.length; iObj++) {
				if (!(dict.containsKey(arKeys[u]))) {
					arNewKeys.push(arAllObjects[iObj].name);
				}
            }
        } else {    
            arNewKeys.push(arKeys[i]);
        }
    }
    return arNewKeys;
},
*/


replaceWildcard:function(arProviders,providersEnum) {
	
	if (null==providersEnum) {
		providersEnum=gigya.services.socialize._arProviders;
		
	}
    var arProvidersNew = [];
    for (var i = 0; i < arProviders.length; i++) {
        if (arProviders[i] == '*') {
            for (var iProvider=0; iProvider < providersEnum.length; iProvider++) {
	            var found = false;
	            for (var u = 0; u < arProviders.length; u++) {
		            if (arProviders[u].toLowerCase() == providersEnum[iProvider].name.toLowerCase()) found = true;
	            }
	            if (!found && !providersEnum[iProvider].explicitOnly) {
		            arProvidersNew.push(providersEnum[iProvider].name);
	            }
            }
        } else {    
            arProvidersNew.push(arProviders[i]);
        }
    }
    return arProvidersNew;
},

hideProvidersByName:function(arProviders, providersToHide,providersEnum) {
    providersToHide = providersToHide.toLowerCase();		
    var arProvidersToHide = providersToHide.split(' ').join('').toLowerCase().split(',');
    arProvidersToHide = this.replaceWildcard(arProvidersToHide,providersEnum);		
    for (var i = 0; i < arProvidersToHide.length; i++) 	{
        for (var u = 0; u < arProviders.length; u++) {
            if (arProviders[u].toString().toLowerCase() == arProvidersToHide[i]) {
	            arProviders.splice(u, 1);
            }
        }
    }
    return arProviders;
},
getAllProviders:function() {
    var arProviders = [];
    for (var provider in providersEnum) {
        arProviders.push(providersEnum[provider]);
    }
    return providersEnum.concat();
},
getProvidersByName:function(providers,providersEnum) {
	providers = (''+providers).split(' ').join('').toLowerCase(); //Casting providers to string to overcome bug #10392
    var arProviders=(''+providers).split(',');
    arProviders = this.replaceWildcard(arProviders,providersEnum);
    var arProvidersObjects = [];
    for (var i = 0; i < arProviders.length; i++) 
    {
        var providerObject = gigya.services.socialize._getProviderByName(arProviders[i],providersEnum);
        if (providerObject != null) {
            arProvidersObjects.push(providerObject);
        }
    }
    return arProvidersObjects;
},
getProvidersForRequiredCapabilities:function(providers, capabilities) {
    if (capabilities==null) capabilities='';
    var arProviders = [];
    for (var i = 0; i < providers.length; i++) 
    {
        var provider = providers[i];
        var validNet = true;
        for (var u = 0; u < capabilities.length; u++) 
        {
            var found=false;
            for (var a = 0; a < provider.arDefaultCapabilities.length; a++) {
                if (provider.arDefaultCapabilities[a].toLowerCase()==capabilities[u].toLowerCase()) {
                    found=true;
                    break;
		        }
	        }
	        if (!found) {
	            validNet = false;
	            break;				            
	        }
        }
        if (validNet) arProviders.push(provider);
    }
    return arProviders;
},
_ConvertToTypedObjects:function(arr,ctor){
	if ((arr==null) || (arr.length==0) || (ctor==null)) return arr;
	var oarr=[];
	var i=0;
	var el=arr[i];
	while(el){
		oarr.push(new ctor(el));
		el=arr[++i];
	};
	return oarr;
},

Provider:function(ID,displayName,width,height,arDefaultCapabilities,iframeWidth,iframeHeight,nativeLoginStr,explicitOnly) {
	this.ID = ID;
	this.arDefaultCapabilities = arDefaultCapabilities;
	this.displayName=displayName;
	this.name=displayName.toLowerCase();
	this.width = width;
	this.height = height;
	this.windowOptions = 'menubar=0,toolbar=0,resizable=1,scrollbars=1,width=' + width + ',height=' + height;
	this.iframeWidth = iframeWidth;
	this.iframeHeight = iframeHeight;
	this.nativeLoginStr = nativeLoginStr;
	this.explicitOnly = explicitOnly;
	this.toString=function(){return this.name};
},
Person:function(po){
	//debugger;
	if (typeof(po)=='object') {
	
	//Basic basicFields
		this.UID=po.UID?po.UID:'';        
        this.nickname=po.nickname?po.nickname:'';		        
		this.photoURL=po.photoURL?po.photoURL:'';		
		this.thumbnailURL=po.thumbnailURL?po.thumbnailURL:'';
		this.isSiteUID=po.isSiteUID?po.isSiteUID:false;
		
     //Extended Fields		
		this.birthDay=po.birthDay?po.birthDay:0;
		this.birthMonth=po.birthMonth?po.birthMonth:0;
		this.birthYear=po.birthYear?po.birthYear:0;
		this.gender=po.gender?po.gender:'';
		this.email=po.email?po.email:'';
		this.proxiedEmail=po.proxiedEmail?po.proxiedEmail:'';		
		this.country=po.country?po.country:'';
		this.state=po.state?po.state:'';
		this.city=po.city?po.city:'';
		this.zip=po.zip?po.zip:'';
		
		this.firstName=po.firstName?po.firstName:'';
		this.lastName=po.lastName?po.lastName:'';
		this.profileURL=po.profileURL?po.profileURL:'';		
		this.age = (this.birthYear=='')?'':(new Date()).getFullYear() - this.birthYear;
	}
	
	else if (typeof(po)=='string') {
		this.UID=this.siteUID=this.nickname=this.photoURL='';
		this.isSiteUID=false;
		if (po.indexOf('_gid_')==0) {
			this.UID=po;
		} else {
			this.siteUID=po;
		}
	}
	else {
		if (gigya.services.socialize.verbose) {
			alert('Gigya Social:' + po + ' is not a user or a user id');
		}
	}
},
	


User:function(uo){
	//debugger;
    gigya.services.socialize.Person.call(this,uo);
    
	if (typeof(uo)=='object') {
		//Basic basicFields
        this.isLoggedIn=uo.isLoggedIn?uo.isLoggedIn:false; 
        this.isConnected = false;
		this.isSiteUser=uo.isSiteUser?uo.isSiteUser:false;
		this.providers=[];
		
		this.identities={};		
		if (uo.identities!=null) {
			for (var net in uo.identities) {	
				this.isConnected = true;				
				this.identities[net]={};
				gigya.services.socialize.Identity.call(this.identities[net],uo.identities[net]);
				this.providers.push(net);
			}
		}
		
		this.timestamp=uo.timestamp?uo.timestamp:'';
		this.UIDSig=uo.UIDSig?uo.UIDSig:'';
		
		this.loginProvider=uo.loginProvider?uo.loginProvider:'';
		this.loginProviderUID=uo.loginProviderUID?uo.loginProviderUID:'';
		this.capabilities =uo.capabilities?uo.capabilities:{login:false, notifications:false, newsfeed:false, friends:false, status:false, contacts:false};		
	}
	else if (typeof(uo)=='string') {
		// Important to leave this so no error will pop if it was a string.
	}	
	else {
		if (gigya.services.socialize.verbose) {
			alert('Gigya Social:' + uo + ' is not a User or a user id');
		}
	}
},

Friend:function(fo){
	//debugger;
    gigya.services.socialize.Person.call(this,fo);
    
	if (typeof(fo)=='object') {
		this.timestamp=fo.timestamp?fo.timestamp:'';
		this.friendshipSig=fo.UIDSig?fo.UIDSig:''; // Arriving from the AS as UIDSig
		this.isSiteUser=fo.isSiteUser?fo.isSiteUser:false;
		this.identities={};		

		if (fo.identities!=null) {
			for (var net in fo.identities) {
				//debugger;
				this.identities[net]={};
				gigya.services.socialize.Identity.call(this.identities[net],fo.identities[net]);
			}
		}
		
	}
	else if (typeof(fo)=='string') {
	}
	else {
		if (gigya.services.socialize.verbose) {
			alert('Gigya Social:' + fo + ' is not a Friend or a user id');
		}
	}
},

Identity:function(io){
	//debugger;
    gigya.services.socialize.Person.call(this,io);
   
	if (typeof(io)=='object') {
        this.isLoginIdentity=io.isLoginIdentity?io.isLoginIdentity:false;
		this.provider=io.provider?io.provider:'';
		this.providerUID=io.providerUID?io.providerUID:'';
		this.allowsLogin=io.allowsLogin?io.allowsLogin:false;
	}
	else {
		if (gigya.services.socialize.verbose) {
			alert('Gigya Socialize:' + io + ' is not an identity');
		}
	}
},

Contact:function(co){
	if (typeof(co)=='object') {
		this.provider=co.provider?co.provider:'';
		this.firstName=co.firstName?co.firstName:'';
		this.lastName=co.lastName?co.lastName:'';
        this.nickname=co.nickname?co.nickname:'';		        
		this.email=co.email?co.email:'';
		this.photoURL=co.photoURL?co.photoURL:'';		
	}
	else if (typeof(co)=='string') {
	}
	else {
		if (gigya.services.socialize.verbose) {
			alert('Gigya Socialize:' + co + ' is not a contact');
		}
	}
},

UserAction:function(uao){ // either an object or a string which is the titleTemplate
  if (arguments.length ==1 && typeof(uao)=='object') {

	this.actorUID=uao.actorUID;
	this.actorNickname=uao.actorNickname?uao.actorNickname:'';
	
	this.actionName=uao.actionName?uao.actionName:'';;
	this.titleTemplate=uao.template?uao.template:'';
	
	this.templateFields=uao.templateFields?uao.templateFields:{};
	
	this.date=new Date();
	this.date.setTime(uao.date);
	
	this.targets=uao.targets?uao.targets:[];
	
	this.images=uao.images?uao.images:[];
	this.actionData1=uao.data1?uao.data1:'';
	this.actionData2=uao.data2?uao.data2:'';
	this.iconURL=uao.icon?uao.icon:'';
	
    this.title = uao.title?uao.title:'';
    this.linkBack = uao.linkBack?uao.linkBack:'';
    this.userMessage = uao.userMessage?uao.userMessage:'';
    this.description = uao.description?uao.description:'';                

    this.actionLinks =uao.actionLinks?uao.actionLinks:[];
    this.mediaItems =uao.mediaItems?uao.mediaItems:[];    
  

  }
  else { 
	this.titleTemplate='';
	this.actorNickame='';
	this.actorUID='';
	this.actionName='';
	this.templateFields={};	
	this.targets=[];
	this.images=[];
	this.actionData1='';
	this.actionData2='';
	this.iconURL='';
	this.actionData1=''
	this.date=new Date(); // To prevent errors with getDate on newly created UserAction Objects
	                      // Actual time on the item would be based on server time.
	                      
    this.title= '';
    this.linkBack = '';
    this.userMessage= '';
    this.description= '';
    this.actionLinks=[];
    this.mediaItems=[];	                      
  }
  if (typeof(uao)=='string') {
	this.titleTemplate=uao;
  }
/*  else {
		if (gigya.services.socialize.verbose) {
			alert('Gigya Social:' + uao + ' is not a user action or a template string');
		}  
  }
*/  
},

TemplateField:function(n,t,h){
	this.fieldName=n;
	this.text=t?t:''; //to avoid JSON parsing errors
	this.href=h?h:'';
},


Collection:function(arr,k){
	this.arr=arr;
	this._key=k?k:'';
}
} // end of initialization of gigya.services.socialize

gigya.services.socialize.showNewsfeedUI=gigya.services.socialize.showFeedUI; //backwards Compatibility

gigya.services.socialize._arProviders=[
	new gigya.services.socialize.Provider(64, 'Facebook', 650, 400,['login','friends','actions','status','photos'], 670,440,'&useFBC=true'),
	new gigya.services.socialize.Provider(1, 'MySpace', 610, 510,['login', 'friends', 'actions', 'status','photos']),
	new gigya.services.socialize.Provider(9012, 'Twitter', 800, 440,['login','friends','notifications','actions','status']),
	new gigya.services.socialize.Provider(9803, 'Yahoo', 627, 567,['login', 'friends', 'actions', 'status','contacts']), //size based on bug#10676
	new gigya.services.socialize.Provider(9042, 'LinkedIn', 865, 471,['login', 'friends', 'status', 'actions', 'notifications']), //size based on bug#10678
	new gigya.services.socialize.Provider(9811, 'Google', 410, 450,['login','actions','status','friends','contacts']),
	new gigya.services.socialize.Provider(9800, 'AOL', 530, 720,['login']),
	new gigya.services.socialize.Provider(4096, 'WordPress', 700, 540,['login']),
	new gigya.services.socialize.Provider(256, 'Blogger', 760, 400,['login']),
	new gigya.services.socialize.Provider(1041, 'Hyves', 700, 540,['login']),
	new gigya.services.socialize.Provider(16, 'LiveJournal', 670, 360,['login']),
	new gigya.services.socialize.Provider(1043, 'VeriSign', 940, 500,['login']),
	new gigya.services.socialize.Provider(1024, 'Typepad', 730, 590,['login']),
	new gigya.services.socialize.Provider(4120, 'OpenID', 730, 590,['login']),
	new gigya.services.socialize.Provider(1045, 'LiveID', 730, 590,['login','contacts']),
	new gigya.services.socialize.Provider(1047, 'Messenger', 520, 450,['login','friends','actions','status'], null,null,null,true)
]

gigya.services.socialize.User.prototype=new gigya.services.socialize.Person({});
gigya.services.socialize.Friend.prototype=new gigya.services.socialize.Person({});
gigya.services.socialize.Identity.prototype=new gigya.services.socialize.Person({});


gigya.services.socialize.UserAction.prototype.getTemplate=function(){
	return this.titleTemplate;
}

gigya.services.socialize.UserAction.prototype.setTemplate=function(a){
	this.titleTemplate=a;
}

gigya.services.socialize.UserAction.prototype.getActor=function(a){
	return {UID:this.actorUID,nickname:this.actorNickname}
}
	
gigya.services.socialize.UserAction.prototype.setActionName=function(a){
	this.actionName=a;return this;
}
		
gigya.services.socialize.UserAction.prototype.getActionName=function(a){
	return this.actionName;
}

gigya.services.socialize.UserAction.prototype.getTemplateFields=function(){
	var fieldsArray=[];
	for (var fn in this.templateFields) {fieldsArray.push(this.templateFields[fn]);}
	return new gigya.services.socialize.Collection(fieldsArray,'fieldName');
}

gigya.services.socialize.UserAction.prototype.setTemplateField=function(n,t,h){
	this.templateFields[n]=new gigya.services.socialize.TemplateField(n,t,h); return this;
}
		
gigya.services.socialize.UserAction.prototype.getTemplateField=function(n){
	return this.templateFields[n]?this.templateFields[n]:null;
}
	
gigya.services.socialize.UserAction.prototype.addTarget=function(t){
	if (typeof(t)=='object') {
		this.targets.push({UID:t.UID,nickname:t.nickname?t.nickname:''});return this;
	}
	else if (typeof(t)=='string') {
		this.targets.push({UID:t,nickname:''});return this;
	}
}

gigya.services.socialize.UserAction.prototype.addActionLink=function(title,href){
    this.actionLinks.push( { text:title, href:(href?href:'') } );
    return this;
}

gigya.services.socialize.UserAction.prototype.addMediaItem=function(obj){
   this.mediaItems.push(obj); return this;
}

gigya.services.socialize.UserAction.prototype.setTitle=function(text){
    this.title = text; return this;
}

gigya.services.socialize.UserAction.prototype.setLinkBack=function(href){
    this.linkBack = href; return this;
}

gigya.services.socialize.UserAction.prototype.setUserMessage=function(text){
    this.userMessage = (text?text:''); return this;
}

gigya.services.socialize.UserAction.prototype.setDescription=function(text){    
    this.description = (text?text:''); return this;
}
		
gigya.services.socialize.UserAction.prototype.addImage=function(s,h){
	this.addMediaItem( { type:'image', src:s, href:h } );
}
		
gigya.services.socialize.UserAction.prototype.getImages=function(){
return new gigya.services.socialize.Collection(this.images,'')
}
		
gigya.services.socialize.UserAction.prototype.getTargets=function(){
return new gigya.services.socialize.Collection(this.targets,'UID')
}
	
gigya.services.socialize.UserAction.prototype.setIconURL=function(url){
this.iconURL=url;return this;
}
		
gigya.services.socialize.UserAction.prototype.getIconURL=function(){
return this.iconURL
}
	
gigya.services.socialize.UserAction.prototype.getDate=function(){
return this.date;
}
	
gigya.services.socialize.UserAction.prototype.setActionData1=function(ad){
this.actionData1=ad;return this;
}
		
gigya.services.socialize.UserAction.prototype.getActionData1=function(ad){
return this.actionData1;
}
		
gigya.services.socialize.UserAction.prototype.setActionData2=function(ad){
this.actionData2=ad;return this;
}
		
gigya.services.socialize.UserAction.prototype.getActionData2=function(ad){
return this.actionData2;	
}

gigya.services.socialize.Collection.prototype.asArray=function(){return this.arr};

gigya.services.socialize.Collection.prototype.each=function(f){
var i=0;
var el=this.arr[i];
while(el){f(el,i);i++;el=this.arr[i];};
}

gigya.services.socialize.Collection.prototype.getById=function(id){if ((typeof this._hash=='undefined') && (k!='')){this._buildHash();};return (this._hash?this._hash:this.arr)[id];}

gigya.services.socialize.Collection.prototype.getSize=function(){return this.arr.length}

gigya.services.socialize.Collection.prototype._buildHash=function(){if(k=='') {return}; var h=this._hash={};var k=this._key;this.each(function(o,i){h[(typeof o[k]=='function')?o[k]:o[k]()]=o});}


	// Resolver
	if (typeof gigya.global.XMLUtils=='undefined') {
	    gigya.global.XMLUtils={
	        CreateXMLFromString:function(sXML) {
                var doc = null;
                if (window.ActiveXObject) {
                    doc=new ActiveXObject("Microsoft.XMLDOM");
                    doc.async="false";
                    doc.loadXML(sXML);
                }
                else {
                    var parser=new DOMParser();
                    doc=parser.parseFromString(sXML,"text/xml");
                }
                
                return doc;
	        },
	        CopyProperties:function(propBag,targetBag,pfx,Proccesor) {
		        if (typeof pfx=='undefined') pfx='';
		        if (typeof targetBag=='undefined') targetBag={}; 
		        if (Proccesor!=null) {
			        for (var propName1 in propBag) {
				        targetBag[pfx+propName1]=Proccesor(propName1,propBag[propName1]);
			        }
		        }
		        else {
			        for (var propName2 in propBag) {
				        targetBag[pfx+propName2]=propBag[propName2];
			        }
		        }
		        return targetBag;	            
	        },    
	        CollectAttributesFromXMLPathToObject:function(xmlobjResource, ResourceNodePathSegments, res, blnCollectFromAncestors, processor) {
		        for (var iPathSegment = 0; ((iPathSegment < ResourceNodePathSegments.length) && (typeof xmlobjResource != 'undefined')); iPathSegment++) {
			        xmlobjResource = xmlobjResource.childNodes[ResourceNodePathSegments[iPathSegment]];
			        if (xmlobjResource!=null && blnCollectFromAncestors) {
				        this.CopyProperties(xmlobjResource.attributes, res, '', processor);
			        }
		        }

		        if (typeof xmlobjResource != 'undefined') {
			        this.CopyProperties(xmlobjResource.attributes,res,'',processor)
		        }
	        },
	        mergeNodes:function(srcNode, targetObject) {

		        if (typeof targetObject.attributes=='undefined') targetObject.attributes = { };
		        if (typeof targetObject.childNodes=='undefined') targetObject.childNodes = { };

		        var targetAttributes = targetObject.attributes;
		        var srcNodeAttributes = srcNode.attributes;
		       /* for (var attName in srcNodeAttributes) {
			        targetAttributes[attName] = srcNodeAttributes[attName];
		        }*/
                
                //debugger;
                if (srcNodeAttributes) {
                    //this.CopyAttributesToObject(srcNodeAttributes, targetAttributes, '');
                    for (var i=0; i<srcNodeAttributes.length; i++) {
                        targetAttributes[srcNodeAttributes[i].nodeName]=srcNodeAttributes[i].nodeValue;
                    }
        		}
		        var targetChildNode;
		        for (var u = 0; u < srcNode.childNodes.length; u++ ) { //add missing child nodes
			        var srcChildNode = srcNode.childNodes[u];
			         targetChildNode=targetObject.childNodes[srcChildNode.nodeName];
			        if (typeof targetChildNode == 'undefined')  {
				        targetChildNode = targetObject.childNodes[srcChildNode.nodeName] = { attributes: { }, childNodes: { }};
			        } 
			        this.mergeNodes(srcChildNode, targetChildNode);
		        }
		        return targetObject;
	        }
	    }
	}
if (typeof gigya.global.resolver=='undefined') {

    gigya.global.resolver=function(proccessor) {
        this.configurations=[];
        this.mergedConfig={};
        this.isMerged=true;
        this._processor=proccessor;
        this.merge=function() {
	        if (!this.isMerged) {
		        this.mergedConfig = {attributes:{},childNodes:{}};
		        for (var i = 0; i < this.configurations.length; i++) {
			        var xmlDoc = this.configurations[i];
			        gigya.global.XMLUtils.mergeNodes(xmlDoc, this.mergedConfig);
		        }
		        this.isMerged = true;
	        }
        }
        this.Resolve=function() {
	        this.merge();
	        var res = { };
	        if (typeof arguments[arguments.length - 1] == 'object') {
		        res = arguments[arguments.length - 1];
	        }
	        for (var u = 0; u < arguments.length; u++) {
		        var arg = arguments[u];
		        var ctor = arg.constructor;
		        if (ctor == String) {
		            
			        var arPaths = arg.split('|');
			        for (var i = arPaths.length-1; i >= 0; i--) {
				        var path = this.trimCharsAtSuffix(this.trimCharsAtPrefix(arPaths[i], ' \n\r\t'), ' \n\r\t');
				        var recur = (path.charAt(0) == '+');
				        var arPath = path.split('/').slice(1);
				        if (recur) {
					        path = path.substring(1);
				        }
				        
				        gigya.global.XMLUtils.CollectAttributesFromXMLPathToObject(this.mergedConfig, arPath, res, recur, this._processor);
			        } 
		        } else if (ctor==Array) {
			        for (var n = 0; n < arg.length; n++) {
				        Resolve(arg[n], res);
			        }
		        }
	        }
	        return res;
        }
	    this.trimCharsAtPrefix=function(s,chars){
		    var idx = 0;
		    if ((typeof s=='undefined') || (s.length==0)) return '';
		    var sl=s.length;					
		    while ((idx<=sl) && (chars.indexOf(s.charAt(idx))>-1)) {
			    idx++;
		    }
		    return s.substring(idx,sl);
	    }
	    this.trimCharsAtSuffix=function(s, chars) {
		    if ((typeof s=='undefined') || (s.length==0)) return '';
		    var idx=s.length-1;
		    while ((idx>=0) && (chars.indexOf(s.charAt(idx))>-1)) {
			    idx--;
		    }
		    return s.substring(0, idx + 1);
			
	    }		    	
        this.addConfig=function(sXML) {
            if (typeof sXML=='string') {
                this.configurations.push(gigya.global.XMLUtils.CreateXMLFromString(sXML));
                this.isMerged=false;
            }
        } 
    }
    gigya.global.resolver.defaultProccessor=function(PropertyName, PropertyValue) {
        var lcasePropertyName = PropertyName.toLowerCase();
        var lastDashIndex = lcasePropertyName.indexOf('-');
        if (lastDashIndex != -1) {
            lcasePropertyName = lcasePropertyName.substring(lastDashIndex + 1, lcasePropertyName.length);
        }
        switch(lcasePropertyName){
            case 'bold':
            case 'italic':
            case 'underline':			
	            return PropertyValue.toString().toLowerCase()=='true'; 
	            break;
            case 'width':
            case 'height':
	            return PropertyValue.replace('%','');
	            break;
            case 'size':
	            return parseInt(PropertyValue);
	            break;
            default:
	            return PropertyValue;
        }
    }    
}


//alert('gigya.services.socialize is now loaded');
//setTimeout('gigya.services.socialize.loadCore()',500);
gigya.services.socialize._injectLoadPixel=function(){
    var apikey;
    var lastScriptURL = gigya._vars.lastScriptURL;
	var p1=lastScriptURL.toLowerCase().indexOf('apikey=');
	if (p1>0) {
	    p1+=7;
	    var p2=lastScriptURL.indexOf('&', p1);
	    if (p2<0) p2=lastScriptURL.length;
	    apikey=lastScriptURL.substring(p1, p2);
    }
    var cimp=new Image(1,1);
    var cimpSrc=gigya._vars.lastScriptProtocol+'://socialize.gigya.com/gs/api.ashx?f=re&e=loadc&now='+(new Date()).getTime();
    if (apikey) cimpSrc+='&ak='+apikey;
    cimp.src=cimpSrc;
}
gigya.services.socialize._injectLoadPixel();

if (typeof onGigyaServiceReady=='function') {onGigyaServiceReady('socialize');}

gigya.services.socialize._injectFBC=function() {
    var fncLoadFB;
    if (typeof gigya.fbAppID != 'undefined') { //new FB API
        fncLoadFB=gigya.services.socialize.loadFB2;
    }
    if (typeof gigya.fbcAPIKey!='undefined' && document.domain.indexOf(gigya.fbcDomain)!=-1) {    
        fncLoadFB=gigya.services.socialize.loadFBC;
        if (typeof gig_xdReceiverUrl=='undefined') {
            document.domain = gigya.fbcDomain;
            gig_xdReceiverUrl=gigya._vars.lastScriptProtocol+'://'+gigya.fbcXdURL;
        }
    }
    
    if (fncLoadFB) {
        window.setInterval('gigya.refreshFbcSession()', 45*60*1000);
        if ((!document.readyState && document.body) || document.readyState == "loaded" || document.readyState == "complete") {
            fncLoadFB();
        } else {
            if (window.attachEvent) {
                window.attachEvent('onload',fncLoadFB);
            } else if (window.addEventListener) {
                window.addEventListener('load',fncLoadFB,false);
            }
        }
    }    
}

gigya.debug=function(c,p) {
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });      
	var moreArgs = { };	
	gigya.services.socialize._AddJSRequest('gigya.services.socialize.plugins.debug','gigya.services.socialize.plugins.debug.debug','PseudoContainer_debug',c,p,{});
}

gigya.nodebug=function() {
	var expires_date = new Date();
	document.cookie = '_gig_dbgConsole_dbg=0;expires=' + expires_date.toGMTString() +";path=/;" 
	document.cookie = '_gig_dbgConsole_log=0;expires=' + expires_date.toGMTString() +";path=/;" 
}

gigya.showLog=function(c,p) {
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });      
	var moreArgs = { };	
	gigya.services.socialize._AddJSRequest('gigya.services.socialize.plugins.debug','gigya.services.socialize.plugins.debug.showLog','PseudoContainer_debug',c,p,{});
}

gigya._activateDebugConsoleIfNeeded=function(){
	var dbg=0;
	if (document.cookie.indexOf('_gig_dbgConsole_dbg=1')!=-1) {
		dbg=1;
	}
	var log=0;
	if (document.cookie.indexOf('_gig_dbgConsole_log=1')!=-1) {
		log=1;
	}
	if (log==1 || dbg==1) {
		gigya.debug({log:log,dbg:dbg});
	}
 };
gigya._activateDebugConsoleIfNeeded();
