//debugger;
if (typeof gigya == 'undefined') {	

	gigya= new Object(); 
	gigya.hideid=function(id){var el=document.getElementById(id); if(el) el.style.display='none';}
	gigya.showid=function(id){var el=document.getElementById(id); if(el) el.style.display='';}
	gigya.getParamFromURL = function(scriptURL) {
		if ( null==scriptURL || ''==scriptURL ) {
			return '';
		}

		var questionPos = scriptURL.indexOf('?');
		if ( questionPos == -1 ) {
			return '';
		}
		
		var params = scriptURL.split('?');
		var values = params[1].split('=');
		
		if ( null==values || ''==values ) {
			return '';
		}
		
		return values[1];
		
	}
	gigya.log=function(){} // placeholder that is replaced by gigya.service.plugins.debug
}

if (typeof gigya._vars == 'undefined') { gigya._vars= new Object(); }

//
//NOTE THAT VARS MUST REASSIGN VALUE EVEN IF THEY WHERE RUN BEFORE SO THEY CAN NOT BE WITHIN AN IF
//

gigya._vars.scripts=document.getElementsByTagName('SCRIPT');
//Use the last script that has a .src, (handle the case where our tag was created using document.createElement or document.write)
for (var iScript=gigya._vars.scripts.length-1;iScript>=0;iScript--) {
	if (gigya._vars.scripts[iScript].src!='') {
		if ((gigya._vars.scripts[iScript].src.toLowerCase().indexOf('gigya.js') > -1) || (gigya._vars.scripts[iScript].src.toLowerCase().indexOf('socialize.js') > -1)) {
			gigya._vars.lastScript=gigya._vars.scripts[iScript];
			break; 
		}
	}
}
gigya._vars.lastScriptURL=gigya._vars.lastScript.src;

gigya._vars.lastScriptProtocol=(gigya._vars.lastScriptURL.toLowerCase().indexOf('https')==0)?'https':'http';;
gigya._vars.lastScriptURLPathPaths=gigya._vars.lastScriptURL.split('/');
gigya._vars.lastScriptURLBase=gigya._vars.lastScriptURLPathPaths[0]+'//'+gigya._vars.lastScriptURLPathPaths[2];



if (typeof gigya.global == 'undefined') {	
	gigya.global= new Object();

	gigya.global.URLDecode= function(str){
		if (str == null) return '';
		var udChars=new Array();
		var ch;
		for (var iChar=0;iChar<str.length;iChar++) {
			ch=str.charAt(iChar);
			if (ch=='%') {
				if(str.charAt(iChar+1).toLowerCase()=='u') {
					udChars.push(String.fromCharCode(parseInt('0x'+str.substring(iChar+2,iChar+6))));
					iChar+=5;
				}
				else {
					udChars.push(String.fromCharCode(parseInt('0x'+str.substring(iChar+1,iChar+3))));
					iChar+=2;
				}
			}
			else if (ch == '+' ) {
				udChars.push(' ');
			}
			else {
				udChars.push(ch);
			}
		}
		return udChars.join('');
	}
		
	gigya.global.URLEncode=function(value){
		var str = '' + value; //just in case that str is not a string
		var ueChars=new Array();
		for (var iChar=0;iChar<str.length;iChar++) {
			var charCode=str.charCodeAt(iChar);
			if (((44<=charCode) && (charCode<=46)) ||
				((48<=charCode) && (charCode<=57)) ||
				((65<=charCode) && (charCode<=90)) ||
				((97<=charCode) && (charCode<=122)) ||
				(95==charCode) ||
				(126==charCode)
			   ) {
				// means its a leagal char for url components
				ueChars.push(str.charAt(iChar));
			}
			else{
				var b;
				var hexChars;
				hexChars='';
				ueChars.push('%');
				if (charCode>127) {
					ueChars.push('u');
					b= (charCode & 0xf000)>>12;
					ueChars.push(String.fromCharCode( ((b>=10)?87:48) + b));   // if b is 0..9 it takes chars 48..57  if its >10 it maps to 97..102 (a..f)
					b=(charCode & 0x0f00)>>8;
					ueChars.push(String.fromCharCode( ((b>=10)?87:48) + b));
				}
				b= (charCode & 0xf0)>>4;
				ueChars.push(String.fromCharCode( ((b>=10)?87:48) + b));
				b=(charCode & 0x0f);
				ueChars.push(String.fromCharCode( ((b>=10)?87:48) + b));

			}
		}
		return ueChars.join('');;
	}


		
	gigya.global.JSONSerialize=function (obj) {

		 var t = typeof (obj);
		 if (t == 'function') return '';
		 if (t != "object" || obj === null) {
			  // simple data type
			  
			  if (t == "string") obj = '"'+obj.replace(/\"/g,'\\"')+'"';
			  return String(obj);
		 }
		 else {
		  // recurse array or object
		  var n, v, json = [], arr = (obj && obj.constructor == Array);
		  for (n in obj) {
			   v = obj[n]; t = typeof(v);
			   if (t == "string") v = '"'+v.replace(/\"/g,'\\"')+'"';
			   else if (t == 'function') v='';
			   else if (t == "object" && v !== null) v = gigya.global.JSONSerialize(v);
			   
			   if (v!='') json.push((arr ? "" : '"' + n.replace(/\"/g,'\\"') + '":') + String(v));
		  }

		  return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
		 }
	};

    gigya.global.JSONDeserialize=function(str) {
	    if (str === "") str = '""'; 
	    eval("var p=" + str + ";"); 
	    return p; 
    } 
	gigya.global.deserializeFromKeyValuePairs=function(urlEncodedString) {
		var o={};
		var pairs=urlEncodedString.split('&');
		for (var iPair=0;iPair<pairs.length;iPair++){
			var pair=pairs[iPair];
			var eqPos=pair.indexOf('=');
			o[pair.substr(0,eqPos)]=gigya.global.URLDecode(pair.substr(eqPos+1));
		}
		return o;
	}
	
	gigya.global.serializeToKeyValuePairs=function(o) {
		var a=[];
		for (var p in o) {
			switch (typeof o[p]) {
				case 'function': 
				break;
				
				case 'array': 
				case 'object': 
					a.push(p + '=' + gigya.global.URLEncode(gigya.global.JSONSerialize(o[p])));
				break;
				default:
					a.push(p + '=' + gigya.global.URLEncode(o[p]));
			}
		}
		var s=a.join('&');
		return s;
	}

	gigya.global._NextZIndex=10000000;
	gigya.global._OpenedWindows = new Object();
	gigya.global._Iframes = new Object();
	gigya.global._CloseTarget = function(targetName) {
		gigya.global._CloseWindow(targetName);
		gigya.global._CloseIframe(targetName);
	}

	gigya.global._CloseWindow = function(windowName) {
		if (gigya.global._OpenedWindows[windowName]!=null) {
			try {
				gigya.global._OpenedWindows[windowName].close(); 
				delete gigya.global._OpenedWindows[windowName];
			} catch (e){}
		}
	}

	gigya.global._CloseIframe = function(iframeID) {
		if (gigya.global._Iframes[iframeID]!=null) {
			try {			
				gigya.global._DeleteIframe(iframeID);
				delete gigya.global._Iframes[iframeID];
			} 
			catch (e){}
		}
	}

	gigya.global._ClearContainer=function(id) {
		try {
			var c=document.getElementById(id);
			if (c!=null) c.innerHTML="";
		}catch(e){}
	}

	gigya.global.valueIsExplicitTrue = function(boolval) {
		var lc=(''+boolval).toLowerCase();
		return (lc=='true' || lc=='1');
	}
	gigya.global.valueIsExplicitFalse = function(boolval) {
		var lc=(''+boolval).toLowerCase();
		return (lc=='false' || lc=='0');
	}
    
    gigya.global.isEmail=function(s){
		if (s.indexOf(' ')>=0) return false;
		
		var emailParts=s.split('@');
		if (emailParts.length!=2) return false;
		if (emailParts[0].length==0) return false;
		if (emailParts[1].length==0) return false;		
		var domainParts=emailParts[1].split('.');
		if (domainParts.length<2) return false;
		for (var d=0;d<domainParts.length;d++){
			if (domainParts[d].length==0 || domainParts[d].indexOf(' ')>0) return false;
		}
		return true;
    }
    
	gigya.global.normalizeParams = function(p,blnCopy,paramConstraints){

		var np = blnCopy?{}:p;  
	     
		for (var paramName in paramConstraints) {
			if ( typeof np[paramName] == 'undefined' ) {
				 np[paramName]=null;
			}
		}

		var constraints;
	                 
		if ( null!=p ) {        
			for (var paramName in p) {
				if (blnCopy) {np[paramName] = p[paramName]};
			}
			
			for (var paramName in np) {
				constraints=paramConstraints[paramName];
				if (constraints!=null) {
					for (var constraintType in constraints) {
						switch (constraintType) {
							case 'nullAs': if (np[paramName]==null) {np[paramName]=constraints[constraintType]}; break;
							case 'emptyAs': if (np[paramName]=='') {np[paramName]=constraints[constraintType]}; break;
							case 'def': if (np[paramName]==null || np[paramName]=='') {np[paramName]=constraints[constraintType]}; break;
							case 'min': np[paramName]=Math.max(np[paramName],constraints[constraintType]); break;
						}
					}
				}
			}                
		} 
	          
		return np;
	}

	gigya.global.ParamsFailValidation=function(c,p,paramConstraints) {
		var m = {};
		if (c!=null) for (var paramName in c) {m[paramName]=c[paramName]};
		if (p!=null) for (var paramName in p) {m[paramName]=p[paramName]};
		
		var constraints;
		for (var paramName in paramConstraints) {
			constraints=paramConstraints[paramName];
			if (constraints!=null) {
				for (var constraintType in constraints) {
					switch (constraintType) {
						case 'req': 
							if ( typeof m[paramName] == 'undefined' ) {
								if (typeof m['callback']=='function') {
									m['callback']( {
										status: 'FAIL',
										statusMessage:'Missing_required_parameter ('+paramName+')',
										errorCode: 400002,
										errorMessage: 'Missing_required_parameter ('+paramName+')'
									});
								}
								else if (typeof m['onError']=='function') {
									m['onError']( {
										eventName:'error',
										context:m['context'],
										errorCode: 400002,
										errorMessage: 'Missing_required_parameter ('+paramName+')'
									});
								}
								return true;
							}
							break;
						case 'nonEmpty': 
							if ( m[paramName] == '' ) {
								if (typeof m['callback']=='function') {
									m['callback']( {
										status: 'FAIL',
										statusMessage:'Invalid_parameter_value ('+paramName+')',
										errorCode: 400006,
										errorMessage: 'Invalid_parameter_value ('+paramName+')'
									});
								}
								else if (typeof m['onError']=='function') {
									m['onError']( {
										eventName:'error',
										context:m['context'],
										errorCode: 400006,
										errorMessage: 'Invalid_parameter_value ('+paramName+')'
									});
								}
								return true;
							}
						break;
					}
				}
			}
		}                
		return false;
	}

	gigya.global.isSafari = function() {
		var ua=navigator.userAgent.toLowerCase();
		return (ua.indexOf('safari')!=-1 && ua.indexOf('chrome')==-1);
	}

	gigya.global.getParamFromURL = function(scriptURL) {
		if ( null==scriptURL || ''==scriptURL ) {
			return '';
		}

		var questionPos = scriptURL.indexOf('?');
		if ( questionPos == -1 ) {
			return '';
		}
		
		var params = scriptURL.split('?');
		var values = params[1].split('=');
		
		if ( null==values || ''==values ) {
			return '';
		}
		
		return values[1];
		
	}

	gigya.global.canPlaceInCenter = function(requirdWidth,requiredHeight) {   
		//return true;
		var viewport = gigya.global._ClientViewport.get();    
		var canDo = (viewport.width >= requirdWidth && viewport.height >= requiredHeight);    
		return canDo;
	}
	gigya.global._ClientViewport = 		{
			getWidth: function() {
				return self.innerWidth || (document.documentElement.clientWidth || document.body.clientWidth);
			},

			getHeight: function() {
				return self.innerHeight || (document.documentElement.clientHeight || document.body.clientHeight);
			},
			
			scrollTop: function() {
				return (window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop );
			},
			
			scrollLeft: function(){ 
				return (window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft);
			}, 
			
			get: function() {
				return { 
					width: this.getWidth(),
					height: this.getHeight(),
					scrollTop: this.scrollTop(),
					scrollLeft: this.scrollLeft(),
					contains: function(x,y) {
						return (x>=this.scrollLeft) && (x<this.scrollLeft+this.width) && (y>=this.scrollTop) && (y<this.scrollTop+this.height)
						
					}
			};
			}
			
	}

	gigya.global.runWithDoc= function(func) {
		if ((!document.readyState && document.body) || document.readyState == "interactive" || document.readyState == "loaded" || document.readyState == "complete") {
			func();
		} else {
			if (window.attachEvent) {
				window.attachEvent('onload', func);
			} else if (window.addEventListener) {
				window.addEventListener('load', func, false);
			}
		}
	}

	gigya.global.loadScript= function(src,scriptElementStore) { 
		var scriptLoader=function (){	
						var script = document.createElement('SCRIPT');
						if (typeof scriptElementStore!='undefined') {scriptElementStore.scriptElement=script}
						script.src = src;
						document.getElementsByTagName('HEAD')[0].appendChild(script);
		}
		
		if (gigya.browser.isIE) {
			gigya.global.runWithDoc(scriptLoader);
		}
		else {
			scriptLoader();
		}
	}

		
	gigya.global._CenterElement = function(elem,options) {
	    
		if(options==undefined) options={};
		
		var viewport = gigya.global._ClientViewport.get();
		var elmWidth = (options.width != undefined) ? options.width : elem.offsetWidth;
		var elmHeight = (options.height != undefined) ? options.height : elem.offsetHeight;
		
		var left = parseInt((viewport.width - elmWidth) / 2, 10);
		var top = parseInt((viewport.height - elmHeight) / 2, 10);
		 
		top += viewport.scrollTop;
		left += viewport.scrollLeft;
		
		if (top<0) top=0;
		if (left<0) left=0;
		
		elem.style.position = "absolute";
		elem.style.left = left + 'px';
		elem.style.top = top + 'px';  
		

	}

	gigya.global._DeleteIframe = function(iframeID) {  
		var ifrel = document.getElementById(iframeID);        
		if ( null!=ifrel ) {    
			ifrel.style.display = 'none';  
			var iframeDiv = ifrel.parentNode;
			if ( null!=iframeDiv ) {
				iframeDiv.innerHTML= '';            
			}
			else {
				iframeDiv = document.getElementById('div_'+iframeID);
				if ( null!=iframeDiv ) {
				   iframeDiv.innerHTML= '';
				}
			}
		}
	}

	gigya.global._CreateIframe = function(url,windowName, windowOptions,width, height,iframeID) {
		//var currUrl= ''+document.location.href;
		var finalUrl = url;
		/*var httpsPos = currUrl.toLowerCase().indexOf('https');
		if ( httpsPos == 0 ) {
			finalUrl = 'https'+(''+url).substring(5,(''+url).length);
		}
		else {
			finalUrl = url;
		}*/
	        
		gigya.global._DeleteIframe(iframeID);  	
		var iframeDiv = document.createElement('div');
	    
		iframeDiv.id = 'div_'+iframeID;  
		iframeDiv.style.zIndex=gigya.global._NextZIndex++;        
		var ifrel = document.createElement('IFRAME');    
		ifrel.style.display='none';
		ifrel.id=iframeID;
		ifrel.style.width=''+width+'px';	
		ifrel.style.height=''+height+'px';	
		ifrel.style.backgroundColor = 'transparent';	
		ifrel.scrolling='no';
		// FF
		ifrel.setAttribute('frameborder','0');
		// IE
		ifrel.setAttribute('frameBorder','0');
		ifrel.allowTransparency='true';
		ifrel.allowtransparency='true';
	    
		/*ifrel.onload=function() {
			ifrel.style.display='';
		}*/
		//if (ifrel.style.zIndex!=null) {
			ifrel.style.zIndex=gigya.global._NextZIndex++;
		//}		
		window.setTimeout('document.getElementById("'+iframeID+'").style.display=""', 200);
		ifrel.setAttribute('src',finalUrl);	
		iframeDiv.appendChild(ifrel);
		
		gigya.global._CenterElement(iframeDiv,{width:width ,height:height} );	
		gigya.global._Iframes[ifrel.id] = ifrel;
		document.body.appendChild(iframeDiv);	
		return ifrel.id;
	}


	gigya.global._OpenTarget = function(url, windowName, windowOptions, inTimeOut, iframeURL, iframeWidth, iframeHeight, forceIframe) { 
		var isSafari = gigya.global.isSafari();
		var useIframe =(!gigya.fbAppID && !isSafari && (forceIframe || (iframeURL!=null && gigya.global.canPlaceInCenter(iframeWidth,iframeHeight))));
		if (useIframe) {
			url = iframeURL;
			gigya.global._CreateIframe(url, windowName, windowOptions,iframeWidth, iframeHeight,windowName);
		} else {
			gigya.global._OpenWindow(url, windowName, windowOptions, inTimeOut);
		}
		if (useIframe) {
			//gigya.global._Iframes[windowName].src = url
		}
		return (useIframe || gigya.global._OpenedWindows[windowName]!=null)
		//return {isSafari: gigya.global.isSafari(), useIframe: useIframe};
	}


	gigya.global._OpenWindow = function(url, windowName, windowOptions, inTimeOut)
	{
		if (typeof windowOptions == 'undefined') {
			windowOptions = 'menubar=0,toolbar=0,resizable=1,width=960,height=680';
		}
		var wo=windowOptions;
		try {
			var w=windowOptions.split('width=')[1].split(',')[0];
			var h=windowOptions.split('height=')[1].split(',')[0];
			var wleft = (screen.width - w) / 2;
			var wtop = (screen.height - h) / 2;
			if (wleft < 0) {
				w = screen.width;
				wleft = 0;
			}
			if (wtop < 0) {
				h = screen.height;
				wtop = 0;
			}    
			wo+=',top='+wtop+',left='+wleft;        
		} catch (e){}

		var newWin = window.open(url, windowName, wo);
		if (!newWin)
		{
			//safari bug fix
			newWin = window.open('', windowName, wo);
			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};
	}	

	gigya.global._onMessage = function(evt) 
	{
	    if(evt!=null) setTimeout(gigya.global.__onMessage,700,evt);
	}

	gigya.global.__onMessage = function(evt) {
	    if(evt!=null && evt.data!=null) {
		    var keyToDelete=gigya.global.handlePossibleCookieEvent(evt.data);
		    if (keyToDelete!='') {
			    gigya.global.removeEventListeners([keyToDelete]);
		    }
		}
	}

	if (window.addEventListener) {
		// For standards-compliant web browsers
		window.addEventListener("message", gigya.global._onMessage, false);
	}
	else {
		window.attachEvent("onmessage", gigya.global._onMessage);
	}
	

	if (gigya.global._cookieEventListeners==null) {
		gigya.global._cookieEventListeners={};
	}
    gigya.global.measureText=function(text,oStyle,maxW) {
        var ruler = document.getElementById('gigya_ruler');
        var rulerText = document.getElementById('gigya_ruler_text');
        if (ruler==null) {
            ruler = document.createElement('div');
            rulerText = document.createElement('span');
            
            ruler.id='gigya_ruler';
            rulerText.id='gigya_ruler_text';
            ruler.style.visibility='hidden';
            ruler.style.margin='0px';
            ruler.style.padding='0px';
            ruler.appendChild(rulerText);
            document.body.appendChild(ruler);
        }
        if (oStyle)  {
			ruler.style.lineHeight=oStyle.size+'px';
            ruler.style.fontFamily=oStyle.font;
            ruler.style.fontSize=oStyle.size+'px';
			ruler.style.fontWeight=((''+oStyle.bold).toLowerCase()=='true')?'bold':'';
        }
        if (maxW) {
            ruler.style.whiteSpace='';
            ruler.style.width=''+maxW+'px';
        } else {
            ruler.style.whiteSpace='nowrap';
            ruler.style.width='';
        }
        ruler.style.overflow='hidden';
        ruler.style.display='';
        rulerText.innerHTML=text;
        var w=rulerText.offsetWidth;
        var h=rulerText.offsetHeight;
        ruler.style.display='none';
        return {w:w,h:h}
    },
	gigya.global.handlePossibleCookieEvent=function(cookieString) {
		var keyVal=cookieString.split('=');
		var handler=gigya.global._cookieEventListeners[keyVal[0]] 
		if (handler!=null) {
			if (typeof handler.callback=='function') {
				var encodedEventObj=unescape(keyVal[1]);
				var eventObj = gigya.global.deserializeFromKeyValuePairs(encodedEventObj);
				var context=handler.context;
				handler.callback(eventObj,context);
			}
			return keyVal[0]; 
		}
		return ''; //no key to delete
	}
	gigya.global.checkForCookieEvents=function() {
		/*
		var newCookieVal=document.cookie;
		if (gigya.global.lastCookie!=newCookieVal) {
			var cookies=newCookieVal.split('; ');
			var eventListenersToDelete=[];
			
			var keyToDelete;
			for (var iCookie=0;iCookie<cookies.length;iCookie++){
				var keyToDelete=gigya.global.handlePossibleCookieEvent(cookies[iCookie]);
				if (keyToDelete!='') eventListenersToDelete.push(keyToDelete); 
			}
			gigya.global.removeEventListeners(eventListenersToDelete);
			gigya.global.lastCookie=newCookieVal;
		}
		*/
	}
	
	gigya.global.removeEventListeners=function(eventListenersToDelete) {
			for (var i=0;i<eventListenersToDelete.length;i++){
				gigya.global.removeCookieEventListener(eventListenersToDelete[i]);
			}	
	}
	
	gigya.global.addCookieEventListener=function(cookieName,context,callback){
		gigya.global._cookieEventListeners[cookieName]={callback:callback,context:context,t:(new Date()).getTime()};
		/*
		if (gigya.global._cookieListener==null) {
			gigya.global._cookieListener=window.setInterval("gigya.global.checkForCookieEvents()",1000);
		}
		*/
	}

	gigya.global.removeCookieEventListener=function(cookieName){
		delete gigya.global._cookieEventListeners[cookieName];
		/*
		for (var p in gigya.global._cookieEventListeners) {
			return; // at least on exists 
		}
		// no handlers left deactivate 
		window.clearInterval(gigya.global._cookieListener);
		gigya.global._cookieListener=null;
		*/		
	}


	gigya.global.onLoginEventFromFlashListener=function(oEvent){
	    //alert('debugger in gigya.global.onLoginEventFromFlashListener');
	    //debugger;
	//	window.setTimeout(function(){gigya.global._onLoginEventFromFlashListener(oEvent)},1);
	//}
	//
	//gigya.global._onLoginEventFromFlashListener=function(oEvent){
		var eventKey=oEvent.rid+'_'+oEvent.lid;
		var handler=gigya.global._cookieEventListeners[eventKey] 
		if (handler!=null) {
			if (typeof handler.callback=='function') {
				var context=handler.context;
				handler.callback(oEvent,context);
			}
			gigya.global.removeCookieEventListener(eventKey);
		}
	}

/*
$asdfd
$asdfd(a,b)
${hello}
${hello world}
${hello('world',$a,$b)}
$hello('world',$a,$b)

$!asdfd
$!asdfd(a,b)
$!{hello}
$!{hello world}
$!{hello('world',$a,$b)}
$!hello('world',$a,$b) */

	gigya.global.fillTemplate=function(template,o){
		var p=/(\$)(!?)([a-z_][a-z_.\d]*)([(][^()]*[)])?|(\$)(!?)\{([a-z_][a-z_.\d]*)([(][^()]*[)])?\}/gi;
		p.lastIndex=0;
		var res=template;
		var matches=p.exec(res);
		var offset;
		while (matches!=null) {
			if (matches[1]=='$') {offset=0} else {offset=4};
			var blnDontInject=matches[2+offset]=='!';
			var identifier=matches[3+offset]; // 0 is the entire expr and 1/5=$ 2/6=! 3/7=identifier 4/8=()'s 
			var para=matches[4+offset];
			if (para==null) para='';
			
			var dbg=0;
			if (identifier.substring(0,1)=='.') {identifier=identifier.substring(1);};
			if (identifier.substring(0,3)=='DBG') {identifier=identifier.substring(3);dbg=1;};
			
			var preTemp='';
			var postTemp=identifier+para;
			while (postTemp!=preTemp) {
			  preTemp=postTemp;
			  
			  var lastIndex=p.lastIndex;
			  postTemp=gigya.global.fillTemplate(preTemp,o);
			  p.lastIndex=lastIndex;
			}

			var v='';
			var skipChars=0;
			if (o[identifier.split('.')[0]]!=null) {
				try{
					if (dbg==1) debugger;
					v=''+eval('o.'+postTemp);
				}
				catch(e) {
				}
			}
			else {
				v='$'+(blnDontInject?'!':'')+postTemp;
				skipChars=1;
			}
			
//            if (matches[0]=='$ELLIPSIS("identifiedItemTitleAndDescription",$charsInEllipsis)') {
//                debugger;
//            }
			if (blnDontInject) {
				res=res.replace(matches[0],'');
			}
			else {
			    //'abc'.replace('b','X$&Y'.replace('$','\\x24')).replace('\\x24','$')
			    /*
			    var _currentRes=String(res);
			    var _matchToReplace=String(matches[0]);
			    var _escapedValue=(''+v).replace(/[$]/g,'$$$$') 

			    var result=_currentRes.replace(_matchToReplace,_escapedValue);
			    var result2=_currentRes.split(_matchToReplace).join(v);
			    
			    //if ((''+v).indexOf('$&')>-1) {
			    //    debugger;
			    //    
			    //}    
			    
			    
			    res=result;
			    */
			    res=res.split(matches[0]).join(v);
				//res=res.replace((''+matches[0]),(''+v).replace('$','$$'))
			}
			p.lastIndex=matches.index+skipChars; // to allow recursive changes in templates that contain templates.
			matches=p.exec(res);
		}
		return res;
	}
		
}

//alert(' navigator.appVersio = ' + navigator.appVersion + '\navigator.userAgent = ' + navigator.userAgent);
if (typeof gigya.browser == 'undefined') {
	gigya.browser={}
	gigya.browser.mobileClients = [ 
		"iphone", "android", "ipad", "midp", "240x320", "blackberry", "netfront", "nokia",
		 "panasonic", "portalmmm", "sharp", "sie-", "sonyericsson", "symbian", "windows ce", 
		 "benq", "mda", "mot-", "opera mini", "philips", "pocket pc", "sagem", "samsung", 
		 "sda", "sgh-", "vodafone", "xda"];
	
	gigya.browser.lcUA=navigator.userAgent.toLowerCase();
	
	 (function(){ //keep namespace clan of temp vars
		var mobileClients=gigya.browser.mobileClients;
		for (var i in mobileClients) {
			if (gigya.browser.lcUA.indexOf(mobileClients[i]) != -1) {
				gigya.browser.isMobile=true;
				return;	
			}
		}
		gigya.browser.isMobile=false;

	 })();
	 gigya.browser.isIE=(navigator.appVersion.indexOf("MSIE") != -1);	 
	 gigya.browser.isIE6=(navigator.appVersion.indexOf("MSIE 6.") != -1);
	 gigya.browser.isIE7=(navigator.appVersion.indexOf("MSIE 7.") != -1);
	 gigya.browser.isIE8=(navigator.appVersion.indexOf("MSIE 8.") != -1);
	 gigya.browser.isIE9=(navigator.appVersion.indexOf("MSIE 9.") != -1);
	 gigya.browser.isChrome=(gigya.browser.lcUA.indexOf("chrome") != -1);
	 gigya.browser.isMAC = (navigator.appVersion.toLowerCase().indexOf("mac") != -1) ? true : false,
	 gigya.browser.supportsPostMessage=(typeof (window.postMessage=='function')) && !(gigya.browser.isIE); // decided not to use it on IE because of too many bugs. see notes in here: http://msdn.microsoft.com/en-us/library/cc197015(VS.85).aspx

}
if (typeof gigya.flash == 'undefined') {
	gigya.flash={

		isIE  : gigya.browser.isIE,
		isIE6  : gigya.browser.isIE6,
		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']=gigya._vars.lastScriptProtocol + '://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']=gigya._vars.lastScriptProtocol + '://www.macromedia.com/go/getflashplayer';
		  
		  return ret;
		}
	}
}
//alert('end of common.js gigya=' + gigya);
