


if(window.console == null || window.console == undefined || !window.console)
console = { log: function() {}, info: function() {}, warn: function() {}, error: function() {}, trace: function() {}, debug: function() {} };
else if(!console.debug)
console.debug = function() {};

var lDojo				=	document.createElement("script");
lDojo.setAttribute("type"		,	"text/javascript"	);
lDojo.setAttribute("src"		, 	"http://webchat.a-cti.com:80"+"/js/webchat/dojo.xd.js");
document.getElementsByTagName("head")[0].appendChild(lDojo);

function loadFiles()
{
	conversion.loadDependency();
}

var conversion	=	
{
		webchatServer		:	"http://webchat.a-cti.com:80" 		, 
		clientId			:	"17005956534"  		,
		type				:	"onpage"  ,
		domain				:	document.location.href	,
		mode				:	"live"				,
		cssPath			:	"https://s3.amazonaws.com/docs.webchat.a-cti.com/documents/onpagechat/BrandedChatWindow.css" 	,
		//cssPath				:	"https://webchat.voicecurve.com/css/docserver/BrandedChatWindow.css" 	,
		chatInProgress		:	false	,
		
		chatWindowTheme		:	""		,
		chatWindowContent	:	""		,
		chatWindowTemplate	:	""		,
		attempt				:	"1"		,
		
		dependentScript		:	""		,
		expData				:	""		,
		
		settings			:	""		,
		chatWindowStyle		:	""		,
		isAgentAvailable	:	""		,
		
		fallbackOfflineMsg	:	"We are currently unavailable. We will get back to you at the latest.",
		
		startChatImagePath		:	'https://s3.amazonaws.com/docs.webchat.a-cti.com/images/chatBanners/black_white_border.png' , 
		startChatImagePosition	:	'custom' ,
		checkForOldDataCount	:	0 ,
		initApi				:	function( webchatServer , clientId  )			// This is to init the api on the whole
		{
			this.webchatServer	=	webchatServer 	;
			this.clientId		=	clientId		;
		},
		
		init				:	function( chatMetaData )
		{
			console.info('Inside the init method!');
			var pchatMetaData			=	chatMetaData						;
			this.chatWindowTemplate		=	pchatMetaData.chatwindow			;
			this.chatWindowTheme		=	pchatMetaData.chatwindowtheme		;
			this.chatInProgress			=	pchatMetaData.chatInProgress		;
		},
		
		getChatMetaData			:	function()
		{
			console.info('Inside the getChatMetaData function!');
			var chatMetaData 					= 	new Object();
			chatMetaData.timestamp				=	new Date().getTime() 	;	//Timestamp . This is used to remove old chats from local storage
			chatMetaData.chatWindowTemplate		=	this.chatWindowTemplate	;
			chatMetaData.chatwindowtheme		=	this.chatWindowTheme    ;
			chatMetaData.chatWindowContent		=	document.getElementById('cschatwindow').innerHTML ;
			chatMetaData.chatInProgress			=	this.chatInProgress	 	;
			chatMetaData.connectionId			=	room.connectionGuid		;
			chatMetaData.agentonxmpp			=	room.agentonxmpp		;
			
			//IF demo skill is available , then save it into local storage
			if( typeof demoskill != 'undefined' && demoskill != null && demoskill != 'null' )
			{
				chatMetaData.demoskill		=	demoskill ;	
			}
			
			return chatMetaData;
		},
		
		getChatSettings			:	function ()						//Used to get the chat settings from the server
		{
			console.info( 'Inside the getChatSettings function!' );
			var callback	=	""	;
			var url			=	this.webchatserver+"/livechat/getchatsettings/"+this.clientid+"/"+callback ;
		},
		
		getChatSettingsCb		:	function ( lSettingsJson )		//Callback to the 'getChatSettings' function
		{
			console.info( 'Inside the getChatSettingsCb function! : '+lSettingsJson );
			if( lSettingsJson !=null && lSettingsJson.result == 'success' )
			{
				this.isAgentAvailable		=	lSettingsJson.isAgentAvailable	;
				var pChatSettings			=	lSettingsJson.settings				;
				this.settings				=	pChatSettings						;
				this.chatWindowStyle		=	pChatSettings.chatWindowStyle		;
				this.chatWindowTheme		=	pChatSettings.chatWindowTheme 		;
				this.chatWindowTemplate		=	pChatSettings.chatWindowTemplate	;
			}
		},
		
		startChat				:	function ()		/*Used to initiate chat for the first time*/
		{	
				if( this.chatInProgress && this.type != "popup")
				{
						console.info('There is a chat in progress already!');
						return ;
				}
				
				//Hide the default start chat image
				if( this.type == 'onpage')
				{
					csIcon.hideIcon();
				}
				
				//Hide the prochat banner 
				try
				{
					csProactiveChat.hideBanner()
				}
				catch(e)
				{
					console.error('Error hiding the prochat banner path :'+e);
				}
				
				//Based on the chat window type trigger the required javascript function
				if(this.type == "popup")
				{
					this.startPopUpChat();
					try
				      {
						if(!csProactiveChat.startChat)
				    	  {
								console.log("Google Analytics detected. Pushed click to chat!");
								analytics.pushClickToChat();	//Calling the pushClickToChat function!
				    	  }
							
				      }
				      catch(e)
				      {
				    	  console.log("Error calling _gaq.push");
				      }
				}
				else if( this.type == 'onpage' )
				{
					conversion.startExperimentalChat();
				}
				else
				{
					this.setChatInProgress(true);
					var callback		=	"conversion.startChatCb"	;
					var url				=	this.webchatServer+"/chatAction.do?action=getclientguid&clientid="+this.clientId+"&callback="+callback+"&attempt="+this.attempt+"&clientUrl="+this.domain ;
					this.doJsonp(url);
					try
				      {
						if(!csProactiveChat.startChat)
				    	  {
								console.log("Google Analytics detected. Pushed click to chat!");
								analytics.pushClickToChat();	//Calling the pushClickToChat function!
				    	  }
							
				      }
				      catch(e)
				      {
				    	  console.log("Error calling _gaq.push");
				      }
				}
		      
		      try
		      {
		    	  csProactiveChat.displayed			=	true ;	//Setting the displayed to true
		    	  csProactiveChat.chatIsInProgress	=	true ;
		    	  csProactiveChat.setCookie()				 ;
		      }
		      catch(e)
		      {
		    	  console.error('Exception while trying to set cookie and stop proactive chat! : '+e);
		      }
		},
		
		startChatCb				:	function (data)	//Handle data got from callback done in startChat
		{
				console.info("Inside the startChatCb function! ");
				console.info('The Guid :: '+data.clientguid+" and the chatwindowtheme is :: "+data.chatwindowtheme);
				data.chatInProgress	=	true ;
				
				this.init( data );												// Init the api
				this.constructChatWindow( data.chatwindow );					// Creating a div and inserting the chatwindowtemplate on the page. NOTE : The first time the element is created the chat window is hidden
				this.applyTheme();												// Applying colors and swapping out logo!
				
				var chatWindowElement	=	chatWindowSelectors.chatWindowElement		;
				document.getElementById(chatWindowElement).style.display	=	"block" ;	//Fade in the chatwindow
				document.getElementById('cs_chatLoader').style.display	=	"block" ;	//Fade in the chatwindow
				
				var flag	=	this.joinChat( data.clientguid );
				if (flag)
				{
					room.triggerRouting();
				}

		},
		
		startExperimentalChat				:	function ()	
		{
			this.setChatInProgress(true);
			var callback		=	"conversion.startExperimentalChatCb"	;
			
			var url				=	this.webchatServer+"/livechat/startonpagechat?clientid="+this.clientId+"&callback="+callback+"&attempt="+this.attempt ;
			if( typeof demoskill != 'undefined' && demoskill != null && demoskill != "null" )
			{
				url				=	url+"&demoskill="+demoskill ;
			}
			
			url					=	url+"&clienturl="+this.domain;
			this.doJsonp(url);
			 
		},
		
		startExperimentalChatCb				:	function ( data )	
		{
			console.info("Inside the startExperimentalChatCb function! "+data);
			
			if (data.toshow == 'chatwindow' )
			{
				if(!csProactiveChat.startChat)
				 {
					analytics.pushClickToChat();	//Calling the pushClickToChat function!
				 }
				this.startChatCb(data);
			}
			else if (data.toshow == 'surveyform' || data.toshow == 'offlineform')
			{
				//Show pre chat survey
				this.expData	=	data ;
				this.chatWindowTheme		=	data.chatwindowtheme		;
				this.constructChatWindow( data.chatwindow );					// Creating a div and inserting the chatwindowtemplate on the page. NOTE : The first time the element is created the chat window is hidden
				this.applyTheme();												// Applying colors and swapping out logo!
				
				document.getElementById('cs_chatLoader').style.display	=	"none" ;	//Fade in the chatwindow
				document.getElementById('offlinemsg').style.display	=	"block" ;	//Fade in the chatwindow
				
				
				if(data.toshow == 'offlineform')
				{
					document.getElementById("cs_form_submit").onclick		= 	function(){ conversion.submitData() }		;
					document.getElementById("cs_custom_message").innerHTML	=	data.offlinemessage ;
					analytics.pushOfflineFormEvent('Show Form');
				}
				else
				{
					document.getElementById('cs_custom_message').innerHTML = "Please tell us about yourself and click on connect to start a chat."
					document.getElementById("cs_form_submit").onclick		= 	function(){ conversion.connectToAgent() }		;
					document.getElementById("cs_form_submit").value		= 	'Connect'		;
					analytics.pushSurveyFormEvent('Show Form');
				}
				
				var chatWindowElement	=	chatWindowSelectors.chatWindowElement		;
				document.getElementById(chatWindowElement).style.display	=	"block" ;	//Fade in the chatwindow
			}
			
		},
		
		connectToAgent		:	function()
		{
			var name		=	document.getElementById("cs_username").value
			var email		=	document.getElementById("cs_email").value
			var message		=	document.getElementById("cs_message").value
			var callBack	=	'conversion.proceedWithChat' ;
			var url			=	this.webchatServer+"/livechat/getclientguid?guestname="+name+"&guestemail="+email+"&guestmessage="+message+"&callback="+callBack+"&clientid="+this.clientId+"&clienturl="+this.domain ;
			this.doJsonp(url);
		},
		
		submitData			:	function()
		{
			var name		=	document.getElementById("cs_username").value
			var email		=	document.getElementById("cs_email").value
			var message		=	document.getElementById("cs_message").value
			var callBack	=	'conversion.showOfflineMessage' ;
			var url			=	this.webchatServer+"/livechat/submitdata?name="+name+"&email="+email+"&message="+message+"&callback="+callBack+"&clientid="+this.clientId+"&clienturl="+this.domain ;
			this.doJsonp(url);
			analytics.pushOfflineFormEvent('Submit Form');
		},
		
		proceedWithChat			:	function( data )
		{
			if( data.result == 'success')
			{
				document.getElementById('offlinemsg').style.display	=	"none" ;	//Fade in the chatwindow
				this.expData.clientguid	=	data.clientguid;
				this.startChatCb(this.expData);
				analytics.pushSurveyFormEvent('Start Chat');
			}
			else if( data.result == 'failure' )
			{
				document.getElementById('offlinemsg').style.display	=	"none" ;	//Fade in the chatwindow
				document.getElementById('cs_form_table').style.display	=	'none';
				if(typeof data.offlinemessage == 'undefined' || data.offlinemessage == null || data.offlinemessage == 'null' )
				{
					data.offlinemessage	=	conversion.fallbackOfflineMsg ;
				}
				
				document.getElementById('cs_custom_message').innerHTML = data.offlinemessage ;		//Display offline message

			}
			
		},
		
		showOfflineMessage			:	function( data )
		{
			console.info( 'Done! :)' );
			document.getElementById('cs_form_table').style.display	=	'none';
			document.getElementById('cs_custom_message').innerHTML = "Your response has been recorded. We'll get back to you as soon as possible."
		},
		
		loadDependency			:	function ()
		{
			if ( this.type != 'popup' )
			{
				console.log( "load dependency" );
				dojo.require("dojox.cometd");
				dojo.require("dojox.cometd.timestamp");
				dojo.require("dojox.cometd.ack");
			}
			this.checkForOldData();
		},
		
		checkForOldData			:	function()
		{
			try
			{
				conversion.checkForOldDataCount++ ;
				
				if( conversion.checkForOldDataCount < 3 )
					this.checkIfLatest();
			}
			catch(e)
			{
				console.error('Exception occurred while trying to sync data : '+e);
				setTimeout( "conversion.checkForOldData()" , 3000 );
			}
		},
		
		joinChat				:	function ( clientGuid )	 	//	Used to join the room if connectionName/id is available
		{	
				
				console.info('Inside the join chat function!');
				room.init( clientGuid, this.webchatServer , this.clientId );
				room.join();
				this.joinChatCb(clientGuid);
				dojo.subscribe("/cometd/meta",room, room._meta)	    ;		// Subscribing to the meta channel
				return true;
		},
		
		joinChatCb				:	function ( clientGuid )	 	//	Used to join the room if connectionName/id is available
		{
				console.info('Callback that is invoked after joinChat has completed execution!');
		},
		
		sendChat				:	function ( e )		//	Used to send chat messages. Get the content from the text box , pass it to the appropriate technology used to send the message to server
		{
			console.info( 'Inside sendChat function' );
			
			if(!e) e = window.event;
			
			if(e.keyCode == 13)
			{
				var inputbox	=	chatWindowSelectors.inputBox;
				var chat		=	document.getElementById(inputbox).value	; /*** TODO : Publish chatdata using chat api */
				if( chat.length	!=	0 )
				{
					room.chat(chat);
				}
				document.getElementById(inputbox).value	=	''	;
				
					if(e.preventDefault())
					{
						try
						{
							e.preventDefault();
						}
						catch(e)
						{
							console.log('Exception while tyring to prevent default '+e);
							e.returnValue	=	false ;
						}
					}
					else
					{
						e.returnValue	=	false ;
					}
				
			}
			
		},
		
		receiveChat				:	function ( from , text )		//	Used to append the chat messages to the UI. This is not the real channel/comet listener. Append the chat message to the message box and apply message color
		{
			var lMessageBox									=	chatWindowSelectors.messagebox;
			document.getElementById(lMessageBox).innerHTML	=	text ;
			this.scrollToBottom();
			this.applyMessageColor();
		},
		
		receiveChatCb			:	function()		//Function that is invoked after completing 'receiveChat'
		{
			console.info( 'Inside the receive chat cb function!' );
		},
		
		leaveChat				:	function ()		//	Used to leave the chat channel. Leave chat room. Disable text box, fade chat window if visitor has pressed close button
		{
			console.info('Inside the leaveChat function');
			room.leave();
			this.setChatInProgress(false);
			this.disableInput(true);
			this.removeDataFromLocalStorage();
			this.leaveChatCb();
			
			var chatWindowElement	=	chatWindowSelectors.chatWindowElement		;
			document.getElementById(chatWindowElement).style.display	=	"none" 	;	//Fade out the chatwindow
			
			//Display the default start chat button again, if default icon variable is true
			csIcon.showIcon();
			
		},
		
		leaveChatCb				:	function()		//Function that is invoked after completing 'leaveChat'
		{
			console.info( 'Indise the leave chat cb function!' );
		},
		
		/* The core chat functionality ends here! */
		
		/* Stuff that needs to be done when user navigates away from one page to another.*/
		
		onLoadAfterNavigate		:	function()
		{
			console.info( 'Inside onLoadAfterNavigate ' );
			// Publish 'naviagetd to..' message
			
		},
		
		/* END of Stuff that needs to be done when user navigates away from one page to another.*/
		
		/* Related to the aesthetics of the chat window */
		
		applyTheme				:	function ()
		{
			var chatWindowTheme	=	this.chatWindowTheme ;
			console.info('Inside the applyTheme function!');
			if( chatWindowTheme.headercolor != null && typeof chatWindowTheme.headercolor != 'undefined' )
			{
				console.info( "The header color is : " + chatWindowTheme.headercolor );
				var chatWindowHeader	=	chatWindowSelectors.header;
				document.getElementById(chatWindowHeader).style.background	=	chatWindowTheme.headercolor ;
			}
			
			if( chatWindowTheme.footercolor != null && typeof chatWindowTheme.footercolor != 'undefined' )
			{
				console.info( "The footer color is : " + chatWindowTheme.footercolor );
				var chatWindowFooter	=	chatWindowSelectors.footer;
				document.getElementById(chatWindowFooter).style.background		=	chatWindowTheme.footercolor ;
			}
			
			if( chatWindowTheme.logopath != null && typeof chatWindowTheme.logopath != 'undefined' )
			{
				console.log("The logo path is : "+chatWindowTheme.logopath);
				var chatWindowLogo	=	chatWindowSelectors.logoHolder;
				document.getElementById(chatWindowLogo).src			=	chatWindowTheme.logopath ;
			}
		},
		
		applyMessageColor		:	function ()
		{
			
			//This is a crazy hackjob! . I am applying the leadcolor for the agent and vice versa.
			//Technically what should happen is that the lead bubble should have the agent bubble and viceversa . But the opposite is happening  
			//it is working however! ;)
			
			var chatWindowTheme	=	this.chatWindowTheme ;
			dojo.query(".name").style(	"color"			, chatWindowTheme.agentcolor 	);
			dojo.query(".agent .name").style("color"	, chatWindowTheme.leadcolor 	);
			
		},
		
		swapAgentAvatar			:	function ( url )
		{
			var lAvatarHolder							=	chatWindowSelectors.avatarHolder	;
			document.getElementById(lAvatarHolder).src	=	url 								;
        	document.getElementById('cs_agentavatar').style.display	=	"block";
		},
		
		playSound				:	function ()
		{
			//Future Implementation
		},
		
		scrollToBottom			:	function ()
		{
			console.log('Scrolling the chat message box to bottom!');
			var lMessageBox		=	chatWindowSelectors.messagebox;
			var objDiv 			= 	document.getElementById(lMessageBox);
			objDiv.scrollTop 	= 	objDiv.scrollHeight;
		},
		
		disableInput			:	function( option )		//Option has to be true or false. If its true, then box is disabled. If its false then its enabled again
		{
			var chatInputBox	=	chatWindowSelectors.inputBox;
			document.getElementById(chatInputBox).disabled	=	option;
			
		},
		/* End of functions related to the aesthetics of the chat window */
		
		loadFiles				:	function ()
		{
				console.info('Inside the load files function!');
				
				//css file having style definitions for chatwindow
				var lStyle	=	document.createElement("link");
				lStyle.setAttribute("rel"	,	"stylesheet"	);
				lStyle.setAttribute("type" 	, 	"text/css"		);
				lStyle.setAttribute("href"	,	this.cssPath	);
				document.getElementsByTagName("head")[0].appendChild(lStyle);
				
		},
		
		bindOnClick				:	function ()		// Once everything is ready attach the startChat function to onclick handlers of dom elements with class = "chatIcon"
		{
			console.info('Binding');
			var chatIcons = getElementsByClassName("chatIcon");
			
			for(var i=0; i<chatIcons.length; i++) 
			{
				chatIcons[i].onclick = function(){ conversion.startChat(); } ;
				chatIcons[i].style.cursor	=	'pointer';
				//chatIcons[i].setAttribute("style","cursor:pointer"); 
			}
			
		},
		startPopUpChat			:	function ()
		{
			this.setChatInProgress(true);
			
			var lPath	=	this.webchatServer+"/livechat/startpopupchat?clientid="+this.clientId;
			
			if( typeof demoskill != 'undefined' && demoskill != null && demoskill != "null" )
			{
				lPath				=	lPath+"&demoskill="+demoskill ;
			}
			
			lPath					=	lPath+"&clienturl="+this.domain ;
			
			window.open(lPath,'Live Chat','width=400,height=330');
		},
		
		doJsonp					:	function (url)
		{
				try
				{
					console.info('Going to call : '+url);
					
			    	var script = document.createElement("script");
			    	script.setAttribute("type","text/javascript");
			    	script.setAttribute("src", url);
			    	document.body.appendChild(script);
				}
				catch(e)
				{
					console.error('Exception while trying to do jsonp : '+e);
				}
		},
		
		constructChatWindow		:	function ( chatWindowTemplate )
		{
			try
			{
				console.info('Inside the constructChatWindow function!');
				var chatWindowContainer	=	chatWindowSelectors.chatWindowContainer ;
				var flag				=	this.createDivElement( chatWindowContainer );					//This is the div element that is going to contain the inline chat window
				if(flag)
				{
					document.getElementById(chatWindowContainer).innerHTML	=	chatWindowTemplate ;		//Inserting the chatwindow div inside chatwindowdiv
					this.attachEventHandlers();																// Attach the event handlers to the chat window
				}
				
			}
			catch(e)
			{
				console.error('Exception while trying to create the chatwindow : '+e);
			}
			
		},
		
		attachEventHandlers		:	function()		// Once the chat window is constructed attach the event handlers to it
		{
			
			var inputBox	=	chatWindowSelectors.inputBox	;
			var leaveButton	=	chatWindowSelectors.leaveButton	;
			document.getElementById(leaveButton).onclick		= 	function(){ conversion.leaveChat() }		;			// 	Attach leave function to close button
			document.getElementById(inputBox).onkeypress		=	function(e){ conversion.sendChat(e) }		;			//	Attach on key press to the input box
			usertyping.init();
    		
		},
		
		createDivElement		:	function( id )
		{
			console.info('Inside the create div');
			var chatDiv	=	document.createElement("div");
			chatDiv.setAttribute("id" , id);
			document.body.appendChild(chatDiv);
			return true;
		},
		
		getDataFromLocalStorage	:	function ()
		{
			if( window['localStorage'] !== null )
			{
				var lChatMetaData	=	localStorage.getItem( 'conversionchatdata' );
				if( lChatMetaData != null )
				{
					lChatMetaData		=	JSON.parse( lChatMetaData );
				}
				return lChatMetaData;
			}
			else
			{
					console.info('Local storage is not available in the browser');
			}
			
		},
		
		setDataIntoLocalStorage	:	function()
		{
			if( window['localStorage'] !== null )
			{
				if( this.chatInProgress == true && this.type != "popup" )
				{
					console.info( 'Chat is in progress. Setting data in localstorage!' );
					var lChatMetaData	=	this.getChatMetaData() ;
					lChatMetaData		=	JSON.stringify( lChatMetaData );
					localStorage.setItem( 'conversionchatdata'	,	lChatMetaData	);
				}
				else
				{
					console.info( 'Chat is not in progress. Not setting data in localstorage!' );
				}
			}
			else
			{
				console.info('Local storage is not available in the browser');
			}
			
		},
		
		removeDataFromLocalStorage	:	function()
		{
			if( window['localStorage'] !== null )
			{
				localStorage.removeItem( 'conversionchatdata' );
			}
			else
			{
				console.info( 'Local storage is not available in this browser' );
			}
			
		},
		
		setChatInProgress			:	function( option )		//Option should be true or false
		{
			console.info( 'Inside the set chat in progress function :'+option );
			this.chatInProgress		=	option ;
		},
		
		checkIfLatest				:	function ()
		{
			
			var currentTime		=	new Date().getTime() ;
			var lChatMetaData	=	this.getDataFromLocalStorage();
			
			if( lChatMetaData == null )
			{
					console.info('No chats in progress.');
					csIcon.showIcon();
					return false ;
			}
			
			if( ( ( currentTime - lChatMetaData.timestamp ) < 60000 ) && (lChatMetaData.chatInProgress == true ) )
			{
					if( typeof demoskill != 'undefined' && demoskill != null && demoskill != 'null' && demoskill != lChatMetaData.demoskill )
					{
							console.info('Different demo skill');
							return;
					}
					console.info( 'Looks like the chat is in progress' );
					this.init( lChatMetaData );										// 	Initialising the api
					this.constructChatWindow( lChatMetaData.chatWindowContent);		//	Reconstructing the chat window
					this.applyMessageColor();										//	Applying the bubble colors
					
					if(lChatMetaData.connectionId != null && lChatMetaData.connectionId != 'null' && typeof lChatMetaData.connectionId != 'undefined' )
					{
						var flag	=	this.joinChat( lChatMetaData.connectionId );	// 	Joining the chat
						if( lChatMetaData.agentonxmpp == "true" )
						{
								console.info( 'looks like user is connected to an xmpp agent!' );
								room.agentonxmpp	=	lChatMetaData.agentonxmpp ;
						}
						
						if(flag)
						{
							this.onLoadAfterNavigate();
						}
						this.scrollToBottom();
					}
					
					return true ;
			}
			else
			{
					console.info( 'No chats in progress!' );
					csIcon.showIcon();
					return false ;
			}
		},
		
		autoStartChat			:	function()
		{
				this.startChat();
		},
		
		appendFileToHead		:	function( url )
		{
			this.dependentScript	=	document.createElement("script");
			this.dependentScript.setAttribute("type","text/javascript"	);
			this.dependentScript.setAttribute("src" , url);
			document.getElementsByTagName("head")[0].appendChild(this.dependentScript);
		}
		
};

var chatWindowSelectors	=	
{
			chatWindowContainer	:	"cschatwindow"			,
			chatWindowElement	:	"cs_main_div"			,
			messagebox			:	"cs_chatmessages"		,
			inputBox			:	"cs_chatinput"			,
			leaveButton			:	"cs_chat_leave"			,
			avatarHolder		:	"cs_chtphoto"			,
			logoHolder			:	"cs_chatwindow_logo"	,
			header				:	"cs_chatHeader"			,
			footer				:	"cs_chatForm"			,
			soundElement		:	"chatSoundPlayer"		,
			localElementName	:	"conversionchatdata"	,
};

conversion.loadFiles();
if(conversion.type == "null" || conversion.type == null )
{
	conversion.type		=	"onpage" ;
}
/* ------------------------------------ For placing the chat Icon in the page ------------------------------------------------------ */

var csIcon	=	
{
		position		:	null	,		//Position of the image on the screen
		imagePath		:	null	,		//Path of the startChatImage
		
		tabStyle		:	null	,		//Style
		chatTab			:	null	,		//The dom element
		startChatImage	:	null	,
		fallBackImage	:	'https://s3.amazonaws.com/docs.webchat.a-cti.com/images/chatBanners/black_white_border.png'	,
		ie8				:	null	,
		
		init			:	function( imagePath , position )
		{
			(imagePath == null || imagePath == '' || imagePath == 'null') ? this.imagePath = this.fallBackImage : this.imagePath = imagePath ;
			this.position	=	position	;
		},
		
		getStyle		:	function()		//Get the style that has to be applied to the startChat button based on position
		{
			this.tabStyle	=	"display:none;position: fixed; z-index: 999999; cursor: pointer;";
			
			if( this.position != null )
			{
				this.position	=	unescape(this.position);
			}
			
			try
			{
				if( typeof cs_iconposition != 'undefined' && cs_iconposition != 'null' )
					this.position	=	cs_iconposition;
			}
			catch(e)
			{
				console.error('Exception while trying to show start chat button : '+e);
			}
			
			//Checking if the browser is IE 8
			if (window.navigator.appName == 'Microsoft Internet Explorer')
			{
				var userAgent	=	window.navigator.userAgent;	
				if( userAgent.indexOf( "MSIE 8.0" ) != -1 ) csIcon.ie8 = true;  
			}
			
			switch (this.position) 
			{
				case 'custom'		:	this.tabStyle	+=	"";	
										break;
										
				case 'Right Center'	:	this.tabStyle	+=	"right: -3px; top: 40%;" ;	
										break;
				
				case 'Left Center'	:	this.tabStyle	+=	"left: -3px; top: 40%;" ;
										break;
										
				case 'Bottom Right'	:	this.tabStyle	+=	"-webkit-transform:rotate(90deg);-moz-transform:rotate(90deg);;-o-transform:rotate(90deg);transform:rotate(90deg);zoom:1;" ;
										if( this.ie8 ){ this.tabStyle += "right: 10%;filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1);bottom: -102px"}else{ this.tabStyle += "right: 6%;-ms-transform:rotate(90deg);bottom: -51px;" }
										break;
										
				case 'Bottom Left'	:	this.tabStyle	+=	"left: 6%; bottom: -51px;-webkit-transform:rotate(90deg);-moz-transform:rotate(90deg);-o-transform:rotate(90deg);transform:rotate(90deg);zoom: 1;-ms-transform:rotate(90deg);" ;
										if( this.ie8 ){ this.tabStyle += "filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1);bottom: -102px"}else{ this.tabStyle += "-ms-transform:rotate(90deg);bottom: -51px;" }
										break;

				default				:	this.tabStyle	+=	"right: -3px; top: 40%;" ;
										break;
			}
			
			return this.tabStyle	; 
		},
		
		constructIcon	:	function()		//Create the dom element , apply style and show the image
		{
			
			this.chatTab	=	document.createElement('div');
			this.chatTab.setAttribute( 'id' 	, 'chatTab' );
			this.chatTab.setAttribute( 'class' 	, 'chatIcon' );
			this.chatTab.setAttribute( 'style' 	, this.getStyle());
			
			this.startChatImage	=	document.createElement('img');
			this.startChatImage.setAttribute( 'src' , this.imagePath );
			this.startChatImage.setAttribute( 'alt' , 'Live Chat');
			
			this.chatTab.appendChild(this.startChatImage);
			document.body.appendChild(this.chatTab);
			
		},
		
		showIcon		:	function()		//Show the constructed image
		{
			if(this.position != 'custom' )
			{
					document.getElementById( 'chatTab' ).style.display	=	'block';
			}
		},
		
		hideIcon		:	function()		//Hide the constructed image
		{
			document.getElementById( 'chatTab' ).style.display	=	'none';
		}
}

csIcon.init( conversion.startChatImagePath , conversion.startChatImagePosition );
csIcon.constructIcon();

/* -------------------------------- ---------------- User typing implementation ---------------- ---------------- ---------------- ---------------- ---------------- ----------------  */


var usertyping = 
{
	activestatus				: "on"			 ,
	lChangeStatusTimerrunning 	: false 		 ,
	lEndStatusTimerRunning		: false 		 ,
	lUserNotified				: false 		 ,
	lHasEnteredTextIndicator	: false			 ,
	lChangeStatusTimer			: ""			 ,
	lEndStatusTimer				: ""			 ,
	lChatInputBox				: "" 			 ,
	chatfrom					: ""			 ,
	lAckType					: ""	 		 ,
	lSide						: ""			 ,
	lAgentName					: ""			 ,
	hasEnteredTextTimer			: ""			 ,
	
	init					:	function()
	{
		this.lAckType	  		=	'clientack' 		;
		this.lSide	  	 		=	'client'			;
		this.lChatInputBox 		=	'cs_chatinput' 		;
		this.lAgentName	 		= 	'User'				;
		this.listen();
		
	},
	setStatusToTyping 		:	function()
	{
		if(!this.lUserNotified)
		{
			//This means user is typing , therefore trigger desired event :)
			dojox.cometd.publish( room.connectionName , { user : room.userName , chat : this.lAckType , clientacknowledgement : "typing" , playsound : false } ) ;
			
			this.lUserNotified					=	true ;
			this.lHasEnteredTextIndicator		=	false	;
			
			console.log('Show has entered text automatically after 4 secs if there are no more key presses. Refer second condition if "listen" function ');
			usertyping.hasEnteredTextTimer			=	setTimeout( "usertyping.setStatusToEnteredText('')" , 4000 );
			
		}
	} ,
	
	setStatusToIdle			:	function()
	{
		//This means user has stopped typing , therefore trigger desired event :)
		// changing status to idle
		dojox.cometd.publish( room.connectionName , { user : room.userName , chat : this.lAckType , clientacknowledgement : "endtyping" , playsound : false } ) ;
		this.lUserNotified					=	false ;
		this.lHasEnteredTextIndicator		=	false	;
	} ,
	
	setStatusToEnteredText	:	function(_lChatMessage)
	{
		clearTimeout(usertyping.lChangeStatusTimer);
		
		if( this.lUserNotified && !this.lHasEnteredTextIndicator)
		{
			dojox.cometd.publish( room.connectionName , { user : room.userName , chat : this.lAckType , clientacknowledgement : "enteredtext" ,enteredtext : _lChatMessage, playsound : false } ) ;
			this.lChangeStatusTimerrunning		=	false	;
			this.lUserNotified					=	false   ;
			this.lHasEnteredTextIndicator		=	true	;
		}
		
	} ,
	
	showUserTyping		:	function()
	{
		
		var lTypingIndicator					=	document.getElementById('typingIndicator');
		lTypingIndicator.style.background		=	'url("https://s3.amazonaws.com/docs.webchat.a-cti.com/documents/onpagechat/typing.gif") right no-repeat #ffffff' ;
	
		lTypingIndicator.innerHTML	=	this.lAgentName+" is " ;
		console.log('The Agent is :: '+this.lAgentName);
		lTypingIndicator.style.display	=	"block" ;
		
	} ,
	
	hideUserTyping		:	function()
	{
		var lTypingIndicator = null ;
		lTypingIndicator	=	document.getElementById('typingIndicator');
		lTypingIndicator.style.display	=	"none" ;
	} ,
	
	showHasEnteredText		:	function (lChatMessage)
	{
		var lTypingIndicator = null ;
		lTypingIndicator	=	document.getElementById('typingIndicator');
		lTypingIndicator.style.background	=	'#ffffff' ;
		lTypingIndicator.innerHTML	=	this.lAgentName+" has entered text" ;
	} ,
	
	listen					:	function()
	{
		console.log('Listening!');
		var lChatInputBox	=	null ;
		lChatInputBox		=	dojo.byId(this.lChatInputBox) ;
		
		dojo.connect( lChatInputBox , 'onkeyup' ,function(e) {
		
		var lChatMessage	=	lChatInputBox.value ;
		if(e.keyCode == dojo.keys.ENTER)
		{
			console.log('Enter key pressed');
			
			this.lUserNotified					=	false ;
			this.lChangeStatusTimerrunning		=	false ;
			this.lHasEnteredTextIndicator		=	false ;
			
			clearTimeout(usertyping.lEndStatusTimer)	 ;
			clearTimeout(usertyping.lChangeStatusTimer)	 ;
			clearTimeout(usertyping.hasEnteredTextTimer) ;
			
			console.log('Cleared timeouts!');
		}
		else
		{
			console.log('The flag is :: '+usertyping.lChangeStatusTimerrunning);
			if(lChatMessage.length >= 1 && !usertyping.lChangeStatusTimerrunning )
			{
				console.log("Inside 1");
				clearTimeout(usertyping.lEndStatusTimer);
				this.lEndStatusTimerRunning	=	false	;
				clearTimeout(usertyping.hasEnteredTextTimer);

				usertyping.lChangeStatusTimer			=	setTimeout( "usertyping.setStatusToTyping()" , 1000 );
				this.lChangeStatusTimerrunning			=	true	;

			}
			else if( lChatMessage.length >= 1 && usertyping.lUserNotified == true   )
			{
				console.log('Inside 2');
				clearTimeout(usertyping.hasEnteredTextTimer);
				try
				{
					usertyping.hasEnteredTextTimer	=	setTimeout( "usertyping.setStatusToEnteredText('')" , 2000 );
				}
				catch(e)
				{
					console.log('Exception here :: '+e);
				}
				
			}
			else if( lChatMessage.length < 1   )
			{
				console.log("Stopping");
				clearTimeout(usertyping.lChangeStatusTimer);
				clearTimeout(usertyping.hasEnteredTextTimer);
				
				usertyping.lChangeStatusTimerrunning	=	false	;
				
				if( (this.lHasEnteredTextIndicator == true || this.lUserNotified == true ) && !this.lEndStatusTimerRunning )
				{
					usertyping.lEndStatusTimer			=	setTimeout( "usertyping.setStatusToIdle()" , 2000 );
					this.lEndStatusTimerRunning			=	true  ;
					this.lHasEnteredTextIndicator		=	false ;
				}
			}
		}
	}

	);

	}
};

/* -------------------------------- ---------------- ---------------- The core part of this api ---------------- ---------------- ---------------- ---------------- ----------------  */

var room = 
{
	connectionName		:	""		,
	connectionGuid		:	""		,
	userName			:	"me"	,
	webchatserver		:	""		,
	connected			:	false	,
	meta				:	""		,
	clientId			:	""		,
	subscription		:	""		,
	agentonxmpp			:	""		,
	
	init				:	function( guid , serverName , clientId )
	{
			this.connectionGuid	=	guid							;
			this.connectionName	=	"/chat/"+this.connectionGuid	;
			this.userName		=	"me"		;
			this.webchatserver	=	serverName	;
			this.clientId		=	clientId	;
	},
	
	chat				:	function( text )
	{
		console.info("Inside the chat function");
        
    	try
    	{
    		dojox.cometd.publish( this.connectionName , { user : this.userName , chat : text , clientacknowledgement : "endtyping" , agentonxmpp	:	this.agentonxmpp } ) ;
    	}
    	catch(e)
    	{
    		console.error("unable to publish the message to the server :: "+e) ;
    	}
	},
	
	_chat				:	function( message )
	{
		console.info( "Inside the _chat function" );
		
		try
    	{
				if( !message.data )
				{
					console.info( "Message is coming as null!" );
					return;
				}
				
				var from 			= message.data.user;
	            var membership 		= message.data.join || message.data.leave;
	            var text 			= message.data.chat;
	            
	            if(typeof text != 'undefined' && text != null)
            	{
	            	conversion.receiveChat( from , text) ;	//This will place the chat in the message box
            	}
	            
	            
	            if( (message.data.leave && message.data.user != "Server") ||  message.data.leaveimmediately == true )	// when anyone of the user disconnect/closes the windows this will break the connection
		        {
		        	this.leave();
		        }
	            
	            if( message.data.pushpage )		//If page push is requested
            	{
	            	this.pushPage(message.data.location);
            	}
	            
	            if(message.data.greeting)
            	{
	            	this.firstMessageAction(message);
            	}
	            this.checkIfAgentOnXmpp(message);
	            this.handleAck(message);			//Handles ack messages sent from server
    	}
    	catch(e)
    	{
    		console.error("Exception while trying to receive message from the server :: "+e) ;
    	}
	},
	
	join				:	function()
	{
		dojox.cometd.ackEnabled 	=	("true") ; 	// enabling the acknowledgment
		dojox.cometd.init(this.webchatserver+"/cometd");
		this.connected	= true	;
	},
	
	triggerRouting			:	function()
	{
		console.info( 'Inside the trigger function!' );
		//this.connected	= true	;
		dojox.cometd.publish( this.connectionName , {user: this.userName , triggerFunction : true } );
	},
	
	_meta				:	function( e )
	{
		console.info( 'Inside meta' );
		
		if(e.action == "disconnect"){}
		
		if (e.action == "handshake") 
   		{	
	            if (e.successful) 
	            {
	            	room.subscription	=	dojox.cometd.subscribe( this.connectionName , room , "_chat");
            		dojox.cometd.publish( this.connectionName , { user: this.userName , join: true });

	            }
	            else if (e.reestablish) 
			    {
	            	var message	=	{ data: { join: true , user: "Server" , chat: "handshake " + e.successful ? "Handshake OK" : "Failed" } } ;
	            	this._chat(message);
			    }
   		}
   		else if (e.action == "connect")
   		{
   			
       			if (e.successful && !this.connected) 
       			{
       				console.log("Connect");
       				var message	=	{ data: { join: true , user: "Server" , chat: "reconnected!" } } ;
       				this._chat(message);
       			}
       			else if (!e.successful && this._connected) 
       			{
       				var message	= { data: { leave: true , user: "Server" } } ;	
       				this._chat(message);
       			}
       			this.connected	=	e.successful;
   		}
		
	},
	leave				:	function()
	{
		
		try
		{
			dojox.cometd.publish( this.connectionName , { user: this.userName , leave: true, chat: "Guest has left. Chat has been disconnected." , clientId: this.clientId , clientacknowledgement : "endtyping" , agentonxmpp	:	this.agentonxmpp });
			
			try
			{
				dojox.cometd.unsubscribe(room.subscription);
			}
			catch(e)
			{
				console.error( 'Exception while trying to unsub  : '+e );
			}
			
		}
		catch(e)
		{
			console.error( 'Exception while trying to leave chat : '+e );
		}
		finally
    	{
    		dojox.cometd.disconnect();
    		console.log("Chat session has been disconnected");
    	}
		
	},
	
	destroy				:	function()
	{
			console.info( 'Inside destroy' );
			this.init( "" , "" , "" );
			this.meta			=	null	;
			room.subscription	=	null	;
	},
	
	startPoll			:	function()
	{
			dojox.cometd.publish( this.connectionName , { user : this.userName , chat : "startkeepalive" , keepalive : "true" } ) ;
	},
	
	handleAck			:	function ( message )
	{
		if( message.data.serveracknowledgement == 'true'  )
    	{
        	console.log("I am here! , Do not severe the connection!");
        	dojox.cometd.publish( this.connectionName , { user : room.userName , chat : "clientack" , clientacknowledgement : "true" } ) ;
    	}
        if( message.data.serveracknowledgement == 'typing' && usertyping.activestatus == 'on')
    	{
        	console.log("Looks like the client has started typing!");
        	usertyping.showUserTyping();
    	}
       
        if( message.data.serveracknowledgement == 'enteredtext' && usertyping.activestatus == 'on' )
    	{
        	console.log("Looks like the client has entered text");
        	usertyping.showHasEnteredText(message.data.enteredtext);
    	}
        
	    if( message.data.serveracknowledgement == 'endtyping' && usertyping.activestatus == 'on' )
    	{
        	console.log("Looks like the client has stopped typing!");
        	usertyping.hideUserTyping();
    	}
	},
	
	pushPage			:	function( location )
	{
		setTimeout( function() {window.location	=	location ;}, 1000 );
	},
	
	firstMessageAction	:	function( message )
	{
		this.startPoll();
		
		var lAvatarUrl	=	message.data.avatarurl	;
		if(typeof lAvatarUrl != 'undefined' && lAvatarUrl != "" && lAvatarUrl != null && lAvatarUrl != 'null' )
    	{
        	console.log('The avatar url :: '+lAvatarUrl);
        	conversion.swapAgentAvatar(lAvatarUrl);
    	}
	},
	
	checkIfAgentOnXmpp	:	function(message)
	{
		if( (message.data.xmppagent != null && typeof message.data.xmppagent != 'undefined' ) && (message.data.xmppagent == 'true' || message.data.xmppagent == true ) )
		{
			room.agentonxmpp	=	"true";
		}
	}
	
};

/* -------------------------------- ---------------- Actions to be executed first everytime a page loads ---------------- ---------------- ---------------- ---------------- ---------------- ----------------  */
var getElementsByClassName = function (className, tag, elm){
	   
	if (document.getElementsByClassName) {
		getElementsByClassName = function (className, tag, elm) {
			elm = elm || document;
			var elements = elm.getElementsByClassName(className),
				nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
				returnElements = [],
				current;
			for(var i=0, il=elements.length; i<il; i+=1){
				current = elements[i];
				if(!nodeName || nodeName.test(current.nodeName)) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	else if (document.evaluate) {
		   
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = "",
				xhtmlNamespace = "https://www.w3.org/1999/xhtml",
				namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
				returnElements = [],
				elements,
				node;
			for(var j=0, jl=classes.length; j<jl; j+=1){
				classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
			}
			try	{
				elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
			}
			catch (e) {
				elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
			}
			while ((node = elements.iterateNext())) {
				returnElements.push(node);
			}
			return returnElements;
		};
	}
	else {
		   
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = [],
				elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
				current,
				returnElements = [],
				match;
			for(var k=0, kl=classes.length; k<kl; k+=1){
				classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
			}
			for(var l=0, ll=elements.length; l<ll; l+=1){
				current = elements[l];
				match = false;
				for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
					match = classesToCheck[m].test(current.className);
					if (!match) {
						break;
					}
				}
				if (match) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	return getElementsByClassName(className, tag, elm);
};

/* -------------------------------------------------------------------------------------------------------------------------------- */
window.onunload	=	function()
{
	conversion.setDataIntoLocalStorage();
}

conversion.bindOnClick();

/* ------------------------------------------------------------------------------------------------------------------------*/


/* This is for google analytics */
var analytics	=	
{
		//accountNumber	:	'UA-19264678-1'	,
		accountNumber	:	null			,
		checkTimer		:	null			,
		count			:	0				,
		check			:	function()
		{
			if( window._gaq  && _gaq.push)
			{
				try
				{
					( conversion.mode == 'live' ) ? 	this.accountNumber	=	'UA-19264678-1' :	this.accountNumber	=	'UA-19264678-3' ; 
				}
				catch(e)
				{
					console.error('Error setting analytics acct no based on mode : '+e);
					this.accountNumber	=	'UA-19264678-1'	;
				}
				
				console.info('Analytics is available!');
				//_gaq.push(['cs._setDomainName', 'webchat.conversionsupport.com']);
				_gaq.push('cs._setClientInfo', true);
				_gaq.push(['cs._setAccount', this.accountNumber]);		//Set the tracker to push events to our account
				this.pushScriptLoad();
			}
			else
			{
				if(this.count < 3)
				{
					console.info('Gonna check for analytics again!');
					this.checkTimer	=	setTimeout( 'analytics.check()' , 1500 );
					this.count++ ;
				}
				else
				{
					console.error('Analytics is not available!');
				}
			}
		},
		
		pushScriptLoad	:	function()
		{
			if( window._gaq  && _gaq.push)
			_gaq.push([ 'cs._trackEvent' , conversion.clientId , 'Script Load' , document.URL  ]);	//Pushing the event to our account
		},
		
		pushClickToChat	:	function()
		{
			if( window._gaq  && _gaq.push)
			_gaq.push([ 'cs._trackEvent' , conversion.clientId , 'Click to Chat' , document.URL  ]);	//Pushing the event to our account
		},
		
		pushProActiveChatEvent	:	function( label )		//label --> Accept chat invitation , Deny chat invitation , Start Chat		
		{
			if( window._gaq  && _gaq.push)
				_gaq.push([ 'cs._trackEvent' , conversion.clientId , 'Proactive Chat' , label  ]);	//Pushing the event to our account
		},
		
		pushOfflineFormEvent	:	function( label )		//label --> Accept chat invitation , Deny chat invitation , Start Chat		
		{
			if( window._gaq  && _gaq.push)
				_gaq.push([ 'cs._trackEvent' , conversion.clientId , 'Offline Form' , label  ]);	//Pushing the event to our account
		},
		
		pushSurveyFormEvent	:	function( label )		//label --> Accept chat invitation , Deny chat invitation , Start Chat		
		{
			if( window._gaq  && _gaq.push)
				_gaq.push([ 'cs._trackEvent' , conversion.clientId , 'Survey Form' , label  ]);	//Pushing the event to our account
		}
}

 /* ------------------------------Proactive chat implementation------------------------------------------ */

/* This is the css required for proactive chat*/
var proActiveCss	=	document.createElement("link");
proActiveCss.setAttribute("rel"	,	"stylesheet"	);
proActiveCss.setAttribute("type" 	, 	"text/css"		);
proActiveCss.setAttribute("href"	,	'https://s3.amazonaws.com/docs.webchat.a-cti.com/documents/proactive.css');

document.getElementsByTagName("head")[0].appendChild(proActiveCss);

var csProactiveChat	=	
{
		clientId			:	null	,	//Subacct number of the client
		proChatBannerPath	:	null	,	//Proactive chat banner image path
		fallBackBanerPath	:	'https://s3.amazonaws.com/docs.webchat.a-cti.com/images/chatBanners/chatBg1_black.png'	,	//Fallback pro chat banner path --> Used when proactive chat banner is not uploaded
		jsonUrl				:	null	,	//Url to call , to get the proactive chat rules
		proActiveRulesJson	:	null	,
		callBackFunctionName:	"csProactiveChat.getProactiveChatRulesCb"	,	//Name of the call back function to be invoked on getting proactive chat details
		
		secondsToLaunch		:	null	,
		maxPageViews		:	null	,
		chatIsInProgress	:	false	,
		
		//Info gathered from visitor
		pageCount			:	0	,	//Total number of pages seen by visitor
		displayed			:	false	,	//This is set to true once prochat banner has been displayed
		
		//Temproary variables used
		script				:	null	,
		proActiveWrapper	:	null	,
		closeButton			:	null	,
		startWrapper		:	null	,
		startChatDiv		:	null	,
		timer				:	null	,
		activeStatus		:	'on'	,
		startChat			:	"false"	,
		/*timeOnSite		:	null	,	//Time spent by visitor on site
		timeOnPage			:	null	,	//Time spent by visitor on current page
		*/
		
		init				:	function( clientId , conversionSupportUrl )
		{
			this.clientId	=	clientId	;
			this.jsonUrl	=	conversionSupportUrl+"/proactivechatrules?clientId="+this.clientId+"&callback="+this.callBackFunctionName;
		},
		
		initFromExternal	:	function( maxPageViews , secondsToLaunch , proChatBannerPath )
		{
			console.info(secondsToLaunch);
			this.maxPageViews		=	maxPageViews		;
			this.secondsToLaunch	=	secondsToLaunch		;
			this.proChatBannerPath	=	proChatBannerPath	;
			
			this.pageCount++ ;
			this.setCookie();
			this.processProactiveChatRulesJsonCb();
			
		},
		
		getProactiveChatRules	:	function()
		{
			if( typeof maxPageViews != 'undefined' || typeof secondsToLaunch != 'undefined'	)
			{
				if(typeof maxPageViews == 'undefined')maxPageViews=0;
				if(typeof secondsToLaunch == 'undefined')secondsToLaunch=0;
				if(typeof proChatBannerPath == 'undefined')proChatBannerPath=null;
				this.initFromExternal( maxPageViews , secondsToLaunch , proChatBannerPath )
			}
			else
			{
				var _secondsToLaunch	=	"null"	;
				var _proChatBanner		=	"null"	;
				this.initFromExternal( 0 , _secondsToLaunch , _proChatBanner )
				
				/*
				//Data is not available locally , therefore we are hitting our server to get data
				this.script	=	document.createElement("script");
				this.script.setAttribute("type","text/javascript");
				this.script.setAttribute( "src" , this.jsonUrl );
				document.body.appendChild(this.script);
				*/
			}	
			
		},
		
		getProactiveChatRulesCb	:	function( data )
		{
			document.body.removeChild(this.script);	//Remove the scripttag after request is complete
			
			if(data == null || data == "null" || data == "")
			{
				console.info("There are no proactive chat rules configured for this client. Data received on callback is "+data);
				return ;		//No rules found
			}
			else
			{
				this.proActiveRulesJson	=	data ;
				this.processProactiveChatRulesJson( data );	//Process the proactive chat rules json here
			}
		},
		
		processProactiveChatRulesJson	:	function( data )
		{
			for (i in data )
			{
				("/*"	==	data[i].pathname) ?	this.secondsToLaunch = (data[i].secToLaunch)	:  this.secondsToLaunch = null	;
				
				( data[i].pathname == 'maxPageViews') ?	this.maxPageViews	=	(data[i].maxPageViews) :	this.maxPageViews = null ; 
				
				( data[i].pathname == 'proActiveChatBanner' ) ? this.proChatBannerPath	=	data[i].proActiveChatBanner : this.proChatBannerPath = null ; 
			}
			console.info( "Max page views : "+this.maxPageViews+" and secondsToLaunch : "+this.secondsToLaunch+" and the prochat banner path is :"+this.proChatBannerPath );
			this.processProactiveChatRulesJsonCb();
		},
		
		processProactiveChatRulesJsonCb	:	function()
		{
			//Checking if the params are set to off or if live chat is in progress
			if( this.maxPageViews == 'off' || this.secondsToLaunch == 'off'	|| csProactiveChat.chatIsInProgress == true )
			{
				console.info('Proactive chat is set to off / live chat is in progress');
				return ;
			}
			
			//Checking if prochat banner path is null. null -> use the fallback banner
			( this.proChatBannerPath == "null" || this.proChatBannerPath == null ) ? (this.proChatBannerPath	=	this.fallBackBanerPath) : (this.proChatBannerPath	=	this.proChatBannerPath) ; 
			
			//If max page views is available , then check if max page views criteria is satisfied else start the timer
			if( this.maxPageViews != null && this.maxPageViews != "null" && this.maxPageViews >= 0 )
			{
				( this.pageCount >= this.maxPageViews ) ?	this.startTimer() : console.info("Max page views is : "+this.maxPageViews+" and no of pages viewed is :"+this.pageCount); 
			}
			else
			{
				console.info('Max page views not set!');
				this.startTimer(this.secondsToLaunch);
			}
		},
		
		startTimer				:	function()
		{
			console.info(this.secondsToLaunch);
			( this.secondsToLaunch != null && this.secondsToLaunch != "null" && this.secondsToLaunch >= 0 ) ? ( this.timer	=	setTimeout( "csProactiveChat.constructBanner()" , this.secondsToLaunch ) ) : console.info('Seconds to launch is coming as null') ;
		},
		
		stopTimer				:	function()
		{
			clearTimeout( this.timer );
		},
		
		constructBanner			:	function()
		{
			//The proactive chat banner is contained in this div. This is the parent div
			this.proActiveWrapper	=	document.createElement("div")
			this.proActiveWrapper.setAttribute("id" , "proActiveWrapper");
			this.proActiveWrapper.setAttribute("style" , "display:none;");
			
			//This div encapsulates the close button
			this.closeButton	=	document.createElement("div")
			this.closeButton.setAttribute("id" , "closeButton");
			this.closeButton.setAttribute("style" , "z-index:99999");
			this.closeButton.setAttribute("onclick" , "csProactiveChat.closeButtonClicked()");
			
			//This div encapsulates the proactive chat banner
			this.startWrapper	=	document.createElement("div")
			this.startWrapper.setAttribute("id" , "startWrapper");
			this.startWrapper.setAttribute("onclick" , "csProactiveChat.proChatBannerClicked()");
			//this.proActiveWrapper.setAttribute("style" , "display:block;");
			
			this.startChatDiv	=	document.createElement("div")
			this.startChatDiv.setAttribute("id" , "startChat");
			
			this.startWrapper.appendChild(this.startChatDiv);
			this.proActiveWrapper.appendChild(this.closeButton);
			this.proActiveWrapper.appendChild(this.startWrapper);
			document.body.insertBefore( this.proActiveWrapper , document.body.childNodes[0]);
			
			this.constructBannerCb();	//Process of building the pro chat banner over. Therefore calling the constructBannerCb function
		},
		
		constructBannerCb		:	function()
		{
			this.showBanner();				// Display the banner to the user
			this.displayed	=	true	;	//Setting the displayed to true
			this.setCookie();				// Since we have showed the proactive chat banner we are setting a cookie, that will help in NOT showing the banner for the next 8 hours
			this.attachOnClickEvents();		// Attach the onclick events
			
			analytics.pushProActiveChatEvent('Show Chat Invitation')
			
		},
		
		attachOnClickEvents		:	function()
		{
			//document.getElementById("proActiveWrapper").onclick	=	"csProactiveChat.proChatBannerClicked()" ;	//Attaching the function to be invoked on click of the banner
			//document.getElementById("closeButton").onclick		=	"csProactiveChat.closeButtonClicked()"	 ;	//Attaching the function to be invoked on click of the close button
		},
		
		proChatBannerClicked	:	function()
		{
			this.hideBanner();	console.info("Starting chat!");
			conversion.startChat();	//Calling Startchat method
			this.startChat	=	true ;
			analytics.pushProActiveChatEvent('Start Chat')
		},
		
		closeButtonClicked		:	function()
		{
			console.info("Fading out the prochat banner");
			this.hideBanner();
			analytics.pushProActiveChatEvent('Deny Chat Invitation')
		},
		
		showBanner				:	function()
		{
			
			if( conversion.chatInProgress == true )
			{
				console.info('Chat is in progress do not show banner');
				return ;
			}
			console.info("Fading in the prochat banner");
			document.getElementById("proActiveWrapper").style.background	=	"transparent url("+this.proChatBannerPath+") no-repeat"
			document.getElementById("proActiveWrapper").style.display		=	"block" ;
			
			if( document.getElementById('cs_overlay') != null )
			{
				document.getElementById('cs_overlay').style.display	=	'block' ;
			}
		},
		
		hideBanner				:	function()
		{
			console.info("Fading out the prochat banner");
			
			if( document.getElementById("proActiveWrapper") != null )
					document.getElementById("proActiveWrapper").style.display	=	"none"	;
			
			if( document.getElementById('cs_overlay') != null )
			{
				document.getElementById('cs_overlay').style.display	=	'none' ;
			}
			
		},
		
		setCookie				:	function()
		{
			if( window['localStorage'] !== null )
			{
				var proChatMetaData				=	new Object()			;
				proChatMetaData.time			=	new Date().getTime() 	;
				
				proChatMetaData.displayed		=	this.displayed 			;
				proChatMetaData.bannerPath		=	this.proChatBannerPath	;
				proChatMetaData.secsToLaunch	=	this.secondsToLaunch	;
				proChatMetaData.maxPageViews	=	this.maxPageViews		;
				proChatMetaData.pageCount		=	this.pageCount  		;
				
				proChatMetaData					=	JSON.stringify( proChatMetaData );
				localStorage.setItem( 'proChatMetaData'	,	proChatMetaData	);
			}
			else
			{
				console.info('Localstorage unavailable!');
			}
		},
		
		getCookie				:	function()
		{
			if(localStorage.getItem( 'proChatMetaData' ) == null )
			{
				console.info('Fresh start!');
				this.getProactiveChatRules();
				//this.initFromExternal( maxPageViews, secondsToLaunch, proChatBannerPath);	//Fresh start
			}
			else
			{
				var proChatMetaData			=	JSON.parse( localStorage.getItem( 'proChatMetaData' ) );
				var timeDifference			=	(new Date().getTime() - proChatMetaData.time) ;
				console.info('difference = '+timeDifference);
				
				if( proChatMetaData.displayed == true &&   timeDifference < 2880000  )	
				{
					//do nothing
					console.info( 'Its bin lesser than 8 hrs since we showed the banner' );
				}
				else if( proChatMetaData.displayed == true &&   timeDifference > 2880000  )	
				{
					console.info('Its bin more than 8 hrs since user saw the prochat invitation')
					this.getProactiveChatRules();
					//this.initFromExternal( maxPageViews, secondsToLaunch, proChatBannerPath);	//Its bin more than 8 hrs since pro chat ran.So starting afresh.
				}
				else
				{
					console.info('We have not shown the pro chat invitation yet and its bin lesser than 8hrs. Therfore fetchin data from localstorage');
					this.initFromLocalStorage(proChatMetaData);		//Lesser than 8 hrs. Referring local storage for data
				}
			}
		},
		
		initFromLocalStorage		:	function( proChatMetaData )
		{
				this.displayed			=	proChatMetaData.displayed	 ;
				this.proChatBannerPath	=	proChatMetaData.bannerPath	 ;
				
				this.secondsToLaunch	=	proChatMetaData.secsToLaunch ;
				this.maxPageViews		=	proChatMetaData.maxPageViews ;	
				this.pageCount			=	proChatMetaData.pageCount  	 ;	//No of pages viewed by the visitor 
				
				this.pageCount++ ;						//Increasing the page count
				console.info('Pagecount is : '+this.pageCount);
				this.processProactiveChatRulesJsonCb();	//Start processing proactive info
				
				this.setCookie();
		},
		
		functionDispatcher			:	function( functionName )		//Future implementation
		{
			if( window['localStorage'] !== null && this.activeStatus == 'on')
			{
					
			}
			else
			{
					console.info('Not invoking since local storage is unavailable or activestatus is off');
					return ;
			}
		}
		
}


try
{
	analytics.check();
}
catch(e)
{
	console.error('Unable to set env for chat analytics! : '+e);
}

try
{
	csProactiveChat.getCookie();
}
catch(e)
{
	console.error('Problem while getting data related to proactive chat! : '+e);
}
