////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////// Controller [Agent] - Sample Client ///////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

var key, name, autojoin, sessionKey, extKey = null;
var allowScreenPop = false;
// For inactive timer
var _inactiveMessageTimer;
var _inactiveMessageCounter = 0;
var _inactiveMessageTimeout = 60; //  pop up display of inactive timeout is 60 sec
var _inactivityMessage = "";
var _iframeId = 'iframeDiv';
var _cbinstance = null;
var _IsInactiveLogOut = false;
var annotate = {};
var hideSelected = false;
var markerHide = false;
var hideAgentMarker = false;
var hideAgentAnnotation = false; 

function cobrowseAgentInit() {

    console.info('Load Complete ' + '[jQuery]: ' + $().jquery);
    this.createInstance();
    console.info('Successfully Initilized');

    document.onkeydown = preventBackspace;
    document.getElementById(_iframeId).contentWindow.document.onkeydown = preventBackspace;


    ///// Inactive Timer///////////////

    $('#avContinue').click(function () {
        _IsInactiveLogOut = false;
        _cbinstance.updateIdleTime(_inactiveMessageCounter);
        $('#inactiveModal').modal('hide');
        stopInactiveMessageTimer();
    });

    $("#inactiveModal").on('hidden.bs.modal', function () {
        if (_IsInactiveLogOut) {
             inactiveLogout();
            _IsInactiveLogOut = false;
        }
    });

    function preventBackspace(event) {
        if (!event) {
            event = window.event;
        }

        var keyCode = event.keyCode;
    
        var isTabPressed  = false;
        if (_cbinstance!=null) {
            isTabPressed = ( keyCode === 9 && (_cbinstance.getAgentData().getAgentControlState() === AvayaCoBrowseClientServices.Services.Cobrowse.Common.AgentControlState.AGENTCONTROLFALSESTATE));
        } 
        
        if ( isTabPressed || (keyCode == 8 &&
                ((event.target || event.srcElement).tagName != "TEXTAREA") &&
                ((event.target || event.srcElement).tagName != "INPUT")) ) {

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

            return false;
        }
    }
    ;

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////// Validate URL parameters and fork the code workflow  ////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    name = getURLParam("name");
    extKey = getURLParam("extkey");
    autojoin = getURLParam("autojoin");

    if (name == "null" || name === "" || name == null) {
        name = "User"
    }
    if (!autojoin) {
        autojoin = false
    }
    console.info("URL Parameters: key:" + key + " name:" + name + " autojoin:" + autojoin);

    //MISC UI
    $("#name").keyup(function () {
        $('#avGreet').text($("#name").val() + '!');
        $('#joinSessionName').val($("#name").val());
    });

    //MISC UI
    $("#joinSessionName").keyup(function () {
        $('#avGreet').text($("#joinSessionName").val() + '!');
        $('#name').val($("#joinSessionName").val());
    });

    registerCallbacksAPI();
    registerCallbacksUI();

    if (allowScreenPop) {
        console.info("ScreenPop Mode: " + allowScreenPop);
        //TODO: fork the flow here depending on parameters passed in URL
    } else {
        console.info("Controller Initialization Complete");
        $('#defaultDiv').show();
        $('#avGreet').text(name + ' !');
        $('#name').val(name);
        $('#joinSessionName').val(name);
    }
}
;
function createInstance() {
    _cbconfig = new AvayaCoBrowseClientServices.Config.CoBrowseConfiguration();
    console.info('Cobrowse Engine (Agent) Load Complete');
    console.info('[jQuery]: ' + $().jquery);
    _cbconfig.serverInfo.hostName = "localhost";
    _cbconfig.serverInfo.port = '8443';
    _cbconfig.serverInfo.isSecure = true;
    _cbconfig.enabled = true;

    var _coBrowseAgentClientService = new AvayaCoBrowseClientServices(_cbconfig);
    _coBrowseAgentClientService.registerLogger(window.console);
    //Setting service context url
    //_coBrowseAgentClientService.initAgentServiceContext("avservice");
    _cbinstance = _coBrowseAgentClientService.createAgentCobrowse(_cbconfig);
    _cbinstance.setIFrame(_iframeId);
    _cbinstance.start();
	setCoBrowseContainerSize();
}
$(window).off("resize.setCoBrowseContainerSize");
$(window).on("resize.setCoBrowseContainerSize",setCoBrowseContainerSize.bind(this));

function setCoBrowseContainerSize(){
	
	$('#cobrowseDiv').height($(window).height() - $('#navigatorDiv').height() - 25);
	$('#cobrowseDiv').width($('#navigatorDiv').width());
}
function registerCallbacksUI() {

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////// Callbacks from GUI //////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    var key = null;

	
	
	var annotationColBtns = new Array();
	annotationColBtns.push($('#redColorBtn'));
	annotationColBtns.push($('#blueColorBtn'));
	annotationColBtns.push($('#greenColorBtn'));
	
	var annotationStrokeSelBtns = new Array();
	annotationStrokeSelBtns.push($('#smallStrokeSizeBtn'));
	annotationStrokeSelBtns.push($('#mediumStrokeSizeBtn'));
	annotationStrokeSelBtns.push($('#largerStrokeSizeBtn'));
	
	var mrkClrSelBtns = new Array();
	mrkClrSelBtns.push($('#btnredClr'));
	mrkClrSelBtns.push($('#btnblueClr'));
	mrkClrSelBtns.push($('#btngreenClr'));
	
	
	annotate._drawShape = new AvayaCoBrowseClientServices.Services.Cobrowse.Common.AnnotationShapeInfo('#A3CEDC','7',AvayaCoBrowseClientServices.Services.Cobrowse.Common.AnnotationShapeType.ANNOTATIONSHAPETYPEFREEHAND);
	_cbinstance.setAnnotation(annotate._drawShape);
	
	//Register the annotation color selection btns 
	for(var i=0; i<annotationColBtns.length; i++){
	annotationColBtns[i].click(function(e){
			annotate.selectedStrokeColor = $(this).attr('val');
			if(annotate._drawShape != undefined){
			annotate._drawShape.setStrokeColor(annotate.selectedStrokeColor);
                        _cbinstance.setAnnotation(annotate._drawShape);
			}
			$("#colorSelectionDiv").hide();
			$("#strokeSizeSelDiv").hide();
			$("#shapeSelectionDiv").hide();
			$("#avStopAnnotationBtn").show();
			if(!hideSelected){
			$("#avHideAnnotationBtn").show();	
			}else{
			$("#avUnHideAnnotationBtn").show(); 	
			}
			if(!hideAgentAnnotation){
			$("#avHideAgentAnnotationBtn").show();	
			}else{
			$("#avUnHideAgentAnnotationBtn").show(); 	
			}
			
			$("#avRemoveAllAgentAnnotationBtn").show();
			$("#avShapeBtn").show();
			$("#avAnnotateColSelBtn").show();
			$("#avAnnotateStrokeSizeSelBtn").show();
	});
	}
	
	
	//Register the marker's color selection btns 
	for(var i=0; i<mrkClrSelBtns.length; i++){
	mrkClrSelBtns[i].click(function(e){
			annotate.selMrkClr = $(this).attr('val');
			if (_cbinstance === null) {
            this.createInstance();
			}
			_cbinstance.setMarkerColor(annotate.selMrkClr);
			$("#divclrselection").hide();
			$("#avStopMarkerBtn").show();
			if(!markerHide){
			$("#avHideCustMarkerBtn").show();	
			}else{
			$("#avUnhideCustMarkerBtn").show(); 	
			}
                        if(!hideAgentMarker){
			$("#avHideAgentMarkerBtn").show();	
			}else{
			$("#avUnhideAgentMarkerBtn").show(); 	
			}
			$("#avRmvAllMarkerBtn").show();
	});
	}
	
	//Button: Select marker color
    $("#avMarkerColSelBtn").click(function () {
		    console.info('Color selection option');
			$("#avStopMarkerBtn").hide();
			$("#avRmvAllMarkerBtn").hide();
			$("#avHideCustMarkerBtn").hide();
			$("#avUnhideCustMarkerBtn").hide();
                        $("#avHideAgentMarkerBtn").hide();
			$("#avUnhideAgentMarkerBtn").hide();
			$("#divclrselection").show();
			$('#btnredClr').show();
			$('#btnblueClr').show();
			$('#btngreenClr').show();
			
	});
	
	//Register for stroke selection btns 
	for(var i=0; i<annotationStrokeSelBtns.length; i++){
	annotationStrokeSelBtns[i].click(function(e){
			annotate.selectedStrokeSizeVal = $(this).attr('val');
			if(annotate._drawShape != undefined){
			annotate._drawShape.setStrokeSize(annotate.selectedStrokeSizeVal);
                        _cbinstance.setAnnotation(annotate._drawShape);
			}
			$("#colorSelectionDiv").hide();
			$("#strokeSizeSelDiv").hide();
			$("#shapeSelectionDiv").hide();
			$("#avStopAnnotationBtn").show();
			if(!hideSelected){
			$("#avHideAnnotationBtn").show();	
			}else{
			$("#avUnHideAnnotationBtn").show(); 	
			}
			if(!hideAgentAnnotation){
			$("#avHideAgentAnnotationBtn").show();	
			}else{
			$("#avUnHideAgentAnnotationBtn").show(); 	
			}
			$("#avRemoveAllAgentAnnotationBtn").show();
			$("#avShapeBtn").show();
			$("#avAnnotateColSelBtn").show();
			$("#avAnnotateStrokeSizeSelBtn").show();
	});
	}
	
	
    //Button: Logout
    $("#avLogOutBtn").click(function () {

        showLogoutConfirmationModal({
            title: 'Are you sure you want to logout?',
            message: 'Press OK to continue...'
        })
    });

    $('#confirmLogout').click(function () {
        $('#logoutConfirmationModal').hide();

        if (_cbinstance === null) {
            this.createInstance();
        }

        var onSuccess = function (data) {
            console.info('LogoutSuccessHandler: Success: '); //ToDo + result.msg);
            cleanup();
            showLogoutModal({
                title: 'You are successfully logged out',
                message: 'You can start another session from the Home Screen or close the browser.',
                type: 'success'
            });
        };

        var onFailure = function (error) {
            console.warn('UI: Logout:: ' + error.message);
            showLogoutModal({
                title: 'Sorry, Unable to Cancel the Session' + error.getMessage(),
                message: 'Please refresh the browser window and start over',
                type: 'warn'
            });
        };
        _cbinstance.logoutSession().then(onSuccess, onFailure);

        //Remove the stored key on logout
        key = null;
    });

    //Button: RequestControl
    $("#avREQControlBtn").click(function () {
        if (_cbinstance === null) {
            this.createInstance();
        }
        var onSuccess = function (data) {
            console.info('Request Control Successfull');
            if (_cbinstance.getAgentData().getCobrowseState()==="Paused"){
                $('#avRELControlBtn').hide();
                $('#avCANControlBtn').hide();
                $('#avREQControlBtn').hide();
            }
            else{
                $('#avRELControlBtn').hide();
                $('#avCANControlBtn').show();
                $('#avREQControlBtn').hide();
            }
        };
        var onFailure = function (error) {
            console.info('Request Control Failed');
            if((error.getReason().indexOf('1085'))>-1){
            showLogoutModal({
                title: 'Page Request control can\'t be processed',
                message: 'Admin has turned off page request control feature.',
                type: 'error'
            });
            }
        };
        _cbinstance.requestControl().then(onSuccess, onFailure);
    });
    
    //Button: FreeHand shape Annotation
    $("#freeHandItem").click(function () {
	    if (_cbinstance === null) {
            this.createInstance();
        }
        var onSuccess = function (data) {
		    console.info('Annotation shape is set to freehand');
			$("#colorSelectionDiv").hide();
			$("#strokeSizeSelDiv").hide();
			$("#shapeSelectionDiv").hide();
			$("#avAnnotateColSelBtn").show();
			$("#avAnnotateStrokeSizeSelBtn").show();	
			$("#avStopAnnotationBtn").show();
			if(!hideSelected){
			$("#avHideAnnotationBtn").show();	
			}else{
			$("#avUnHideAnnotationBtn").show(); 	
			}
                        if(!hideAgentAnnotation){
			$("#avHideAgentAnnotationBtn").show();	
			}else{
			$("#avUnHideAgentAnnotationBtn").show(); 	
			}
			$("#avRemoveAllAgentAnnotationBtn").show();
			$("#avShapeBtn").show();
	    };
        var onFailure = function (error) {
            console.info('Annotation request Failed');
        };
		 
		annotate._drawShape.setAnnotationType(AvayaCoBrowseClientServices.Services.Cobrowse.Common.AnnotationShapeType.ANNOTATIONSHAPETYPEFREEHAND);
		if(annotate.selectedStrokeColor != undefined){
			annotate._drawShape.setStrokeColor(annotate.selectedStrokeColor);
		}
		if(annotate.selectedStrokeSizeVal != undefined){
			annotate._drawShape.setStrokeSize(annotate.selectedStrokeSizeVal);
		}
     	_cbinstance.setAnnotation(annotate._drawShape).then(onSuccess, onFailure);
    });
    
    //Button: Rectangle shape Annotation
    $("#recItem").click(function () {
	    if (_cbinstance === null) {
            this.createInstance();
        }
        var onSuccess = function (data) {
		    console.info('Annotation shape is set to rectangle');
			$("#colorSelectionDiv").hide();
			$("#strokeSizeSelDiv").hide();
			$("#shapeSelectionDiv").hide();
			$("#avAnnotateColSelBtn").show();
			$("#avAnnotateStrokeSizeSelBtn").show();	
			$("#avStopAnnotationBtn").show();
			if(!hideSelected){
			$("#avHideAnnotationBtn").show();	
			}else{
			$("#avUnHideAnnotationBtn").show(); 	
			}
                        if(!hideAgentAnnotation){
			$("#avHideAgentAnnotationBtn").show();	
			}else{
			$("#avUnHideAgentAnnotationBtn").show(); 	
			}
			$("#avRemoveAllAgentAnnotationBtn").show();
			$("#avShapeBtn").show();
	    };
        var onFailure = function (error) {
            console.info('Annotation request Failed');
        };
		 
		annotate._drawShape.setAnnotationType(AvayaCoBrowseClientServices.Services.Cobrowse.Common.AnnotationShapeType.ANNOTATIONSHAPETYPERECTANGLE)
		if(annotate.selectedStrokeColor != undefined){
			annotate._drawShape.setStrokeColor(annotate.selectedStrokeColor);
		}
		if(annotate.selectedStrokeSizeVal != undefined){
			annotate._drawShape.setStrokeSize(annotate.selectedStrokeSizeVal);
		}
     	_cbinstance.setAnnotation(annotate._drawShape).then(onSuccess, onFailure);
    });
	
	//Button: Circle shape Annotation
    $("#cirItem").click(function () {
	    if (_cbinstance === null) {
            this.createInstance();
        }
        var onSuccess = function (data) {
		    console.info('Annotation shape is set to circle');
			$("#colorSelectionDiv").hide();
			$("#strokeSizeSelDiv").hide();
			$("#shapeSelectionDiv").hide();
			$("#avAnnotateColSelBtn").show();
			$("#avAnnotateStrokeSizeSelBtn").show();	
			$("#avStopAnnotationBtn").show();
			if(!hideSelected){
			$("#avHideAnnotationBtn").show();	
			}else{
			$("#avUnHideAnnotationBtn").show(); 	
			}
                        if(!hideAgentAnnotation){
			$("#avHideAgentAnnotationBtn").show();	
			}else{
			$("#avUnHideAgentAnnotationBtn").show(); 	
			}
			$("#avRemoveAllAgentAnnotationBtn").show();
			$("#avShapeBtn").show();
	    };
        var onFailure = function (error) {
            console.info('Set Annotation request Failed');
        };
		
		annotate._drawShape.setAnnotationType(AvayaCoBrowseClientServices.Services.Cobrowse.Common.AnnotationShapeType.ANNOTATIONSHAPETYPECIRCLE)
		if(annotate.selectedStrokeColor != undefined){
			annotate._drawShape.setStrokeColor(annotate.selectedStrokeColor);
		}
		if(annotate.selectedStrokeSizeVal != undefined){
			annotate._drawShape.setStrokeSize(annotate.selectedStrokeSizeVal);
		}
     	_cbinstance.setAnnotation(annotate._drawShape).then(onSuccess, onFailure);
    });
	
	
    //Button: Start Annotation
    $("#avStartAnnotationBtn").click(function () {
        if (_cbinstance === null) {
            this.createInstance();
        }
        var onSuccess = function (data) {
		    console.info('Allowed to annotate');
			$("#avStopAnnotationBtn").show();
			$("#avHideAnnotationBtn").show();
                        $("#avHideAgentAnnotationBtn").show();
			$("#avRemoveAllAgentAnnotationBtn").show();
			$("#avShapeBtn").show();
			$("#avAnnotateColSelBtn").show();
			$("#avAnnotateStrokeSizeSelBtn").show();
			$("#avStartAnnotationBtn").hide();
			$("#avStartMarkerBtn").hide();
			$("#avStopMarkerBtn").hide();
			$("#avRmvAllMarkerBtn").hide();
			$("#avHideCustMarkerBtn").hide();
			$("#avUnhideCustMarkerBtn").hide();
                        $("#avHideAgentMarkerBtn").hide();
			$("#avUnhideAgentMarkerBtn").hide();
	    };
        var onFailure = function (error) {
            console.info('Annotation request Failed');
        };
     	_cbinstance.startAnnotation().then(onSuccess, onFailure);
    });
	
	//Button: Start Annotation
    $("#avStartMarkerBtn").click(function () {
        if (_cbinstance === null) {
            this.createInstance();
        }
        var onSuccess = function (data) {
		    console.info('Allowed to mark :: ' + data.message);
			$("#avStopMarkerBtn").show();
			$("#avRmvAllMarkerBtn").show();
			$("#avHideCustMarkerBtn").show();
                        $("#avHideAgentMarkerBtn").show();
			$('#avMarkerColSelBtn').show();
			$("#avStartMarkerBtn").hide();
			$("#avStartAnnotationBtn").hide();
	    };
        var onFailure = function (error) {
            console.info('start marker request Failed');
        };
        _cbinstance.setMarkerColor("orange");
        _cbinstance.enableMarker().then(onSuccess, onFailure);
    });
	
	
	
	

	
	//Button: Select Annotation color
    $("#avAnnotateColSelBtn").click(function () {
		    console.info('Color selection option');
			$("#avStopAnnotationBtn").hide();
			$("#avHideAnnotationBtn").hide();
			$("#avUnHideAnnotationBtn").hide();
                        $("#avHideAgentAnnotationBtn").hide();
			$("#avUnHideAgentAnnotationBtn").hide();
			$("#avRemoveAllAgentAnnotationBtn").hide();
			$("#avShapeBtn").hide();
			$("#avAnnotateStrokeSizeSelBtn").hide();
			$("#strokeSizeSelDiv").hide();
			$("#shapeSelectionDiv").hide();
			$("#colorSelectionDiv").show();
			$('#redColorBtn').show();
			$('#blueColorBtn').show();
			$('#greenColorBtn').show();
	});
	
	//Button: Select Annotation stroke size
    $("#avAnnotateStrokeSizeSelBtn").click(function () {
		    console.info('Stroke size selection option');
			$("#avStopAnnotationBtn").hide();
			$("#avHideAnnotationBtn").hide();
			$("#avUnHideAnnotationBtn").hide();
                        $("#avHideAgentAnnotationBtn").hide();
			$("#avUnHideAgentAnnotationBtn").hide();
			$("#avRemoveAllAgentAnnotationBtn").hide();
			$("#avShapeBtn").hide();
			$("#avAnnotateColSelBtn").hide();
			$("#colorSelectionDiv").hide();
			$("#shapeSelectionDiv").hide();
			$("#strokeSizeSelDiv").show();
			$('#smallStrokeSizeBtn').show();
			$('#mediumStrokeSizeBtn').show();
			$('#largerStrokeSizeBtn').show();
	});
	
	//Button: Select Annotation shape type
    $("#avShapeBtn").click(function () {
		    console.info('Annotation shape type selection option');
			$("#avStopAnnotationBtn").hide();
			$("#avHideAnnotationBtn").hide();
			$("#avUnHideAnnotationBtn").hide();
                        $("#avHideAgentAnnotationBtn").hide();
			$("#avUnHideAgentAnnotationBtn").hide();
			$("#avRemoveAllAgentAnnotationBtn").hide();
			$("#avAnnotateColSelBtn").hide();
			$("#avAnnotateStrokeSizeSelBtn").hide();
			$("#colorSelectionDiv").hide();
			$("#strokeSizeSelDiv").hide();
			$("#shapeSelectionDiv").show();
			$("#freeHandItem").show();
			$('#recItem').show();
			$('#cirItem').show();
	});
	
   
    //Button: Stop Annotation
    $("#avStopAnnotationBtn").click(function () {
        if (_cbinstance === null) {
            this.createInstance();
        }
        var onSuccess = function (response) {
		    console.info(response.data);
			$("#avStopAnnotationBtn").hide();
			$("#avHideAnnotationBtn").hide();
			$("#avUnHideAnnotationBtn").hide();
                        $("#avHideAgentAnnotationBtn").hide();
			$("#avUnHideAgentAnnotationBtn").hide();
			$("#avRemoveAllAgentAnnotationBtn").hide();
			$("#avShapeBtn").hide();
			$("#avAnnotateColSelBtn").hide();
			$("#avAnnotateStrokeSizeSelBtn").hide();
			$("#avStartAnnotationBtn").show();
			$("#avStartMarkerBtn").show();
	    };
        var onFailure = function (error) {
            console.info(error._message);
        };
     	_cbinstance.stopAnnotation().then(onSuccess, onFailure);
    });
	
	//Button: Stop marker
    $("#avStopMarkerBtn").click(function () {
        if (_cbinstance === null) {
            this.createInstance();
        }
        var onSuccess = function (response) {
		    console.info(response.message);
			$("#avStopMarkerBtn").hide();
			$("#avRmvAllMarkerBtn").hide();
			$("#avHideCustMarkerBtn").hide();
			$("#avUnhideCustMarkerBtn").hide();
                        $("#avHideAgentMarkerBtn").hide();
			$("#avUnhideAgentMarkerBtn").hide();
			$("#avMarkerColSelBtn").hide();
			$("#avStartMarkerBtn").show();
			$("#avStartAnnotationBtn").show();
	    };
        var onFailure = function (error) {
            console.info(error.data);
        };
     	_cbinstance.disableMarker().then(onSuccess, onFailure);
    });
	
	
    //Button: hide customer Annotation
    $("#avHideAnnotationBtn").click(function () {
        if (_cbinstance === null) {
            this.createInstance();
        }
        var onSuccess = function (response) {
		    console.info(response.data);
			hideSelected = true;
			$("#avUnHideAnnotationBtn").show();
			$("#avHideAnnotationBtn").hide();
	    };
        var onFailure = function (error) {
            console.info(error._message);
        };
     	_cbinstance.hideAllCustomerAnnotations().then(onSuccess, onFailure);
    });
	
    $("#avUnHideAnnotationBtn").click(function () {
    if (_cbinstance === null) {
        this.createInstance();
    }
    var onSuccess = function (response) {
                console.info(response.data);
					hideSelected = false;
                    $("#avUnHideAnnotationBtn").hide();
                    $("#avHideAnnotationBtn").show();
        };
    var onFailure = function (error) {
        console.info(error._message);
    };
    _cbinstance.unHideAllCustomerAnnotations().then(onSuccess, onFailure);
    });
	
    //Button: hide customer Annotation
    $("#avHideAgentAnnotationBtn").click(function () {
        if (_cbinstance === null) {
            this.createInstance();
        }
        var onSuccess = function (response) {
		    console.info(response.data);
			hideAgentAnnotation = true;
			$("#avUnHideAgentAnnotationBtn").show();
			$("#avHideAgentAnnotationBtn").hide();
	    };
        var onFailure = function (error) {
            console.info(error._message);
        };
     	_cbinstance.hideAllAgentAnnotations().then(onSuccess, onFailure);
    });
	
    $("#avUnHideAgentAnnotationBtn").click(function () {
    if (_cbinstance === null) {
        this.createInstance();
    }
    var onSuccess = function (response) {
                console.info(response.data);
					hideAgentAnnotation = false;
                    $("#avUnHideAgentAnnotationBtn").hide();
                    $("#avHideAgentAnnotationBtn").show();
        };
    var onFailure = function (error) {
        console.info(error._message);
    };
    _cbinstance.unHideAllAgentAnnotations().then(onSuccess, onFailure);
    });
	
    $("#avHideCustMarkerBtn").click(function () {
    if (_cbinstance === null) {
        this.createInstance();
    }
    var onSuccess = function (response) {
                console.info(response.data);
					markerHide = true;
                    $("#avHideCustMarkerBtn").hide();
                    $("#avUnhideCustMarkerBtn").show();
        };
    var onFailure = function (error) {
        console.info(error.data);
    };
    _cbinstance.hideAllCustomerMarkers().then(onSuccess, onFailure);
    });
	
	
    $("#avUnhideCustMarkerBtn").click(function () {
    if (_cbinstance === null) {
        this.createInstance();
    }
    var onSuccess = function (response) {
                console.info(response.data);
					markerHide = false;
                    $("#avUnhideCustMarkerBtn").hide();
                    $("#avHideCustMarkerBtn").show();
        };
    var onFailure = function (error) {
        console.info(error.data);
    };
    _cbinstance.unHideAllCustomerMarkers().then(onSuccess, onFailure);
    });
	
    $("#avHideAgentMarkerBtn").click(function () {
    if (_cbinstance === null) {
        this.createInstance();
    }
    var onSuccess = function (response) {
                console.info(response.data);
                    hideAgentMarker = true;
                    $("#avHideAgentMarkerBtn").hide();
                    $("#avUnhideAgentMarkerBtn").show();
        };
    var onFailure = function (error) {
        console.info(error.data);
    };
    _cbinstance.hideAllAgentMarkers().then(onSuccess, onFailure);
    });
	
	
    $("#avUnhideAgentMarkerBtn").click(function () {
    if (_cbinstance === null) {
        this.createInstance();
    }
    var onSuccess = function (response) {
                console.info(response.data);
                    hideAgentMarker = false;
                    $("#avUnhideAgentMarkerBtn").hide();
                    $("#avHideAgentMarkerBtn").show();
        };
    var onFailure = function (error) {
        console.info(error.data);
    };
    _cbinstance.unHideAllAgentMarkers().then(onSuccess, onFailure);
    });
	
	
	
    //Button: hide customer Annotation
    $("#avRmvAllMarkerBtn").click(function () {
        if (_cbinstance === null) {
            this.createInstance();
        }
      _cbinstance.removeAllAgentMarkers();//.then(onSuccess, onFailure);
    });
	
    //Button: hide customer Annotation
    $("#avRemoveAllAgentAnnotationBtn").click(function () {
        if (_cbinstance === null) {
            this.createInstance();
        }
      _cbinstance.clearAllAgentAnnotations();//.then(onSuccess, onFailure);
    });    
    

    //Button: ReleaseControl
    $("#avRELControlBtn").click(function () {
        if (_cbinstance === null) {
            this.createInstance();
        }
        var onSuccess = function (data) {
            console.info('Release Control Successfull');
            agentUIState('InProgress');
        };
        var onFailure = function (error) {
            console.info('Release Control Failed');
        };
        _cbinstance.releaseControl().then(onSuccess, onFailure);
    });

    //Button: ReleaseControl
    $("#avCANControlBtn").click(function () {
        if (_cbinstance === null) {
            this.createInstance();
        }
        var onSuccess = function (data) {
            console.info('Cancel request Control Successfull');
            agentUIState('InProgress');
        };
        var onFailure = function (error) {
            console.info('Cancel request Control Failed');
        };
        _cbinstance.cancelRequestControl().then(onSuccess, onFailure);
    });
    //Button: Sync
    $('#avRefreshBtn').click(function () {
        _cbinstance.onDemandUpdate();
    });

    //Join Live Session (input: name, sessoin Key) -- Customer Initiated Session
    $("#avJoinLiveSessionBtn").click(function () {
        if (_cbinstance === null) {
            this.createInstance();
        }

       
        var name = $('#joinSessionName').val();
        var sessionKey = $('#sessionKey').val();
        
          
        var onSuccess = function (data) {
            console.info('UI: login::  Agent joined the session successfully');
            switchMode();
            agentUIState('InProgress');

        };
        var onFailure = function (error) {
            updateUIonError(error.getMessage(),"Join Session");           

        };
        _cbinstance.joinLiveSession(name, sessionKey).then(onSuccess, onFailure);
    });

    //Request new cobrowse Session -- Agent Initiated Session
    $("#avCreateBtn").click(function () {

        ///
        if (_cbinstance === null) {
            this.createInstance();
        }

        
        var name = $('#name').val();
        
        var locale = $('#lang_selection').val();


        var onSuccess = function (data) {
            //Store the key for Join
            key = _cbinstance.getAgentData().getPassPhrase();
            $('#defaultDiv').hide();
            $('#authPhrase').text(_cbinstance.getAgentData().getPassPhrase());
            try{
                $('#preJoinName').html(decodeURIComponent(_cbinstance.getAgentData().getAgentName()) + ',');
            } catch(e) {
                $('#preJoinName').html(_cbinstance.getAgentData().getAgentName() + ',');
            }            
            $('#preJoinDiv').fadeIn(100);
            $('#preJoinDivBtnGroup').slideDown(600);

        };

        var onFailure = function (error) {
            updateUIonError(error.getMessage(), "Create Session");          
            console.warn('UI: login:: ' + error.getMessage());
        };
        _cbinstance.requestSession(name, locale).then(onSuccess, onFailure);


    });

    $('#avPreJoinCancelBtn').click(function () {
        $('#errorAlertPreJoin').addClass('hide');
        $('#errorAlertDefaultDiv').addClass('hide');
        ///
        if (_cbinstance === null) {
            this.createInstance();
        }

        var onSuccess = function (data) {
            console.info('avPreJoinCancelBtnHandler: Success');
            showLogoutModal({
                title: 'Session Cancelled, Thank you.',
                message: 'Session KEY has been invalidated, You can start another session from the Home Screen or close the browser.',
                type: 'success'
            });
        };

        var onFailure = function (error) {
            console.warn('avPreJoinCancelBtnHandler: error: ' + error.getMessage());
            showLogoutModal({
                title: 'Sorry, Unable to Cancel the Session',
                message: 'Some Error occurred while cancelling the session, Please refresh the browser window',
                type: 'warn'
            });
        };
        _cbinstance.logoutSession().then(onSuccess, onFailure);

        //Remove the stored key on cancel
        key = null;
        $('#defaultDiv').show();
        $('#preJoinDiv').hide();
    });

    //Join Session (input: sessionkey) :: Agent Initiated Session
    $("#avPreJoinGoBtn").click(function () {
        ///
        if (_cbinstance === null) {
            this.createInstance();
        }
        
        var acstoken = _cbinstance.getAgentData().getAgentAuthCode();

        var onSuccess = function (data) {
            switchMode();
            agentUIState('start');
        };

        var onFailure = function (error) {
            $('#errorAlertPreJoin span').text('Unable to Join Session (' + error.getMessage() + ')');
            $('#errorAlertPreJoin').removeClass('hide');
            console.error('UI: login:: ' + error.getMessage());
        };
        _cbinstance.joinSession(acstoken).then(onSuccess, onFailure);
    });
}
;

function registerCallbacksAPI() {

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////// Callbacks from API //////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    _cbinstance.addOnPauseCallback(function () {
        agentUIState('Paused');
    });

    _cbinstance.addOnResumeCallback(function () {        
            agentUIState('InProgress');       
    });

    _cbinstance.addOnControlGrantCallback(function () {
        agentUIState('agentInControl');
    });
	
	 _cbinstance.addOnAnnotationEnabledCallback(function () {        
            agentUIState('AnnotationEnabled');       
    });

    _cbinstance.addOnControlDenialCallback(function () {
        showDenyModal({
            title: 'Your Request has been denied',
            message: 'You may send another Request Control.'
        });
        agentUIState('InProgress');
    });

    _cbinstance.addOnControlRevokeCallback(function () {
        agentUIState('InProgress');
        if ($('#inactiveModal').is(':visible')) {
            stopInactiveMessageTimer();
            $('#inactiveModal').modal('hide');
        }
    });

    //Callback handlers when remote party (customer) closes the session.
    _cbinstance.addOnSessionCloseCallback(function (evt) {
        $('#inactiveModal').modal('hide');
        stopInactiveMessageTimer();
        console.info('onSessionCloseHandler');
        cleanup();
        if (evt.err) {
            showLogoutModal({
                title: 'Session Closed due to Network Error',
                message: evt.msg,
                type: 'error'
            });
        } else {
            if ($('#logoutConfirmationModal')) {
                $('#logoutConfirmationModal').hide();
            }
            var str = evt.msg.split(":");
            var title = "Session Closed by the Customer";
            var message = "You can start another session from the Home Screen or close the browser.";

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

            showLogoutModal({
                title: title,
                message: message,
                type: 'success'
            });
        }
    });

    _cbinstance.addOnCustomerJoinCallback(function () {
        setStatusText(_cbinstance.getAgentData().getCustomerName() + ' is Connected');
        if (_cbinstance.getAgentData().getAgentControlState() === AvayaCoBrowseClientServices.Services.Cobrowse.Common.AgentControlState.AGENTCONTROLTRUESTATE) {
            _cbinstance.disableMarker();
            agentUIState('agentInControl');
        }else{
            agentUIState(_cbinstance.getAgentData().getCobrowseState());
        }
    });


    _cbinstance.addOnConnectionFailureCallback(function (evt) {
        $('#avRefreshBtn').prop('disabled', true);
        var title;
        var message;
        if (evt.isDisconnected) {
            cleanup();
            if(evt.isAgentSessionNotFound){
                title='Session not found.';
                message='Customer is logout or Session not found.';
            }else{
                title='Maximum reconnect attempts exceeded ';
                message='Maximum reconnect attempts exceeded to Server.';
            }
            showLogoutModal({
                title: title,
                message: message,
                type: 'warn'
            });
            stopInactiveMessageTimer();
        }

    });

    _cbinstance.addOnConnectionCallback(function (evt) {		
        if (_cbinstance.getAgentData().getAgentControlState() ===  AvayaCoBrowseClientServices.Services.Cobrowse.Common.AgentControlState.AGENTCONTROLTRUESTATE) {
            agentUIState('agentInControl');
        }
        else {
			if (evt.AISJoin == true) {
				switchMode();
                agentUIState('start');
            }
            else
			{				
                agentUIState(_cbinstance.getAgentData().getCobrowseState());
			}
        }
    });

    _cbinstance.addOnInActivityTimeOutOccurredCallback(function (message) {
        _inactivityMessage = message;
         if (!_IsInactiveLogOut) {
            startInactiveMessageTimer();
        }
    });
    
    _cbinstance.addOnStopInActivityTimeOutCallback(function (message) {
        _IsInactiveLogOut = false;
        console.info('UI :: addOnStopInActivityTimeOutCallback called '+message);
        stopInactiveMessageTimer();

    });
    
    _cbinstance.addOnCustomerDeadCallback(function () {
    });
    
    _cbinstance.addOnCoBrowseWindowResizeCallback(function (winSize) {
        if (winSize.height > $(window).height()) {
            $('#cbeCustScreen').show();
        }
        else {
            $('#cbeCustScreen').hide();
        }
    });   
	_cbinstance.addOnMouseMoveCallback(function (mousePosition) {       
        //console.info('UI :: mousePosition '+mousePosition);    
		var mouseLeft = mousePosition.left - ($('#'+_iframeId).width()/2);
		var mouseTop = mousePosition.top - ($('#'+_iframeId).height()/2)
		$('#'+_iframeId)[0].contentWindow.scrollTo(mouseLeft, mouseTop);
		$('#cobrowseDiv').animate({ scrollTop: mouseTop, scrollLeft: mouseLeft});
		//window.scrollTo(mousePosition.left - ($(window).width()/2), mousePosition.top - ($(window).height()/2));

    });
}
;

function agentUIState(state) {
    console.info('Changing agent state to :' + state);
    switch (state) {
        case 'start':
            $('#avRefreshBtn').hide();             
            $('#cbPaused').hide();
            $('#cbInProgress').hide();          
            $('#avStartAnnotationBtn').hide();
            $('#avStartMarkerBtn').hide();
            $('#avShapeBtn').hide();
            $('#avRemoveAllAgentAnnotationBtn').hide();
            $('#avStopAnnotationBtn').hide();
            $('#avStopMarkerBtn').hide();
            $('#avRmvAllMarkerBtn').hide();
            $('#avHideCustMarkerBtn').hide();
            $('#avUnhideCustMarkerBtn').hide();
            $('#avHideAgentMarkerBtn').hide();
            $('#avUnhideAgentMarkerBtn').hide();
            $('#avAnnotateColSelBtn').hide();
            $('#avMarkerColSelBtn').hide();
            $('#colorSelectionDiv').hide();
            $('#divclrselection').hide();
            $('#avMarkerColSelBtn').hide();
            $('#shapeSelectionDiv').hide();
            $('#avAnnotateColSelBtn').hide();
            $('#strokeSizeSelDiv').hide();
            $('#avHideAnnotationBtn').hide();
            $('#avUnHideAnnotationBtn').hide();
            $('#avHideAgentAnnotationBtn').hide();
            $('#avUnHideAgentAnnotationBtn').hide();
            $('#cbeStatus').show();
            break;
        case 'InProgress':
            $('#avRefreshBtn').hide();
            $('#cbPaused').hide();
            $('#cbInProgress').show();           
            $('#avStartAnnotationBtn').hide();
            $('#avStartMarkerBtn').hide();
            $('#avStopMarkerBtn').hide();
            $('#avRmvAllMarkerBtn').hide();
            $('#avHideCustMarkerBtn').hide();
            $('#avUnhideCustMarkerBtn').hide();
            $('#avHideAgentMarkerBtn').hide();
            $('#avUnhideAgentMarkerBtn').hide();
            $('#avShapeBtn').hide();
            $('#avAnnotateColSelBtn').hide();
            $('#colorSelectionDiv').hide();
            $('#divclrselection').hide();
            $('#avMarkerColSelBtn').hide();
            $('#avAnnotateStrokeSizeSelBtn').hide();
            $('#strokeSizeSelDiv').hide();
            $('#shapeSelectionDiv').hide();
            $('#avRemoveAllAgentAnnotationBtn').hide();
            $('#avStopAnnotationBtn').hide();
            $('#avStopMarkerBtn').hide();
            $('#avHideAnnotationBtn').hide();
            $('#avUnHideAnnotationBtn').hide();
            $('#avHideAgentAnnotationBtn').hide();
            $('#avUnHideAgentAnnotationBtn').hide();           
            $('#cbeStatus').hide();
            $('#startDiv').hide();
            $('#cobrowseDiv').show();
            $('#preJoinDiv').hide();
            //Button: Logout
            $('#avLogOutBtn').show();
            switchControlButton(_cbinstance.getAgentData().getAgentControlState());
            break;            
        case 'Paused':
            $('#avRefreshBtn').hide();
            $('#cbPaused').show();
            $('#cbInProgress').hide();
            $('#avStartAnnotationBtn').hide();
            $('#avStartMarkerBtn').hide();
            $('#avStopMarkerBtn').hide();
            $('#avRmvAllMarkerBtn').hide();
            $('#avHideCustMarkerBtn').hide();
            $('#avUnhideCustMarkerBtn').hide();
            $('#avHideAgentMarkerBtn').hide();
            $('#avUnhideAgentMarkerBtn').hide();
            $('#avShapeBtn').hide();
            $('#avAnnotateColSelBtn').hide();
            $('#colorSelectionDiv').hide();
            $('#divclrselection').hide();
            $('#avMarkerColSelBtn').hide();
            $('#shapeSelectionDiv').hide();
            $('#avAnnotateStrokeSizeSelBtn').hide();
            $('#strokeSizeSelDiv').hide();
            $('#avRemoveAllAgentAnnotationBtn').hide();
            $('#avStopAnnotationBtn').hide();
            $('#avStopMarkerBtn').hide();
            $('#avUnHideAnnotationBtn').hide();
            $('#avHideAnnotationBtn').hide();
            $('#avUnHideAgentAnnotationBtn').hide();
            $('#avHideAgentAnnotationBtn').hide();
            $('#cbeStatus').hide();			
            $('#startDiv').hide();
            $('#cobrowseDiv').show();
            $('#preJoinDiv').hide();
            //Button: Logout
            $('#avLogOutBtn').show();
            switchControlButton();
            break;

        case 'agentInControl':
            $('#defaultDiv').hide();
            $('#startDiv').hide();
            $('#cobrowseDiv').show();
            $('#avLogOutBtn').show();
            $('#avRefreshBtn').prop('disabled', false);
            $('#avRefreshBtn').show();
            $('#avRELControlBtn').show();
            $('#avCANControlBtn').hide();
            $('#cbPaused').hide();
            $('#cbInProgress').show();
            $('#avStartAnnotationBtn').show();
            $('#avStartMarkerBtn').show();
            $('#avREQControlBtn').hide();
            $('#cbeStatus').hide();
            $('#avStopMarkerBtn').hide();
            $('#avRmvAllMarkerBtn').hide();
            $('#avHideCustMarkerBtn').hide();
            $('#avUnhideCustMarkerBtn').hide();
            $('#avHideAgentMarkerBtn').hide();
            $('#avUnhideAgentMarkerBtn').hide();
            $('#avMarkerColSelBtn').hide();
            $("#avStopAnnotationBtn").hide();
            
            $("#avHideAnnotationBtn").hide();
            $("#avUnHideAnnotationBtn").hide();

            $("#avHideAgentAnnotationBtn").hide();
            $("#avUnHideAgentAnnotationBtn").hide();
			
            
            $("#avRemoveAllAgentAnnotationBtn").hide();
            $("#avShapeBtn").hide();
            $("#avAnnotateColSelBtn").hide();
            $("#avAnnotateStrokeSizeSelBtn").hide();

            switchControlButton(_cbinstance.getAgentData().getAgentControlState());
            break;
        case 'logout':
            $('#avRefreshBtn').hide();
            $('#avRELControlBtn').hide();
            $('#avCANControlBtn').hide();
            $('#cbPaused').hide();
            $('#cbInProgress').hide();
            $('#avREQControlBtn').hide();
            $('#avStartAnnotationBtn').hide();
            $('#avStartMarkerBtn').hide();
            $('#avStopMarkerBtn').hide();
            $('#avRmvAllMarkerBtn').hide();
            $('#avHideCustMarkerBtn').hide();
            $('#avUnhideCustMarkerBtn').hide();
            $('#avHideAgentMarkerBtn').hide();
            $('#avUnhideAgentMarkerBtn').hide();
            $('#avShapeBtn').hide();
            $('#avAnnotateColSelBtn').hide();
            $('#colorSelectionDiv').hide();
            $('#shapeSelectionDiv').hide();
            $('#divclrselection').hide();
            $('#avMarkerColSelBtn').hide();
            $('#avAnnotateStrokeSizeSelBtn').hide();
            $('#strokeSizeSelDiv').hide();
            $('#avRemoveAllAgentAnnotationBtn').hide();
            $('#avStopAnnotationBtn').hide();
            $('#avStopMarkerBtn').hide();
            $('#avHideAnnotationBtn').hide();
            $('#avUnHideAnnotationBtn').hide();
            $('#avHideAgentAnnotationBtn').hide();
            $('#avUnHideAgentAnnotationBtn').hide();
            $('#cbeStatus').hide();
            break;
            case 'Waiting for Customer':
                    switchMode();
                    break;
            case 'Idle':
            key = _cbinstance.getAgentData().getPassPhrase();
            $('#defaultDiv').hide();
            $('#authPhrase').text(_cbinstance.getAgentData().getPassPhrase());
            try{
                $('#preJoinName').html(decodeURIComponent(_cbinstance.getAgentData().getAgentName()) + ',');
            } catch(e) {
                $('#preJoinName').html(_cbinstance.getAgentData().getAgentName() + ',');
            }
            $('#preJoinDiv').fadeIn(100);
            $('#preJoinDivBtnGroup').slideDown(600);
			break;
			case 'AnnotationEnabled':
			$("#avStopAnnotationBtn").show();
			$("#avHideAnnotationBtn").show();
			$("#avHideAgentAnnotationBtn").show();
			$("#avRemoveAllAgentAnnotationBtn").show();
			$("#avShapeBtn").show();
			$("#avAnnotateColSelBtn").show();
			$("#avAnnotateStrokeSizeSelBtn").show();
			$("#avStartAnnotationBtn").hide();
			$("#avStartMarkerBtn").hide();
			$("#avStopMarkerBtn").hide();
			$("#avRmvAllMarkerBtn").hide();
			$("#avHideCustMarkerBtn").hide();
			$("#avUnhideCustMarkerBtn").hide();
			$("#avHideAgentMarkerBtn").hide();
			$("#avUnhideAgentMarkerBtn").hide();
 			break;
    }
    
}
function switchControlButton(state){
     switch (state) {
        case AvayaCoBrowseClientServices.Services.Cobrowse.Common.AgentControlState.AGENTCONTROLFALSESTATE:
            $('#avRELControlBtn').hide();
            $('#avCANControlBtn').hide();
            $('#avREQControlBtn').show();
            break;
        case AvayaCoBrowseClientServices.Services.Cobrowse.Common.AgentControlState.AGENTCONTROLTRUESTATE:
            $('#avRELControlBtn').show();
            $('#avCANControlBtn').hide();
            $('#avREQControlBtn').hide();
            break;
        case AvayaCoBrowseClientServices.Services.Cobrowse.Common.AgentControlState.AGENTCONTROLPENDINGSTATE:
            $('#avRELControlBtn').hide();
            $('#avCANControlBtn').show();
            $('#avREQControlBtn').hide();
            break;
        default:
            $('#avRELControlBtn').hide();
            $('#avCANControlBtn').hide();
            $('#avREQControlBtn').hide();
    }
}
function showLogoutModal(info) {

    $('#logoutModal').modal('show');
    $('#logoutModalMsg').text(info.message);
    if (info.type == 'success') {
        $('#logoutModalTitle').text(info.title).removeClass('label-danger').addClass('label-success');
    } else {
        $('#logoutModalTitle').text(info.title).removeClass('label-success').addClass('label-danger');
    }
}
;
// Changes for Deny Control 
function showDenyModal(info) {

    $('#denyModal').modal('show');
    $('#denyModalMsg').text(info.message);
    $('#denyModalTitle').text(info.title).removeClass('label-success').addClass('label-danger');
    $('#denyModal').modal({
        backdrop: 'static',
        keyboard: false
    })
}
;

// Changes for logoutConfirmationModal Control 
function showLogoutConfirmationModal(info) {
    $('#logoutConfirmationModal').modal(); // initialize
    $('#logoutConfirmationModal').modal('show');
    $('#logoutConfirmationModal').show().on('hide', function () {
        $('#logoutConfirmationModal').modal('show');
    });
    $('#logoutConfirmationModalMsg').text(info.message);
    $('#logoutConfirmationModalTitle').text(info.title).removeClass('label-success').addClass('label-danger');
    $('#logoutConfirmationModal').modal({
        backdrop: 'static',
        keyboard: false
    })
}
;

function switchMode() {

    console.info('switchMode: BEGIN');

    //Show or hide relevant UI components
    $('#startDiv').hide();
    $('#cobrowseDiv').show();
    $('#preJoinDiv').hide();

    //Update Status
    setStatusText('Waiting for Customer (KEY: ' + decodeURIComponent(_cbinstance.getAgentData().getPassPhrase()) + ')');

    //Button: Logout
    $('#avLogOutBtn').show();

    console.info('switchMode: END');
}
;

function cleanup() {

    setStatusText('');
    $('#sessionKey').val('');

    //Show or hide relevant UI components
    $('#cobrowseDiv').hide();
    $('#startDiv').show();
    $('#defaultDiv').show();
    $('#preJoinDiv').hide();
    $('#helpMenu').show();

    $('#cbeCustScreen').hide();
    $('#avLogOutBtn').hide();
    agentUIState('logout');
    $('#denyModal').hide();
    $('.modal-backdrop').remove();
    stopInactiveMessageTimer();
    $('#errorAlertDefaultDiv span').text("");
    $('#errorAlertDefaultDiv').addClass('hide');
	annotate._drawShape = new AvayaCoBrowseClientServices.Services.Cobrowse.Common.AnnotationShapeInfo('#A3CEDC','7',AvayaCoBrowseClientServices.Services.Cobrowse.Common.AnnotationShapeType.ANNOTATIONSHAPETYPEFREEHAND);
			annotate.selectedStrokeSizeVal = '7';
			annotate.selectedStrokeColor = '#A3CEDC';
}
;

function setStatusText(msg) {
    if (msg) {
        $('#cbeStatus').text(msg);
        $('#cbeStatus').show();
    } else {
        $('#cbeStatus').hide();
    }
}
;

function getURLParam(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null;
}
;


///////For inactive Timeout /////////////////

function showInactiveModal(info) {
    // $('#inactiveModal').modal(); // initialize
    $('#inactiveModal').modal('show');
    $('#inactiveModal').show().on('hide', function () {
        $('#inactiveModal').modal('show');
    });
    $('#inactiveModalTitle').css('padding', '3px');
    $('#inactiveModalMsg').text(info.message);
    $('#inactiveModalTitle').text(info.title).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 inactiveLogout() {
    if (_cbinstance === null) {
        this.createInstance();
    }
    _cbinstance.updateIdleTime(_inactiveMessageCounter);
    $('#inactiveModal').modal('hide');
    stopInactiveMessageTimer();
    var reason = "inactive_timeout";
    var onSuccess = function (data) {
        console.info('LogoutSuccessHandler: Success: ');
        cleanup();
        showLogoutModal({
            title: 'Inactivity Timeout',
            message: _inactivityMessage,
            type: 'success'
        });
        _inactivityMessage = "";
    };
    var onFailure = function (error) {
        console.warn('UI: Logout:: ' + error.message);
        showLogoutModal({
            title: 'Sorry, Unable to Cancel the Session' + error.getMessage(),
            message: 'Please refresh the browser window and start over',
            type: 'warn'
        });
    };
    _cbinstance.logoutSession(reason).then(onSuccess, onFailure);

    //Remove the stored key on logout
    key = null;

    ///
}
;

function startInactiveMessageTimer() {
    _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({
        title: 'You will be logged out within 60 seconds.  Do you want to stay signed in ?',
        message: 'Press Yes to continue...'
    })
}
;

function stopInactiveMessageTimer() {
    if (_inactiveMessageTimer != null) {
        clearInterval(_inactiveMessageTimer);
    }
    $('#warningMsg').text("");
    _inactiveMessageCounter = 0;
}
;
function updateUIonError(sysMsg, compMsg) {  
    var dispMsg;
    if (sysMsg && sysMsg.indexOf("Unknown Error") > -1) {
        dispMsg='Error in network.Please retry after sometime.';       
    }else if(sysMsg){
        dispMsg=sysMsg;   
    }else{
        dispMsg='Error in network.Please retry after sometime.';
    }
    $('#errorAlertDefaultDiv span').text('Unable to '+compMsg+' (' + dispMsg + ')');
    $('#errorAlertDefaultDiv').removeClass('hide');    
}
;

