//This is called when all the dependent JS files are loaded.
var _inactiveTimer;
var _inactiveInterval = 5000; // Inactive timer polling interval set as 5 sec

var _inactiveMessageTimer;
var _inactiveMessageCounter = 0;
var _inactiveMessageTimeout = 60; // 60 sec to respond inactivity popup
var _inactiveMessage = "You are logout due to inactive" ;

var _cbinstance = null;
var _pending = false;
var _isUIcallBackRegistered = false;
var _IsInactiveLogOut = false; 
var _burst = false;
var annotate;
var _cbconfig;

//Sample: use in custom logic when html head/body css style link or src image tags are parsed to convert the relative to absolute path 
//var replaceContextNameFromPath = "/local/";

function cobrowseInit() {
    _pending = false;
    document.onkeydown = preventTabNavigation;
    _cbconfig = new AvayaCoBrowseClientServices.Config.CoBrowseConfiguration();
    console.info('AVCOBROWSE Engine (Customer) Load Complete');
    console.info('[jQuery]: ' + $().jquery);
    _cbconfig.serverInfo.hostName = "localhost";
    _cbconfig.serverInfo.port = '8443';
    _cbconfig.serverInfo.isSecure = true;
    _cbconfig.enabled = true;

    var _coBrowseCustomerClientService = new AvayaCoBrowseClientServices();
    _coBrowseCustomerClientService.registerLogger(window.console);
    

    var cssUrlProperties = "content,background-image";
    var selectors= "span,div"; 
    try{
        //Set the avservice context name supported context names are {"services", "avservice"} default is services 
        //_coBrowseCustomerClientService.initCustServiceContext("avservice");
        _cbinstance=_coBrowseCustomerClientService.createCustomerCobrowse(_cbconfig);
        if(_cbinstance)
        {
                _cbinstance.addElementIDToRemove("cbeToolbar");
                // Call Hover API to support Pseudo elements in web page
                _cbinstance.setCSSHoverFile('{"css": ""}');
				
				//To support the images specified in the internal or inline style sheet
                _cbinstance.addUrlPropertySelectors(cssUrlProperties, selectors);
                _cbinstance.addClassSelForPseudoElemtBefore("content",'.icon-image[_ngcontent-wwx-c0]');
                _cbinstance.addClassSelForPseudoElemtAfter("content",'.icon-header[_ngcontent-wwx-c0]');
                
                _cbinstance.dropdownSupport();
                // Uncomment below code to test child textnode sync between Agent and the Customer
                // _cbinstance.enableChildNodeSync();
                // Uncomment below code if there is an iframe with Cross Origin Content
                // _cbinstance.removeCrossOriginIFrameContent();
				$('#id-of-ui-container').bind('DOMNodeInserted',function(event){
					
					if(!_burst){
						setTimeout(function(){ 
							// Support UI navigation in single page app.
							_cbinstance.setCSSHoverFile('{"css": "","navigate":true');
							_burst = false;
							console.log('avinash burst constrol');
						}, 3000);
					}
					
					_burst = true;
					
				});
                console.info('Successfully Initilized');
                registerAPIcallback();
                _cbinstance.start();
        }
	}catch(e){
		console.log(e);
	}
	
    function preventTabNavigation(event) {
        if (!event) {
            event = window.event;
        }

        var keyCode = event.keyCode;
        
        
        if (  event.keyCode === 9 && (_cbinstance.getCustomerData().getAgentControlState() === AvayaCoBrowseClientServices.Services.Cobrowse.Common.AgentControlState.AGENTCONTROLTRUESTATE) ) {

            if (navigator.userAgent.toLowerCase().indexOf("msie") == -1) {
                event.stopPropagation();
            } else {
                event.returnValue = false;
            }

            return false;
        }
    }
    ;
    
    
}

function registerAPIcallback() {
    _cbinstance.addOnConnectionResetCallback(function (evt) { //TODO :: sync with init
        console.info('UI: AV.COBROWSEAPI [onReady] - BEGIN >>>> ');
        
        createUI();
		if(!_toolbarCreated){
			registerAnnotationActions();
			_toolbarCreated = true;
		}
		
		if (!_isUIcallBackRegistered) {
            registerCallbacksUI();
            _isUIcallBackRegistered = true;
         }
        if (evt.resume) {
            showProgressUI('Reconnecting ......');
        } else {
            resetUI(); //IDLE State
        }
        console.info('UI: AV.COBROWSEAPI [onReady] - END >>>> ');
    });

    _cbinstance.addOnConnectionCallback(function (evt) {
        console.info('UI: AV.COBROWSEAPI [onStart] - BEGIN >>>> ');
        // TODo: Fetch from dataset 

        if (evt.paused) {
            _pending = evt.ctrlReqPending;
            evt.ctrlReqPending = false;
        }
        connected(evt.paused, evt.agentControl, evt.agentName, evt.customerName, evt.ctrlReqPending);
        if (evt.agentName) {
            setLiveUserStatus('Co-browsing is in progress!');
            if (!evt.agentControl)
                if (!evt.paused)
                    $('#cbePauseBtn').show();
        } else {
            setLiveUserStatus('Waiting for agent');
            $('#cbePauseBtn').hide();
        }
        if (evt.key) {
            $('#cbeKey').text('Key: ' + evt.key);
        }
        setDisclaimerText('Privacy policy:\nCSO will not see sensitive data like SSN, Card numbers.');

        console.info('UI: AV.COBROWSEAPI [onStart] - END >>>> ');
    });

    _cbinstance.addOnConnectionFailureCallback(function (evt) {
        console.info('UI: AV.COBROWSEAPI [onFail] - BEGIN >>>> ');
        updateUIonError(evt.msg);
        //TODO: stopinactive timer
        console.info('UI: AV.COBROWSEAPI [onFail] - END >>>> ');
    });

    _cbinstance.addOnSessionCloseCallback(function (evt) {
        $('#inactiveModal').modal('hide');
	stopInactiveMessageTimer();
        console.info('UI: AV.COBROWSEAPI [onSessionClose] - BEGIN >>>> ');
        resetUI();
        //TODO - stopInactiveTimer();
        if ($('#cbeLogoutModelDiv')) {
            $('#cbeLogoutModelDiv').modal('hide');
        }
        var str = evt.msg.split(":");
        var title = 'Session Closed by the Agent';
        var message = 'You can start another session or close the browser';

        if (str.length > 0) {
            if (str[0] === "inactive_timeout") {
                title = 'Inactive Session by Agent';
            } else if (str[0] === "session_timeout") {
                title = 'Session Timeout by System';
            } else {
                title = 'Session Closed by the Agent';
            }
            message = str[1];
        }


        $('#cbeSessionCloseDiv').modal('show');
        showSessionCloseConfirmationModal({
            title: title,
            message: message,
            type: 'success'
        });

        console.info('UI: AV.COBROWSEAPI [onSessionClose] - END >>>> ');
    });



    _cbinstance.addOnControlRequestCallback(function (evt) {
        _pending=true;
        console.info("Received Control request from: " + evt.agent);
        updateOnChangeInControl('pending');

    });

    _cbinstance.addOnControlReleaseCallback(function (evt) {
        _pending=false;
        console.info("Agent [" + evt.agent + "] has released Control.");
        updateOnChangeInControl('release');

    });
    _cbinstance.addOnCancelRequestControlCallback(function (evt) {
        _pending=false;
        console.info("Agent [" + evt.agent + "] has canceled Control.");
        updateOnChangeInControl('cancel');

    });
    
    
    /*
	//Register the below callback to skip the OOTB client sdk logic to convert the relative path for the link/image tags to absolute path present head or HTML body
	
	/*
	//Write custom logic to convert the relative path to absolute path for the external style 'links' defined in the HTML body
	_cbinstance.addOnUpdateHtmlBodyLinkCallback(function (data) {
                    var href = data.href;
                    try {	               
                                    if (href.indexOf("/") === 0 || href.indexOf("http") !== 0) {
                                            data.href = href.replace(replaceContextNameFromPath, "/");
                                    } 

                } catch (ex) {
                    AvayaCoBrowseClientServices.Base.CobrowseLogger.error('Exception in addOnUpdateHtmlBodyLinkCallback: ' + ex);

                }
    });
	
	
	//Write custom logic to convert the relative path to absolute path for the  source of the 'image' defined in the HTML body
	_cbinstance.addOnUpdateHtmlBodyImageCallback(function (data) {
            var src = data.src;
            try{
            if (src.indexOf("/") === 0 || src.indexOf("http") !== 0) {
                       data.src = src.replace(replaceContextNameFromPath,"/");
                    }
            } catch (ex) {
            AvayaCoBrowseClientServices.Base.CobrowseLogger.error('Exception in addOnUpdateHtmlBodyImageCallback: ' + ex);
            }
     });

	
	
	//Write custom logic to convert the relative path to absolute path for the external style 'link' defined in the HTML body
    _cbinstance.addOnUpdateHtmlHeadCallback(function (data) {
            var href = data.href;
            try {	               
                    if (href.indexOf("/") === 0 || href.indexOf("http") !== 0) {
                        data.href = href.replace(replaceContextNameFromPath, "/");
                } 

            } catch (ex) {
                AvayaCoBrowseClientServices.Base.CobrowseLogger.error('Exception in head cloning link: ' + ex);

            }
    });*/

     _cbinstance.addOnfireInactivityCallback(function (msg) {
        console.info(' fire addOnfireInactivityCallback call ');
       _inactiveMessage = msg; 
       if (!_IsInactiveLogOut) {
            startInactiveMessageTimer();
        }
    });

    _cbinstance.addOnStopInactivityTimerCallback(function (msg) {
        _IsInactiveLogOut = false;
        console.info('UI ::  fire addOnStopInactivityTimerCallback call '+msg);
        stopInactiveMessageTimer();

    });




    _cbinstance.addOnAgentJoinCallback(function (evt) {

        $('#cbeToolbar').draggable('enable');
        $('#cbeToolbar').css('-webkit-user-select', 'none');
        $('#cbeToolbar').css('-moz-user-select', 'none');
        if (evt.agentName) {
            setLiveUserStatus('Co-browsing is in progress!');
        } else {
            setLiveUserStatus('Waiting for agent');
        }
        connected((evt.cobrowseState == 'InProgress' ? false : true), (evt.agentControlState == 'false' ? false : true), evt.agentName, evt.customerName, (evt.agentControlState == 'pending' ? true : false));
    });
    

    _cbinstance.addOnAgentDeadCallback(function (evt) {
        //TODO : Feature use
    });
    
    function showSessionCloseConfirmationModal(info){
			$('#cbeSessionCloseDiv').modal('show');
			$('#cbeSessionCloseDiv').show().on('hide', function() { 
				$('#cbeSessionCloseDiv').modal('show'); 
			});
			$('#sessionCloseConfirmationModalMsg').text(info.message);
			$('#sessionCloseConfirmationModalTitle').text(info.title).addClass('label-success');
			$('#cbeSessionCloseDiv').modal({
				backdrop: 'false',
				keyboard: false  // to prevent closing with Esc button (if you want this too)
			})
		};

}
;



function registerCallbacksUI() {

 

      $('#avContinue').click(function () {
        _IsInactiveLogOut = false;
        _cbinstance.updateIdleTime(_inactiveMessageCounter);
        $('#inactiveModal').modal('hide');
        stopInactiveMessageTimer();
        console.info("Acknowledge inactive pop up");
    });
    
    $("#inactiveModal").on('hidden.bs.modal', function () {
        if (_IsInactiveLogOut) {
             inactiveLogout();
            _IsInactiveLogOut = false;
        }
    });
    
    $("#inactiveMessageModal").on('hidden.bs.modal', function () {
        resetUI();
    });

    $("#cbeJoinBtn").click(function () {
        

        
        var name = $('#cbeCustName').val();
        var sessionKey = $('#cbeSessionKey').val();
        var emailid = $('#cbeCustEmailIdJoinMode').val();
        var onSuccess=function (data) {
            console.info('UI: joinSession (success)');
            showProgressUI("Connecting Please wait..."); // Message from api.js
            //TODO - startInactiveTimer();
            $('#cbeCustName').blur();
            $('#cbeSessionKey').blur();
            $('#cbeCustEmailIdJoinMode').blur();
			//$('#annotate-controls').show();
            $('#feature-controls').show();
            $("#joinsessionchkcustconsent").prop("checked",true);
            _cbconfig.consent = true;
        };

        var onFailure=function (error) {
            var errorMsg="Unable to Join Session ("+error.getMessage()+")";
            updateUIonError(errorMsg);
            console.error('UI: joinSession:: ' + error.getMessage());

        };

        _cbinstance.joinSession(name, sessionKey, emailid).then(onSuccess.bind(this),onFailure);
        ///
    });

    // Added cancel button

    $('#cbeCancelBtn1,#cbeCancelBtn2').click(function (e) {      

        if(e.currentTarget.innerText === "Cancel"){
            resetUI();
            return;
        }
        var onSuccess = function (data) {
            console.info('UI: logout (success)');
            resetUI();
            stopInactiveMessageTimer();
            $("#joinsessionchkcustconsent").prop("checked",true);
            $("#reqsessionchkcustconsent").prop("checked",true);
            _cbconfig.consent = true;

        };

        var onFailure = function (error) {
            var errorMsg="Unable to logout ("+error.getMessage()+")";
            updateUIonError(errorMsg);
            console.error('UI: logout:: ' + error.getMessage());

        };

        _cbinstance.logoutSession().then(onSuccess.bind(this),onFailure);
        ///
    });
    
    $('#joinsessionchkcustconsent,#reqsessionchkcustconsent').click(function(){
		setCustomerConsent($(this).prop("checked"))
	});
   	
    function setCustomerConsent(consent){
            _cbconfig.consent = consent;
    }




    $("#cbeRequestBtn").click(function () {
        //reset value of pending while requesting new session
        _pending=false;
        var name = $('#cbeCustNameReqMode').val();
        var locale = $('#lang_selection').val();
        var emailid = $('#cbeCustEmailIdReqMode').val();
        var onSuccess=function (data) {
            console.info('UI: requestSession (success)');
            showProgressUI(_cbinstance.getCustomerData().getCobrowseState());
            setLiveUserStatus(_cbinstance.getCustomerData().getCobrowseState());
            $('#cbeKey').text('Key: ' + _cbinstance.getCustomerData().getPassPhrase());
            $('#cbeToolbar').draggable('disable');
            $('#cbeToolbar').css('-webkit-user-select', 'inherit');
            $('#cbeToolbar').css('-moz-user-select', 'inherit');
            $('#cbeCustNameReqMode').blur();
            $('#cbeCustEmailIdReqMode').blur();
            $("#reqsessionchkcustconsent").prop("checked",true);
            _cbconfig.consent = true;
        };

        var onFailure= function (error) {
            var errorMsg="Unable to Create Session ("+error.getMessage()+")";
            updateUIonError(errorMsg);
            console.error('UI: requestSession:: ' + error.getMessage());
        };

        _cbinstance.requestSession(name, locale, emailid).then(onSuccess.bind(this), onFailure);
    });

    $("#cbePauseBtn").click(function () {
        var onSuccess = function () {
            console.info("Change State as Pause");
            updateOnPause(true);
        };
        
        var onFailure = function (errorObject) {
             console.log('unable to change state: Paused' );
             console.error("error message :: " + errorObject.getMessage() );
        };
        
        _cbinstance.pause().then(onSuccess.bind(this), onFailure);        
            console.info('Customer requested to pause the session, removing the control request!');
            $('#cbeRequestDiv').hide();
            if(_cbinstance.getCustomerData().getAgentControlState()==="pending"){
                _pending = true;
            }else{
                _pending = false;
            }        
    });

    $("#cbeResumeBtn").click(function () {
        var onSuccess = function () {
            console.info("Change State as InProgress");
            updateOnPause(false);
        };
        var onFailure = function (errorObject) {
           console.log('unable to change state: as Resume');
           console.error("error message :: " + errorObject.getMessage() );
        };
        if (_pending) {
            $('#cbeRequestDiv').show();
            _pending = false;
        }
        _cbinstance.resume().then(onSuccess.bind(this), onFailure);
    });

    $("#cbePreJoinBtn").click(function () {
        $('#cbeRequestMode').hide();
        $('#cbeJoinMode').show();
        $('#cbeHeaderDiv').show();
        $('#cbeStartDiv').show();
        $('#cbePreStartDiv').hide();
        $('#Joinlang_selection').hide();
        $('#cbeStatusText').text('Join Co-browse Session');
        //override height attribute to cbeToolbar set by jquery draggable
        $("#cbeToolbar").css('height', 'auto');
    });

    $("#cbePreRequestBtn").click(function () {
        $('#cbeJoinMode').hide();
        $('#cbeRequestMode').show();
        $('#cbeHeaderDiv').show();
        $('#cbeStartDiv').show();
        $('#Joinlang_selection').show();
        $('#cbePreStartDiv').hide();
        $('#cbeStatusText').text('Request Co-browse Session');
        //override height attribute to cbeToolbar set by jquery draggable
        $("#cbeToolbar").css('height', 'auto');
    });
    //Pre Start GUI


    $("#cbeStopBtn").click(function () {
        $('#cbeLogoutModelDiv').modal('show');
        $('#cbeLogoutModelDiv').show().on('hide', function () {
            $('#cbeLogoutModelDiv').modal('show');
        });
        $('#logoutConfirmationModalMsg').text('Press OK to continue...');
        $('#logoutConfirmationModalTitle').text('Are you sure you want to logout?').removeClass('label-success').addClass('label-danger');
        $('#cbeLogoutModelDiv').modal({
            backdrop: 'false',
            keyboard: false  // to prevent closing with Esc button (if you want this too)
        })
    });

    $('#confirmLogout').click(function () {
        $('#cbeLogoutModelDiv').modal('hide');
        
      
        var onSuccess = function (src) {
            console.info('UI: logout (success)');
            resetUI();
			annotate.enableMarkerFeature = !(annotate.enableMarkerFeature);
			_cbinstance.disableMarker();
			$('#btnMarker').attr('title', 'Enable marker');
			$('#annotate-controls').css("display", "inline-block"); 
                        annotate.showingAnnotationToolBar = false;
		    stopInactiveMessageTimer();
			//$('#annotate-controls').hide();
			//$('#feature-controls').attr('features','hide');
			//$('#feature-controls').attr('features','show');
			$('#feature-controls').css('display', 'none');
			$('#feature-controls').hide();
            $("#joinsessionchkcustconsent").prop("checked",true);
			$("#reqsessionchkcustconsent").prop("checked",true);
           _cbconfig.consent = true;
        };

        var onFailure = function (error) {
            console.error('UI: Logout:: ' + error.getMessage());
        };

        _cbinstance.logoutSession().then(onSuccess.bind(this), onFailure);
    });

    $("#cbeAllowBtn").click(function() {
        
        var onSuccess = function () {       
        updateOnChangeInControl("grant");
		annotate.enableMarkerFeature = !(annotate.enableMarkerFeature);
		_cbinstance.disableMarker();
		$('#btnMarker').attr('title', 'Enable marker');
		$('#annotate-controls').css("display", "inline-block"); 
		annotate.showingAnnotationToolBar = false;
        
		};
        var onFailure = function (error) {       
                console.warn('Unable to Grant Control, reason: ' + error.getMessage());
        };    
        
        _cbinstance.grantControl().then(onSuccess.bind(this), onFailure);
        // @TODO : stopInactiveTimer();
    });

    $("#cbeRevokeBtn").click(function() {
        var onSuccess = function () {       
            updateOnChangeInControl("revoke");
        };
        var onFailure = function (error) {       
                console.warn('Unable to Revoke Control, reason: ' + error.getMessage());
        };
        _cbinstance.revokeControl().then(onSuccess.bind(this), onFailure);
    });

    $("#cbeDenyBtn").click(function() {
        var onSuccess = function () {       
            updateOnChangeInControl("deny");
        };
        var onFailure = function (error) {       
                console.warn('Unable to Deny Control, reason: ' + error.getMessage());
        };
   
        _cbinstance.denyControl().then(onSuccess.bind(this), onFailure);
    });
    
    $("#cbeRetryBtn").click(function() {
        $('#cbeStartDiv').show();
        $('#cbeErrorDiv').hide();
        //$('#cbeSessionKey').css({ "border": "1px solid red" });
	$('#cbeStatusText').text('Join Co-browse Session');
	$('#cbeState').removeClass().addClass('cbe-icon-status cbe-icon-grey');
    });

    $("#cbeCancelBtn").click(function() {
        $('#cbeStartDiv').show();
        $('#cbeErrorDiv').hide();
		$('#cbeStatusText').text('Join Co-browse Session');
		$('#cbeState').removeClass().addClass('cbe-icon-status cbe-icon-grey');
    });
};

function registerAnnotationActions(){
	
	annotate = this; 
	annotate.showingAnnotationToolBar = false;
	annotate.enableMarkerFeature = false;
	annotate.hideAgentAnnotations = false;
	annotate.hideAgentMarkers = false;
        
        annotate.hideCustomerAnnotations = false;
	annotate.hideCustomerMarkers = false;
	

	/*$('#feature-controls').draggable({ x`
			opacity: 0.7, 
			containment: "window", 
			cancel: ".do-not-drag-me", 
			scroll: false, 
			axis: "x,y", 
			distance: 10
	});*/
	
	
	
	
	var colorGUIElements= new Array();
	colorGUIElements.push($('#imgRedCol'));
	colorGUIElements.push($('#imgBlueCol'));
	colorGUIElements.push($('#imgGreenCol'));
	
	
	var brushColors = new Array();
	brushColors.push($('#redMarkerCol'));
	brushColors.push($('#blueMarkerCol'));
	brushColors.push($('#greenMarkerCol'));
	
	
	var annoationSizeSelection= new Array();
	annoationSizeSelection.push($('#annotationSizeSmall'));
	annoationSizeSelection.push($('#annotationSizeMedium'));
	annoationSizeSelection.push($('#annotationSizeLarge'));
	
	var actionElements = new Array();
	actionElements.push($('#freehand'));
	actionElements.push($('#shapeRec'));
	actionElements.push($('#shapeCir'));
	
	$('#divEnablemarker').click(function (e){
		annotate.enableMarkerFeature = !(annotate.enableMarkerFeature);
		if(annotate.enableMarkerFeature){
			if(annotate.selectMarkerColor != undefined){
				color = annotate.selectMarkerColor;
			}
			_cbinstance.enableMarker();
			$('#btnMarker').attr('title', 'Disable marker');
			$('#annotate-controls').css("display", "none");
		}else{
			_cbinstance.disableMarker();

			$('#hideMarkers').removeClass();
			$('#hideMarkers').addClass('hideAgentMarkersClass');
			annotate.hideAgentMarkers = false;
			$('#hideSelfMarkers').removeClass();
			$('#hideSelfMarkers').addClass('hideSelfMarkersClass');
			annotate.hideCustomerMarkers = false;
			$('#btnMarker').attr('title', 'Enable marker');
			$('#annotate-controls').css("display", "inline-block"); 
		}
	});
        
        $('#divClearMarkers').click(function(e){
		_cbinstance.clearAllMarkers();
	});
	
	$('#hideMarkers').click(function(e){
		if(!annotate.enableMarkerFeature || _cbinstance._customerCobrowseService._coBrowseDataSet.coBrowseData.coBrowseSessionInfo.agentControlState === AvayaCoBrowseClientServices.Services.Cobrowse.Common.AgentControlState.AGENTCONTROLTRUESTATE ){
			return;
		}
		annotate.hideAgentMarkers = !annotate.hideAgentMarkers;
		if(annotate.hideAgentMarkers){
		_cbinstance.hideAllAgentMarkers();
		$(this).removeClass();
		$(this).addClass('unHideAgentMarkersClass');
		}else{
		_cbinstance.unHideAllAgentMarkers();	
		$(this).removeClass();
		$(this).addClass('hideAgentMarkersClass');
		}
	});
        
        $('#hideSelfMarkers').click(function(e){
			if(!annotate.enableMarkerFeature || _cbinstance._customerCobrowseService._coBrowseDataSet.coBrowseData.coBrowseSessionInfo.agentControlState === AvayaCoBrowseClientServices.Services.Cobrowse.Common.AgentControlState.AGENTCONTROLTRUESTATE){
			return;
			}
            annotate.hideCustomerMarkers = !annotate.hideCustomerMarkers;
            if(annotate.hideCustomerMarkers){
                _cbinstance.hideAllCustomerMarkers();
				$(this).removeClass();
				$(this).addClass('unHideSelfMarkersClass');
	        }else{
                _cbinstance.unHideAllCustomerMarkers();
				$(this).removeClass();
				$(this).addClass('hideSelfMarkersClass');
            }
	});
	
	$('#toggler').click(function (e){
		annotate.showingAnnotationToolBar = !(annotate.showingAnnotationToolBar);
		annotate.enableMarkerFeature = false;
		var onSuccess = function(data) {
				console.info('UI:' + data.message);
				$('#annotate-controls').attr('showing',annotate.showingAnnotationToolBar);
				if(annotate.showingAnnotationToolBar){
				$('#toggler').attr('title', 'Disable draw mode');
				$('#btnMarker').attr('disabled', 'disabled');
				$('#divMarkerControl').attr('showcolor', false);
                                annotate._drawShape = data.annotationType;
				
				}else{
					$('#toggler').attr('title', 'Enable draw mode');
					$('#btnMarker').removeAttr('disabled', 'disabled');
					$('#divMarkerControl').attr('showcolor', true);
					$('#unhide').removeClass();
					$('#unhide').addClass('agentHide');
					annotate.hideAgentAnnotations = !annotate.hideAgentAnnotations;
					$('#selfHideBtn').removeClass();
					$('#selfHideBtn').addClass('selfHide');
					annotate.hideCustomerAnnotations = !annotate.hideCustomerAnnotations;
				}
			};
			var onFailure= function (data) {
				console.info(data._message);
				annotate.showingAnnotationToolBar = false;
			};
		if(annotate.showingAnnotationToolBar){
			_cbinstance.startAnnotation().then(onSuccess.bind(this), onFailure);
			
		}else {
			
			_cbinstance.stopAnnotation().then(onSuccess.bind(this), onFailure);
			
		}
	});
	
	
	$('#removeAll').click(function(e){
		$('#annotate-controls').attr('mode', 'clearAll');
		_cbinstance.clearAllCustomerAnnotations();
	});
        
	$('#unhide').click(function(e){
		
		$('#annotate-controls').attr('mode', 'unHide');
		annotate.hideAgentAnnotations = !annotate.hideAgentAnnotations;
		if(annotate.hideAgentAnnotations){
		_cbinstance.hideAllAgentAnnotations();
		//$(this).css("background-image","url('../img/agent-unhide.svg')");
		$(this).removeClass();
		$(this).addClass('agentunhide');
		}else{
		_cbinstance.unHideAllAgentAnnotations();	
		//$(this).css("background-image","url('../img/agent-hide.svg')");
		$(this).removeClass();
		$(this).addClass('agentHide');
		}
	});
	$('#selfHideBtn').click(function(e){
		$('#annotate-controls').attr('mode', 'selfHide');
		annotate.hideCustomerAnnotations = !annotate.hideCustomerAnnotations;
		if(annotate.hideCustomerAnnotations){
                    _cbinstance.hideAllCustomerAnnotations();
					//$(this).css("background-image","url('../img/customer-unhide.jpg')");
					$(this).removeClass();
					$(this).addClass('custunHide');
		}else{
                    _cbinstance.unHideAllCustomerAnnotations();	
					//$(this).css("background-image","url('../img/customer-hide.jpg')");
							$(this).removeClass();
							$(this).addClass('selfHide');  
		}
	});
	
	
	for(var i=0; i<colorGUIElements.length; i++){
	colorGUIElements[i].click(function(e){
			annotate.selectedStrokeColor = $(this).attr('val');
			$('#clrChoice')[0].style.backgroundColor = annotate.selectedStrokeColor;
			if(annotate._drawShape != undefined){
			annotate._drawShape.setStrokeColor(annotate.selectedStrokeColor);
			}
	});
	}
	
	for(var i=0; i<brushColors.length; i++){
	brushColors[i].click(function(e){
			annotate.selectMarkerColor = $(this).attr('val');
			//$('#clrChoice')[0].style.backgroundColor = annotate.selectedStrokeColor;
			_cbinstance.setMarkerColor(annotate.selectMarkerColor);
	});
	}
	
	
	for(var i=0; i<annoationSizeSelection.length; i++){
	annoationSizeSelection[i].click(function(e){
			annotate.selectedStrokeSize = $(this).attr('val');
			if(annotate._drawShape != undefined)
			annotate._drawShape.setStrokeSize(annotate.selectedStrokeSize);
	});
	}
 	
 	
	
	for(var i=0; i<actionElements.length; i++){
	actionElements[i].click(function(e){
		if($(this).attr('id') == 'freehand'){
			$('#annotate-controls').attr('mode', 'draw');
			if( annotate._drawFreeHand == undefined){
			//Default AnnotationShapeType is freehand
			annotate._drawFreeHand = new AvayaCoBrowseClientServices.Services.Cobrowse.Common.AnnotationShapeInfo();
			}
			annotate._drawShape = annotate._drawFreeHand;
		}else if($(this).attr('id') == 'shapeRec'){
			$('#annotate-controls').attr('mode', 'draw-rec');
			if(annotate._drawShapeRec == undefined){
				annotate._drawShapeRec = new AvayaCoBrowseClientServices.Services.Cobrowse.Common.AnnotationShapeInfo();
				annotate._drawShapeRec.setAnnotationType(AvayaCoBrowseClientServices.Services.Cobrowse.Common.AnnotationShapeType.ANNOTATIONSHAPETYPERECTANGLE);
			}
			annotate._drawShape = annotate._drawShapeRec;
			
		}else if($(this).attr('id') == 'shapeCir'){
			$('#annotate-controls').attr('mode', 'draw-circle');
			if(annotate._drawShapeCir == undefined){
				annotate._drawShapeCir = new AvayaCoBrowseClientServices.Services.Cobrowse.Common.AnnotationShapeInfo();
				annotate._drawShapeCir.setAnnotationType(AvayaCoBrowseClientServices.Services.Cobrowse.Common.AnnotationShapeType.ANNOTATIONSHAPETYPECIRCLE);
			}
			annotate._drawShape = annotate._drawShapeCir;
		}
			if(annotate.selectedStrokeColor != undefined)
			annotate._drawShape.setStrokeColor(annotate.selectedStrokeColor);
		
			if(annotate.selectedStrokeSize != undefined)
			annotate._drawShape.setStrokeSize(annotate.selectedStrokeSize);
		
		
			var onSuccess = function(data) {
				console.info('UI: success' + data.message);
			};
			var onFailure= function (error) {
				var errorMsg="Error in setting the shape to draw";
				console.info(errorMsg + error._message);
				
			};
			_cbinstance.setAnnotation(annotate._drawShape).then(onSuccess.bind(this), onFailure);
	});
	}
	_cbinstance.addElementIDToRemove("feature-controls");
	//Uncomment the below lines for marker feature
	//_cbinstance.enableMarker();
	//_cbinstance.setMarkerColor('red');
	
	$('#feature-controls').hide();
};

function connected(paused, agentControl, agent, customer, ctrlReqPending) {

    $('#cbeStartDiv').hide();
    $('#cbeProgressDiv').hide();
    $('#cbeInProgressDiv').show();
    $('#cbeErrorDiv').hide();
    try {
        $('#cbeCustInfo').html('Hello ' + decodeURIComponent(customer) + '!');
    } catch(e){
        $('#cbeCustInfo').html('Hello ' + customer + '!');
    }
    $('#cbeStatusText').text('Connected to');
    if (agent) {
        $('#cbeState').removeClass().addClass('cbe-icon-status cbe-icon-green');
    } else {
        $('#cbeState').removeClass().addClass('cbe-icon-status cbe-icon-yellow');
    }
    $('#cbeAgentName').text(agent);

    updateOnPause(paused);
    
    if (! paused) {
        if (ctrlReqPending) {
            updateOnChangeInControl("pending");
        } else if (agentControl) {
            updateOnChangeInControl("grant");
        } else if (agentControl === false) {
            updateOnChangeInControl("release");
            updateOnPause(paused);
            if (paused === false)
                $('#cbeLiveStatus').text('Co-browsing is in progress!');
        }
    }
    $('#cbeHeaderDiv').show();
    $('#cbeDisclaimerDiv').show();
    $('#cbeToolbar').show();
	//$('#annotate-controls').show();
	$('#feature-controls').show();
}
;

function updateUIonError(msg) {
    $('#cbePreStartDiv').hide();
    $('#cbeStartDiv').hide();
    $('#cbeInProgressDiv').hide();
    $('#cbeProgressDiv').hide();
    $('#cbeDisclaimerDiv').hide();
    $('#cbeErrorDiv').show();

    if (msg && msg.indexOf("Unknown Error") > -1) {
        $('#cbeErrMsg').text('Error in network.Please retry after sometime.');
    }else if(msg && msg.indexOf("Retrying") > -1){
		$("#cbeRetryBtn").hide();
        $('#cbeErrMsg').text(msg);
        $('#cbeStatusText').text('Error: ' + msg.substring(0, 20) + '...');
    }else if(msg){
		$('#cbeErrMsg').text(msg);
        $('#cbeStatusText').text('Error: ' + msg.substring(0, 20) + '...');
	}else{
        $('#cbeErrMsg').text('Error in network.Please retry after sometime.');
    }
//    if (typeof msg === "undefined") {
//        $('#cbeErrMsg').text('Error in network.Please retry after sometime.');
//    } else if (msg.indexOf("undefined") > -1) {
//        $('#cbeErrMsg').text('Error in network.Please retry after sometime.');
//    } else {
//        $('#cbeErrMsg').text(msg);
//        $('#cbeStatusText').text('Error: ' + msg.substring(0, 20) + '...');
//    }

    $('#cbeState').removeClass().addClass('cbe-icon-status cbe-icon-red');
}
;

function showProgressUI(msg) {
    $('#cbeStartDiv').hide();
    $('#cbeInProgressDiv').hide();
    $('#cbeProgressDiv').show();
    $('#cbeProgressMsg').text(msg);
    $('#cbeState').removeClass().addClass('cbe-icon-status cbe-icon-cbe-icon-yellow');
};

function updateOnPause(paused) {
    if (paused) {
        $('#cbePauseBtn').hide();
        //Disabling requestDiv during pause
        if(_cbinstance.getCustomerData().getCobrowseState()==="Paused"){
            $('#cbeRequestDiv').hide();
        }
        //Disabling Resume button from UI
        $('#cbeResumeBtn').show();
        
        
    } else {
        //Disabling Pause button from UI
        $('#cbePauseBtn').show();
        $('#cbeResumeBtn').hide();
        if(_cbinstance.getCustomerData().getAgentControlState()==="pending"){
            if(_cbinstance.getCustomerData().getCobrowseState()==="InProgress"){
                $('#cbeRequestDiv').show();
            }
        }
    }
};

function updateOnChangeInControl(state) {
    
    if (state === 'grant') {
        $('#cbeRequestDiv').hide();
        $('#cbeRevokeBtn').show();
        $('#cbePauseBtn').hide();
        //setLiveUserStatus('Permission granted! Agent is now in control of your Web page, you can revoke the control any time or stop the session.');
        setLiveUserStatus('Permission granted! Agent is controlling your Web page');
        //TODO stopInactiveTimer();
		annotate.showingAnnotationToolBar = false;
		
		$('#unhide').removeClass();
		$('#unhide').addClass('agentHide');
		
		$('#selfHideBtn').removeClass();
		$('#selfHideBtn').addClass('selfHide');
		

		
		
		$('#annotate-controls').attr('showing',false);
		$('#toggler').attr('title', 'Enable draw mode');
		$('#btnMarker').removeAttr('disabled', 'disabled');
		$('#divMarkerControl').attr('showcolor', true);
		
		
		$('#hideMarkers').removeClass();
		$('#hideMarkers').addClass('hideAgentMarkersClass');
		
		$('#hideSelfMarkers').removeClass();
		$('#hideSelfMarkers').addClass('hideSelfMarkersClass');
		
		
		//$('#hideMarkers').css("background-image","url('../img/agent-hide.svg')");
		//$('#hideSelfMarkers').css("background-image","url('../img/customer-hide.jpg')");
		
		$('#btnMarker').attr('title', 'Enable marker');
		$('#annotate-controls').css("display", "inline-block");
        annotate.enableMarkerFeature = false;
		annotate.hideAgentMarkers = false;
		annotate.hideCustomerMarkers = false;		
		
		annotate.hideAgentAnnotations = false;
		annotate.hideCustomerAnnotations = false;
		
    } else if (state === 'revoke') {

        $('#cbeRevokeBtn').hide(); // hide revoke button

        $('#cbePauseBtn').show(); // Now user can pause
        setLiveUserStatus('Successfully revoked Control permission from Agent, you are back in control');
       // TODO startInactiveTimer();
    } else if (state === 'release') {

        $('#cbeRevokeBtn').hide();
        $('#cbePauseBtn').show();
        setLiveUserStatus('Agent has released the control, you are back in control');
        //TODO startInactiveTimer();
    } else if (state === 'cancel') {
        $('#cbeRequestDiv').hide();
        setLiveUserStatus('Agent has cancelled the control request');
        //TODO startInactiveTimer();
    }else if (state === 'deny') {
        $('#cbeRequestDiv').hide();
        setLiveUserStatus("You denied Agent's request to Control");
    } else if(state === 'pending') {
        $('#cbeRequestDiv').show();
        $('#cbeLiveStatus').text('Co-browsing is in progress!');

        //If minimized, then maximize
        _winMinimized = false;
        $("#cbeMainSubDiv").show();
        $("#cbeMinimize").removeClass('cbe-icon-maximize').addClass('cbe-icon-minimize');
    }
};

function setDisclaimerText(msg) {
    $('#cbeDisclaimerDiv').text(msg);
}
;

function setLiveUserStatus(msg) {
    $('#cbeLiveStatus').text(msg);
}
;



function showPassPhraseModal(info) {
    $('#cbePassPhraseModelDiv').modal(); // initialize
    $('#cbePassPhraseModelDiv').modal('show');
    $('#cbePassPhraseModelDiv').show().on('hide', function () {
        $('#cbePassPhraseModelDiv').modal('show');
    });
    $('#cbePassPhraseModalMsg').text(info.message);
    $('#cbePassPhraseModalTitle').text(info.title);
    $('#cbePassPhraseModelDiv').modal({
        backdrop: 'false',
        keyboard: false  // to prevent closing with Esc button (if you want this too)
    })
}
;

function startInactiveMessageTimer() {
    console.info('START INACTIVE MESSAGE TIMER');
    _inactiveMessageCounter = 0;
    if (_inactiveMessageTimer != null) {
        clearInterval(_inactiveMessageTimer);
    }
    _inactiveMessageTimer = setInterval(function () {
        _inactiveMessageCounter = _inactiveMessageCounter + 1;
        $('#warningMsg').text(" Your session is terminating within  " + (_inactiveMessageTimeout - _inactiveMessageCounter) + " seconds");
        if (_inactiveMessageCounter >= _inactiveMessageTimeout) {
            inactiveLogout();
        }
    }, 1000);
    showInactiveModal();
}
;

function stopInactiveMessageTimer() {
    console.info('STOP INACTIVE MESSAGE TIMER ');
    if (_inactiveMessageTimer != null) {
        clearInterval(_inactiveMessageTimer);
    }
    clearInterval(_inactiveMessageTimer);
    $('#warningMsg').text("");
    _inactiveMessageCounter = 0;
}
;


function showInactiveModal(info) {
    $('#inactiveModal').modal('show');
    $('#inactiveModalMsg').text('Press Yes to continue....');
    $('#inactiveModalTitle').css('padding', '3px');
    $('#inactiveModalTitle').text('You will be logged out within 60 seconds.  Do you want to stay signed in ?').removeClass('label-success').addClass('label-danger');
    $('#inactiveModal').modal({
        backdrop: 'static',
        keyboard: false  // to prevent closing with Esc button (if you want this too)
    })
    _IsInactiveLogOut = true;
}
;
function showInactiveMessageModal(info) {
    $('#inactiveMessageModal').modal('show');
    $('#inactiveMessageModalMsg').text(_inactiveMessage); //TODO
    $('#inactiveMessageModalTitle').text("Inactive Timeout").removeClass('label-success').addClass('label-danger');
    $('#inactiveMessageModal').modal({
        backdrop: 'static',
        keyboard: false  // to prevent closing with Esc button (if you want this too)
    })
	if ($('#cbeLogoutModelDiv')) {
            $('#cbeLogoutModelDiv').modal('hide');
    }
}
;

 function inactiveLogout() {
        _cbinstance.updateIdleTime(_inactiveMessageCounter);
        $('#inactiveModal').modal('hide');        
        var reason = "inactive_timeout";
        var onSuccess = function () {
            console.info('UI: logout (success)');
            stopInactiveMessageTimer();
        };
        var onFailure = function (error) {
            console.error('error in inactive logout:: ' + error.getMessage());
        };
        _cbinstance.logoutSession(reason).then(onSuccess.bind(this), onFailure);
        showInactiveMessageModal();
    };



function resetUI() {
    //header
    $('#cbeCustNameReqMode').val("");
    $('#cbeCustName').val("");
    $('#cbeSessionKey').val("");
    $('#cbeKey').val("");
    $('#cbeKey').empty();
    $('#cbeHeaderDiv').hide();
    $('#cbeStatusText').text('');
    $('#cbeAgentName').text('');
    setLiveUserStatus('Connection closed!');
    $('#cbeState').removeClass().addClass('cbe-icon-status cbe-icon-grey');
    $('#denyModal').hide();
    $('.modal-backdrop').remove();    
    $('#cbeErrorDiv').hide();
	//$('#annotate-controls').attr('showing',false);
	//$('#feature-controls').attr('features','hide');

	annotate._drawShape = new AvayaCoBrowseClientServices.Services.Cobrowse.Common.AnnotationShapeInfo();
	annotate.selectedStrokeColor = 'red';
	annotate.selectedStrokeSize = '5';
    $("#cbePreJoinBtn").click(function () {
        $('#cbeRequestMode').hide();
        $('#cbeJoinMode').show();
        $('#cbeHeaderDiv').show();
        $('#cbeStartDiv').show();
        $('#cbePreStartDiv').hide();
        $('#Joinlang_selection').hide();
        $('#cbeStatusText').text('Join Co-browse Session');
        //override height attribute to cbeToolbar set by jquery draggable
        $("#cbeToolbar").css('height', 'auto');
    });

    $("#cbePreRequestBtn").click(function () {
        $('#cbeJoinMode').hide();
        $('#cbeRequestMode').show();
        $('#cbeHeaderDiv').show();
        $('#cbeStartDiv').show();
        $('#Joinlang_selection').show();
        $('#cbePreStartDiv').hide();
        $('#cbeStatusText').text('Request Co-browse Session');
        //override height attribute to cbeToolbar set by jquery draggable
        $("#cbeToolbar").css('height', 'auto');

    });
    //Pre Start GUI

    //Hide other DIV
    $('#cbeInProgressDiv').hide();
    $('#cbeRequestDiv').hide();
    $('#cbeDisclaimerDiv').hide();
    $('#cbeWaitForAgentDiv').hide();
    $('#cbeStartDiv').hide();
    $('#cbeRevokeBtn').hide();

    //Pre Start GUI
    $('#cbePreStartDiv').show();
    $('#cbeToolbar').show();

    //handle placeholder for IE8/ 9
    if (navigator.appVersion.indexOf("MSIE 8.") !== -1 || navigator.appVersion.indexOf("MSIE 9.") !== -1) {
        $('#cbeCustName, #cbeSessionKey, #cbeCustNameReqMode').each(function () {
            var obj = $(this);
            if (obj.attr('placeholder') !== '') {
                if ($.trim(obj.val()) === '' && obj.attr('type') !== 'password') {
                    obj.val(obj.attr('placeholder'));
                }
            }
        });

        $('#cbeCustName, #cbeSessionKey, #cbeCustNameReqMode').focus(function () {
            var obj = $(this);
            if (obj.val() === obj.attr('placeholder')) {
                obj.val('');
            }
        });

        $('#cbeCustName, #cbeSessionKey, #cbeCustNameReqMode').blur(function () {
            var obj = $(this);
            if ($.trim(obj.val()) === '') {
                obj.val(obj.attr('placeholder'));
            }
        });
    }
}
;
