var ns = (navigator.userAgent.indexOf("Gecko") > 0) ? true : false;
var ie = document.all;
var viewWin = null;//the viewing window
var onceOnly = true;//to report a message once only
var isAjax = false;
var dontShowExitDialog = false;//so that when user tries to exit it shows the dialog message unless this is set to true.
var isTourismQuebecPage = false;
//http://rizwan/chat/CustomerRequest.jsp?switchId=11001&secure=false&link=index.html&contGroupId=1&bodyText=Hello
//onLoad="openViewingWindow(<%= link %>)"

function checkKey(e){//when enter key is pressed on textArea, then send message
   var inputArea = document.getElementById('inputArea');
   var applet = document.getElementById('chatApplet');
   var theCode;
   if (ie) theCode = e.keyCode;
   else if (ns) theCode = e.which;

   if (theCode==10){//for ctrl+Enter (works only in IE, for NS it still sends code=13)
	inputArea.value +='\n';
	return false;
   }//if
   if (theCode==13){
    if (isAjax) sendMessageAjax();
     else sendMessageToApplet();
     return;
   }//if
   if (inputArea.value.length == 1){
    if (isAjax) sendMessageNoTimeout("*custResponding*");
     else applet.custResponding();
   }//if
}//func


function setButtonState(set){
  var disableButton = true;
  if (set=="false") disableButton = true;
  else disableButton = false;
   var sendButton = document.getElementById("sendButton");
   var inputArea = document.getElementById("inputArea");
   sendButton.disabled=disableButton;
   inputArea.disabled=disableButton;
}//func

function checkKeyEvent(e){//when return key is pressed anywhere on the form
        return (e.keyCode == 13);
}//func

//roomName and chatSession can be null if it is NOT a quedChat
function sendRequestForChat(secure,link,conference,contGroupId,bodyText,presentation,switchId,quedChat,customerInterfacePage){//function called from CustomerRequest.jsp
  isAjax = true;//set this manually to toggle between Ajax/applet communication modes (ajax is recommended)
  var cName = document.getElementById("custName");
  var cEmail = document.getElementById("custEmail");
  var rName = document.getElementById("roomName");
  var chatS = document.getElementById("chatSession");
  var language = document.getElementById("language");

  var roomName = rName.value;
  var chatSession = chatS.value;
  var custName = TrimString(cName.value);//trim it
  custName = custName.replace(' ','_');//replace space by '_' char
  var custEmail = TrimString(cEmail.value);//trim it
  var queuedChat = (quedChat==null || quedChat=="false" || quedChat=="")?"false":"true";
  var selectedAgentName = "";
  var listArray;
  if (queuedChat=="false" && conference!="true"){//i.e. it is a direct chat request (for a qued chat this element may be missing from the form)
      selectedAgentName = document.getElementById("selectedAgentName");
      listArray = selectedAgentName.value.split(".");
  }else{
      selectedAgentName = "9999.Admin";//some arbitrary value (a chat request will never be sent out to the agent, look ChatApplet.java)
      listArray = selectedAgentName.split(".");
  }//else

  var agentId = listArray[0];//the agent id
  var agentName =listArray[1];//the agent name

  	if (selectedAgentName.value==''){
		alert('Sorry, no agent available at this time');
		return;
	}//if
        if (!evaluateFields(custName,custEmail)) return;//checks the validity of customers name and email address
        var jspToLoad = isAjax?customerInterfacePage:"CustomerInterface.jsp";
        var url = jspToLoad+"?custName="+custName+"&custEmail="+custEmail+"&switchId="+switchId+
                  "&secure="+secure+"&agentId="+agentId+"&link="+link+"&conference="+conference+"&contGroupId="+contGroupId+
                  "&bodyText="+bodyText+"&presentation="+presentation+"&quedChat="+queuedChat+"&roomName="+
                   roomName+"&chatSession="+chatSession+"&language="+language.value;
        parent.location = url;
        isTourismQuebecPage = customerInterfacePage.indexOf("TQ.jsp")!=-1;
        resizeAndSetLocation();
}//func

function resizeAndSetLocation(){//re-size and set location of parent window
        if (isTourismQuebecPage) parent.window.resizeTo(500,700);
        else parent.window.resizeTo(850,550);//width & height
        parent.window.moveTo(0,self.screen.height/8);//position it to the left of screen
}//func

/**
*     var url = "CustomerInterface.jsp?roomName="+roomName+"&chatSession="+chatSession+"&custName="+name+
              "&custEmail="+email+"&switchId="+switchId+"&secure="+secure+"&link="+link+"&fromWebWatch=true"+
              "&agentId="+agentId;
* @return
*/

//used to evaluate customer's name and email address
function evaluateFields(custName,custEmail){
  if (evaluateCustomerName(custName)==false) return false;
  if (evaluateCustomerEmail(custEmail)==false) return false;
  return true;//everything went through fine therefore return true
}//func

function evaluateCustomerName(custName){
        var pleaseEnter = document.getElementById("pleaseEnter");
        var noSpace = document.getElementById("noSpace");
  	if (custName==''){
		alert(pleaseEnter.value+'.');
		return false;
	}//if
        //spaces are allowed in the name now
//        if (custName.indexOf(' ')!=-1){//check for white spaces in name
//          alert(noSpace.value+".");
//          return false;
//        }//if
        return true;//all went well, return true
}//func

function evaluateCustomerEmail(custEmail){
        var sendTranscript = document.getElementById("sendTranscript");
        var emailInvalid = document.getElementById("emailInvalid");
	if (custEmail==''){
		//alert(sendTranscript.value+'.');
		return true;//allow an empty email to go through
	}//if
        if (!isEmail(custEmail)){
          alert(emailInvalid.value);
          return false;
        }//if
        return true;//all went well, return true
}//func

//---------------------------------------
function sendRequestForConference(secure,link,conference,contGroupId,bodyText,roomName,chatSession,switchId,agentId,presentation,lang){
  var cName = document.getElementById("custName");
  var cEmail = document.getElementById("custEmail");
  var custName = TrimString(cName.value);
  var custEmail = TrimString(cEmail.value);
  if (!evaluateFields(custName,custEmail)) return;//checks the validity of customers name and email address

//create the url
  var url = "CustomerInterfaceAjax.jsp?secure="+secure;
  url += "&link="+link;
  url += "&conference="+conference;
  url += "&contGroupId="+contGroupId;
  url += "&bodyText="+bodyText;
  url += "&roomName="+roomName;
  url += "&chatSession="+chatSession;
  url += "&switchId="+switchId;
  url += "&custName="+custName;
  url += "&custEmail="+custEmail;
  url += "&agentId="+agentId;
  url += "&presentation="+presentation;
  url += "&language="+lang;

  parent.location = url;
}//end func
//---------------------------------------

function TrimString(sInString) {
  sInString = sInString.replace( /^\s+/g, "" );// strip leading
  return sInString.replace( /\s+$/g, "" );// strip trailing
}//func

function isEmail(str) {
  // are regular expressions supported?
  var supported = false;
  if (window.RegExp) {
    var tempStr = "a";
    var tempReg = new RegExp(tempStr);
    if (tempReg.test(tempStr)) supported = true;
  }
  if (!supported) return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
  var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
  var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
  return (!r1.test(str) && r2.test(str));
}//func

//if message has multiple lines and also contains links, use this function
function checkMessageForTokens(message,td2){
    var lineArray = message.split("\n");
    for (i=0;i<lineArray.length;i++){
    if (lineArray[i].indexOf('http')!=-1 || lineArray[i].indexOf('www')!=-1){
        //now tokenize it by space chars
        var url = "";
        var listArray = lineArray[i].split(" ");//split it to word by word
        var msg = lineArray[i];
        for (k=0;k<listArray.length;k++){
          if (listArray[k].indexOf('http')!=-1){//if it only contains http (no need to check for 'www')
                 url = listArray[k];//add the entire url
                 msg = msg.replace(listArray[k],"");
                 break;
          }//if
          if (listArray[k].indexOf('www')!=-1){//if it only contains www add http to it
                 url = "http://"+listArray[k];
                 msg = msg.replace(listArray[k],"");
                 break;
          }//if
        }//for
        var newlink = document.createElement('a');
        sometext = document.createTextNode(msg+" <"+url+">");
 	newlink.setAttribute('target', 'linkWindow');
	newlink.setAttribute('href', url);
	newlink.appendChild(sometext);
	td2.appendChild (newlink);
        td2.appendChild(document.createElement("BR"));//also a new line
    }else{
        appendTableRow(lineArray[i]+'\n',td2);
    }//else
    }//for
}//func

function appendTableRow(message,td2){
    for (var i=0;i<message.length;i++){
        var aChar = message.charAt(i);
        if (aChar=='\n') td2.appendChild(document.createElement("BR"));
        else td2.appendChild (document.createTextNode(aChar));
    }//for
}//func

	var scrollVal = 0;
        var customerName = "";
	function addRow(name,message,messageType){//this function called by the applet only
		var tbody = document.getElementById('myTable').getElementsByTagName("TBODY")[0];
		var row = document.createElement("TR")
		var td1 = document.createElement("TD")
		td1.width = "10%";
                td1.scope = "row";
		td1.appendChild(document.createTextNode(name))
		var td2 = document.createElement("TD")
		td2.width = "90%";
                td2.scope = "row";
//                if (ns){//for NS just append the whole message
//                  td2.appendChild (document.createTextNode(message));
//                }else{
//                    for (var i=0;i<message.length;i++){
//                         var aChar = message.charAt(i);
//                         if (aChar=='\n') td2.appendChild(document.createElement("BR"));
//                         else td2.appendChild (document.createTextNode(aChar));
//                     }//for
//                }//else
//-------------------introduced to make a hyperlink if text contains http/www string
		if (message.indexOf('http')!=-1 || message.indexOf('www')!=-1){//grab any string that contains the following (http/www)
			checkMessageForTokens(message,td2);
		}else{//append as usual
                        appendTableRow(message,td2);
                }//else
//------------------------------------------------------------------------------


		row.appendChild(td1);
		row.appendChild(td2);
                tbody.appendChild(row);

                if (messageType=="true"){//color for agent message
                    if (isTourismQuebecPage){
                        row.style.color ="#333333";
		        row.style.fontSize ="9pt";
                    }else row.style.background ="#e7f7fc";
                }else{//color for customers' message
                    if (isTourismQuebecPage){
                        row.style.color ="#999999";
		        row.style.fontSize ="9pt";
                    }else row.style.background ="#fffdf0";
                }
   		var theDiv = document.getElementById("myDiv");
		var scrollbox = document.getElementById("scrollEnabled");
		scrollVal = theDiv.scrollTop;
		if (scrollbox.checked) row.scrollIntoView(true);
		else theDiv.scrollTop = scrollVal;
                var onTopBox = document.getElementById('alwaysOnTop');
                if (onTopBox.checked) window.focus();
                document.getElementById('inputArea').focus();
	}//function

function agentResponding(){
    var typedImage = document.getElementById('typingImage');
    typedImage.src = "images/typing.gif";
}//func

function resetImage(){
  var typedImage = document.getElementById('typingImage');
  typedImage.src = "images/transparent.gif";
}//func

function addImage(imageUrl){
  var theAgentImage = document.getElementById('agentImage');
  theAgentImage.src = imageUrl;
}//func

function enableSound(){
  var applet = document.getElementById('chatApplet');
  var soundCheckbox = document.getElementById('sound');
  applet.soundEnabled(soundCheckbox.checked);
}//func

function clearField(){
  var inputArea = document.getElementById('inputArea');
    inputArea.value = "";
    inputArea.focus();
}//func

function sendMessageToApplet(){
  var applet = document.getElementById('chatApplet');
  var inputArea = document.getElementById('inputArea');
  if (inputArea.value=="") return;//nothing was typed by the customer
  applet.broadcastMessage(inputArea.value+" *custMsg*");
  setTimeout('clearField()',100);
}//function


function openViewingWindow(link){
  var winParam = "WIDTH=700,HEIGHT=500,resizable=1,scrollbars,toolbar,location,dependent";
  viewWin = window.open(link,"ViewingWindow",winParam);
  setTimeout("moveViewingWindow()",1000);//move it after some time delay
  onceOnly = true;//reset it to true again as a new window has been opened
  setInterval("reportLinkToApplet()",5000);//report every five seconds
}//func

function moveViewingWindow(){//a helper function to openViewingWindow() which is invoked after some time
  if (viewWin==null || viewWin.closed) return;
  try{//can stop working if page loaded in viewer is not same domain
    viewWin.moveTo(self.screen.width-700,0);
    viewWin.focus();
  }catch(ex){}
}//func

function reportLinkToApplet(){
  var applet = document.getElementById('chatApplet');
  if (viewWin==null || viewWin.closed){
    //report to applet that viewing window is closed
    if (onceOnly){//report this message once only
      var msg = "The viewing window is closed *browserWindowClosed*";
      if (isAjax) sendMessage(msg);
      else applet.broadcastMessage(msg);
      onceOnly = false;
    }//if
    return;//don't do anything
  }//if
  var currentLoc = null;
  try{
     currentLoc = viewWin.location.href;
  }catch(ex){
    if (isAjax) pageViewed(null);
    else applet.pageViewed(null);
    return;
  }//catch
  if (isAjax) pageViewed(currentLoc);
  else applet.pageViewed(currentLoc);
//  setTimeout("reportLinkToApplet()",5000);//report every five seconds
}//function


function pushPage(someUrl){
  if (viewWin==null || viewWin.closed) openViewingWindow(someUrl);
  else viewWin.location = someUrl;
  viewWin.focus();
}//func

function closeViewingWindow(){
  if (viewWin==null || viewWin.closed) return;
  viewWin.close();
}//func

function askBeforeQuit(reallyWish){
      if (dontShowExitDialog) return ;//not to show the dialog if it is not needed
      return reallyWish;
}//end askBeforeQuit

//---------functions for modalDia.jsp
function setReturnValue(affirmative){
	if (affirmative){
		var yes = document.getElementById('yesButton');
		var no = document.getElementById('noButton');
		var question = document.getElementById('questionLabel');
		var theDiv = document.getElementById('myDiv');
		yes.style.visibility = 'hidden';
		no.style.visibility = 'hidden';
		question.style.visibility = 'hidden';
		theDiv.style.visibility = 'visible';
	}else{
                if (ns) top.opener.dialogWin.returnedValue = "0";
                else window.returnValue = "0";
                window.close();
	}//else
}//function

function acceptChat(accept){
	var name = TrimString(document.getElementById('nameField').value);
	var email = TrimString(document.getElementById('emailField').value);
	if (accept){
		if (!evaluateFields(name,email)) return;
                if (ns) top.opener.dialogWin.returnedValue = name+"|"+email;
	        else window.returnValue = name+"|"+email;
	}else{
          if (ns) top.opener.dialogWin.returnedValue = "0";
          else window.returnValue = "0";
	}//else
        window.close();//closes the modalDia window
}//func
//---------end functions for modalDia.jsp

