//alert('in Gigya.Social.js.JS');

if (typeof Gigya == 'undefined') {	Gigya= new Object(); }

if (typeof Gigya.Social == 'undefined') {
	Gigya.Social= new Object();
}
if (typeof Gigya.Global == 'undefined') {
	Gigya.Global= new Object();
}

if (typeof Gigya.Global._NextZIndex == 'undefined') {
	Gigya.Global._NextZIndex=1000;
}

if (typeof Gigya.Global._OpenedWindows == 'undefined') {
	Gigya.Global._OpenedWindows = new Object();
}

Gigya.Global._CloseWindow = function(windowName) {
    if (Gigya.Global._OpenedWindows[windowName]!=null) 
    {
		try {
			Gigya.Global._OpenedWindows[windowName].close(); 
			delete Gigya.Global._OpenedWindows[windowName];
		}
		catch (ex)
		{
			debugger;
		}
    }
}

Gigya.Global.isSafari = function() {
    return (navigator.userAgent.toLowerCase().indexOf('safari')!=-1);
}

Gigya.Global._OpenWindow = function(url, windowName, windowOptions, inTimeOut)
{
    if (typeof windowOptions == 'undefined') {
        windowOptions = 'menubar=0,toolbar=0,resizable=1,width=960,height=680';
    }
    var newWin = window.open(url, windowName, windowOptions);
    if (!newWin)
    {
        //safari bug fix
        newWin = window.open('', windowName, windowOptions);
        if (newWin && newWin.location)
        {
            newWin.location.href = url;
        }
    }
    if (!newWin && !inTimeOut)
    {
        window.setTimeout('Gigya.Global._OpenWindow("' + url + '", "' + windowName + '", "' + windowOptions + '", true)', 10);
        return;
    }
    if (newWin && newWin.focus)
    {
        newWin.focus();
    }
    Gigya.Global._OpenedWindows[windowName] = newWin;
    return (Gigya.Global._OpenedWindows[windowName] != null);
}

Gigya.Global._GetElementPos=function(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	};
	return {left:curleft,top:curtop};
}	

//alert(' navigator.appVersio = ' + navigator.appVersion + '\navigator.userAgent = ' + navigator.userAgent);
Gigya.Flash={

isIE  : (navigator.appVersion.indexOf("MSIE") != -1) ? true : false,
isWin : (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false,
isOpera : (navigator.userAgent.indexOf("Opera") != -1) ? true : false,
isFF :(navigator.userAgent.indexOf("Firefox") != -1) ? true : false,

AC_Generateobj:function(objAttrs, params, embedAttrs) { 
    var str = '';
    
	if (this.isIE && this.isWin && !this.isOpera)	{
		str += '<object ';
		for (var i in objAttrs) {str += i + '="' + objAttrs[i] + '" ';}
		str += '>';
		for (var i in params) {str += '<param name="' + i + '" value="' + params[i] + '" /> ';}
		str += '</object>';
	}
	else {
		str += '<embed ';
		for (var i in embedAttrs) {str += i + '="' + embedAttrs[i] + '" ';}
		str += '> </embed>';
	}
	return str;
},

AC_FL_GetContent:function(){
	var ret = this.AC_GetArgs(arguments);
	return this.AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
},

AC_GetArgs:function(args, classid, mimeType){
	var ret = {};
	ret.embedAttrs = {};
	ret.params = {};
	ret.objAttrs = {};
	for (var i=0; i < args.length; i=i+2){
		var currArg = args[i].toLowerCase();    
		switch (currArg){	
			case "movie":	
				ret.embedAttrs["src"] = args[i+1];
				ret.params["movie"] = args[i+1];
			break;
			case "id":  
			case "width":
			case "height":
			case "align":
			case "name":
			case "z-index":
				ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
			break;
			default:
				ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
		}
  }
  ret.objAttrs['codebase']='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0';
  ret.objAttrs["classid"] = "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000";
  ret.embedAttrs["type"] ="application/x-shockwave-flash";
  ret.embedAttrs['pluginspage']='http://www.macromedia.com/go/getflashplayer';
  
  return ret;
}

} // Gigya.Flash

Gigya.Social.CenteredComponentDivID='WFComponentDiv_'+(new Date()).getTime();

Gigya.Social._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.Social._DescribeObjectRec(o[p],on+'['+p+']',levels-1,a);
				}
				else {
					Gigya.Social._DescribeObjectRec(o[p],on+'.'+p,levels-1,a);
				}
			}
		}
		//if (o.constructor==Date) {
			//a.push(
		//}
	}
}

Gigya.Social.describeObject = function(o,oname,desc,levels){
	var a=new Array();
	a.push(desc);
	Gigya.Social._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
Gigya.Social._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.Social._HandleObjectRepresentation(o[i],fnBefore,fnAfter);
		}
		if (fnAfter) {fnAfter(o,i,typeof o[i])} // not using t becasue it could have changed
	}
}

Gigya.Social._HandleObjectRepresentation = function(o){
	Gigya.Social._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.Social.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;
		}
	)
}

Gigya.Social._LoadSWF=function(rid){
	var oRID=Gigya.Social._parseRID(rid);
	var req=oRID.req;
	var w=req.w;
	var h=req.h;
	var swfName=req.servicedBy;
	
	var confObj=req.confObj;
	var wmode='opaque';
	if ((confObj!=null) && (confObj.nowmode!=null)) {
		wmode='';
	}
	
	var swfurl='http://cdn.gigya.com/Wildfire/swf/'	+ swfName + '.swf';	
	var container=oRID.container;
	
	var ContainerIDAndSWFName=container.id+'_'+swfName;
	
	var html='';
	//html += '<div style="position:relative;top:50%;text-align:center;font-size:12px;z-index:50;" id="'+this.id+'_progress"><center><img  src="'+this.config.progressImageSrc+'"></center></div>';
	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.Social._swfs  == 'undefined') Gigya.Social._swfs={};
	//Gigya.Social._swfs[container.id+'_'+swfName]={container:container};
	//if (Gigya.Social.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;
	
	//window[ContainerIDAndSWFName] = document.getElementById(ContainerIDAndSWFName);
	
	return;
	//With Timeout
	var expr= 'document.getElementById(\'' + container.id + '\').innerHTML=\''+html.replace('\'','\\\'')+'\'';
	//var expr2= 'Gigya.Social._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"
/*
Gigya.Social._SetContainerHTML=function(containerID,html){
	document.getElementById(containerID).innerHTML=html;
}
*/

Gigya.Social._escapeXML=function(s) {
	return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
}

Gigya.Social._SerializePropertyToBuffer=function(o,p,a){ a.push('<property id="' + p + '">'); Gigya.Social._SerializeToBuffer(o[p],a); a.push('</property>');}
Gigya.Social._SerializeObjectToBuffer=function(o,a) {a.push('<object>'); for (var prop in o) { Gigya.Social._SerializePropertyToBuffer(o,prop,a); } ;	a.push('</object>');}
Gigya.Social._SerializeArrayToBuffer=function(arr,a){a.push('<array>');	for (var i=0; i<arr.length; i++) { Gigya.Social._SerializePropertyToBuffer(arr,i,a); }; a.push('</array>');}

Gigya.Social._SerializeToBuffer=function(v,a){
	    var value=v;
		var type = typeof(v);
		if (type == 'string') {	
			if (value=='') {
				return Gigya.Social._SerializeObjectToBuffer({EmptyString:true},a);
			}
			else {
				a.push('<string>'+Gigya.Social._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.Social._SerializeArrayToBuffer(value,a);}
		else if (type == "object") {return Gigya.Social._SerializeObjectToBuffer(value,a);} 
		else {return "<null/>";}
}

Gigya.Social._SerializeArgs=function(args){
	var a=new Array();
	a.push('<arguments>');
	for (var i=0; i<args.length; i++) {	Gigya.Social._SerializeToBuffer(args[i],a); }			
	a.push('</arguments>');
	return a.join('');
}

Gigya.Social._RegisterSWF=function(ContainerAndSWF,isComponent){
	var ri='Gigya.Social._ReissueRequests(\'' + ContainerAndSWF + '\');';
	var swf=document.getElementById(ContainerAndSWF);
	if (swf!=null) {
	    swf.swfLoaded = true;
	}
	window.setTimeout(ri,50);
}

Gigya.Social._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;
		//container=container.parentElement;
	}
	else {
		container=swf.parentNode;
		//container=container.parentNode;
	}
	
	var Reqs=container.Reqs; // Array
	var req;
	for (var r=0;null!=(req=Reqs[r]);r++) {
		
		if (req.Loaded!=true) {
			req.Loaded=true;
			var op=req.request.operation;
			if ((op.indexOf('UI')==op.length-2) ) {
				if (typeof Gigya.Social._UIComponentsResyncInfo=='undefined') Gigya.Social._UIComponentsResyncInfo=[];
				Gigya.Social._UIComponentsResyncInfo[container.id]={rid:req.rid}
				
				var response={status:'LOAD',operation:op,context:req.context,statusMessage:''};
				if (typeof req.callback=='function') req.callback(response);
			}
			
			else switch (op) {
				case 'showFriendsSelect':
				case 'showFindYourFriends':
				case 'showApproval':
				case 'showSendVerification':
					//alert(' op = ' + op + ' ' + req.context.ridToRetry + ' ' + req.rid);
					if (Gigya.Social._UIComponentsResyncInfo==null) Gigya.Social._UIComponentsResyncInfo = {};
					Gigya.Social._UIComponentsResyncInfo[container.id]={rid:req.rid}; // the actual login request.
					break;
				default: 
					//alert(' op = ' + op + ' ' + req.rid);
				
			}
			
			Gigya.Social._DoRequest(req.rid);
		}
	}
}

//Sync login state of all components after a change in any of them.
Gigya.Social._DispatchChange=function(ridSource,blnSyncSelf,event,data){
	var rid;
	var GS=Gigya.Social;
	var serializedArgs=GS._SerializeArgs([event,data])
	for (var containerID in GS._UIComponentsResyncInfo) {
		rid=GS._UIComponentsResyncInfo[containerID].rid;
		if ((ridSource!=rid) || (blnSyncSelf==true)) {
			GS._InvokeMethodOnRID(rid,'handleChange',serializedArgs);
			if (GS.verbose) alert('_DispatchChange called on ' + rid);
		}
		else {
			if (GS.verbose) alert('skipping _DispatchChange for ' + rid);
		}
	}
	return true;
}

Gigya.Social._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};
}

Gigya.Social._DoRequest=function(rid){
	try {
		
		var oRID=Gigya.Social._parseRID(rid);
		var req=oRID.req;
		var swf=oRID.swf;
		
		if ((typeof swf.CallFunction !='function') && (typeof swf.CallFunction !='unknown')) return;

		req.container.style.visibility='';
		window.setTimeout('Gigya.Social.__DoRequest(\''+rid+'\')',50);
	}
	catch(e){
		if (Gigya.Social.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);
		}
	}
}		



Gigya.Social.__DoRequest=function(rid){
	try {
		if (Gigya.Social.verbose) {
			alert( 'Gigya.Social.__DoRequest ' + rid);
		}
		var oRID=Gigya.Social._parseRID(rid);
		var req=oRID.req;
		var swf=oRID.swf;
		if (!swf.swfLoaded) return;
		if ((typeof swf.CallFunction !='function') && (typeof swf.CallFunction !='unknown')) return;

		var xmlInvoke=['<invoke name="',req.method,'" returntype="javascript">',req.serializedArgs,'</invoke>'].join('');
		if (Gigya.Social.verbose) {
			//prompt('running invoke',xmlInvoke);
			alert(xmlInvoke);
		}
		
		ret=swf.CallFunction(xmlInvoke);
	//  if (ridp[1]!='WSSCore')	{
	//		req.container.style.display='none';
	//		//req.container.style.visiblity='hidden';
	//	}
		
	}
	catch(e){
		if (Gigya.Social.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);
		}
	}
}

Gigya.Social._InvokeMethodOnRID=function(rid,method,serializedArgs){
	try {
		if (Gigya.Social.verbose) {
			alert( 'Gigya.Social._InvokeMethodOnRID ' + rid);
		}
		var oRID=Gigya.Social._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.Social.verbose) {
			alert(xmlInvoke);
		}
		ret=swf.CallFunction(xmlInvoke);
	}
	catch(e){
		if (Gigya.Social.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);
		}
	}
}


Gigya.Social._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 ];
}


Gigya.Social._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;
}

Gigya.Social._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.src="http://google.com";

		ifrel.style.position='absolute';
		ifrel.style.width='1px';
		ifrel.style.height='1px';
		if (ifrel.style.zIndex!=null) {
			ifrel.style.zIndex=Gigya.Global._NextZIndex++;
		}
	}

	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;
	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.Social.js:document.body.firstChild is null - can not create container ' + id);
		} 
		else {
			alert('Gigya.Social.js:document.body.insertBefore is null - can not insert container ' + id);
		}
	}
	else {
		alert('Gigya.Social.js:document.body is null - can not Create container ' + id);
	}
	//el.onclick=function(){this.firstChild.style.display='none'};
	return el;
}

Gigya.Social._SetContainerSizeAndPosition=function(container,w,h,blnCenter){
/*	alert(['Gigya.Social._SetContainerSizeAndPosition ' ,
	      'container = ' + container.id,
	      'w = ' + w,
	      'h = ' + h,
	      'blnCenter = ' + blnCenter].join('\n'));
*/	      
	//if (container.style.zIndex==null) {
	if (container.style.zIndex==null || blnCenter) {
		container.style.zIndex=Gigya.Global._NextZIndex++;
	}
	
	if ((container.style.width!=''+w+'px') || (container.style.height!=''+h+'px')) {
		container.style.width=''+w+'px';
		container.style.height=''+h+'px';

	}
	
	if (blnCenter) {
		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;
		}

		
		var scrl=Gigya.Social._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';
	}
}

Gigya.Social._LoadRequiredFor=function(rid){
	var oRID=Gigya.Social._parseRID(rid);
	return (oRID.swf==null);
}

Gigya.Social._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.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)  {
	
/*						var m=[];
						var c=0;
						for (attr in el) {
							if ((''+ el[attr])=='opaque') {alert(attr);}
							m.push(attr)
							if (c++==9) {m.push('\n');c=0;}
						}
						m.push('\n');
						//m.push(el.Attributes['wmode']);
						m.push(el.getAttribute('wmode')); 
						m.push(el.parentNode.innerHTML);
						alert(m.join(','));
*/	

						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);

						}
					}
				}
			}
		}
	}
}

Gigya.Social._AddRequest=function(operation,servicedBy,methodName,containerID,w,h,blnCenter,blnShowClose,confObj,autoLogin,callback,context,args,moreArgs){	
	var GS=Gigya.Social;
	if (methodName=='') methodName=operation;

	//HANDLE Container Defaults/Get/Create/Resize&Pos
	if (containerID=='' || containerID==null) {	
		blnCenter=true;
		blnShowClose=true;
		containerID=GS.CenteredComponentDivID;
	}
	var container=GS._GetContainer(containerID);
	
	if (container==null) {
		container=GS._CreateContainer(containerID);
	}
	
	var ifrel= document.getElementById('gigya_ifr_'+containerID);
	
	if (ifrel!=null) {
		GS._SetContainerSizeAndPosition(ifrel,w,h,blnCenter);
	}
	GS._SetContainerSizeAndPosition(container,w,h,blnCenter);
	//if (blnCenter) 
	   GS._HandleEmbedAndObjectsBelow(container,w,h);

	//if (servicedBy=='WSSCore') {container.style.display='none';}
	var Reqs=(container.Reqs?container.Reqs:(container.Reqs=[]));
	
	var rid=Reqs.length+'@'+servicedBy+'@'+container.id;
	args[0]=rid;
	var req=Reqs[Reqs.length]={
			rid:rid,
			servicedBy:servicedBy,container:container,method:methodName,
			serializedArgs:GS._SerializeArgs(args),
			confObj:confObj,autoLogin:autoLogin,callback:callback,context:context,moreArgs:moreArgs
			,w:w,h:h,
			request:{operation:operation,args:args,status:'',callback:callback,context:context}
	};
	//if (confObj.verbose) prompt('serializedArgs',req.serializedArgs);
	Gigya.Social._TryExecute(rid);
}

Gigya.Social._TryExecute=function(rid){
	var GS=Gigya.Social;
	if (GS._LoadRequiredFor(rid)) { 
		GS._LoadSWF(rid);
	}
	else {
		GS._DoRequest(rid);
	}

}

Gigya.Social._CreateRetryObject=function(ridToRetry){
	//alert('creating retry for ' + ridToRetry);
	var o={};
	o.callback=function(response){
		//alert('In Retry Callback with response');
		var ridToRetry=this.context.ridToRetry;
		var oRID=Gigya.Social._parseRID(ridToRetry);
		
		var req=oRID.req;
		
		if (response.status=='FAIL' || response.status=='ERROR') {
			var originalCallback=req.callback;
			response.context=req.context;
			//Gigya.Social._ClearRequest(response.context.ridToRetry);
			if (originalCallback!=undefined) { originalCallback(response) };
		}
		else {
			//set IgnoreSnooze to false
			if (req.request.operation=='login') {
				req.request.args[2]=false;
				req.serializedArgs=Gigya.Social._SerializeArgs(req.request.args);
			}
			if (req.request.operation=='getUserInfo') {
				req.autoLogin=false;
				//req.serializedArgs=Gigya.Social._SerializeArgs(req.request.args);
			}			
			Gigya.Social._TryExecute(response.context.ridToRetry);
		}
	};
	o.context={ridToRetry:ridToRetry};
	return o;
}

Gigya.Social._AdjustResponseStatus=function(response){
	switch ((''+response.status).toUpperCase()) {
	    case 'IMPORT_FAIL':
		case 'FAIL':response.status='ERROR';break;
		case 'NEW_USER':
		case 'NO_AUTH_SITE':response.status='NOT_LOGGED_IN';break;
		case 'INVALID_SITE':response.status='INVALID_KEY';break;
		case 'NO_AUTH_LEVEL':response.status='UNAUTHORIZED';break;
	}
}

Gigya.Social._HandleResponse=function(rid,response){
    if (response.statusMessage==undefined) {
        response.statusMessage = '';
    }
    //if (rid=="0@Newsfeed@divWildfirePost") debugger;
    //if (response==null) debugger;
	if (Gigya.Social._Responses==null) {
	    Gigya.Social._Responses={};
	    Gigya.Social._uidx=0;
	}
	var uidx=Gigya.Social._uidx++;
	Gigya.Social._Responses[rid+'_'+uidx]=response;
	var expr='Gigya.Social.__HandleResponse(\'' + rid + '\',\'' + rid +'_'+uidx + '\');';
	//var expr = 'Gigya.Social._test(\'' + rid + '\');';
	window.setTimeout(expr,5);
	return true;
}

Gigya.Social.__HandleResponse=function(rid,key){
    var response=Gigya.Social._Responses[key];
	delete Gigya.Social._Responses[key];

	var oRID=Gigya.Social._parseRID(rid);
	var req=oRID.req;
	
	Gigya.Social._AdjustResponseStatus(response);
/*	
	if (ridp[1]=='WSSCore') {
	//container.style.display='none';
	//container.style.visibility='hidden';
	}
*/
	
	var retry;
//	alert(Gigya.Social.describeObject(response,'response','JS Got response for operation ' + req.request.operation + ' for rid='+rid,4)+'\n=============\n'+Gigya.Social.describeObject(req,'req','req for operation ' + req.request.operation + ' for rid='+rid,4));

	Gigya.Social._HandleObjectRepresentation(response);
	if (Gigya.Social.verbose || req.confObj.verbose) {
		alert(Gigya.Social.describeObject(response,'response','JS response after empty string fix for operation ' + req.request.operation + ' for rid='+rid,4)+'\n=============\n'+Gigya.Social.describeObject(req,'req','req for operation ' + req.request.operation + ' for rid='+rid,10));
	}
	
	
	response.context=req.request.context;
	if (response.context == null) response.context = {};
	response.operation=req.request.operation;
	if (response.user) {
		response.user=new Gigya.Social.User(response.user);
	}
	if (response.friends) {
		response.friends=new Gigya.Social.Collection(Gigya.Social._ConvertToTypedObjects(response.friends,Gigya.Social.User),'gigyaUID');
	}
	
	if (response.friend) {
		response.friend=new Gigya.Social.Collection(Gigya.Social._ConvertToTypedObjects(response.friend,Gigya.Social.User),'gigyaUID');
	}	
	
	if (response.actions) {
		response.actions=new Gigya.Social.Collection(Gigya.Social._ConvertToTypedObjects(response.actions,Gigya.Social.UserAction),'gigyaUID');
	}
	if (response.communityActions) {
		response.communityActions=new Gigya.Social.Collection(Gigya.Social._ConvertToTypedObjects(response.communityActions,Gigya.Social.UserAction),'gigyaUID');
	}
	
	if (response.Action && (response.Action!='') && (response.Action!='undefined')) {
		if (response.Action.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.container.Reqs = [];
			
		}
		if (response.Action.Action=='Show') {
			var rc=response.context;
			var ra=response.Action;
			switch(response.Action.Form){
			    case 'SNLogin':
					if (req.autoLogin) { 
						retry=Gigya.Social._CreateRetryObject(rid);
						Gigya.Social._showSNLogin(req.confObj,false,retry.callback,retry.context);
						return;// only return if no need to return result yet.
					}			    
				case 'FindYourFriends':
					if (req.autoLogin) { 
						retry=Gigya.Social._CreateRetryObject(rid);
						Gigya.Social._showFindYourFriends(req.confObj,
													  ra.showDontAsk,ra.showCancel,
													  retry.callback,retry.context
													  );
						return;// only return if no need to return result yet.
					}
					
					break;
				case 'FriendsSelect':
					if (req.autoLogin) {
						retry=Gigya.Social._CreateRetryObject(rid);
						Gigya.Social._showFriendsSelect(req.confObj,
													ra.textKey,ra.showDontAsk,ra.showCancel,
													retry.callback,retry.context
													);
						return;// only return if no need to return result yet.
					}
					break;
				case 'Approval':
					if (req.autoLogin) {
						retry=Gigya.Social._CreateRetryObject(rid);
						Gigya.Social._showApproval(req.confObj,
										   ra.showDontAsk,
										   retry.callback,retry.context
										   );
						return;// only return if no need to return result yet.
					}
					break;
				case 'SendVerification':
						//retry=Gigya.Social._CreateRetryObject(rid);
						Gigya.Social._showSendVerification(req.confObj,
										   req.moreArgs.listOfGIGUIDs,req.moreArgs.body,req.moreArgs.subject,
										   req.callback,req.context
										   );
						return;// only return if no need to return result yet.
				break;
				case 'mergeAlert':
				    Gigya.Social._showMerge(req.confObj,
										   req.moreArgs.loginToken,req.moreArgs.signature,response.sck, response.currentUsername, response.siteUsername,
										   req.callback,req.context
										   );
				    return;
				case 'loginMergeAlert':
				    Gigya.Social._showLoginMerge(req.confObj,
										   response.actionTicket, response.currentUsername, response.siteUsername,
										   req.callback,req.context
										   );
				    return;				    
				break;
					
			}
		}
		//alert('no action could be performed (autoLogin==false) response.Action was '+ response.Action );
	}
	else {
	//	alert('response.Action was empty');
	}
	
	delete response.Action;
	if (Gigya.Social.verbose || req.confObj.verbose) alert('before callback \n' + Gigya.Social.describeObject(response,'response','response to be passed to callback for ' + req.request.operation + ' for rid='+rid,4)+'\n=============\n'+Gigya.Social.describeObject(req.callback,'req.callback','req.callback for operation ' + req.request.operation + ' for rid='+rid,4));
	if (typeof req.callback=='function') {
		req.callback(response);
	}
	else {
		if (Gigya.Social.verbose || req.confObj.verbose) {alert ('No callbeck found to call on ');}
	}
}

Gigya.Social.loadCore=function() {
    if (document.body!=null && document.body.firstChild!=null) {
        Gigya.Social._AddRequest('dummy','WSSCore','','coreDiv',1,1,true,false,{},true,undefined,{},['rid',{}]);
    } else {
        window.setTimeout('Gigya.Social.loadCore()', 500);
    }
}

Gigya.Social.login=function(confObj,callback,context,network){
	var ignoreSnooze=true;
	var windowOptions;
	switch (network) {
	    case 'myspace': windowOptions = 'menubar=0,toolbar=0,resizable=1,width=820,height=640'; break;
	    case 'facebook': windowOptions = 'menubar=0,toolbar=0,resizable=1,width=550,height=450'; break;
	}
	if (network!=null) {
	    Gigya.Global._OpenWindow('http://wildfire.gigya.com/wildfire/wait.htm', 'WFS_loginTo' + network.toLowerCase(), windowOptions)
	}
	Gigya.Social._AddRequest('login', 'WSSCore', '', 'coreDiv', 1, 1, true, false, confObj, true, callback, context, ['rid', confObj, ignoreSnooze, network]);	
}

Gigya.Social.logout=function(confObj,callback,context,network){	
	Gigya.Social._AddRequest('logout','WSSCore','','coreDiv',1,1,true,false,confObj,true,callback,context,['rid',confObj,network]);
}

Gigya.Social.clearInfo=function(confObj,callback,context){	
	Gigya.Social._AddRequest('clearInfo','WSSCore','','coreDiv',1,1,true,false,confObj,true,callback,context,['rid',confObj]);
}

Gigya.Social.getExLoginToken=function(confObj,callback,context,username,userEmail){
	Gigya.Social._AddRequest('getChallenge','WSSCore','','coreDiv',1,1,true,false,confObj,false,callback,context,['rid',confObj,username,userEmail]);
}
Gigya.Social.exLogin=function(confObj,callback,context,loginToken, signature){
	Gigya.Social._AddRequest('externalLogin','WSSCore','','coreDiv',1,1,true,false,confObj,false,callback,context,['rid',confObj,loginToken,signature], {loginToken: loginToken, signature: signature});
}
Gigya.Social.getUserInfo=function(confObj,callback,context,autoLogin){
	Gigya.Social._AddRequest('getUserInfo','WSSCore','','coreDiv',1,1,true,false,confObj,autoLogin,callback,context,['rid',confObj]);
}
Gigya.Social.getFriends=function(confObj,callback,context,autoLogin){
	Gigya.Social._AddRequest('getFriends','WSSCore','','coreDiv',1,1,true,false,confObj,autoLogin,callback,context,['rid',confObj]);
}
Gigya.Social.getFriendInfo=function(confObj,callback,context,autoLogin,friendGigyaUserID){
	Gigya.Social._AddRequest('getFriendInfo','WSSCore','','coreDiv',1,1,true,false,confObj,autoLogin,callback,context,['rid',confObj,friendGigyaUserID]);
}
Gigya.Social.sendNotification=function(confObj,callback,context,autoLogin,listOfGIGUIDs,body,subject){
	listOfGIGUIDs=Gigya.Social._ExtractListOfGIGUIDs(listOfGIGUIDs);
	Gigya.Social._AddRequest('sendNotification','WSSCore','dispatchSendNotification','coreDiv',1,1,true,false,confObj,autoLogin,callback,context,['rid',confObj,listOfGIGUIDs,body,subject],{listOfGIGUIDs:listOfGIGUIDs,body:body,subject:subject});
}
Gigya.Social.reportUserAction=function(confObj,callback,context,autoLogin,userAction){
	Gigya.Social._AddRequest('reportUserAction','WSSCore','','coreDiv',1,1,true,false,confObj,autoLogin,callback,context,['rid',confObj,userAction]);
}
Gigya.Social.getActions=function(confObj,callback,context,autoLogin,count,siteActionOnly,filterTarget,filterActionName,filterActionData1,filterActionData2){
    if (siteActionOnly==null) {siteActionOnly=true};
	Gigya.Social._AddRequest('getActions','WSSCore','','coreDiv',1,1,true,false,confObj,autoLogin,callback,context,['rid',confObj,count,siteActionOnly,filterTarget,filterActionName,filterActionData1,filterActionData2]);
}


Gigya.Social.showFriendSelectorUI=function(confObj,callback,context,containerID,width,height,dialogCaption,selectionLimit,showCancel){
	var showCloseX=(containerID==null || containerID=='');
	Gigya.Social._AddRequest('showFriendSelectorUI','FriendsSelector','',containerID,width,height,false,showCloseX,confObj,false,callback,context,['rid',confObj,containerID,width,height,dialogCaption,selectionLimit,showCancel,showCloseX]);
}
Gigya.Social.showNotificationUI=function(confObj,callback,context,containerID,width,height,bodyTemplate,defaultUserMsessage,subject,checkboxStatus,editable,dialogCaption,showCancel){
	var closeWhenDone=(containerID==null || containerID=='');
	var showCloseX=closeWhenDone;
	Gigya.Social._AddRequest('showNotificationUI','Notifications','',containerID,width,height,false,showCloseX,confObj,false,callback,context,
		['rid',confObj,containerID,width,height,bodyTemplate,defaultUserMsessage,subject,checkboxStatus,editable,dialogCaption,showCancel,showCloseX,closeWhenDone]);
}
Gigya.Social.showActionsUI=function(confObj,callback,context,containerID,width,height,count,siteActionOnly,filterTarget,filterActionName,filterActionData1,filterActionData2,dialogCaption,showClose){
	if (siteActionOnly==null) {siteActionOnly=true};
	var showCloseX=(containerID==null || containerID=='');
	Gigya.Social._AddRequest('showActionsUI','Newsfeed','',containerID,width,height,false,showCloseX,confObj,false,callback,context,['rid',confObj,containerID,width,height,count,siteActionOnly,filterTarget,filterActionName,filterActionData1,filterActionData2,dialogCaption,showClose,showCloseX]);
}

Gigya.Social.showEditFriendsUI=function(confObj,callback,context,containerID,width,height,dialogCaption,showClose){
	var showCloseX=(containerID==null || containerID=='');
	var blnCenter=false;
	if (containerID==null || containerID=='') {
		containerID='EditFriendsDiv';
		blnCenter=true;	
	};
	Gigya.Social._AddRequest('showEditFriendsUI','EditFriends','',containerID,width,height,blnCenter,showCloseX,confObj,false,callback,context,['rid',confObj,containerID,width,height,dialogCaption,showClose,showCloseX]);
}

//showEditFriendsUI(rid, confObj, containerId:String, width:Number, height:Number, dialogCaption:String, showCancel:Boolean, showClose:Boolean)

Gigya.Social.showLoginUI=function(confObj,callback,context,containerID, width, height){
    var enabledNetworks='';
    var disabledNetworks='';
    
    if (confObj != null) {
        if (confObj.enabledNetworks != null) {
            enabledNetworks = ',' + confObj.enabledNetworks.toLowerCase() + ',';
        }
        if (confObj.disabledNetworks != null) {
            disabledNetworks = ',' + confObj.disabledNetworks.toLowerCase() + ',';
        }
    }
    if (enabledNetworks.indexOf(',email,')==-1 || disabledNetworks.indexOf(',email,')!=-1) {
       Gigya.Social._showSNLogin(confObj, true, callback, context,containerID, width, height, 'showLoginUI');
    } else {
       Gigya.Social._showFindYourFriends(confObj,false,false,callback,context,containerID, width, height, true, 'showLoginUI');
    }
}
Gigya.Social._showSNLogin=function(confObj,getAvailableNetworks,callback,context,containerID,width,height,originalOperation){
    var showCloseX=(containerID==null || containerID=='');
    if (containerID==null) {
        containerID = 'bSocialDiv_300_200';
        width = 300;
        height = 200;
    }
    if (originalOperation==null) {
        originalOperation='showSNLogin';
    }
    Gigya.Social._AddRequest(originalOperation,'bSocial','showSNLogin',containerID,width,height,true,false,confObj,false,callback,context,['rid',confObj,getAvailableNetworks,width,height,showCloseX]);
}
Gigya.Social._showFindYourFriends=function(confObj,showDontAsk,showCancel,callback,context,containerID,width,height,getAvailableNetworks,originalOperation){
    var showCloseX=(containerID==null || containerID=='');
    if (containerID==null) {
        containerID = 'bSocialDiv';
        width = 400;
        height = 400;        
    }
    if (originalOperation==null) {
        originalOperation='showFindYourFriends';
    }
	Gigya.Social._AddRequest(originalOperation,'bSocial','showFindYourFriends',containerID,width,height,true,false,confObj,true,callback,context,['rid',confObj,showDontAsk,showCancel,getAvailableNetworks, width, height,showCloseX]);
}
Gigya.Social._showFriendsSelect=function(confObj,textKey,showDontAsk,showCancel,callback,context){
	Gigya.Social._AddRequest('showFriendsSelect','bSocial','','bSocialDiv',400,400,true,false,confObj,true,callback,context,['rid',confObj,textKey,showDontAsk,showCancel]);
}
Gigya.Social._showApproval=function (confObj,showDontAsk,callback,context){
	Gigya.Social._AddRequest('showApproval','bSocial','','bSocialDiv',400,400,true,false,confObj,true,callback,context,['rid',confObj,showDontAsk]);
}
Gigya.Social._showSendVerification=function (confObj,listOfFriendIDs,body,subject,callback,context){
	Gigya.Social._AddRequest('showSendVerification','bSocial','','bSocialDiv',400,400,true,false,confObj,true,callback,context,['rid',confObj,listOfFriendIDs,body,subject]);
}
Gigya.Social._showMerge=function (confObj,loginToken,signature,sck,currentUsername,siteUsername,callback,context){
	Gigya.Social._AddRequest('showMerge','bSocial','','mergeMessageDiv',300,300,true,false,confObj,true,callback,context,['rid',confObj,loginToken,signature,sck,currentUsername, siteUsername]);
}
Gigya.Social._showLoginMerge=function(confObj,actionTicket,currentUsername,siteUsername,callback,context){
	Gigya.Social._AddRequest('showLoginMerge','bSocial','','mergeMessageDiv',300,300,true,false,confObj,true,callback,context,['rid',confObj,actionTicket,currentUsername, siteUsername]);
}

Gigya.Social._ExtractListOfGIGUIDs=function(source) {
	switch (typeof source) {
		case 'string': return source;
		case 'object':
			if (typeof source.gigyaUID != 'undefined') { return source.gigyaUID; }
			if (source instanceof Gigya.Social.Collection) {
				var a=[];
				source.each(
					function(o,i) {
						var gigyaUID=Gigya.Social._ExtractListOfGIGUIDs(o);
						if ((gigyaUID!=null) && (gigyaUID!='')) {a.push(gigyaUID);}
					}
				);
				return a.join(',');
			}
	}
}

Gigya.Social._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;
}


Gigya.Social.User=function(uo){
	if (typeof(uo)=='object') {
		this.gigyaUID=uo.gigyaUID?uo.gigyaUID:'';
		this.siteUID=uo.siteUID?uo.siteUID:'';
		this.name=uo.name?uo.name:'';
		this.photoURL=uo.photoURL?uo.photoURL:'';
		this.network=uo.network?uo.network:'';
		this.networks=uo.networks?uo.networks:{};
	}
	else if (typeof(uo)=='string') {
		this.gigyaUID=this.siteUID=this.name=this.photoURL='';
		if (uo.indexOf('_gid_')==0) {
			this.gigyaUID=uo;
		} else {
			this.siteUID=uo;
		}
	}
	else {
		if (Gigya.Social.verbose) {
			alert('Gigya Social:' + uo + ' is not a user or a user id');
		}
	}
}
Gigya.Social.User.prototype = {
	getUID:function(){return this.siteUID?this.siteUID:this.gigyaUID;}
}

Gigya.Social.UserAction=function(uao){ // either an object or a string which is the titleTemplate
  if (typeof(uao)=='object') {

	this.actor=new Gigya.Social.User({gigyaUID:uao.actorGigyaUID,name:uao.actorName?uao.actorName:'',siteUID:uao.actorSUID?uao.actorSUID:''});
	
	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=[];
	if (uao.targetGigyaUID && uao.targetGigyaUID!='') {
		this.addTarget({gigyaUID:uao.targetGigyaUID,name:(uao.targetName?uao.targetName:''),siteUID:(uao.targetSUID?uao.targetSUID:'')});
	}
	this.images=uao.images?uao.images:[];
	this.actionData1=uao.data1?uao.data1:'';
	this.actionData2=uao.data2?uao.data2:'';
	this.iconURL=uao.icon?uao.icon:'';

  }
  else if (typeof(uao)=='string') {
	this.titleTemplate=uao;
	this.actorName='';
	this.actorGigyaUID='';
	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.
  }
  else {
		if (Gigya.Social.verbose) {
			alert('Gigya Social:' + uao + ' is not a user action or a template string');
		}  
  }
}

Gigya.Social.TemplateField=function(n,t,h){
	this.fieldName=n;
	this.text=t?t:''; //to avoid JSON parsing errors
	this.href=h?h:'';
}

Gigya.Social.UserAction.prototype={
	getTemplate:function(a){return this.titleTemplate;},
	
	getActor:function(a){return this.actor},
	
	setActionName:function(a){this.actionName=a;return this;},
	getActionName:function(a){return this.actionName;},

	getTemplateFields:function(){
		var fieldsArray=[];
		for (var fn in this.templateFields) {fieldsArray.push(this.templateFields[fn]);}
		return new Gigya.Social.Collection(fieldsArray,'fieldName');
	},

	setTemplateField:function(n,t,h){this.templateFields[n]=new Gigya.Social.TemplateField(n,t,h); return this;},
	getTemplateField:function(n){return this.templateFields[n]?this.templateFields[n]:null;},
	
	addTarget:function(t){this.targets.push(new Gigya.Social.User(t));return this;},
	addImage:function(s,h){this.images.push({imageSrc:s,imageHref:(h?h:'')});return this;},
	getImages:function(){return new Gigya.Social.Collection(this.images,'')},
	getTargets:function(){return new Gigya.Social.Collection(this.targets,'getUID')},
	
	setIconURL:function(url){this.iconURL=url;return this;},
	getIconURL:function(){return this.iconURL},
	
	getDate:function(){return this.date;},
	
	setActionData1:function(ad){this.actionData1=ad;return this;},
	getActionData1:function(ad){return this.actionData1;},
	setActionData2:function(ad){this.actionData2=ad;return this;},
	getActionData2:function(ad){return this.actionData2;}
	
}

Gigya.Social.Collection=function(arr,k){
	this.arr=arr;
	this._key=k?k:'';
}
Gigya.Social.Collection.prototype={
	asArray:function(){return this.arr},
	each:function(f){var i=0;var el=this.arr[i];while(el){f(el,i);i++;el=this.arr[i];};},
	getById:function(id){if ((typeof this._hash=='undefined') && (k!='')){this._buildHash();};return (this._hash?this._hash:this.arr)[id];},
	getSize:function(){return this.arr.length},
	_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});}
}
setTimeout('Gigya.Social.loadCore()',500);
