( function () {
	window.addEventListener( 'tizenhwkey', function( ev ) {
		if( ev.keyName === "back" ) {
			var page = document.getElementsByClassName( 'ui-page-active' )[0],
				pageid = page ? page.id : "";
			if( pageid === "main" ) {
				try {
					tizen.application.getCurrentApplication().exit();
				} catch (ignore) {
				}
			} else {
				window.history.back();
			}
		}
	} );
} () );


function changeText(data){
	 document.getElementById("textData").innerHTML= 'Reply from App2: '+data;
}

function getDataByAppControl(){
    var appControl = null, successCallback = null, errorCallback = null, appControlReplyCallback = null;
    // Define the data structure describing application control details
    appControl = new tizen.ApplicationControl("http://tizen.org/appcontrol/operation/customAppControl", null,null, null);
    
    // Define the method to call when the invocation ends successfully
    successCallback = function() {
        console.log("launch application control succeed");
    };

    // Define the method to invoke when an error occurs
    errorCallback = function(e) {
        alert("App 2 Sample \n must be installed.");
        console.error("launch application control failed. reason: " + e.message);
    };
    
    // Define the method to invoke when the application gets back results from the App 2 application
    appControlReplyCallback = {
	    // When succeeded to get a reply from the App 2 application
	    onsuccess: function(data) {
	        	changeText(data[0].value[0]);
		        console.log(data[0].value[0]);
	       
	    },
	    // When failed to get a reply from the App 2 application
	    onfailure: function() {
	        alert("Failed to get a reply \n from the App 2");
	        console.error("Failed to get a reply from the App 2");
	    }
    };
    
    try {
        // Launch an application with the specified application control
        tizen.application.launchAppControl(
            appControl,
            null,
            successCallback,
            errorCallback,
            appControlReplyCallback
        );
    } catch (error) {
        console.error("launchAppControl(): " + error.message);
    }
    
      
}


function setEvent() {
	document.querySelector("#btn-call").addEventListener("click", getDataByAppControl);
}

function init() {
	setEvent();
}

window.onload = init;
