////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Controller  - Sample Client //////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

var _iframeId = 'iframeDiv';
var _csinstance = null;


function contextStoreInit() {

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

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

    registerCallbacksUI();

}
;

function authorizationSettings(){
	if($("#enableAuthorization").is(':checked')){
		$("#Authorization").show();
	}else{
		$("#Authorization").hide();
	}
}

function createInstance() {
	var clusterIP = $('#clusterIP').val();
	var guestUsage = ($("#enableAuthorization").is(':checked') ? false : true);
	resetResponse();

    _csconfig = new AvayaDataStoreClient.Config.CsConfiguration();
    console.info('Data Store Engine Load Complete');
    console.info('[jQuery]: ' + $().jquery);
	_csconfig.isGuest = guestUsage;
	if (!guestUsage){
		var token = $('#token').val();
		_csconfig.serverInfo.token = token;
	}
	_csconfig.serverInfo.hostName = clusterIP;
    _csconfig.serverInfo.isSecure = false;
    _csconfig.enabled = true;
    var _customerManagementClient = new AvayaDataStoreClient(_csconfig);
    _customerManagementClient.registerlogger(window.console);
    _csinstance = _customerManagementClient.createDataStoreService(_csconfig, 'CustomerManagement');
}

//function createInstanceWithoutAuthorization() {
//	var clusterIP = $('#clusterIP').val();
//	resetResponse();
//
//    _csconfig = new AvayaDataStoreClient.Config.CsConfiguration();
//    console.info('Data Store Engine Load Complete');
//    console.info('[jQuery]: ' + $().jquery);
//	_csconfig.isGuest = true;
//	_csconfig.serverInfo.hostName = clusterIP;
//    _csconfig.serverInfo.isSecure = false;
//    _csconfig.enabled = true;
//    var _customerManagementClient = new AvayaDataStoreClient(_csconfig);
//    _customerManagementClient.registerlogger(window.console);
//    _csinstance = _customerManagementClient.createDataStoreService(_csconfig, 'CustomerManagement');
//}

function resetRequestDetails(){
	$('#requestMethodName').text('');
	$('#requestBody').text('');

	if (document.getElementById('requestDetail')){
		document.getElementById('requestDetail').style.display = 'none';
	}
	document.getElementById('progressDiv').style.display = 'none';
}

function resetResponse(){
	$('#responseMessageSuccess').text('');
	$('#responseMessageError').text('');
	$('#responseMessageErrorCode').text('');
	if (document.getElementById('responseAlertSuccess')){
		document.getElementById('responseAlertSuccess').style.display = 'none';
	}
	if (document.getElementById('responseAlertError')){
		document.getElementById('responseAlertError').style.display = 'none';
	}
}

function requestDetails(methodName, requestBody){
	resetRequestDetails();
	$('#requestMethodName').text(methodName);
		document.getElementById('requestBodyLabel').style.display = 'block';
	if (requestBody === ""){
		document.getElementById('requestBodyLabel').style.display = 'none';
	}
	$('#requestBody').text(requestBody);
	document.getElementById('requestDetail').style.display = 'block';
	$('#progressMessage').text('Processing...');
	document.getElementById('progressBar').className ='progress-bar progress-bar-info progress-bar-striped active';
	document.getElementById('progressDiv').style.display = 'block';
}

function onSuccess (response) {
	$('#response').val(JSON.stringify(response));
	$('#responseMessageSuccess').text(JSON.stringify(response));
	document.getElementById('responseAlertSuccess').style.display = 'block';
	$('#progressMessage').text('Complete');
	document.getElementById('progressBar').className='progress-bar progress-bar-success';
};

function onFailure (error) {
	var err = error._reason.responseText;
	var requestType = "Request";
	console.error(requestType + ' FAILED: ' + err);
	if (err === ""){
        err = "Connection to Customer Management Service Failed. Please ensure IP has been set, ensure the browser is CORS enabled or check connection";
	}else{
		$('#responseMessageErrorCode').text(error._reason.status);
	}
	$('#responseMessageError').text(err);
	document.getElementById('responseAlertError').style.display = 'block';
	$('#progressMessage').text('Failed');
	document.getElementById('progressBar').className='progress-bar progress-bar-danger';
};


//function generateToken() {
//	var scope = $('#scope').val();
//	var username = $('#username').val();
//	var password = $('#password').val();
//
//	this.createInstanceWithoutAuthorization();
//
//	var onTokenSuccess = function (response) {
//		var generatedToken = response.token;
//		$('#token').val(generatedToken);
//		$('#responseMessageSuccess').text(generatedToken);
//		document.getElementById('responseAlertSuccess').style.display = 'block';
//	};
//
//	var onTokenFailure = function (error) {
//		var err = error._reason.responseText;
//		console.error('Token Generatation FAILED: ' + err);
//		$('#token').val(err);
//		$('#responseMessageError').text(err);
//		$('#responseMessageErrorCode').text(error._reason.status);
//		document.getElementById('responseAlertError').style.display = 'block';
//	};
//
//	_csinstance.generateToken(scope,username,password).then(onTokenSuccess,onTokenFailure);
//
//}

function getCRMRecord() {
    var custId = $('#custId-GetCRMRecord-input').text().trim();
    var crmId = $('#crmId-GetCRMRecord-input').text().trim();
    var phone = $('#phone-GetCRMRecord-input').text().trim();
    var email = $('#email-GetCRMRecord-input').text().trim();
    var social = $('#social-GetCRMRecord-input').text().trim();

    requestDetails('getCRMRecord', "");
	this.createInstance();
    _csinstance.getCRMRecord(custId, crmId, phone, email, social).then(onSuccess, onFailure);
}

function getCustomerId() {
    var crmId = $('#crmId-GetCustomerId-input').text().trim();
    var phone = $('#phone-GetCustomerId-input').text().trim();
    var email = $('#email-GetCustomerId-input').text().trim();
    var social = $('#social-GetCustomerId-input').text().trim();


    requestDetails('getCustomerId', "");
    this.createInstance();
    _csinstance.getCustomerId(crmId, phone, email, social).then(onSuccess, onFailure);
}

function getCustomerJourney() {
    var workReqId = $('#getCustomerJourneyWorkReqId').val();
    var custId = $('#custId-GetCustomerJourney-input').text().trim();

    requestDetails('getCustomerJourney', "");
    this.createInstance();
    _csinstance.getCustomerJourney(workReqId, custId).then(onSuccess, onFailure);
}

function registerCallbacksUI() {

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

    var key = null;

    //Request new context creation
    $("#avCreateBtn").click(function () {
		this.createContext();

    });
}
;

function cleanup() {
    $('#contextData').val('');
}
;

function openRequest(evt, reqName) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(reqName).style.display = "block";
    evt.currentTarget.className += " active";
};


/* Set the width of the side navigation to 250px */
function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
};

/* Set the width of the side navigation to 0 */
function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
};

function editLabel(element) {
        var txt = $("#"+element).text();
		if (txt ===''){
			txt = $("#"+element).val();
		}
    $("#" + element).replaceWith("<input id='" + element + "' maxlength='30' type='text' />");
        $("#"+element).val(txt);
};

function saveLabel(element) {
        var txt = $(this).val();
        $(this).replaceWith("<span id='"+element+"' class='"+element.class+"' ></span>");
		if (txt !==''){
			$("#"+element).text(txt);
		}else{
			$("#"+element).text('"+element.default+"');
		}
};

   $(document).on("click", "span.queryParams", function () {
    var clickedID = $(this).attr('id');
	var txt = $("#"+clickedID).text();
		var pl = $(this).attr('title');
		if (txt ===''){
			txt = $("#"+clickedID).val();
		}
		$("#clearField").hide();
		$("#"+clickedID).replaceWith("<input class='queryParams queryInput' id='"+clickedID+"' maxlength='30' type='text' /><span id='clearField' class='glyphicon glyphicon-remove queryInput' onClick='clearLabel(this, "+clickedID+");' ></span></span>");
		$("#"+clickedID).attr("placeholder", pl);
        $("#"+clickedID).val(txt);
	});

    function clearLabel(self, obj) {
		var objId = obj.id;
		var	selfId = self.id;
        $("#"+objId).val('');
        $("#"+selfId).remove();
        $("#"+objId).blur();
	}

	$(document).on("blur", "input.queryInput", function () {

    var blurredID = this.id;
	var txt = $(this).val();
	var pl = $(this).attr('placeholder');
	if (txt !=='' && txt !== pl){
		if (!(blurredID.includes('input'))){
			$(this).replaceWith("<span class='label label-success queryParams' id='"+blurredID+"-input' ><span class='glyphicon glyphicon-ok' > "+ txt + " </span></span>");
		}else{
			$(this).replaceWith("<span class='label label-success queryParams' id='"+blurredID+"' ><span class='glyphicon glyphicon-ok' > "+ txt + " </span></span>");
		}

		$("#"+blurredID+"-input").attr("title", pl);
	}else{
		$(this).replaceWith("<span class='label label-default queryParams' id='"+blurredID+"' ></span>");
		$("#"+blurredID).text(pl);
		$("#"+blurredID).attr("title", pl);
	}
	$("#clearField").remove();
	});

