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.services.socialize= {

_GlobalEventHandlers : {
    onLogin:{idx:0},     
    onConnect:{idx:0},     
    onDisconnect:{idx:0},
    onLogout:{idx:0}            
} ,
 
_PopupContainers:{},

CenteredComponentDivID:'WFComponentDiv_'+(new Date()).getTime(),
GetCenteredComponentDivID:function(popupName){
	return this.CenteredComponentDivID+'_'+popupName;
},

_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 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='+ContainerIDAndSWFName+'&SWFModuleID='+ ContainerIDAndSWFName +'&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,5);
	//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 ri='gigya.services.socialize._ReissueRequests(\'' + ContainerAndSWF + '\');';
	var swf=document.getElementById(ContainerAndSWF);	

	if (swf!=null) { swf.swfLoaded = true; }
      
    var lastUnderscorePos = ContainerAndSWF.lastIndexOf('_');
    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 });\n' +
	        '}'
	    );	    	    
	}   	
	gigya.services.socialize.addEventHandlers({},p);	   
	window.setTimeout(ri,50);
},

_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+'\')',50);
		}
	}
	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;
		/* 
		//commented on 2.3.5.1
		if ((typeof swf.CallFunction !='function') && (typeof swf.CallFunction !='unknown')) return;
		var xmlInvoke=['<invoke name="exec" returntype="javascript">',req.serializedArgs,'</invoke>'].join('');
		*/
		if (gigya.services.socialize.verbose) {			
			alert(xmlInvoke);
		}

  	    //alert(xmlInvoke);
		//ret=swf.CallFunction(xmlInvoke);	
		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);
		}
	}
},

/*
// commented on 2.3.5.1
_InvokeMethodOnRID:function(rid,method,serializedArgs){
	try {
		if (gigya.services.socialize.verbose) {
			alert( 'gigya.services.socialize._InvokeMethodOnRID ' + rid);
		}
		var oRID=gigya.services.socialize._parseRID(rid);
		var swf=oRID.swf;
		
		if ((typeof swf.CallFunction !='function') && (typeof swf.CallFunction !='unknown')) return;

		var xmlInvoke=['<invoke name="',method,'" returntype="javascript">',serializedArgs,'</invoke>'].join('');
		if (gigya.services.socialize.verbose) {
			alert(xmlInvoke);
		}
		ret=swf.CallFunction(xmlInvoke);
	}
	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 _InvokeMethodOnRID ' + 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.lastScriptProtocol + '://cdn.gigya.com/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);
			}
//			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.firstChild is null - can not create container ' + id);
		} 
		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 ( blnCenter ) { 
	    if (container.style.zIndex==null || blnCenter) {
		    container.style.zIndex=gigya.global._NextZIndex++;
	    }
    	
    	 
	    if ((container.style.width!=''+w+'px') || (container.style.height!=''+h+'px')) {
	        //debugger;
		    container.style.width=''+w+'px';
		    container.style.height=''+h+'px';			    
	    }	    
		
		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 obstaclePositions=new Array();
	var optionalPositions=new Array();
	optionalPositions.push({t:0,l:0});
	var viewport = gigya.global._ClientViewport.get(); 
	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;
	if (container.id=='coreDiv') {
		gigya.services.socialize._DodgeEmbedsAndIframes(container,w,h)
		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) {
				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:'No such containerID :'+containerID + ' while calling '+methodName
        };              
        
        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 = {
                operation: methodName , 
                context: p['context'],
                status:'FAIL', 
                statusMessage:'No such containerID :'+containerID
            };
            
            callback(resp);
        }        
    }                
},

//_AddRequest:function(operation,servicedBy,methodName,containerID,w,h,blnCenter,blnShowClose,confObj,autoLogin,callback,context,args,moreArgs){	
_AddRequest:function(operation,servicedBy,methodName,containerID,w,h,blnCenter,blnShowClose,c,p,moreArgs){	

	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']};	
		    

	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;
	}
		
		
   // 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 (ifrel!=null) {
		GS._SetContainerSizeAndPosition(ifrel,w,h,blnCenter);
	}
	GS._SetContainerSizeAndPosition(container,w,h,blnCenter);
	GS._HandleEmbedAndObjectsBelow(container,w,h);
	
    if ( containerID =='coreDiv' ) {	
	    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,5);
	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;
		
	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') {
			//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.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 = '';
    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';
                statusMessage = 'The event handler \''+knowEvtHandlerName+'\' is not a function';
            }
        }
    } 
            
    if ( typeof p['callback'] == 'function' ) {
        var response = { status:status, statusMessage: statusMessage, 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);
  }  
} , 

loadCore:function() {
    if (document.body!=null && document.body.firstChild!=null) {
        gigya.services.socialize._AddRequest('dummy','WSSCore','','coreDiv',1,1,true,false,{},true,undefined,{},['rid',{}]);
    } else {
        window.setTimeout('gigya.services.socialize.loadCore()', 500);
    }
},
	
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); 	
},	
	

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); 	
},
	
login:function(c,p){
    p = gigya.global.normalizeParams(p,true,{ containerID:{nullAs:''}, provider:{nullAs:''}});		
	var moreArgs = {};	
	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 = {};
	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 = { };			
	//RAVIV
	try {document.getElementById(containerID).innerHTML="";}catch(e){}
	gigya.services.socialize._AddRequest('showFriendSelectorUI','Gigya.Socialize.FriendSelector','',containerID,p['width'],p['height'],true,false,c,p,moreArgs);
},	
	
showActionsUI: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:325} });	 
	var moreArgs = { };		
	gigya.services.socialize._AddRequest('showActionsUI','Gigya.Socialize.NewsFeed','',containerID,p['width'],p['height'],true,false,c,p,moreArgs);
},				

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 {            
		//RAVIV
		try {document.getElementById(containerID).innerHTML="";}catch(e){}
	    p = gigya.global.normalizeParams(p,false, { width:{def:120}, height:{def:110} });	 	    
    }
        
	var moreArgs = { };	
    gigya.services.socialize._AddRequest('showLoginUI','Gigya.Socialize.Login','',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 {      
		//RAVIV
		try {document.getElementById(containerID).innerHTML="";}catch(e){}
	    p = gigya.global.normalizeParams(p,false, { width:{def:110}, height:{def:65} });	 	    
    }
     
	var moreArgs = { };	
    gigya.services.socialize._AddRequest('showConnectUI','Gigya.Socialize.Login','',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 {
		//RAVIV
		try {document.getElementById(containerID).innerHTML="";}catch(e){}
        p = gigya.global.normalizeParams(p,false, { width:{def:310}, height:{def:250} });	   	
	}
	    
			                 
	var moreArgs = { };	
    gigya.services.socialize._AddRequest('showEditConnectionsUI','Gigya.Socialize.EditConnections','',containerID,p['width'],p['height'],true,false,c,p,moreArgs);
},	

hideUI:function(c,p) {
    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
        };
        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;
},

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:'';
		
     //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='';
		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.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(a){
	return this.titleTemplate;
}

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;
    try{
        apikey=gigya._vars.lastScriptURL.split('?')[1].split('apikey=')[1].split('&')[0];
    } catch(e){}        
    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();