

var _wcsPopUpWin =	'';
if( window.isMessageListenerAttached == undefined )
	window.isMessageListenerAttached = false;

(function() {
	
	if( !window.console || typeof window.console == 'undefined' || window.console == null || window.console == undefined )
		console = { log: function() {}, info: function() {}, warn: function() {}, error: function() {}, trace: function() {}, debug: function() {} };
	else if(!console.debug)
		console.debug = function() {};
		
		var subacctno		= 	"1773736738" ;
		var wcs				=	"http://webchat.conversionsupport.com:80" 		 ;
		var imagepath 		= 	"https://commondatastorage.googleapis.com/docs.webchat.a-cti.com/images/chatBanners/green_white_border.png" ;
		var position 		= 	"Right Center"  ;
		var bannerpath 		=  "null" ;
		var timeinterval 	=  "null" ;
		var agentAvailable 	=  "false" ;
		var overflow 		=  "on" ;
		var type 			=  "onpage" ;
		var monitoring 		=  "on" ;
		var uniqueKey		=	"7spkc9xo77ic7b78ckbiyjad" + new Date().getTime() ;
		var offlineMessage	=	"We are currently not available.Please leave your details and we will get in touch with you as soon as possible. ";
		var tabTitle		=	"Live Chat";
		var tabInstruction	=	"Questions, Concerns, Feedback? We're ready to help you!";
		var placeholderText	=	"Your Message...";
		var headerColour	=	"#d7e0cb";
		var newDesign		=	"false";
		console.log("tabTitle::"+tabTitle+" tabInstruction::"+tabInstruction+" placeholderText::"+placeholderText+" headerColour ::"+headerColour+" newDesign ::"+newDesign);
		// added temprovarily by pradeep for adding image colour
		var imagecolor		=   "#wge24jj";
		//ronak
			language 		=	"null";
		var whitelabel		=	"null";
		console.log("language is :::"+language);
		console.log("whitelabel is :::"+whitelabel);
		/* 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://commondatastorage.googleapis.com/docs.webchat.a-cti.com/documents/proactive.css');
		proActiveCss.setAttribute("href"	,	'//cschatdemo.appspot.com/css/proactivechat.css');
		document.getElementsByTagName("head")[0].appendChild(proActiveCss);
	
	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);
	};
	
	var _metaData	=	
	{
			channelName		:	null  ,
			state			:	null  ,
			condition		:	null  ,
			timeStamp		:	null  ,
			chatTranscript	:	null  ,
			isConnected		:	false ,	//Set to true only when chat is in progress. Set to false when chat is disconnected or when chat is not in progress
			inProgress		:	false ,	//Set to true whenever there is a comet connection open
			joinedtime		:   null,
			
			init			:	function( channelName , state , condition , timeStamp , chatTranscript , inProgress , isConnected ,joinedtime )
			{
				this.channelName	=	channelName		;
				this.state			=	state			;
				this.condition		=	condition		;
				this.timeStamp		=	timeStamp		;
				this.chatTranscript	=	chatTranscript	;
				this.inProgress		=	inProgress		;
				this.isConnected	=	isConnected		;
				this.joinedtime		=   joinedtime		;
			},
			
			reInit			:	function( data )
			{
				this.channelName	=	data.channelName	;
				this.state			=	data.state			;
				this.condition		=	data.condition		;
				this.timeStamp		=	data.timeStamp		;
				this.chatTranscript	=	data.chatTranscript	;
				this.inProgress		=	data.inProgress		;
				this.isConnected	=	data.isConnected	;
				this.joinedtime		= 	data.joinedtime		;
			}
	}
	
	var proactivechat	=
	{
		fallbackbanner	:	"https://commondatastorage.googleapis.com/docs.webchat.a-cti.com/images/chatBanners/chatBg1_black.png"	,
		noShow			:	false,
		timer			:	null,
		key				:	""	,
		
		build			:	function( bannerpath )
		{
			if( document.documentElement.clientWidth < 450 ) { //console.info('Looks like screen size is small. Therefore not displaying prochat banner.'); 
				return; }

			//Construct black screen
			var blackScr = document.createElement('div');blackScr.setAttribute("id" , "csproBlackScreen");
			blackScr.setAttribute('style','display:none;background: black;top:0px;left:0px;width:100%;height:100%;border:none;padding:0px;position: fixed;z-index:999999;opacity:.7;filter:alpha(opacity=70);' );
			document.body.insertBefore( blackScr , document.body.childNodes[0] );
		
			//The proactive chat banner is contained in this div. This is the parent div
			var proActiveWrapper	=	document.createElement("div");
			var wrapperStyle 		= 	( document.documentElement.clientWidth < 450 ) ? 'display:none;zoom:76%;' : 'display:none;' ;
			proActiveWrapper.setAttribute("id" , "proActiveWrapper");
			proActiveWrapper.setAttribute("style" , wrapperStyle);
			
			//This div encapsulates the close button
			var closeButton	=	document.createElement("div");
			closeButton.setAttribute("id" , "closeButton");
			closeButton.setAttribute("style" , "z-index:999999");
			closeButton.onclick	=	function(){ document.getElementById('proActiveWrapper').style.display = 'none';document.getElementById('csproBlackScreen').style.display = 'none'; };
			
			//This div encapsulates the proactive chat banner
			var startWrapper	=	document.createElement("div");
			startWrapper.setAttribute("id" , "startWrapper");
			startWrapper.onclick	=	function(){ $conversion.startChat();document.getElementById('proActiveWrapper').style.display = 'none';document.getElementById('csproBlackScreen').style.display = 'none'; };
			
			var startChatDiv	=	document.createElement("div");
			startChatDiv.setAttribute("id" , "startChat");
			
			startWrapper.appendChild(startChatDiv);
			proActiveWrapper.appendChild(closeButton);
			proActiveWrapper.appendChild(startWrapper);
			document.body.insertBefore( proActiveWrapper , document.body.childNodes[0] );
			
			if( bannerpath == null || bannerpath == '' || bannerpath == 'null' || typeof bannerpath == 'undefined' )
				bannerpath	=	this.fallbackbanner;
			
			this.show(bannerpath);
			
		},
		
		show		:	function( bannerpath )
		{
			var banner	=	document.getElementById("proActiveWrapper") ;
			if( banner != null && this.noShow == false )
			{
				document.getElementById('csproBlackScreen').style.display = 'block';
				banner.style.background	=	"transparent url("+bannerpath+") no-repeat"
				banner.style.display	=	"block" ;
				this.setCookie(this.key);
			}
			
			recordEvent('Proactive chat',document.URL);	//Recording proactive-chat banner.
		},
		
		hide		:	function()
		{
			if( document.getElementById('proActiveWrapper') != null )
			{
				document.getElementById('proActiveWrapper').style.display = 'none';
				document.getElementById('csproBlackScreen').style.display = 'none';
			}
		},
		
		startTimer	:	function( bannerpath , timeinterval )
		{
			if( timeinterval != '' && timeinterval != null && timeinterval != 'null' && typeof timeinterval != 'undefined' && timeinterval > 0 && timeinterval != 'off')
					this.timer	=	setTimeout( function() {proactivechat.build(bannerpath)} , timeinterval );
		},
		
		stopTimer	:	function()
		{
			clearTimeout( this.timer );
		},
		
		setCookie	:	function( key )
		{
			if( detectStorage() == false )
			{
				return;
			}
			
			localStorage.setItem( key , new Date().getTime() );
		},
		
		removeCookie : function( key )
		{
			if( detectStorage() == false )
			{
				return;
			}
			
			localStorage.removeItem( key );
		},
		
		verify		 :	function()
		{
			if( detectStorage() == false )
			{
				return;
			}
			
			var data	=	localStorage.getItem( this.key );
			if( data == null || data == 'null' || typeof data == 'undefined' || ( new Date().getTime() - data > 3600000))
			{
				this.removeCookie( this.key );
				return true;
			}
			else
			{
				//console.log('Proactive banner was shown within the last hour.');
				return false ;
			}
			
		}
	}
	
	var chatButton	=	
	{
		id				:	'conversionChatTab',
		fallbackimage	:	'https://commondatastorage.googleapis.com/docs.webchat.a-cti.com/images/chatBanners/black_white_border.png',
		fallbackpos		:	'Right Center',
		// added temprovarily by pradeep for adding image colour
		fallbackcolor	:   'FCFCFC',
		
		noshow			:	false,
		
		build	:	function( imagepath , position,bgcolor)
		{
			
			if( imagepath	== "" || imagepath == null || typeof imagepath == 'undefined' || imagepath == 'null' )
			{
				imagepath	=	chatButton.fallbackimage;
			}
			
			if( position == '' || position == null || typeof position == 'undefined' || position == 'null' )
				position = chatButton.fallbackpos;
			
			if( position == 'custom')
				this.noshow	=	true;
			
			var chatTab	=	document.createElement('div');
			chatTab.setAttribute( 'id' 	, 'conversionChatTab' );
			chatTab.setAttribute( 'class' 	, 'chatIcon' );
			chatTab.setAttribute( 'style' 	, this.getStyle(position));
			chatTab.onclick	=	function(){$conversion.startChat();};
			
			var startChatImage	=	document.createElement('img');
			startChatImage.setAttribute( 'src' , imagepath );
			startChatImage.setAttribute( 'alt' , 'Live Chat');
			startChatImage.setAttribute( 'style' , 'maring:0px;padding:0px;border:0px;');
			
			//added by pradeep for adding image colour
			//console.info("Backgorund color for image is : "+bgcolor);			
			if( bgcolor == null || bgcolor == "" || typeof imagecolor == 'undefined' || bgcolor == 'null')
			{
				bgcolor 	= 	chatButton.fallbackcolor;
			}
			
			startChatImage.style.background = '#'+bgcolor;
			
			
			chatTab.appendChild(startChatImage);
			document.body.appendChild(chatTab);
						
			if( position != 'custom')
				chatTab.style.display = 'block' ;
				
		},
		
		show	:	function()
		{
			if( document.getElementById(this.id) != null && this.noshow == false)
				document.getElementById(this.id).style.display	=	'block'
		},
		
		checkAndShow	:	function()
		{
			if( document.getElementById(this.id) != null && this.noshow == false)
				document.getElementById(this.id).style.display	=	'block'
			else
				this.build(imagepath, position,imagecolor);
					
		},
		
		hide	:	function()
		{
			if( document.getElementById(this.id) != null )
				document.getElementById(this.id).style.display	=	'none'
		},
		
		getStyle		:	function(position)		//Get the style that has to be applied to the startChat button based on position
		{
			var tabStyle	=	"display:none;position: fixed; z-index: 99999; cursor: pointer;";
			var ie8			=	( window.navigator.appName == 'Microsoft Internet Explorer' && (window.navigator.userAgent).indexOf( "MSIE 8.0" ) != -1 ) ? true : false ;
			
			switch (position) 
			{
				case 'custom'		:	tabStyle	+=	"";	
										break;
										
				case 'Right Center'	:	tabStyle	+=	"top: 40%;" ;
										tabStyle 	+=	(window.navigator.userAgent.indexOf('Opera Mini') != -1 && subacctno == '1667099495') ? "left: "+(document.documentElement.clientWidth - 30)+"px;" : "right: -3px;" ;
										break;
				
				case 'Left Center'	:	tabStyle	+=	"left: -3px; top: 40%;" ;
										break;
										
				case 'Bottom Right'	:	tabStyle	+=	"-webkit-transform:rotate(90deg);-moz-transform:rotate(90deg);;-o-transform:rotate(90deg);transform:rotate(90deg);zoom:1;" ;
										if( ie8 ){ tabStyle += "right: 10%;filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1);bottom: -102px"}else{ tabStyle += "right: 6%;-ms-transform:rotate(90deg);bottom: -51px;" }
										break;
										
				case 'Bottom Left'	:	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( ie8 ){ tabStyle += "filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1);bottom: -102px"}else{ tabStyle += "-ms-transform:rotate(90deg);bottom: -51px;" }
										break;

				default				:	tabStyle	+=	"right: -3px; top: 40%;" ;
										break;
			}
			
			return tabStyle	; 
		}
	}
	
	var conversion	=	
	{
			hidecsBrand :   false	,
			whiteLabelVal : false	,
			wcs			:	null	,
			subacctno	:	null	,
			
			updateTimer	:	null	,
			key			:	null	,
			
			targetWindow   :	null	,
			
			init		:	function( subacctno )
			{
				this.subacctno	=	subacctno 			;
				this.key		=	'csmd-'+subacctno	;
				proactivechat.key = 'pc-'+subacctno	;
				this.verify();
			},
			
			store			:	function( channelName, state, condition, timeStamp, chatTranscript, inProgress , isConnected , joinedtime)
			{
				//console.info('***** Inside store ****** ');			
				_metaData.init( channelName, state, condition, timeStamp, chatTranscript, inProgress , isConnected , joinedtime);
				localStorage.setItem( this.key , JSON.stringify(_metaData) );
				
				//This will update the object in localstorage once in every 60 seconds.
				this.startUpdater();
			},
			
			retreive		:	function( key )
			{
				try
				{
					var data	=	localStorage.getItem(key);
					return JSON.parse(data);
				}
				catch(e)
				{
					//console.error('localstorage is not available : '+e);				
					return null;
				}
				
			},
			
			remove			:	function( key )
			{
				localStorage.removeItem(key);
			},
			
			update			:	function( key , metaData )
			{
				localStorage.setItem( key , JSON.stringify(metaData) );
			},
			
			flush		:	function()
			{
				localStorage.clear();
			},
			
			startUpdater : function()
			{
				//Get object from localstorage update the time stamp, put it back into localstorage.
				var object			=	this.retreive(this.key);
				if( object != null && object != 'null' )
				{
					object.timeStamp=new Date().getTime();
					this.update( this.key , object);
					this.updateTimer = setTimeout( function(){conversion.startUpdater()}, 60000) ; 
				}
					
			},
			
			stopUpdater	 :	function()
			{
				//console.log('Stopping the timer!');
				clearTimeout(this.updateTimer);
			},
			
			verify		:	function()
			{
				var time	=	new Date().getTime();
				var object	=	conversion.retreive(conversion.key);
				
				if(  typeof object == 'undefined' || object == '' ||  object == null || object == "null" || ( ((time - object.timeStamp)/1000) > 63 ) || type == 'popup' )
				{
						//TODO : Show chat button
						chatButton.build(imagepath, position,imagecolor);
						
						//TODO : Check if prochatbaner was shown in the last 1 hour. If not then start timer
						if( ( overflow == 'on' || agentAvailable == true || agentAvailable == 'true' ) && proactivechat.verify() == true )
							proactivechat.startTimer( bannerpath , timeinterval);
						
						//TODO : Fetch new data, initialise metadata object , connect based on data available in hand.
						if( type != 'popup' )
						{
							//This implies user has chosen on page chat.
							if( monitoring == 'on' && ( agentAvailable == true || agentAvailable == 'true') )
							{
								//console.info( 'Connecting to the server!' );								
								if( typeof demoskill == 'undefined' )
								{
									demoskill	=	null	;
								}
								else
								{
									//console.log('Demo skill is : '+demoskill);
									uniqueKey	=	demoskill+"/"+uniqueKey;
									//console.info('The uniquekey is : '+uniqueKey+". This is after the demoSkill processing.");
								}
								
								//TODO : Initialise meta data and connect to server rightaway.Post vital info such as current pageUrl , previousPage , pageTitle. Start a channel
								this.store( '/visitor/'+subacctno+"/"+uniqueKey , 'Looking Around' , 'viewing' , new Date().getTime() , "" , false , true ,new Date().getTime() );
								 
								var data			=	new Object() ;
								data.connectionName	=	'/visitor/'+subacctno+"/"+uniqueKey ;
								data.connectionGuid	=	uniqueKey;
								data.previousPage	=	document.referrer;
								data.pageUrl		=	document.URL;
								data.pageTitle		=	document.title ;
								data.state			=	'Looking Around';
								data.condition		=	'viewing'	;
								data.timeinmillisec	=	new Date().getTime();
								data.clientId		= 	subacctno ;
								data.offlineMessage	=	offlineMessage;
								data.action			=	'start'	;
								data.joinedtime		= 	new Date().getTime();
								this.postMessage( data );
								
							}
							else
							{
								var tempData = { clientId: subacctno, offlineMessage: offlineMessage};
								this.postMessage( tempData );
								//console.info('Monitoring enabled ? '+ monitoring+" and is anyone available? :"+agentAvailable);	//Do Nothing
							}
						}
						
				}
				else
				{
						//This means chat is in progress. So do not show the start chat button. Do not initiate proactive chat timer
						//console.info('******Progress?******?');						
						
						//TODO : Use this data available in hand to reInit meta data. Connect back to this channel
						_metaData.reInit( object );
						localStorage.setItem( this.key , JSON.stringify(_metaData) );
						
						//This will update the object in localstorage once in every 60 seconds.
						this.startUpdater();
												
						//TODO : Connect to comet server as an existing user and publish metadata info available based on data available.
						var data			=	new Object();
						data.connectionName	=	object.channelName;
						
						if( object.channelName != null && typeof object.channelName != 'undefined')
							data.connectionGuid	=	object.channelName.split('/')[3];
							
						data.previousPage	=	document.referrer;
						data.pageUrl		=	document.URL;
						data.pageTitle		=	document.title ;
						data.state			=	object.state;
						data.condition		=	object.condition;
						data.time			=	new Date().getTime();
						data.timeinmillisec	=	new Date().getTime();
						data.chatHistory	=	object.chatTranscript;
						data.clientId		= 	subacctno ;
						data.offlineMessage	=	offlineMessage;
						data.action			=	'resume'	;
						data.joinedtime		=   object.joinedtime;
						this.postMessage( data );
						
						//TODO:Unhide main chat window and scroll msg box to bottom if chat is in progress, implied by inProgress flag.
						if( _metaData.inProgress )
							document.getElementById('csContainer').style.display='block';
					
						if( object.condition == 'done' || object.condition == 'viewing')
						{
							chatButton.checkAndShow();
						}
				}
				
			},
			
			startChat		:	function()
			{
				//TODO : Chat button has been clicked so do not bother user with the prochat banner for atleast 1 hr.
				proactivechat.stopTimer();
				proactivechat.setCookie(proactivechat.key);
				
				//Hide the proactive chat banner if its bin displayed
				proactivechat.hide();
				
				//TODO : If type is popupchat => startPopUpChat
				if( type == 'popup' )
				{
					//Open on page chat
					var lPath	 =	wcs+"/livechat/loadpopchat?clientid="+subacctno+"&clienturl="+document.URL;
					_wcsPopUpWin = window.open(lPath,'LiveChat','width=450,height=450');
					
					/*
					var lPath	=	wcs+"/livechat/startpopupchat?clientid="+subacctno+"&clienturl="+document.URL;
					window.open(lPath,'LiveChat','width=400,height=330');
					*/
					
					recordEvent('Chat-popup',document.URL);	//Recording start chat event.					
					return; 
				}
				
				//If chat is in progress return ( To be on the safer side unhide chat window )
				if( _metaData.inProgress == true && _metaData.isConnected == true )
				{
					if( document.getElementById('csContainer') != null )
						document.getElementById('csContainer').style.display = 'block' ;
					
					//console.info('Chat is in progress!');
					return ;
				}
				
				//TODO : Hide the chat icon since start chat button has been clicked.
				chatButton.hide();
				
				// TODO : Check if anyone is online to answer chat
				var script	=	document.createElement('script');
				script.setAttribute( 'type' , 'text/javascript' );
				if( typeof demoskill != 'undefined' && demoskill != null && demoskill != 'null' )
				{
					script.setAttribute( 'src' 	, wcs+"/livechat/getstatus/"+demoskill+"."+subacctno+"?callback=$conversion.startChatCb" );
				}
				else
				{
					script.setAttribute( 'src' 	, wcs+"/livechat/getstatus/"+subacctno+"?callback=$conversion.startChatCb" );
				}
				
				document.body.appendChild(script);
				
			},
			
			startChatCb		:	function( data )
			{
			   //console.info('inside startchatcb');
			   //console.info(data);
				var state 		= 	"" ;
				var condition	=	"" ;
				
				//TODO : Unhide the iframe, and postmessage signalling target window to  start chat, if overflow is enabled or if monitoring is on or if agent is available to answer chat
				if( data == 1 )
				{
					if( _metaData.isConnected )
					{
						//TODO : Publish start chat message.
						var data = new Object();
						data.action	=	'publishStartChatMessage';
						this.postMessage(data);
					}
					else
					{
						//TODO : Initialise meta data, start a connection and then publish startchat message.
						
						//TODO : Initialise meta data and connect to server rightaway.Post vital info such as current pageUrl , previousPage , pageTitle. Start a channel
						this.store( '/visitor/'+subacctno+"/"+uniqueKey , 'Looking Around' , 'viewing' , new Date().getTime() , "" , false , true);
						 
						var data			=	new Object() ;
						data.connectionName	=	'/visitor/'+subacctno+"/"+uniqueKey ;
						data.connectionGuid	=	uniqueKey;
						data.previousPage	=	document.referrer;
						data.pageUrl		=	document.URL;
						data.pageTitle		=	document.title ;
						data.state			=	"Trying to initiate a chat"	;
						data.condition		=	"incoming";
						data.time			=	new Date().getTime();
						data.joinedtime		= 	new Date().getTime();
						data.action			=	'start'	;
						this.postMessage( data );
						
						data.action	=	'publishStartChatMessage';
						this.postMessage( data );
					}

					state		=	"Trying to initiate a chat"	;
					condition	=	"incoming";
					
					recordEvent('Chat',document.URL);	//Recording start chat event.
				}
				else if( data == 2 )
				{
					//Show prechat survey form
					if( _metaData.isConnected )
					{
							//TODO : Publish showing prechat survey form and on submit start chat.
					}
					else
					{

						//TODO : Initialise meta data and connect to server rightaway.Post vital info such as current pageUrl , previousPage , pageTitle. Start a channel
						this.store( '/visitor/'+subacctno+"/"+uniqueKey , 'Looking Around' , 'viewing' , new Date().getTime() , "" , false , true);
						 
						var data			=	new Object() ;
						data.connectionName	=	'/visitor/'+subacctno+"/"+uniqueKey ;
						data.connectionGuid	=	uniqueKey;
						data.previousPage	=	document.referrer;
						data.pageUrl		=	document.URL;
						data.pageTitle		=	document.title ;
						data.state			=	"Showing prechat survey form"	;
						data.condition		=	"prechatsurvey";
						data.time			=	new Date().getTime();
						data.action			=	'start'	;
						this.postMessage( data );

					}
					
					var data = new Object();
					data.state		=	"Showing prechat survey form";
					//data.condition	=	"prechatsurvey";
					data.condition	=	"incoming";
					data.action				=	'prechatsurvey';
					this.postMessage(data);
					
					state		=	"Showing prechat survey form";
					condition	=	"prechatsurvey";
					
					recordEvent('Pre-chat survey',document.URL);	//Recording pre-chat survey event.
				}
				else if( data == 3 )
				{
					//Show offlineform
					if( _metaData.isConnected )
					{
						//TODO : Publish showing offline form message
						var data = new Object();
						data.action	=	'publishStartChatMessage';
						this.postMessage(data);
					}
					else
					{
						//TODO : Show offline form
						var data = new Object();
						data.clientId	= 	subacctno ;
						data.offlineMessage = offlineMessage;
						data.action		=	'showofflineform';
						this.postMessage(data);
					}
					
					state		=	"Showing Offline Form";
					condition	=	"offlineform";
					
					recordEvent('Offline form',document.URL);	//Recording offline form event.
				}
				
				//TODO : set the inProgress flag to true
				_metaData.inProgress	=	true;
				
				//TODO : Update status & condition
				_metaData.state		=	state;
				_metaData.condition	=	condition;
				
				//TODO : Unhide the chat window
				if( document.getElementById('csContainer') != null )
					document.getElementById('csContainer').style.display = 'block' ;
				
				//TODO : Put meta data back into localstorage
				_metaData.timeStamp	=	new Date().getTime();
				this.update( this.key , _metaData );
				
			},
			
			stopChat		:	function()
			{
				//TODO : Hide the iframe, and postmessage signalling target window to  stop chat and clear the messagebox and the clear chat transcript in the meta data contained here
				
				if( document.getElementById('csContainer') != null )
					document.getElementById('csContainer').style.display = 'none' ;
				
				if( monitoring == 'on' )
				{
					//TODO : Publish stop chat message.
					var data = new Object();
					data.action	=	'publishStopMessage';
					this.postMessage(data);
					
					//TODO : Update local storage
					_metaData.state			 =	'done';
					_metaData.condition		 =	'done';
					_metaData.inProgress	 =	false ;
					_metaData.chatTranscript =	''	  ;	
					this.update( this.key , _metaData);
				}
				else
				{
					//TODO : Close the channel. Clear local data.
					this.closeChannel();
				}
				
				//TODO : Show the StartChat button
				chatButton.checkAndShow();
				recordEvent('End Chat',document.URL);	//Recording end start chat event.
			},
			
			openChannel		:	function()
			{
				//TODO : Open a channel to the server
				
			},
			
			closeChannel	:	function()
			{
					//TODO : Hide chat window
					if( document.getElementById('csContainer') != null )
						document.getElementById('csContainer').style.display = 'none' ;
				
					//TODO : Close the channel. Also if there is a chat in progress show disconnected message to the user
					var data			=	new Object();
					data.connectionName	=	_metaData.channelName;
					data.action			=	'leave';
					this.postMessage(data);
					
					//Change values in the local _metaData object.
					_metaData.state			 =	'done';
					_metaData.condition		 =	'done';
					_metaData.inProgress	 =	false ;
					_metaData.isConnected	 =	false ;
					_metaData.chatTranscript =	''	  ;	
					
					//TODO : Stop the update timer. Also clear out the local storage data
					this.remove(this.key);
					this.stopUpdater();
					
					//TODO : Show the StartChat button
					chatButton.checkAndShow();
					
			},
			
			pushPage		:	function( location )
			{
				window.location	=	location;
			},
			
			showChatSurvey	:	function()
			{
				
			},
			
			postMessage		:	function( data )
			{
				//console.info('Inside post message');			
				 ( this.targetWindow == null ) ? this.targetWindow = document.getElementById('monitor').contentWindow : null;
				 if( this.targetWindow != null )
					 this.targetWindow.postMessage( JSON.stringify( data ) , '*' );
			}
			
	}
	
	if( !window.$conversion ){window.$conversion=conversion;}
	if( !window.$conversion.metaData ){window.$conversion.metaData=_metaData;}
	
	var limitations	=	( window.postMessage ) ? 'noprobs' : 'issues' ;
	
	function detectStorage()
	{
		//console.info('Inside detectStorage!');	
		try
		{
			var currentTime	=	new Date().getTime();
			localStorage.setItem( currentTime , currentTime );
			localStorage.removeItem( currentTime );
			return true;
		}
		catch(e)
		{
			return false;
		}
	}
	
	/* Build the iframe that has the core implementation */
	if( type == 'popup' ||  detectStorage() == false || limitations == 'issues' )
	{
		type	=	'popup';
		//console.log('Initialising the api!');		
		$conversion.init( subacctno );
	}
	else
	{
		//Create the iframe and append it to the body.
		var container	=	document.createElement('div');
		container.setAttribute( 'class' , 'csContainer'  		);
		container.setAttribute( 'id' 	, 'csContainer'  		);
		//container.setAttribute("style" , "position:fixed;bottom:10px;right:10px;height:330px;width:290px;display:none;z-index:9999999");
		container.setAttribute("style" , "position:fixed;bottom:0px;right:0px;height:347px;width:290px;display:none;z-index:9999999;");
		document.body.appendChild(container);
		
		var closeImg	=	document.createElement('img');
		closeImg.setAttribute( 'src' , 'https://commondatastorage.googleapis.com/docs.webchat.a-cti.com/dev/templates/close_icon.png' );
		closeImg.setAttribute( 'alt' , 'Close Chat' )
		//closeImg.setAttribute("style" , "position: absolute;top: -13px;z-index: 99999;width:20px;right:-6px;cursor: pointer;");
		closeImg.setAttribute("style" , "position: absolute;top: -14px;z-index: 99999;width:20px;right:3px;cursor: pointer;");
		closeImg.onclick = function(){ $conversion.stopChat();};
		container.appendChild( closeImg );
		
		var _csFrame	=	document.createElement('iframe');
		_csFrame.setAttribute( 'frameBorder' , '0'  			);
		_csFrame.setAttribute( 'id'     	 , 'monitor' 		);
		//_csFrame.setAttribute( 'src'    	 , wcs+"/pages/BrandedChatWindow.jsp?clientid="+subacctno );
		_csFrame.setAttribute( 'src'    	 , wcs+"/pages/BrandedChatWindow-exp.html#"+subacctno+"#"+language);
		_csFrame.setAttribute( 'style'    , 'display:block;height:350px;width:280px;border: none;position: absolute;right: 10px;bottom: 4px; background: transparent;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0px 0px 8px #000;-moz-box-shadow:0px 0px 8px #000;box-shadow:0px 0px 8px #000;' );
		
		var onIFrameLoad	=	function(){
				
			if( typeof window.csConfig != 'undefined' && window.csConfig != null )
			{
				try
				{
					var data = {};
					data.fb = csConfig.fbPageName;
					data.twitter  = csConfig.twitterHandle;
					data.font	  = csConfig.fontType;
					data.fontSize = csConfig.textsize;
					data.fontTabSize = csConfig.textTabsize;
					data.showPhoneField = csConfig.showPhoneField || false  ;
					data.phoneRequired =  csConfig.phoneRequired  || false  ;
					//data.action = 'showSocialMedia';
					data.action = 'initSettings';
					conversion.postMessage( data );
				}
				catch(e)
				{
					//console.error('Couldnt post sm links!');					
				}
			}
			
			$conversion.init(subacctno);
		};
		
		if( window.addEventListener )
			_csFrame.addEventListener( 'load' , onIFrameLoad , false );
		else
			_csFrame.attachEvent( 'onload' , onIFrameLoad  );

		container.appendChild( _csFrame );
		
		
		//Attaching the backlink
		
		if( typeof window.csConfig != 'undefined' && window.csConfig != null )
		{
			console.info("inside cs config for hiding powered by");
			try
			{
				this.hidecsBrand	= csConfig.hidePoweredBy  || false	;
			}
			catch(e)
			{
				//console.error('');					
			}
		}
		
		this.whiteLabelVal = (whitelabel  === 'true')?true:false;
		
		console.log("whiteLabelVal :: "+whiteLabelVal);
		
		var backLink		= 	document.createElement('a');
		backLink.setAttribute( 'href'  , 'http://www.conversionsupport.com' ) ;
		backLink.setAttribute('target','_blank');
		
		backLink.innerHTML	=	'Powered By Conversion Support'
		console.info("hide cs brand "+this.hidecsBrand);
		
		checkingAnalytics();
		
		if(this.hidecsBrand || this.whiteLabelVal)
		{
			backLink.setAttribute( 'style' , 'font-size:10px;color:#fafafa;text-decoration:none;position:absolute;padding:9px;display:none;bottom:4px;right:12px;font-weight:normal;line-height: 0px;' );
		}
		else
		{
			backLink.setAttribute( 'style' , 'font-size:10px;color:#fafafa;text-decoration:none;position:absolute;padding:9px;display:block;bottom:4px;right:12px;font-weight:normal;line-height: 0px;' );
		}

		container.appendChild(backLink);
		
	}
	
	if(window.onload) 
	{
		var load = window.onload;
		window.onload = function() 
		{
			load();
			//TODO : Attach the startChatFunction to all elements with chatIcon as class
			var chatIcons = getElementsByClassName("chatIcon");
			for(var i=0; i<chatIcons.length; i++) 
			{
				chatIcons[i].onclick = function(){ $conversion.startChat() } ;
				chatIcons[i].style.cursor	=	'pointer';
			}
		}
	} 
	else 
	{
		window.onload	=	function()
		{
			//TODO : Attach the startChatFunction to all elements with chatIcon as class
			var chatIcons = getElementsByClassName("chatIcon");
			for(var i=0; i<chatIcons.length; i++) 
			{
				chatIcons[i].onclick = function(){ $conversion.startChat() } ;
				chatIcons[i].style.cursor	=	'pointer';
			}
			
			try
			{
				if( typeof chatIcons == 'undefined' || chatIcons == null || chatIcons.length <= 0 )
				{
					var chatIcon	=	document.getElementById('chatIcon');
					if(chatIcon != null )
					{
						chatIcon.onclick		=	function(){ $conversion.startChat() } ;
						chatIcon.style.cursor	=	'pointer';
					}
							
				}
				
			}
			catch(e)
			{
				
			}
		}
	}
	
	if(window.onunload) 
	{
		var unload	=	window.onunload;
		window.onunload = function()
		{
			unload();
			
			//Update timestamp if data is available in localStorage.
			var object			=	$conversion.retreive();
			//console.log('Object is : '+object);			
			if( object != null && object != 'null' )
			{
				object.timeStamp=new Date().getTime();
				$conversion.update( $conversion.key , object);
			}
		}
	}
	else
	{
		window.onunload = function()
		{
			//Update timestamp if data is available in localStorage.
			var object			=	$conversion.retreive();
			//console.log('Object is : '+object);
			if( object != null && object != 'null' )
			{
				object.timeStamp=new Date().getTime();
				$conversion.update( $conversion.key , object);
			}
		}
	}
	
	
	
	function _csListener( event )
	{
		//Check if this event is from the parent window. True -> Process Else return
		//console.info('Got a message from the iframe :)');
		//console.info( event );		
		if(event.origin.indexOf("webchat") == -1)
		{
			return;
		}
		
		var data	=	JSON.parse(event.data);
		if( data.invoke == 'pagepush')
		{
			conversion.pushPage(data.url);
		}
		else if( data.invoke == 'showInvitation')
		{
			proactivechat.build(bannerpath);
		}
		else if(data.invoke == 'startchat')
		{
			recordEvent('Chat',document.URL);	//Recording start chat event.
		}
		else if( data.invoke	==	'update' )
		{
			_metaData.state		 =	data.state;
			_metaData.condition	 =	data.condition;
			_metaData.timeStamp	 =	new Date().getTime();
			
			if( data.chat != null && data.chat != '' && data.chat != 'null' && typeof data.chat != 'undefined' )
			{
				_metaData.chatTranscript	=	_metaData.chatTranscript + data.chat ;
			}

			if( data.action == 'leave' )
			{
				//Clear the chat map. set in progress to false.
				_metaData.chatTranscript	=	''	  ;
				_metaData.inProgress		=	false ;
				if( monitoring != 'on' )
					conversion.closeChannel();
				
			}
			else if( data.action == 'show' || data.action == 'offlineform' )
			{
				_metaData.inProgress =	true;
				
				//TODO : Unhide the chat window
				if( document.getElementById('csContainer') != null )
					document.getElementById('csContainer').style.display = 'block' ;
				
				//Hide the chat tab if its visible
				chatButton.hide();
				
				//Hide if the prochatscreen is visible
				proactivechat.hide();
			}
			
			conversion.update(conversion.key , _metaData );
		}
		
	}
	
	var _csAutoStart	=	
	{
				key	:	"csAutoStartChat",
				
				start	:	function()
				{
					if( _metaData.inProgress == true && _metaData.isConnected == true )	//Check if chat is in progress then return.
						return;
					
					if( overflow == 'on' )	//If someone is online then trigger chat.
					{
						this.startCb('true')
						return;
					}
					
					//If connection is existing check if someone is available and ready to chat.
					var script	=	document.createElement('script');
					var src		=	wcs+'/livechat/checkforreadyusers/'+subacctno+"?callback=$conversion.autoChat.startCb" ;
					script.setAttribute( 'type' , 'text/javascript' );
					script.setAttribute( 'src'  , src );
					document.body.appendChild(script);
				},
				
				startCb	:	function(data)
				{
					//console.info('inside startCb');					
					if(data=='true' || data==true)
					{
						$conversion.startChat();	//Start chat
						this.setCookie( this.key , 1343301486066 , 0.0833 );	//Set cookie
					}
					
				},
				
				check	:	function()
				{
					var timeStamp	=	this.readCookie(this.key);
					if( typeof timeStamp == 'undefined' || timeStamp == null || timeStamp == 'null' || timeStamp == '')
						this.start();
				},
				
				setCookie:	function( cookieName, cookieValue, nDays )
				{
					 //Set cookie with timestamp and key 'csAutoStartChat'
					 var today = new Date();
					 var expire= new Date();
					 if (nDays==null || nDays==0) nDays=1;
					 expire.setTime(today.getTime() + 3600000*24*nDays);
					 document.cookie = cookieName+"="+escape(cookieValue)+ ";expires="+expire.toGMTString();
				},
				
				readCookie	:	function( cookieName )
				{
					 var theCookie=" "+document.cookie;
					 var ind=theCookie.indexOf(" "+cookieName+"=");
					 if (ind==-1) ind=theCookie.indexOf(";"+cookieName+"=");
					 if (ind==-1 || cookieName=="") return "";
					 var ind1=theCookie.indexOf(";",ind+1);
					 if (ind1==-1) ind1=theCookie.length; 
					 return unescape(theCookie.substring(ind+cookieName.length+2,ind1));
				}
	};
	
	if( !window.$conversion.autoChat ){window.$conversion.autoChat=_csAutoStart;}
	
	if( !window.isMessageListenerAttached ) {
		if( window.addEventListener )
			window.addEventListener( 'message' , _csListener , false )
		else
			window.attachEvent( 'onmessage' , _csListener );
		window.isMessageListenerAttached = true;
	}
	
	var recordEvent = (function() {
		var category = 'ConversionSupport-'+subacctno;
		return function(action,label)
		{
			console.log("triggering analytics for "+action+"and"+label);
			( window._gaq  && _gaq.push) ? _gaq.push(['_trackEvent', category, action, label]) : ''; //console.info('Category : '+category+', Action : '+action+', label : '+label);
			
			if(window._gaq  && _gaq.push)
			{
				console.log("analytics is there");
				_gaq.push(['_trackEvent', category, action, label])
			}
			else
			{
				console.log("sorry no analytics is present");
			}
			try
			{
				( window.ga ) ? ga('send', 'event',category, action, label) : '' ;
				( window.ga ) ? ga('agg_Track.send', 'event',category, action, label) : '' ;
			} 
			catch(e) 
			{
				console.error('Error pushing data to universal analytics : '+e);
			}
		}
	})();
	
} )();

function checkingAnalytics()
{
	console.log("checking analytics");
	
	if(window._gaq  && _gaq.push)
	{
		console.log("analytics is there");
		//_gaq.push(['_trackEvent', category, action, label])
	}
else
	{
		console.log("sorry no analytics is present");
	}
	}

//Called when the api is ready to roll!
if( typeof conversionReady == 'function' )
{
	conversionReady();
}
