﻿var focused = false;
var lastNotify = new Date();
var nextMsgId = 0;
var MsgPrefix = "vMsg_";
var msgTxtBox = "vMESSAGE";
var typingStatus = "vTYPINGSTATUS";
var timerDivId = "vStopwatch";
var swfsndId = -1;
var wasUpdated = false;
var disableRightClick = false;

if ('undefined' != typeof HTMLAnchorElement) {
    if (!HTMLAnchorElement.prototype.click) {
        HTMLAnchorElement.prototype.click = function() {
            var ev = document.createEvent('MouseEvents');
            ev.initEvent('click', true, true);
            if (this.dispatchEvent(ev) !== false) {
                //safari will have already done this, but I'm not sniffing safari
                //just in case they might in the future fix it; I figure it's better
                //to trigger the action twice than risk not triggering it at all
                document.location.href = this.href;
            }
        }
    }
}

function debug(obj) {
    if ('undefined' != typeof console)
        console.log("%o", obj);
}

function scrollDiv() {
    var d;
    if ((d = document.getElementById('vCONVERSATIONCONTAINER')) && ('undefined' != typeof d.scrollTop)) {
        d.scrollTop = 5000;
    }
    setMessageFocus();  
}

function checkEnter(e) { //e is event object passed from function invocation
    var characterCode;  // literal character code will be stored in this variable
    if (e && e.which) { //if which property of event object is supported (NN4)
        e = e;
        characterCode = e.which;  //character code is contained in NN4's which property
    }
    else {
        if (typeof event == 'undefined')
            return true;
            
        e = event;
        characterCode = e.keyCode;  //character code is contained in IE's keyCode property
    }

    if (characterCode == 13) { //if generated character code is equal to ascii 13 (if enter key)
        SendMsg();
        return false;
    } else if (characterCode == 116) {
        //e.returnValue = false;
        //if (typeof event != undefined && event.keyCode)
        //    event.keyCode = 0;
        //e.cancelBubble = true;
    } else {
        var now = new Date();
        var elapse = now.getSeconds() - lastNotify.getSeconds();
        var sameMinute = now.getMinutes() - lastNotify.getMinutes();
        if (sameMinute != 0 || elapse >= 10) {
            PageMethods.SetTypingNotification(OnNotificationComplete);
            lastNotify = new Date();
        }
        var messageBox = document.getElementById(msgTxtBox);
        if (messageBox) {
            messageBox.focus();
            //setMessageFocus();
        }
        return true;
    }
}

//document.attachEvent("onkeydown", page_onkeydown_handler);
document.onkeydown = checkEnter;

function page_onkeydown_handler(e) { 
    switch (event.keyCode) {
        case 116: // 'F5'
            if (window.event) {
                window.event.returnValue = null;
                event.keyCode = 0;
            }
            else
                e.preventDefault();
        
            /*
            if(event.returnValue)
                event.returnValue = false;

            event.keyCode = 0;
            
            if(event.cancelBubble)
                event.cancelBubble = true;
            */
                
            //window.status = "You can't refresh this page.............";
            break;
    } 
}

function AgentTyping(isAgent) {
    var tStatus = document.getElementById(typingStatus);
    if (tStatus != null) {
        if (isAgent) {
            tStatus.style.display = 'inline';
        } else {
            tStatus.style.display = 'none';
        }
    }
}

function CheckMessage() {
    debug("CheckMessage()");
    PageMethods.GetMessages(OnMessageNotificationComplete);
    //setMessageFocus();
}

function SendMsg() {
    var messageBox = document.getElementById(msgTxtBox);
    if (messageBox) {
        var dt = new Date();
        var tempId = dt.getHours().toString() + dt.getMinutes().toString() + dt.getUTCMilliseconds().toString();

        PageMethods.SendMessage(messageBox.value, tempId, OnMessageNotificationComplete);

        if (messageBox.value != "") {
            if (typeof _visitorName != 'undefined' && _visitorName)
                AddMessage(tempId, _visitorName, messageBox.value, _visitorName);
        }

        messageBox.value = "";
        setMessageFocus();
    }
}

function UpdateCheck() {
    if (wasUpdated) {
        setTimeout("UpdateCheck()", 7000);
        wasUpdated = false;
    } else {
        PageMethods.GetMessages(OnMessageNotificationComplete);
    }
}

function AddMessage(MessageID, UserName, Message, VisitorName, tempId) {
    wasUpdated = true;

    //debug("AddMessage:" + MessageID + " Visitor:" + UserName);
    nextMsgId = parseInt(MessageID);

    if (tempId) {
        if (document.getElementById(MsgPrefix + tempId) != null) {
            document.getElementById(MsgPrefix + tempId).id = MsgPrefix + MessageID;
            //debug("found tempid=" + tempId);
        } else {
            //debug("not found tempid=" + tempId);
        }
    }

    if (document.getElementById(MsgPrefix + MessageID) == null) {
        if (UserName == "visitor")
            UserName = VisitorName;

        var msgClass = "vMsgAgentName";
        var txtClass = "vMsgAgentText";
        if (VisitorName == UserName) {
            msgClass = "vMsgVisitorName";
            txtClass = "vMsgVisitorText";
        }

        var newMessage = "<span class=\"" + msgClass + "\">" + UserName + ":</span> <span class=\"" + txtClass + "\">" + Message + "</span>";

        if (UserName == "System" || UserName == "Notice")
            newMessage = "<span class=\"vSystemMsg\">" + newMessage + "</span>";

        newMessage = "<span id=\"" + MsgPrefix + MessageID + "\" name=\"" + MsgPrefix + MessageID + "\" class=\"vMsgLine\">" + newMessage + "</span>\n";

        var d;
        if ((d = document.getElementById('vCONVERSATIONCONTAINER')) && ('undefined' != typeof d.scrollTop)) {
            d.innerHTML += newMessage;
            scrollDiv();
            PlaySound();
        }
    }
}

function PushPage(pushurl, MessageID) {
    if (document.getElementById(MsgPrefix + MessageID) == null) {
        eval("window.open('" + pushurl + "', 'VelaroCoBrowsing');");
    }
}

function OpenTranscript(print) {
    disableExitMsg();
    if (typeof roomid != 'undefined') {
        var printSettings = "";
        if (print)
            printSettings = "&print=yes&email=noreply@velaro.com";

        this.newWin = window.open('EmailTranscript.aspx?rid=' + roomid + printSettings, 'VelaroEmail', 
                'toolbar=no,location=no,directories=no,menubar=no,status=no,scrollbars=no,resizable=yes,replace=no'); 
        
        this.newWin.focus(); 
        this.newWin.opener = window;
    }
    enableExitMsg();
}

function EarlyPostscript() {
    disableExitMsg();
    if (typeof postsurveyurl != 'undefined') {
        if (postsurveyurl != "") {
            this.newWin = window.open(postsurveyurl, 'VelaroFeedback',
                'toolbar=no,location=no,directories=no,menubar=no,status=no,scrollbars=no,resizable=yes,replace=no');

            this.newWin.focus();
            this.newWin.opener = window;            
        }
    }
    enableExitMsg();    
}

var soundEnabled = true;
function ToggleSound() {
    soundEnabled = !soundEnabled;
    debug("sound=" + soundEnabled);
    var soundOn = document.getElementById("vSOUNDON");
    if (soundOn)
        soundOn.style.display = (!soundEnabled ? "none" : "inline");

    var soundOff = document.getElementById("vSOUNDOFF");
    if (soundOff)
        soundOff.style.display = (!soundEnabled ? "inline" : "none");
}

function PlaySound() {
    if (!soundEnabled)
        return;

    debug("sound enabled");
    if (typeof soundUrl != 'undefined') {
        document.getElementById("sndDummy").innerHTML =
                "<embed src=\"" + soundUrl + "\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
    }
}

function SendFocus() {
    if(!focused)    
        self.focus();
}

function hasFocus(bol) {
    focused = bol;
}

function OnMessageNotificationComplete(result, methodName) {
    if (result != '') {
        var message_array = result.split("%%");
        var currentMsg;
        for (i=0;i<message_array.length;i++) {
            try {
                currentMsg = message_array[i];
                debug(message_array[i]);
                eval(message_array[i]);                
            }
            catch (ex) {
                debug("error: " + ex + " : " + currentMsg);
            }
        }
        
        //setMessageFocus();
    }
}

function OnNotificationComplete(result, methodName) {
    if (result != '') {
    }
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

function confirmExit() {
    document.location = document.location + '&closeme=yes';
}

var usesurveytemp = "";
function disableExitMsg() {
    if (typeof usesurvey != 'undefined') {
        //usesurveytemp = usesurvey;
        usesurvey = "";
        window.onbeforeunload = null;
        //setTimeout("enableExitMsg()", 5000);
    }

    return true;
}

function enableExitMsg() {
    if (typeof usesurvey != 'undefined') {
        usesurvey = usesurveytemp;
        window.onbeforeunload = onBeforeUnloadAction;
    }

    return true;
}

function setMessageFocus() {    
    var messageBox = document.getElementById(msgTxtBox);
    if (messageBox) {
        setCursor(messageBox, messageBox.value.length, messageBox.value.length);
    }
    //debug("setMessageFocus()");
}

function setMessageFocusToBegin() {
    var messageBox = document.getElementById(msgTxtBox);
    if (messageBox) {
        setCursor(messageBox, 1, 1);
    }
    debug("setMessageFocus()");
}

function setCursor(el, st, end) {
    if (el.setSelectionRange) {
        el.focus();
        el.setSelectionRange(st, end);
    }
    else {
        if (el.createTextRange) {
            range = el.createTextRange();
            range.collapse(false);
            range.select();
        }
    }
}

/* Begin Stopwatch */
var nowHours = 0;
var nowMins = 0;
var nowSecs = 0;

function tickingTheTock() {
    //debug("tickingTheTock(): Calculating Time"); 
    if (nowSecs > 59) {
        nowSecs = 0;
        nowMins++;
    }

    if (nowMins > 59) {
        nowHours++;
        nowMins = 0;
    }

    showHours = chkTick(nowHours);
    showMins = chkTick(nowMins);
    showSecs = chkTick(nowSecs);

    var tmrDiv = document.getElementById(timerDivId);

    nowSecs++;

    if (tmrDiv) {
        tmrDiv.style.display = 'inline';
        tmrDiv.innerHTML = showHours + " : " + showMins + " : " + showSecs;
        tickTimer = setTimeout("tickingTheTock()", 1000);
    } else {
        debug("tickingTheTock(): TimerDiv not found"); 
    }
}

function chkTick(n) {
    if (n < 10) {
        n = "0" + n;
    }
    return n;
}
/* End Stopwatch */

/* Disable Right Click */
var isNS = (navigator.appName == "Netscape") ? 1 : 0;
var EnableRightClick = 0;
if (isNS) document.captureEvents(Event.MOUSEDOWN || Event.MOUSEUP);
function mischandler() {
    if (EnableRightClick == 1) { return true; }
    else { return false; }
}
function mousehandler(e) {
    if (EnableRightClick == 1) { return true; }
    var myevent = (isNS) ? e : event;
    var eventbutton = (isNS) ? myevent.which : myevent.button;
    if ((eventbutton == 2) || (eventbutton == 3)) return false;
}
function keyhandler(e) {
    var myevent = (isNS) ? e : window.event;
    if (myevent.keyCode == 96)
        EnableRightClick = 1;
    return;
}

if (disableRightClick) {
    document.oncontextmenu = mischandler;
    document.onmousedown = mousehandler;
    document.onmouseup = mousehandler;
}
/* End Disable Right Click */


function onBeforeUnloadAction() {
    if (typeof usesurvey != 'undefined') {
        if (usesurvey != "") {
            PageMethods.VisitorExitChat(OnNotificationComplete);
            window.location = usesurvey;
        }
    }
    if (typeof msgcancel != 'undefined') {
        var msg = msgcancel;
        return msg;
    }

    if (typeof event != 'undefined')
        if (typeof event.cancelBubble != 'undefined')   
            event.cancelBubble = true;
}

window.onbeforeunload = onBeforeUnloadAction;
