//all firefox os app stuff is in here
//requires cordova.js, webchemy.js, lib.js, ui.js
LIB.firefoxOS = {};

(function() {
	"use strict";

	var ENABLED_ANALYTICS = true;

	//localStorage.setItem("isProVersion", "false"); //cross frame communication
	//localStorage.setItem("proKeyPrice", "$0.99");
	

	
	//add a hidden iframe to the body
	function hiddenIframe(url) {
		var iframe = document.createElement("iframe");
		iframe.src = url;
		LIB.css(iframe, {
			position: "absolute",
			left: 0,
			top: 0,
			width: 0,
			height: 0,
			opacity: 0,
			pointerEvents: "none"
		});
		document.body.appendChild(iframe);
		return iframe;
	}
	
	var addWatermark = (function() {
		var watermark = new Image();
		watermark.src = "watermark.png?v=6";
		return function(canvas) {
			var c = canvas.getContext("2d");
			var w = Math.min(402, canvas.width);//Math.min(Math.min(450, canvas.width), Math.max(450, canvas.width / 4));
			var h = (w / watermark.width) * watermark.height;
			c.drawImage(watermark, canvas.width - w - 13, canvas.height - h, w, h);
		};
	})();
	
	
	function makeBlob(canvas) {
		var parts, binStr, buf, view, i, blob;
		parts = canvas.toDataURL("image/png").match(/data:([^;]*)(;base64)?,([0-9A-Za-z+/]+)/);
		binStr = atob(parts[3]);
		buf = new ArrayBuffer(binStr.length);
		view = new Uint8Array(buf);
		for (i = 0; i < view.length; i += 1) {
			view[i] = binStr.charCodeAt(i);
		}
		blob = new Blob([view], {'type': parts[1]});
		return blob;
	}
	
	
	LIB.firefoxOS.webchemyApp = function(p) { //all code for the android version goes in here
		var wc;
		if(!window.cordova) {
			return false;
		}
		if(ENABLED_ANALYTICS) {
			//iframe does the tracking
			hiddenIframe("http://webchemy.org/analytics.php?auth=62385432");
		}
		
		
		p.callback({endSplashAnimation: true});
		wc = new Webchemy({
			port: "FirefoxOSApp",
			retina: true,
			callback: function(val) {
				//todo
				if(val.save) {
				
				
					var pop = new UI.androidSavePopup({
						webchemy: wc,
						image: val.save,
						callback: function(val) {
							if(val.share) {
								//console.log("SHARE!");
							}
						}
					});
					
					var d = new Date();
					var dateStr = d.getFullYear() + "-" + d.getMonth() + "-" + d.getDate() + "_" + d.getHours() + "-" + d.getMinutes() + "-" + d.getSeconds();
					var blob = makeBlob(val.save);
					var sdcard = navigator.getDeviceStorage("pictures");
					var request = sdcard.addNamed(blob, "webchemy" + dateStr + ".png");
					request.onsuccess = function () {
					  pop.saved();
					  //var name = this.result;
					  //console.log('File "' + name + '" successfully wrote on the sdcard storage area');
					}
					// An error typically occur if a file with the same name already exist
					request.onerror = function () {
						pop.failed();
					  //console.warn('Unable to write the file: ' + this.error);
					}
				}
			}
		});

        //document.addEventListener('deviceready', onDeviceReady, false);

		return true;
	};
})();
