( 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();
			}
		}
	} );
} () );

var reqAppControl = null;

/**
 * Take decision if the app is launched by AppControl or not 
 * 
 */
function checkAppControl() {
    try {
        // Get the requested application control passed to the current application
        reqAppControl = tizen.application.getCurrentApplication().getRequestedAppControl();

        if (reqAppControl && reqAppControl.appControl.operation === "http://tizen.org/appcontrol/operation/customAppControl") {
            // Display the information about the requested Application Control
            console.log("Launched by AppControl");
            document.getElementById("data").innerHTML= "Launched by AppControl";
        	
        } else {
        	 console.log("Direct Launched");
        }
    } catch (error) {
        console.error("checkAppControl(): " + error.message);
    }
}




function init(){
    checkAppControl();
    
    document.querySelector("#btnSend").addEventListener("click", function() {
        try {
        	
        	 var data = null;

         try {
             
        	 var dateData = document.getElementById("dateData").value;
        	 var timeData = document.getElementById("timeData").value;
        	 var notRobot = document.getElementById("notRobot").value;
        	 var sendData = dateData+' '+timeData+' '+notRobot;
        	 // Define the data in a key/value-pair format to be passed through the Application Control interface
             // The value must be a DOMString array
             data = new tizen.ApplicationControlData("text", [sendData]);

             // Pass the data to the App 2
             // The data must be an Object array
             reqAppControl.replyResult([data]);

             // Close the current application (App 1)
             tizen.application.getCurrentApplication().exit();
         } catch (e) {
             alert("Return failed. \n reason: " + e.message);
             console.error("return failed. reason: " + e.message);
         }
        	
        	
        	
        	
            tizen.application.getCurrentApplication().exit();
        } catch (error) {
            console.error("getCurrentApplication(): " + error.message);
        }
    });
    
    
}

window.onload = init;
