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() {
    FB.Connect.forceSessionRefresh(function() {
        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= {

_GlobalEventHandlers : {
    onLogin:{idx:0},     
    onConnect:{idx:0},     
    onDisconnect:{idx:0},
    onLogout:{idx:0},
    onFBCLoaded:{idx:0}
} ,
 
_PopupContainers:{},

CenteredComponentDivID:'WFComponentDiv_'+(new Date()).getTime(),
GetCenteredComponentDivID:function(popupName){
	return this.CenteredComponentDivID+'_'+popupName;
},
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, gigya._vars.lastScriptProtocol+'://'+gigya.fbcXdURL);
        });
        FB.ensureInit(function() {
            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({},{
                    onLogin: function() {FB.Connect.forceSessionRefresh()},
                    onConnect: function() {FB.Connect.forceSessionRefresh()},
                    onLogout: function(){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);
},
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 {
            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 scrollTop=document.documentElement.scrollTop;
        if (scrollTop==0) scrollTop=document.body.scrollTop;	  
		var tnode = document.createElement('div');
			tnode.style.position='absolute';
			tnode.style.top=''+scrollTop+'px';
			tnode.style.left='0px';
			tnode.style.overflow='hidden';
			tnode.style.display='none';
			tnode.id='darkenScreenObject';
			tnode.innerHTML='&nbsp;';
		tbody.appendChild(tnode);
		dark=document.getElementById('darkenScreenObject');
	  }
	  if (vis) {
		var vph;
		var vpw;
		document.body.style.overflow =  'hidden';
		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);
		 document.body.style.overflow =  '';
	  }    
},
_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 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 ];
},


_GetContainer:function(id){
	if (id=='') return null;
	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.flash.isIE && gigya.flash.isWin) {
		ifrel = document.createElement('IFRAME');
		ifrel.id='gigya_ifr_'+id;
		ifrel.frameborder="0";
		ifrel.frameBorder="0";
        ifrel.allowtransparency=true;
		ifrel.style.position='absolute';
		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'));
*/	      
//debugger;
    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';
	}
},

_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];
            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]);
        }
    }
},
_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)");
    }
},
_AddJSRequest:function(servicedBy,methodName,containerID,c,p){	
    var container=document.getElementById(containerID);
    gigya.services.socialize._SetContainerSizeAndPosition(container,p.width,p.height,false);
	var Reqs=(container.Reqs?container.Reqs:(container.Reqs=[]));	
	var rid=Reqs.length+'@'+servicedBy+'@'+containerID;
	
	var req=Reqs[Reqs.length]={
		rid:rid,			
		servicedBy:servicedBy,
		container:container,
		method:methodName,
		context:p['context'],
		c:c,
        p:p,
        operation:methodName
	};
	
    var func;
    try {func = eval(methodName)} catch(e){}
    if (typeof func!='undefined') {
        eval(methodName+'(c,p,{rid:rid})');
    } else {
        var pr=gigya.services.socialize.pendingJSRequests;
        var loadScript=false;
        
        if (typeof pr=='undefined') {
            pr=gigya.services.socialize.pendingJSRequests=[];
        }  
        if (typeof pr[servicedBy]=='undefined') {
            pr[servicedBy]=[];
            loadScript=true;
        }
        pr=pr[servicedBy];
        pr.push({serviceName:servicedBy,methodName:methodName,c:c,p:p,i:{rid:rid}});
        
        if (loadScript) {
            var container=document.getElementById(p['containerID']);
            var script=document.createElement('SCRIPT');
            script.src=gigya._vars.lastScriptURLBase +'/js/' + servicedBy + '.js';
            container.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 ( 'coreDiv'!=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) {
		    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);
	}

	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;
	//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) {
					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') {
		    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.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'],
                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 eventObjCopy;
    var needToInvoke;
    var ListenerTypes=['component','other'];
	for (var iListenerType=0;iListenerType<ListenerTypes.length;iListenerType++) {
		var listenerType=ListenerTypes[iListenerType];
		for (var hcKey in eventHandlers ) {
			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 ) { 	
			        eventHandlers[hcKey]['handler'](eventObjCopy);
			    }
		    }
	    }
    }
} , 

_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);
  }  
} , 

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); 	
},	
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); 	    
},
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); 	    
},

notifyLogin:function(c,p){	
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	var moreArgs = {};
	gigya.services.socialize._AddRequest('notifyLogin','Gigya.Socialize.Core','','coreDiv',1,1,true,false,c,p,moreArgs); 	
},	
	
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); 	
},	
	
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); 	
},	

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); 	
},
	
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); 	
},
_getProviderByName:function(provider) {
    var arProviders=gigya.services.socialize._arProviders;
    for (var i=0; i<arProviders.length; i++) {
        if (arProviders[i].name.toLowerCase()==provider.toLowerCase()) return arProviders[i];
    }
},
_SNLink:function(c,p,SNLinkMethod,methodName,rid,lid,permissions,getPermissionsOnly){
	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: methodName , 
            context: p['context'],
            status:'FAIL', 
            statusMessage:'Invalid_provider',
            errorCode: 400099,
            errorMessage: 'Invalid_provider'
        };
        
        callback(resp);	    
	    return false;
	}
	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=encodeURIComponent(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'];
	
	if (typeof sessionExpiration!='undefined') ap['sessionExpiration'] = sessionExpiration;
	if (typeof pd!='undefined') ap['pd'] = pd;
	if (typeof su!='undefined') ap['su'] = su;
	if (typeof permissions!='undefined') {
		ap['perms'] = permissions;
		if (getPermissionsOnly) {
		    useIframe = true;
		    forceIframe = true;		    
		    ap['getPerms'] = true;	
		}
	}	
	
	var ad=encodeURIComponent(gigya.services.socialize._createObjectQueryString(ap));
    if (useIframe && provider.nativeLoginStr) ad += encodeURIComponent(provider.nativeLoginStr);
    
	var url=gigya._vars.lastScriptProtocol+'://socialize.gigya.com/GS/SNLink.aspx?rid='+rid+'&m='+SNLinkMethod+'&d='+domain+'&ak='+c['APIKey']+'&ad='+ad+'&sn='+snid;
    var invite = p.invite;
	if (typeof invite == 'object') {
		if (invite.title) url+='&ivTl='+encodeURIComponent(invite.title);
		if (invite.text) url+='&ivT='+encodeURIComponent(invite.text);
		if (invite.name) url+='&ivN='+encodeURIComponent(invite.name);
		if (invite.actionText) url+='&ivAT='+encodeURIComponent(invite.actionText);
		if (invite.actionURL) url+='&ivAU='+encodeURIComponent(invite.actionURL);
		if (invite.repeatFreq) url+='&ivIF='+encodeURIComponent(invite.repeatFreq);
		if (invite.repeatCap) url+='&ivIC='+encodeURIComponent(invite.repeatCap);
		if (invite.reinviteFreq) url+='&ivRF='+encodeURIComponent(invite.reinviteFreq);
		if (invite.reinviteCap) url+='&ivRC='+encodeURIComponent(invite.reinviteCap);
		if (p['provider'].toLowerCase()=='facebook') windowOptions = 'menubar=0,toolbar=0,resizable=1,width=630,height=520,scrollbars=1';
	}
    var pixelURL=gigya._vars.lastScriptProtocol+'://socialize.gigya.com/gs/api.ashx?f=re&e='+methodName+'&ak='+c['APIKey']+'&sn='+snid;	
    if (typeof pd!='undefined') {
        pixelURL+='&pd='+encodeURIComponent(pd);
    }

    var imgPixel=new Image();
    imgPixel.src=pixelURL;
    
	//window.open(url, 'GS_login_'+p['provider'], windowOptions);
	
	var iframeUrl;
	if (useIframe) iframeUrl = url;
	
	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 + '=' + encodeURIComponent(params[pName]));
	}
	return arParams.join('&');    
},
_listenerID:(new Date()).getTime(),
requestPermissions:function(c,p){
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''}, provider:{nullAs:''}});		
	var moreArgs = {};	
	var ReqsLength=0;
	var corediv=document.getElementById('coreDiv');
	if (corediv!=null && corediv.Reqs!=null) {
	    ReqsLength=corediv.Reqs.length;
	}
	var lid=gigya.services.socialize._listenerID;
	if (gigya.services.socialize._SNLink(c,p,'cn','requestPermissions',ReqsLength+'@Gigya.Socialize.Core@coreDiv',lid,p['permissions'],true)) {
	    moreArgs['listenerID']=lid;
	    gigya.services.socialize._AddRequest('requestPermissions','Gigya.Socialize.Core','','coreDiv',1,1,true,false,c,p,moreArgs); 	
	};
},
login:function(c,p){
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''}, provider:{nullAs:''}});		
	var moreArgs = {};	
	var ReqsLength=0;
	var corediv=document.getElementById('coreDiv');
	if (corediv!=null && corediv.Reqs!=null) {
	    ReqsLength=corediv.Reqs.length;
	}
	var lid=gigya.services.socialize._listenerID;
	if (gigya.services.socialize._SNLink(c,p,'au','login',ReqsLength+'@Gigya.Socialize.Core@coreDiv',lid)) {
	    moreArgs['listenerID']=lid;
	    gigya.services.socialize._AddRequest('login','Gigya.Socialize.Core','','coreDiv',1,1,true,false,c,p,moreArgs); 	
	};
},


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);
},	
	
connect:function(c,p){	
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	var moreArgs = {};	
	var ReqsLength=0;
	var corediv=document.getElementById('coreDiv');
	if (corediv!=null && corediv.Reqs!=null) {
	    ReqsLength=corediv.Reqs.length;
	}
	var lid=gigya.services.socialize._listenerID;
	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:''} });
	var moreArgs = {};
	gigya.services.socialize._AddRequest('disconnect','Gigya.Socialize.Core','','coreDiv',1,1,true,false,c,p,moreArgs);
},			

getUserInfo:function(c,p){
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	var moreArgs = { };
	var windowName = 'WFS_getUserInfo' ;
	moreArgs['windowName']=windowName;
	gigya.services.socialize._AddRequest('getUserInfo','Gigya.Socialize.Core','','coreDiv',1,1,true,false,c,p,moreArgs); 
},
linkAccounts:function(c,p){
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	var moreArgs = { };
	var windowName = 'WFS_getUserInfo' ;
	moreArgs['windowName']=windowName;
	gigya.services.socialize._AddRequest('linkAccounts','Gigya.Socialize.Core','','coreDiv',1,1,true,false,c,p,moreArgs);     
},
unlinkAccounts:function(c,p){
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });
	var moreArgs = { };
	gigya.services.socialize._AddRequest('unlinkAccounts','Gigya.Socialize.Core','','coreDiv',1,1,true,false,c,p,moreArgs);     
},
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;
	}
	var moreArgs = { };	
	gigya.services.socialize._AddRequest('getFriendsInfo','Gigya.Socialize.Core','','coreDiv',1,1,true,false,c,p,moreArgs);
},	
	

	
sendNotification:function(c,p){	
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} });    
    p['recipients']=gigya.services.socialize._ExtractListOfGIGUIDs(p['recipients']);    
	var moreArgs = { };
	gigya.services.socialize._AddRequest('sendNotification','Gigya.Socialize.Core','','coreDiv',1,1,true,false,c,p,moreArgs);	
},	
	

publishUserAction:function(c,p){  
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''} }); 
	var moreArgs = { };	
	gigya.services.socialize._AddRequest('publishUserAction','Gigya.Socialize.Core','','coreDiv',1,1,true,false,c,p,moreArgs);	
	
} ,
	
	
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'];	
	p = gigya.global.normalizeParams(p,false, {width:{def:510},height:{def:315}});
	var moreArgs = { };		
	gigya.global._ClearContainer(containerID);
    moreArgs['grayOut']=true;
	gigya.services.socialize._AddRequest('showShareUI','Gigya.Socialize.Share_%lang','',containerID,p['width'],p['height'],true,false,c,p,moreArgs);
},				

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);
},
showNewsfeedUI: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.showNewsfeedUI',p['containerID'],c,p);
},
showLoginUI:function(c,p){  
//gigya.services.socialize.showHTMLLoginUI(c,p);return;
    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} });	 	    
    }
        
	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} });	 	    
    }
     
	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} });	   	
	}
			                 
	var moreArgs = { };	
    gigya.services.socialize._AddRequest('showEditConnectionsUI','Gigya.Socialize.EditConnections_%lang','',containerID,p['width'],p['height'],true,false,c,p,moreArgs);
},	

hideUI:function(c,p) {
    gigya.services.socialize.GrayOut(false);
    for (var containerID in gigya.services.socialize._PopupContainers) {
        gigya.services.socialize._PopupContainers[containerID].innerHTML = '';
        var ifrel=document.getElementById('gigya_ifr_'+containerID);
        if ( null!=ifrel ) { 
            ifrel.style.visibility = 'hidden';     
        }
    }
    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(',');
			}
	}
},

_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,name,width,height,iframeWidth,iframeHeight,nativeLoginStr) {
	this.ID = ID;
	this.name = name;
	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.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.capabilities =uo.capabilities?uo.capabilities:{login:false, notifications:false, newsfeed:false, friends:false, status: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:'';		
	}
	else {
		if (gigya.services.socialize.verbose) {
			alert('Gigya Social:' + io + ' is not an identity');
		}
	}
},

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:'';
}
}

gigya.services.socialize._arProviders=[
	new gigya.services.socialize.Provider(64, 'Facebook', 480, 400, 500,440,'&useFBC=true'),
	new gigya.services.socialize.Provider(1, 'MySpace', 610, 510),
	new gigya.services.socialize.Provider(9012, 'Twitter', 800, 440),
	new gigya.services.socialize.Provider(9803, 'Yahoo', 610, 440),
	new gigya.services.socialize.Provider(9042, 'LinkedIn', 730, 590),
	new gigya.services.socialize.Provider(9811, 'Google', 410, 450),
	new gigya.services.socialize.Provider(9800, 'AOL', 530, 720),
	new gigya.services.socialize.Provider(4096, 'WordPress', 700, 540),
	new gigya.services.socialize.Provider(256, 'Blogger', 760, 400),
	new gigya.services.socialize.Provider(1041, 'Hyves', 700, 540),
	new gigya.services.socialize.Provider(16, 'LiveJournal', 670, 360),
	new gigya.services.socialize.Provider(1043, 'VeriSign', 940, 500),
	new gigya.services.socialize.Provider(1024, 'Typepad', 730, 590),
	new gigya.services.socialize.Provider(4120, 'OpenID', 730, 590),
	new gigya.services.socialize.Provider(1045, 'LiveID', 890, 560)
]

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});}


//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() {
    if (gigya.fbcAPIKey!='' && document.domain.indexOf(gigya.fbcDomain)!=-1) {
        window.setInterval('gigya.refreshFbcSession()', 45*60*1000);
        document.domain = gigya.fbcDomain;
        if ((!document.readyState && document.body) || document.readyState == "loaded" || document.readyState == "complete") {
            gigya.services.socialize.loadFBC();
        } else {
            if (window.attachEvent) {
                window.attachEvent('onload',gigya.services.socialize.loadFBC);
            } else if (window.addEventListener) {
                window.addEventListener('load',gigya.services.socialize.loadFBC,false);
            }
        }
    }
}
