/******************************************************************************
 [Alaska_ActiveAgent.js]
 
 Copyright (C) 2007 Next IT Corporation, Inc. Spokane, WA. All Rights Reserved. 
 This document is confidential work and intellectual property of Next IT 
 Corporation. Permission to copy, distribute or use any portion of this file 
 is prohibited without the express written consent of Next IT Corporation.

 Version Date        Name        Changes in:  BasePage     Agent
 ----------------------------------------------------------------------------
 0.9.0   07/25/2007  smccabe     
     Refactored all page info and page error out into it's own file.  
     This file contains only agent window specific functions.
     
*******************************************************************************/

// instance of ActiveAgent_PageInfo used in the ActiveAgent_SetPageInfo function
var ActiveAgent_PageName = 'Agent.aspx';
var ActiveAgent_AgentWindow = null;

var StartLiveChatWithPromptFlag = false;
var UserFirstName = "";
var DefaultUserFirstName = "You Asked";
//var location ;	//this is put in here for the Alaska Easy Biz page that tries to redirect agent.\  As of 2/15/08, took out so agent will vocalize in Safair.  Alaska to modify EasyBiz code.

// instance of ActiveAgent_WebCheckInStatus used in the ActiveAgent_WebCheckInStatus function
//var _AA_WebCheckIn = new ActiveAgent_WebCheckInStatus()

//////////////////////////////////////////////////////////////////////////////////////////
/*
This section is to capture a question sent on load (denoted by "q" in the querystring params).
If have initial question to process, then don't play inital welcome prv, wait and only play prv
for the answer.

*////////////////////////////////////////////////////////////////////////////////////////
var Launch_SentQuestion = false; // Detect the welcome message, and send the query string question after it comes back
var Launch_QuestionQueryStart = "?q=";
var Launch_Query = decodeURIComponent(document.URL);
Launch_Query = Launch_Query.replace(/^\s+|\s+$/g,"");   //trim spaces

var Launch_QuestionQueryIndex = Launch_Query.indexOf(Launch_QuestionQueryStart);

function CheckDisableSound()
{   
   	if (CheckForQuerystringQuestion())
	{   
	    //disable sound so welcome message won't play since have a question to submit (otherwise welcome prv will get cut off part way through)
	    Agent.IsSoundEnabled = false;   
	}
}
function CheckForQuerystringQuestion()
{
	//make sure there is querystring parameters AND value (so they don't send blank through)
	if (Launch_QuestionQueryIndex > -1 && Launch_QuestionQueryIndex < (Launch_Query.length - Launch_QuestionQueryStart.length))
	{ 
        return true;
	}	
	return false; 
}
			
function DelayedInit()
{   	
	if (CheckForQuerystringQuestion())
	{
		var questionToSend = Launch_Query.substring(Launch_QuestionQueryIndex + Launch_QuestionQueryStart.length);
		Agent.IsSoundEnabled = true;
		Launch_SentQuestion = true;
		AgentTemplate.AskAgent(questionToSend);
	}
}
	 
function ActiveAgent_HandleInitialQuestion()
{
    if (!Launch_SentQuestion)
	{
		setTimeout(DelayedInit, 50); // Must delay, so that the welcome message can render welcome before the question asked
	    Launch_SentQuestion = true;
	}
}

////////////////////////////////////////////////////////////////////////////////
// Function:    ActiveAgent_PageLoadTasks
// Description:
//      function called by Jenn to continually check for alaska page errors
//      Also attach to AgentResponse event and filter responses to non-handled
//      page errors
//      
////////////////////////////////////////////////////////////////////////////////
function ActiveAgent_PageLoadTasks()
{
    //hide the Live Chat link initally because FPML controls whether it is shown or not.
    ShowHideLiveChatLink(false);
    // if the page isn't already, start polling for error info
    if(_AA_PageInfo.GetErrorTimerID == 0)
    {
        _AA_PageInfo.GetErrorTimerID = setInterval('_AA_PageInfo.GetPageError()', _AA_PageInfo.PollingInterval);
    }
    
    // if the page isn't already, start polling for web check in status
    // if(_AA_WebCheckIn.WebCheckInTimerID == 0)
    // {
    //    _AA_WebCheckIn.WebCheckInTimerID = setInterval('_AA_WebCheckIn.GetWebCheckInStatus()', _AA_WebCheckIn.PollingInterval);
    // }

    //get IP
    IPCheck = document.getElementById('_IP').value;
    
    // hook into the OnBeforeQuestionSent Agent event.  before the question is sent, we'll append page information
    Agent.attachEvent("OnBeforeQuestionSent", ActiveAgent_GetPageInfo);    
	Agent.attachEvent("OnAppCall", ActiveAgent_HandleAppCalls);
    Agent.attachEvent("OnAgentResponse", ActiveAgent_HandleInitialQuestion);
    Agent.attachEvent("OnAgentResponse", ActiveAgent_HandleAgentResponse);
    Agent.attachEvent("OnChatStarted", ActiveAgent_HandleChatStarted);
    Agent.attachEvent("OnChatStaffConnected", ActiveAgent_HandleChatStaffConnected);
    Agent.attachEvent("OnChatEnded", ActiveAgent_HandleChatEnded);
    Agent.attachEvent("OnChatEnded", PromptForSurvey);
    
    //check to see if cookies are disabled
    if(!AreCookiesEnabled())
    {
	    Agent.DoAppEvent("CookiesDisabled", "");
    }
    Agent.DoAppEvent("NewUser", "Jenn");    //will tell fpml to disply welcome message

    window.resizeTo(PopupTemplate.Width, PopupTemplate.Height); 
};

function DoTrainMe()
{
	var trainwin = window.open('TrainMe.aspx', 'trainme', 'top=100px,left=200px,width=375px,height=285px,scrollbars=no,menubar=no,resizable=no,location=no,status=no,titlebar=no,toolbar=no');
};

//ActiveAgent_WebCheckInStatus.prototype.PollingInterval = 1000; //ms
//ActiveAgent_WebCheckInStatus.prototype.GracePeriod = 2000; //ms
//ActiveAgent_WebCheckInStatus.prototype.CookieName = 'ActiveAgent_PageInfo';
//ActiveAgent_WebCheckInStatus.prototype.URLProperty = 'URL';
//ActiveAgent_WebCheckInStatus.prototype.FormNameProperty = 'FormName';
//ActiveAgent_WebCheckInStatus.prototype.DateTimeProperty = 'DateTime';    

//function ActiveAgent_WebCheckInStatus() 
//{
//    this.WebCheckInTimerID = 0;
//    this.WebCheckInEventDone = false;

//    this.GetWebCheckInStatus = function()
//    {
//        var formName = this.GetWebCheckInCookieValue();
//        //check for webCheckIn form.  This code will be moved once we implement the PNR events
//		if(formName == 'PrintBoardingPass')
//		{
//			if(this.WebCheckInEventDone == false)
//			{
//				this.WebCheckInEventDone = true;
//				//send AppEvent to FPML
//				 Agent.DoAppEvent('WebCheckinAlert', 'General');
//			}
//		}
//		else
//		{
//			this.WebCheckInEventDone = false;
//		}           
//    };
//    
//    this.GetWebCheckInCookieValue = function()
//    {
//		var WebCheckInCookie;
//		
//		try
//		{
//			WebCheckInCookie = GetCookie(this.CookieName);
//		}
//		catch(ex)
//		{
//			_ActiveAgent_HandleError(ex);
//		}
//		
//		var now = new Date();
//		var rtn;
//		
//		if(WebCheckInCookie != null)
//		{
//			var formName = WebCheckInCookie.Values[this.FormNameProperty];
//		    var dateTime = WebCheckInCookie.Values[this.DateTimeProperty];

//			// if now is between the datetime and the datetime + polling interval + 2 seconds,
//			// return the error code.  else return null.
//			if ((now.getTime() - dateTime) < (this.PollingInterval + this.GracePeriod))
//			{
//				rtn = formName;
//			}
//		}
//	    
//	    return rtn;
//    };
//}

function ActiveAgent_HandleAgentResponse(obj)
{
	var appendViewPage = true;
	var NavUrl = false;
	var NavUrlValue = '';
	var showLiveChatLink = false;
	
	if (obj.ClientScriptCalls != null)
	{
	    for(var i = 0; i < obj.ClientScriptCalls.length; i++)
	    {
	        if(obj.ClientScriptCalls[i].Name == "AppendLinkToResponse")
	        {
	            appendViewPage = false;
	        }
	        else if(obj.ClientScriptCalls[i].Name == "NavUrl")
	        {
	            NavUrl = true;
	            NavUrlValue = obj.ClientScriptCalls[i].Value;
	        }
	        else if(obj.ClientScriptCalls[i].Name == "ShowLiveChatLink")
	        {
	            showLiveChatLink = true;
	        }
	    }
	}
	
	if ( NavUrl && NavUrlValue.length > 0 && appendViewPage)
	{
	    AppendPageLink(obj, NavUrlValue, "View Page");
	}
	
	ShowHideLiveChatLink( showLiveChatLink );
	SetUserInputFocus();
};

function ActiveAgent_HandleAppCalls(br, e)
{
	switch (e.Name)
	{
	    case "AppendLinkToResponse":
        case "OfferUserSurvey":
        case "DNNAppendLinkToResponse":
	        var linkParts = e.Value.split('|');
	        if (linkParts.length = 2)
	        { 
	            AppendPageLink(br, linkParts[0], linkParts[1]);
	        }
            break;			
        case "SetUserFirstName":
            UserFirstName = e.Value;
            break; 
        case "GoToLiveChat":
            AgentTemplate.StartChat();
            break;
        case "AppendMultiCity":
			br.Response += e.Value;
			break;
    }
};

function ActiveAgent_HandleChatStarted(agentID, cb)
{
    //header image
    document.getElementById('headerImageTd').className = 'connect_bg';
    document.getElementById('imgHeader').src = 'images/gap.gif';
   //title image
    document.getElementById('headerTitleTd').className = 'title_live';
    document.getElementById('imageTitle').src = 'images/gap.gif';

    
    document.getElementById('imgAskMe').src = 'images/mid_ask_connect.gif';
	document.getElementById('askMeTR').className = 'midbgconnect';
    if(UserFirstName != "")
    {
		Agent.User.Name = UserFirstName;
	}
	else
	{
		Agent.User.Name = DefaultUserFirstName ;
	}
};

function ActiveAgent_HandleChatStaffConnected(agentID, cb)
{
    //header image
    document.getElementById('headerImageTd').className = 'live_bg';
    document.getElementById('imgHeader').src = 'images/gap.gif';
   //title image
    document.getElementById('headerTitleTd').className = 'title_live';
    document.getElementById('imageTitle').src = 'images/title_live_connect.gif';
   
    document.getElementById('imgAskMe').src = 'images/mid_ask_connect.gif';
	document.getElementById('askMeTR').className = 'midbgconnect';
};

function ActiveAgent_HandleChatEnded(agentID, cb)
{
    //header image
    document.getElementById('headerImageTd').className = 'jenn_bg';
    document.getElementById('imgHeader').src = 'images/jenn.gif';
   //title image
    document.getElementById('headerTitleTd').className = 'title_big';
    document.getElementById('imageTitle').src = 'images/title_bar.gif';
    document.getElementById('imgAskMe').src = 'images/mid_ask.gif';
	document.getElementById('askMeTR').className = 'midbg';
    StartLiveChatWithPromptFlag = false;
    Agent.User.Name = DefaultUserFirstName ;
};

function AppendPageLink(AgentResponseObject, URL, linkText)
{
    var link = '<img src="images/gap.gif" width="5px" /> <a href="javascript:;" onclick="Agent.fireEvent(\'OnRedirect\', \'' + URL + '\')">' + linkText + '</a>';
    
    var responseTextEndIndex = AgentResponseObject.Response.indexOf("<br");
    if(responseTextEndIndex <= 0)
    {
        responseTextEndIndex = AgentResponseObject.Response.indexOf("<table class=\"aa_heresmore\"");
    }
    
    if( responseTextEndIndex > 0)
    {
        AgentResponseObject.Response = AgentResponseObject.Response.substring(0, responseTextEndIndex) + link + '<br />' + AgentResponseObject.Response.substr(responseTextEndIndex); 
    }
    else
    {
        AgentResponseObject.Response += link;
    }	            
};

function ShowHideLiveChatLink(ShowLink)
{
    if( ShowLink )
    {
        document.getElementById("LiveChatDiv").style.display = 'inline';
    }
    else if ( StartLiveChatWithPromptFlag )
    {
        document.getElementById("LiveChatDiv").style.display = 'inline';
    }
    else
    {
        document.getElementById("LiveChatDiv").style.display = 'none';
    }
};

function StartLiveChatWithPrompt()
{
    if(UserFirstName == "")
    {
        StartLiveChatWithPromptFlag = true;
        Agent.User.Name = "Name";
        Agent.DoAppEvent("PromptForName", "");
    }
    else
    {
        AgentTemplate.StartChat();
    }
    return false;
};

function EndLiveChat()
{
    StartLiveChatWithPromptFlag = false;
    Chat.End('User Ended', true);
	return false;
};

function PromptForSurvey()
{
    Agent.DoAppEvent("ActiveChatSessionEnded", "");
};

function SetUserInputFocus()
{
    // only set focus if our frame is shown and our window has focus
   
    if(AgentTemplate != null )
	{	if(AgentTemplate.InputBox.disabled == false)
		{
			AgentTemplate.InputBox.focus();
		}
	}
};

function GoHome()
{
    Agent.fireEvent("OnRedirect", "http://www.alaskaair.com");
};

/*
function InitJennDisable()
{
      //SOAPClient.Timeout = 2000; // Shorten timeout for testing (DELETE ME)
      
      var timeoutWait = 30000; // Pause 30 seconds if a timeout occurs
      var timeoutMessage = 'I\'m sorry. I\'m currently overworked and need a vacation.  Try again when I can fit you into my schedule.';
      var timeoutPRV = ''; // We can reference a PRV voice for this message as well
      
      // Catch good responses so we can wind down inflated wait times
      Agent.attachEvent("OnAgentResponse", ReduceTimeoutWait);

      // Override base error handling (capture timeout for friendly message)
      Agent._CheckErrorBase = Agent._CheckError; // Core/Base reference
      Agent._CheckError = function(o) // Copied from core, then modified
      {
            if (o instanceof Error)
            {	
				  if (GetErrorMessage(o) != 'A network timeout occurred') // Supress the network timeouts
                  {
                        throw o; // Throw the error
                  }
                  else if (AgentTemplate) // If we are including the AgentTemplate.js we can show the message in a system message
                  {
                        // We want to pretty up the message, and disable the UI for a period of time
                        Agent.Ignore(o); // Ignore the response
                        AgentTemplate.AppendResponse(AgentTemplate.AgentName, timeoutMessage, false);
                        
                        if (Agent.IsSoundEnabled && timeoutPRV.length > 0)
                              Agent.fireEvent("OnPlaySound", timeoutPRV);
                        
                        if (timeoutWait < 30000) // Ensure that it doesn't dip below the minimum level
                              timeoutWait = 30000;
                        
                        DisableJenn(timeoutWait);
                        
                        // Increase wait time for consecutive timeouts, decrease back to original after some good responses
                        if (timeoutWait < 120000)
                              timeoutWait += 30000; // Add another 30 seconds to the wait for each timeout that occurs
                  }
            }
      };
      function DisableJenn(timeout)
      {
            DisableInputs(true);
            AgentTemplate.DisableUI();
            $('tdChatHistory').className = 'responsebgDisabled';
            $('tdSound').className = 'responsebgDisabled';
			setTimeout(EnableJenn, timeout);
      };
      function EnableJenn()
      {
            DisableInputs(false);
            $('tdChatHistory').className = 'responsebg';
            $('tdSound').className = 'soundbg';

            AgentTemplate.EnableUI();
      };
      function ReduceTimeoutWait(br)
      {
            if (timeoutWait > 30000)
                  timeoutWait -= 15000; // Subtract 15 seconds for each good response, until we're back to original value
      };

};
*/