window.addEventListener('DOMContentLoaded', function(evt) {
	
    document.addEventListener('tizenhwkey', function(evt) {
        if(evt.keyName === 'back') {
            tizen.application.getCurrentApplication().exit();        	
        }
    });		
	
	try {
		/*
		 *	check files from package /images folder in Tizen platform
		 */
		tizen.filesystem.resolve('wgt-package/images', resolveHandler, errorHandler, 'r');
		document.getElementById('file-selector-wrapper').style.display='none';
	} catch(err) {
		/*
		 *	show file input in desktop web browser
		 */
		document.getElementById('file-list-wrapper').style.display='none';
		var fileSelector = document.getElementById('file-selector');
		fileSelector.addEventListener('change', function(evt) {
			loadFile(this.files[0]);
			this.value = '';
		});		
	};
	
	/*
	 *	list files from package /images directory
	 */
	function resolveHandler(dir) {
		dir.listFiles(function(files){
			files.forEach(function(el,i) {		
				var li = document.createElement('li');
				li.innerHTML = el.name;
				li.setAttribute('data-file-path','images/'+el.name);
				li.addEventListener('touchstart',function(evt){
					loadFile2(this.getAttribute('data-file-path'));
				});
				document.getElementById('file-list').appendChild(li);
			});
		}, errorHandler);
	}
	
	/*
	 *	load file in desktop browser
	 */
	function loadFile(file) {
		console.log('FileReader load: ' + file.name);
		var reader = new FileReader();
		reader.addEventListener('load', function(evt){
			var buffer = evt.target.result;
			processRawData(buffer);
		});
		reader.addEventListener('error', errorHandler);
		reader.readAsArrayBuffer(file);
	}
	
	/*
	 *	load file in Tizen platform
	 */
	function loadFile2(filePath) {
		var req = new XMLHttpRequest();
		req.responseType = 'arraybuffer';
		req.addEventListener('load', function(evt){
			console.log(evt);
			var buffer = evt.target.response;
			processRawData(buffer);
		});
		req.addEventListener('error', errorHandler);
		req.open('GET', filePath, true);
		req.send();
	}	
	
	/*
	 *	reading image data from an array buffer and displaying it by canvas element
	 */	
	function processRawData(buffer) {
		var dv = new DataView(buffer),
			imgMeta = {};
		imgMeta.bmpType = String.fromCharCode(dv.getUint8(0)) + String.fromCharCode(dv.getUint8(1));
		imgMeta.fileSize = dv.getUint32(2, true)/1024;
		imgMeta.imageDataStart = dv.getUint32(10, true);
		
		console.log( 'file type: ' + imgMeta.bmpType ); // BM
		console.log( 'file size: ' + imgMeta.fileSize );
				
		imgMeta.headerSize = dv.getUint32(14, true);
		console.log('header size: ' + imgMeta.headerSize);
		if(imgMeta.headerSize!=40) {
			console.log('not supported bmp header');
			return;
		}
		
		imgMeta.imgWidth = dv.getUint32(18, true);
		imgMeta.imgHeight = dv.getUint32(22, true);
		imgMeta.bitsPerPixel = dv.getUint16(28, true);
		
		console.log('image width: ' + imgMeta.imgWidth);
		console.log('image height: ' + imgMeta.imgHeight);
		console.log('bits per pixel: ' + imgMeta.bitsPerPixel);
		
		var rowSize = Math.floor(((imgMeta.bitsPerPixel * imgMeta.imgWidth + 31) / 32)) * 4,
			pixels = new Uint8Array(buffer, imgMeta.imageDataStart),
			cnvs = document.getElementById('bmp-view'),
			ctx = cnvs.getContext('2d'),
			imageData = ctx.createImageData(imgMeta.imgWidth, imgMeta.imgHeight);
		
		cnvs.width = imgMeta.imgWidth;
		cnvs.height = imgMeta.imgHeight;

		console.log('type: ' + typeof imageData.data + ' , instanceof Uint8ClampedArray: ' + (imageData.data instanceof Uint8ClampedArray));
		
		for (var y = 0, ylen = imgMeta.imgHeight; y < ylen; ++y) { 
			for (var x = 0, bmpIndex, ctxIndex, xlen = imgMeta.imgWidth; x < xlen; ++x) {				 
				bmpIndex = x * 3 + rowSize * y;
				ctxIndex = (x+imgMeta.imgWidth*(imgMeta.imgHeight-y))*4; 
				imageData.data[ctxIndex] = pixels[bmpIndex + 2];
				imageData.data[ctxIndex + 1] = pixels[bmpIndex + 1];
				imageData.data[ctxIndex + 2] = pixels[bmpIndex];
				imageData.data[ctxIndex + 3] = 255;
			} 
		}		
		ctx.putImageData(imageData, 0, 0);
	}
	
	function errorHandler(err) {
		console.log(err);
	}	
});
