var Wildfire = new Object();
Wildfire.onSend = null;
Wildfire.onPostComment = null;
Wildfire.onPostProfile = null;
Wildfire.modules = new Object();
Wildfire.modulesArray = new Array();

/*** PUBLIC METHODS ***/
	
	Wildfire.initShare = function(partner, targetId, width, height, config)
	{   
	
		return Wildfire._createModule(
							"share",
							partner,
							targetId,
							width,
							height,
							config,
							'cssURL,cornerRoundness,initialMessageType,domainForCallback,partner,source,partnerData,width,height,emailTabHidden,customCheckboxVisible,customCheckboxChecked,customCheckboxText,' +
							'internalColor,frameColor,externalColor,tabTextColor,textColor,fontType,fontSize,' +
							'headerInternalColor,headerFrameColor'
							);
	}
 
	Wildfire.initPost = function(partner, targetId, width, height, config)
	{	
		return Wildfire._createModule(
							"post",
							partner,
							targetId,
							width,
							height,
							config,
							'cssURL,cornerRoundness,width,height,domainForCallback,partner,source,partnerData,networksToShow,contentIsLayout,'+
							'internalColor,frameColor,externalColor,tabTextColor,textColor,fontType,fontSize,location');
	}

	//DEPRECATED, replaced by initShare */
	Wildfire.init = Wildfire.initShare;

	//DEPRECATED, replaced by module.applyConfig*/
	Wildfire.applyConfig= function(config)
	{
		if (isnotnull(Wildfire.share)) Wildfire.share.applyConfig(config);
	}

/*** PRIVATE METHODS ***/
	Wildfire._createModule = function (moduleType, partner, targetId, width, height, config, getParams)	
	{	
		try {
			config.location = document.location.href;
		} catch(err) {}
		
		config.partner = partner;
		config.width = width;
		config.height = height;

		// validate input params
		if ( undef(moduleType) || undef(partner) || undef(targetId) || undef(width) || undef(height)|| undef(config)) return;

		var module = this[targetId] = this.modules[targetId] = this.modulesArray[this.modulesArray.length] = new WildfireModule();
		module.copyConfig(config);
		module.ready = false;
		module.type = moduleType;
		module.id = targetId;
		module.partner = partner;
		module.width = width;
		module.height = height;
		module.container = document.getElementById(targetId);		  
		module.container.style.width  = width + "px";
		module.container.style.height = height + "px";

		module.qsParams = new Array();
		var getParamArray = getParams.split(',');
		for (var i=0; i<getParamArray.length ; i++)
			Wildfire._addQSParam(module,getParamArray[i]);
		
		module.init(true); // true means check ping for safe mode
		return module;
	};
	
	Wildfire._raiseModulesUpdate = function() 
	{
		var moduleList = "";
		for(var key in this.modules) moduleList += key + ",";
				
		var eventData = {'type':'modulesUpdate','modules':moduleList};

		this._raiseSysEvent(eventData);
	}
	
	Wildfire._raiseSysSignoutEvent = function() {
		this._raiseSysEvent({'type':'signout'});
	}
	
	Wildfire._raiseSysEvent = function(eventData) 
	{
		if (this.modulesArray.length<=1) return;
		
		for(var key in this.modules)
			this.modules[key].raiseSysEvent(eventData);
	}
	
	Wildfire._onFrameLoaded = function(moduleId) 
	{
		var ui = document.getElementById(moduleId+"_UIFrame");
		if (ui!=null) ui.style.visibility="visible";	

		var pdiv = document.getElementById(moduleId+"_progress");
		if (pdiv!=null) pdiv.style.display = "none";

		this.modules[moduleId].UIFrame.style.visibility="visible";	
		this.modules[moduleId].applyConfig();
		this.modules[moduleId].ready = true;
		
		setTimeout("Wildfire._raiseModulesUpdate()",1500);
	};

	Wildfire._addQSParam = function(module,pName) {
		if ( def(typeof module.config) && def(module.config[pName]) ) {
			module.qsParams[module.qsParams.length] = pName+'='+Wildfire._URLEncode(module.config[pName]);
		}
	};

	Wildfire._URLEncode=function (s){
		if (encodeURIComponent) {
			return encodeURIComponent(s);
		}
		else {
			es=escape(s);
			return es.replace(/\+/g,'%2b').replace(/%20/g,'+').replace(/[/]/g,'%2f').replace(/%3D/g,'%3d');
		}
	};

	Wildfire._onCallback = function(WFEvent) {
		try {
			switch(WFEvent.type)
			{
				case 'send':
					if (isnotnull(Wildfire.onSend))
						Wildfire.onSend(WFEvent);
					break;
				case 'postComment':
					if (isnotnull(Wildfire.onPostComment))
						Wildfire.onPostComment(WFEvent);
					break;
				case 'postProfile':
					if (isnotnull(Wildfire.onPostProfile))
						Wildfire.onPostProfile(WFEvent);
					break;

			}
		} catch (err) {
			//GIGYAONLY:alert('exception in _onCallback: '+err.description);
		}
	};

	function WildfireModule()
	{
		this.formsContainer = null;
		this.pingTimeout = null;
	}
	
	WildfireModule.prototype.pingOK = function(ok) 	
	{

		window.clearTimeout(this.pingTimeout);
		this.config.safeMode = !ok;
		this.init(false);
	}
	
	WildfireModule.prototype.init = function(checkPing) 
	{
		if (!this.config.safeMode && checkPing && this.pingTimeout==null)
		{
			var script = document.createElement("script");
			script.src = "http://wildfire.gigya.com/wildfire/jsping.ashx?mid="+this.id + "&rand=" + Math.random() + Math.random();
			this.container.appendChild(script);
			this.pingTimeout = window.setTimeout("Wildfire.modules['"+this.id+"'].pingOK(false)",10000);
			return;
		}
		var qs = this.qsParams.join('&');
		qs += ("&mid="+this.id);
		
		var html = "";
		var formsHTML = "";
		var UIURL = "http://wildfire.gigya.com/wildfire/"+this.type + "Main.aspx?" + qs;
		if (this.config.safeMode)
		{
			UIURL = this.getSafeModeURL();
			if (UIURL==null) {
				Wildfire[this.id] = Wildfire.modules[this.id] = Wildfire.modulesArray[Wildfire.modulesArray.length] = null;
				return null;
			}
			html += "<iframe allowtransparency='true' id="+this.id +"_UIFrame name="+this.id+"_UIFrame style='width:" + this.config.width + "px;height:" + this.config.height + "px;display:inherit;visibility:inherit' frameborder=0 scrolling=no></iframe>";
			formsHTML += "<form id='"+this.id+"_postForm' action='"+UIURL+"' method='POST' target="+this.id+"_UIFrame  style='display:none'></form>";
		}
		else if (this.config.simple)
		{
			if (this.type=="post") UIURL = "http://wildfire.gigya.com/wildfire/postMain.aspx";
			if (this.type=="share") UIURL = "http://wildfire.gigya.com/wildfire/shareSimple.aspx";
			if (UIURL==null) {
				Wildfire[targetId] = Wildfire.modules[targetId] = Wildfire.modulesArray[Wildfire.modulesArray.length] = null;
				return null;
			}
			html += "<iframe allowtransparency='true' id="+this.id +"_UIFrame name="+this.id+"_UIFrame style='width:" + this.config.width + "px;height:" + this.config.height + "px;display:inherit;visibility:inherit' frameborder=0 scrolling=no></iframe>";
			formsHTML += "<form id='"+this.id+"_postForm' action='"+UIURL+"' method='POST' target="+this.id+"_UIFrame  style='display:none'></form>";
		} else {
			html += "<div style='position:relative;top:50%;text-align:center;font-size:12px;' id='"+this.id+"_progress'><center><img  src='"+this.config.progressImageSrc+"'></center></div>";
			html += "<iframe allowtransparency='true' onload='Wildfire._onFrameLoaded(\""+this.id+"\")' id="+this.id+"_UIFrame style='visibility:hidden;width:" + this.config.width + "px;height:" + this.config.height + "px;' src='"+ UIURL + "' frameborder=0 scrolling=no></iframe>";			
			html += '<iframe id="IFREndlessActivityBugFix" style="display:none;width:100px;height:10px"></iframe>';
			html += this._createCBFrame();

			formsHTML += "<form id='"+this.id+"_postForm' action='http://wildfire.gigya.com/wildfire/WFHandler.ashx?cmd=config' method='POST' target='"+this.id+"_postTargetFrame'  style='display:none'></form>";			
			formsHTML += "<form id='"+this.id+"_sysEventForm' action='http://wildfire.gigya.com/wildfire/WFHandler.ashx?cmd=sysEvent' method='POST' target='"+this.id+"_sysEventFrame'  style='display:none'></form>";
		}
		
		this.injectWFCode(html,formsHTML);	
		
		// if cant create callback frame, disable callbacks
		if (document.getElementById(this.id+"_wfCBFrame")==null)
		{
			this.config.domainForCallback = null;
		}
			
		this.UIFrame = document.getElementById(this.id+"_UIFrame");
		this.postForm = document.getElementById(this.id+"_postForm");
		this.sysEventForm = document.getElementById(this.id+"_sysEventForm");
		
		if (this.config.simple || this.config.safeMode) this.applyConfig(); // normal modules get config on frame load
	}
	
	WildfireModule.prototype._createCBFrame = function() 
	{
		if ( def(this.config.domainForCallback) && document.getElementById(this.id+'_wfCBDiv')==null ) 
		{
			try {
				document.domain = this.config.domainForCallback;	
				/*
				//GIGYAONLY:alert('changing document.domain from:' + document.domain + ' to: '+ this.config.domainForCallback);
				if (document.domain != this.config.domainForCallback) {
					document.domain = this.config.domainForCallback;	
				}
				else {
					//GIGYAONLY:alert('actualy skipping the change');
				}
				//GIGYAONLY:alert('document.domain set to: '+document.domain);
				*/
				return "<iframe name='"+this.id+"_wfCBFrame' style='visibility:hidden;width:0px;height:0px;' src='http://wildfire."+this.config.domainForCallback+"/wildfire/WFHandler.ashx?domain="+escape(this.config.domainForCallback)+"'></iframe>";
				
			} catch(ex) {
				//GIGYAONLY:alert('Unable to create Iframe for callback: '+ex.description);
				return "";
			}
		} else {
			return "";
		}
	}
	
	WildfireModule.prototype.copyConfig = function(config) 
	{
		// clone config obj to module
		if (config!=null) {
			this.config = {};
			for(var key in config) this.config[key] = config[key];
		}

		// apply default values
		if ( undef(this.config.progressImageSrc) )
			this.config.progressImageSrc = "http://cdn.gigya.com/WildFire/i/progress_ani.gif";
		
		if ( undef(this.config.cornerRoundness) ) 
			this.config.cornerRoundness=1;

		if ( undef(this.config.simple) )
			this.config.simple = navigator.userAgent.toLowerCase().indexOf('safari')!=-1;
	}

	WildfireModule.prototype.getSafeModeURL = function() 
	{
		if (this.type=="post") return "http://backup.gigya.com/WFSimple/post.aspx";
		if (this.type=="share") return "http://backup.gigya.com/WFSimple/share.aspx";
		return null;
	}
	
	// check if page already has 'form' tag, if yes, insert div to contain our forms, outside of it.
	WildfireModule.prototype.injectWFCode= function(html,formsHTML)
	{
		var el=this.container;
		for(;((el!=null) && ((''+el.tagName).toLowerCase() !='form'));el=el.parentNode);
		if (el!=null) { 
			this.container.innerHTML = html;
			this.formsContainer = document.createElement('div');
			this.formsContainer.style.display='none';
			el.parentNode.insertBefore(this.formsContainer,el);
			this.formsContainer.innerHTML = formsHTML;
			
		} else
		{
			this.container.innerHTML = html + formsHTML;
		}
	};
	
	WildfireModule.prototype.raiseSysEvent = function(eventData) 
	{
		if (this.sysEventForm==null || !this.ready)  return;
		
		var s = new Array(); var i=0;
		for(var key in eventData) {
			if (typeof key != 'function' && eventData[key]!=null) {
				s[i++] = "<input type=hidden name='"+key+"'/>"
			}
		}
		
		this.sysEventForm.innerHTML = s.join('');

		//set value (using foo.value handles escaping of strings better...)
		for (var i=0;i<this.sysEventForm.length; i++) {
			this.sysEventForm[i].value = eventData[this.sysEventForm[i].name];
		}
		this.sysEventForm.submit();
	};
	
	WildfireModule.prototype.applyConfig = function(conf) 
	{
		if (conf!=null) this.copyConfig(conf);
		
		if (this.config==null) return;
		
		if (this.config.location==null || this.config.location=="")
		{
			try { config.location = document.location.href;} catch(err) {}
		}

		this.config.partner = this.partner;
		this.config.width	= this.width;
		this.config.height	= this.height;
		// check if templates are IDs or actual values

		// For Post
		this._getTemplate('defaultContent');
		this._getTemplate('myspaceContent');
		this._getTemplate('hi5Content');
		this._getTemplate('friendsterContent');
		this._getTemplate('xangaContent');
		this._getTemplate('livejournalContent');
		this._getTemplate('freewebsContent');
		this._getTemplate('facebookContent'); 
		this._getTemplate('beboContent');
		this._getTemplate('bloggerContent');
		this._getTemplate('taggedContent');
		this._getTemplate('typepadContent');
		this._getTemplate('blackplanetContent');
		
		//For Share
		this._getTemplate('defaultTemplate');
		this._getTemplate('commentTemplate');
		this._getTemplate('emailTemplate');
		this._getTemplate('myspaceTemplate');
		this._getTemplate('hi5Template');
		this._getTemplate('friendsterTemplate');
		this._getTemplate('xangaTemplate');
		this._getTemplate('freewebsTemplate');

		// build config fields
		var s = new Array(); var i=0;
		for(var key in this.config) {
			if (typeof key != 'function' && this.config[key]!=null) {
				s[i++] = "<input type=hidden name='"+key+"'/>"
			}
		}

		this.postForm.innerHTML = s.join('');

		//set value (using formfield.value handles escaping of strings better...)
		for (var i=0;i<this.postForm.length; i++) {
			this.postForm[i].value = this.config[this.postForm[i].name];
		}
		this.postForm.submit();
		
		window.setTimeout('Wildfire._EndlessActivityBugFix();',1000);
	};
	
	Wildfire._EndlessActivityBugFix=function(){
		var ifr=document.getElementById('IFREndlessActivityBugFix');
		if (ifr!=null) {
			ifr.src='http://cdn.gigya.com/wildfire/i/n.gif';
		}
	};
	
	WildfireModule.prototype._getTemplate = function (key) {
		if ( isnotnull(this.config[key]) ) {
			try {
				if ( isnotnull(document.getElementById(this.config[key])) )
					this.config[key] = document.getElementById(this.config[key]).value;
			} catch (e) {
				//GIGYAONLY:alert('Unable to get template for key :'+ key + '\n' + ex.description);
			}
		}
	};
	
	function undef(o) { return (typeof(o)=='undefined');}
	function def(o) { return (typeof(o)!='undefined');}
	function isnotnull(o) { return (def(o) && (o!=null));}