var $$ = {
	trim: function(s) {
		return s.replace(/(^\s*)|(\s*$)/g, "");
	},
	random: function(min, max, exact) {
		if (arguments.length === 0) {
			return Math.random();
		} else if (arguments.length === 1) {
			max = min;
			min = 0;
		}
		var range = min + (Math.random() * (max - min));
		return exact === void(0) ? Math.round(range) : range.toFixed(exact);
	},
	bytesToSize: function (bytes) {
        var sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
        if (bytes == 0) return '0 B';
        var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
        if (i == 0) return bytes + ' ' + sizes[i];
        return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
    },
	initEvent: function() {
		//drop file
		document._OnDropFile = function(filepath) {
			if (!$("#open").is(":hidden")) $$.OpenAPK(filepath);
		}
		$(document).bind("contextmenu",function(e){   
	        return false;
	    });
		$('.header .config').click(function() {
			$$.LoadSetting();
			return false;
		});
		$('.header .close').click(function() {
			$$.callpy('do_close', '');
			return false;
		});
		$('#btn-select').click(function() {
			$$.SelectAPK();
		});
		$('#btn-back').click(function() {
			$$.GoOpenPage();
		});
		$('#btn-install').click(function() {
			$$.InstallAPK();
		});
		$('#btn-after').click(function() {
			$$.AfterAPK();
		});
		$('#btn-save-config').click(function() {
			$$.SaveSetting();
		});
		$$.initFile();
	},
	initABG: function() {
		var alist = $("a.bb");
		var alen = alist.length;
		for (var x = 0; x < alen; x++) {
			var elac = $(alist[x]); (function(ela) {
				var bbfile = 'images/' + ela.attr("bb");
				if (typeof bbfile == 'string') {
					var img = new Image();
					img.onload = function() {
						var width = this.width / 3;
						var height = this.height;
						ela.css('background', 'url("' + bbfile + '") no-repeat 0px top');
						ela.css('width', width + 'px');
						ela.css('height', height + 'px');
						ela.css('display', 'block');
						ela.hover(function() {
							ela.css("background-position", "-" + width + "px top")
						},
						function() {
							ela.css("background-position", "0px top")
						});
						ela.bind("mousedown",
						function(e) {
							ela.css("background-position", "-" + width * 2 + "px top")
						});
						ela.bind("mouseup",
						function(e) {
							ela.css("background-position", "0px top")
						});
					}
					img.src = bbfile;
				}
			})(elac);
		}
	},
	checkUpdate: function() {
		$$.callpy('do_loadsetting', '',function(result) {
			var json = JSON.parse(result);
			if (json['autoupdate']) {
				$$.callpy('do_checkupdate', 'http://www.apkpure.com/apk-install-version.htm',function(result) {
					if (result == "1") {
						$('#updateModal').modal();
					}
				});
			}
		});
	},
	initFile: function() {
		$('#file').remove();
		var f = $('<input type="file" id="file">');
		f.change(function() {
			$$.OpenAPK($(this).val());
		});
		$('#open .select').append(f);
	},
	alert: function(s) {
		$('#alert .modal-body').text(s);
		$('#alert').modal();
	},
	OpenUpdate: function() {
		$('#updateModal').modal('hide');
		$$.callpy('do_openurl', 'http://www.apkpure.com/apk-install.htm/?utm_source=apkinstall&utm_medium=update&utm_campaign=software');
	},
	callpy: function(url, param, callback) {
		if (typeof param == 'object') param = JSON.stringify(param);
		window.external.CallPy(url, param,
		function(result) {
			if (callback) callback(result);
		});
	},
	LoadSetting: function() {
		$$.callpy('do_loadsetting', '',function(result) {
			var json = JSON.parse(result);
			$('#ck_scanapk').attr("checked", json['scanapk']);
			$('#ck_autoupdate').attr("checked", json['autoupdate']);
			$('#configModal').modal();
		});
	},
	SaveSetting: function() {
		var json = {
			'scanapk': ($('#ck_scanapk:checked').length > 0 ? true: false),
			'autoupdate': ($('#ck_autoupdate:checked').length > 0 ? true: false)
		};
		$$.callpy('do_savesetting', json,function(result) {
			$('#configModal').modal('hide');
		});
	},
	GoOpenPage: function() {
		$$.initFile();
		$('#open').show();
		$('#info').hide();
		$('#install').hide();
	},
	GoInfoPage: function() {
		$('#open').hide();
		$('#info').show();
		$('#install').hide();
	},
	GoInstallPage: function() {
		$('#open').hide();
		$('#info').hide();
		$('#install').show();
	},
	SelectAPK: function() {
		$('#file').trigger('click');
	},
	OpenAPK: function(filepath) {
		if (typeof filepath != 'string' || filepath.length == 0) return;
		$$.callpy("do_openapk", filepath,function(result) {
			var json = JSON.parse(result);
			if (json['err'] != 'ok') {
				$$.alert(json['err']);
				$$.GoOpenPage();
				return;
			}
			$("#apkicon").attr('src', json['icon']);
			$("#apkname").html(json['name']);
			$("#apksize").html($$.bytesToSize(json['size']));
			$$.OpenAPK.ext = json['ext'].toUpperCase();
			$("#file_type").html($$.OpenAPK.ext);
			$("#apkver").html(json['version']);
			$("#sdkver").html(json['android_sdk']);
			document['_apkfile'] = filepath;
			$$.GoInfoPage();
		});
	},
	animateTween:['Quadratic','Circular','Cubic','Quartic','Quintic','Exponential'],
	animateList:[
		{t:3000,x:10,a:'Quadratic'},
		{t:10000,x:5,a:'Circular'},
		{t:2000,x:15,a:'Cubic'},
		{t:10000,x:10,a:'Quartic'},
		{t:2000,x:20,a:'Quintic'},
		{t:7000,x:10,a:'Exponential'},
		{t:60000,x:10,a:'Quadratic'},
		{t:120000,x:10,a:'Quadratic'}
	],
	animate:function(time) {
		requestAnimationFrame($$.animate);
		TWEEN.update(time);
	},
	setProgress: function(t,fn) {
		if (t==1) {
			$$.setProgress.animate = 0;
			$$.setProgress.animateIndex = 0;
			$$.setProgress.now = 0;
			$$.setProgress.tween = null;
			$("#progress").css('width', '0%');
		} else if(t==2) {
			if($$.setProgress.animateIndex < $$.animateList.length){
				var al = $$.animateList[$$.setProgress.animateIndex];
				$$.setProgress.tween = new TWEEN.Tween({x:$$.setProgress.now}).to({x:$$.setProgress.now+al.x},al.t).easing(TWEEN.Easing[$$.animateTween[$$.random(0,$$.animateTween.length-1)]].InOut).onUpdate(function(){
					var x = Math.round(this.x);
					$$.setProgress.now = x;
					//$("#progress").text(x + '%');
					$("#progress").css('width', x + '%');
	            }).onComplete(function(){
	            	$$.setProgress.animateIndex++;
	            	$$.setProgress(2);
	            }).start();
	            if($$.setProgress.animate==0){
	            	$$.animate();
	            	$$.setProgress.animate=1;
	        	}
	        }
		}else if(t==3){
			if($$.setProgress.tween){
				$$.setProgress.tween.stop();
				$$.setProgress.tween = new TWEEN.Tween({x:$$.setProgress.now}).to({x:100},1500).easing(TWEEN.Easing.Exponential.InOut).onUpdate(function(){
					var x = Math.round(this.x);
					$$.setProgress.now = x;
					$("#progress").css('width', x + '%');
	            }).onComplete(function(){
	            	fn && fn();
	            }).start();
	        }else{
	        	fn && fn();
	        }
		}
	},
	InstallAPK: function() {
		filepath = document['_apkfile'];
		if (typeof filepath != 'string' || filepath.length == 0) return;
		$("#install_info .c").html('');
		$("#loading").show();
		$("#install_info").hide();
		$$.GoInstallPage();
		$("#progress_info").html('Initializing, please wait ...');
		$$.setProgress(1);
		var isSetProgress = false;
		var progressinfo = setInterval(function() {
			$$.callpy("do_getprogress", '',function(result) {
				var json = JSON.parse(result);
				if(json['msg']){
					$("#progress_info").html(json['msg'].replace(/APK/g, $$.OpenAPK.ext));
					if(!isSetProgress){
						isSetProgress = true;
						$$.setProgress(2);
					}
				}
			});
		},1000);
		var info = {
			location: 0,
			file: filepath
		};
		$$.callpy("do_installapk", info,function(result) {
			var json = JSON.parse(result);
			$$.setProgress(3,function(){
				document['_apkok'] = json['err'];
				$("#install_info .c").html(json.msg.replace(/APK/g, $$.OpenAPK.ext));
				$("#loading").hide();
				$("#install_info").show();
				$("#progress_info").html('');
				clearInterval(progressinfo);
			});
		});
	},
	AfterAPK: function() {
		if (document['_apkok'] == true) $$.GoOpenPage();
		else $$.GoInfoPage();
	},
	init: function() {
		$$.checkUpdate();
		$$.initEvent();
		$$.initABG();
		//Check command line
		$$.callpy("do_checkcommandline", "", function(result) {
			if (typeof result == 'string' && result.length > 1) {
				$$.OpenAPK(result);
			}
		});
	}
};

(function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] 
                                   || window[vendors[x]+'CancelRequestAnimationFrame'];
    }
 
    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); }, 
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };
 
    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());

$(function() {
	$$.init();
});