var level,isOn;						// variable level of brightness, to check current on/off statuss
var divImage,onImage,offImage;		// variable for div, UI image switch
var inputDiv;

( function () {	
		
	//init variables
	divImage=document.getElementById("divImage");
	onImage="url(\'/" + "../images/on.png" + "\')";
	offImage="url(\'/" + "../images/off.png" + "\')";
	
	inputDiv = document.getElementById("sliderInID");
	
	// Check Camera Flash Support
	var isSupported = tizen.systeminfo.getCapability("http://tizen.org/feature/camera.back.flash"); 
	
	var button = document.querySelector('#divImage');
	
	if(isSupported){
		 button.addEventListener("click",function() {
			 changeImage();			//Change UI button
		 });
	 }
	else{
		alert("LED Flashlight not supported");
	}
	
	
	 level=6;    //default level
	 isOn=0;     //default led off
	 
    window.addEventListener( 'tizenhwkey', function( ev ) {
        if( ev.keyName === "back" ) {
            var activePopup = document.querySelector( '.ui-popup-active' ),
                page = document.getElementsByClassName( 'ui-page-active' )[0],
                pageid = page ? page.id : "";

            if( pageid === "main" && !activePopup ) {
                try {
                	ledFlashOFF();			// Turn off the Flashlight on app exit
                    tizen.application.getCurrentApplication().exit();
                } catch (ignore) {
                }
            } else {
            	ledFlashOFF();
                window.history.back();
            }
        }
    } );
 
} () );

function changeValueCallback(){
	level=document.getElementById("sliderInID").value;
		
	if(isOn === 1){
		ledFlashON();	// To adjust LED Flashlight Level on Change of Input (if On)
	}
}

function changeImage(){		//UI switch on off
	if(isOn === 0){			// LED Flcurrently off	
		isOn = 1;	
		divImage.style.backgroundImage = onImage;
		ledFlashON();
	}
	
	else if (isOn === 1){
		isOn = 0;	
		divImage.style.backgroundImage = offImage;
		ledFlashOFF();
	}
}

function ledFlashON(){	                 // Turn LED On
	
	tizen.systeminfo.getPropertyValue("CAMERA_FLASH", function(flash){
		    try {
		    	flash.setBrightness(level/10);	//set brightness level 0~1
		    	//flash.setBrightness(1);       //Case: If device hardware support is for 0 & 1 only 
		    } 
		    catch (error) {
	            alert("Setting flash brightness failed: " + error.message);
	        }
		    }),
		    function (error) {
	        	alert("Error, name: " + error.name + ", message: " + error.message);
		    }
}

function ledFlashOFF(){   	// Turn LED Off
	tizen.systeminfo.getPropertyValue("CAMERA_FLASH", function(flash){
			try {
				flash.setBrightness(0);	//set brightness level 0~1
			}
			catch (error) {
				alert("Setting flash brightness failed: " + error.message);
			}
    	}),
    	function (error) {
    		alert("Error, name: " + error.name + ", message: " + error.message);
    }
}