/**
	Auto Zoom Extension for Google Chrome by Szsz.pl

	Copyright (c) 2009, 2010, Szsz.pl All rights reserved
	Use of this source code is governed by a BSD-style license
	that can be found in the LICENSE file.
*/

(function() {

function setCookie(k, v, path)
{
	var d=new Date();

	/* erase settings from subdirectory (older releases) */
	document.cookie = k + "=" + escape(v) + ";expires=" + d.toGMTString();

	d.setDate(d.getDate() + 30);
	document.cookie = k + "=" + escape(v) + ";path=" + (path || "/") + ";expires=" + d.toGMTString();

}

function getCookie(k)
{
	var b, e;

	b = document.cookie.indexOf(k + "=");
	if (b == -1) return null;
	b += k.length + 1;

	e = document.cookie.indexOf(";", b);
	if (e == -1) e = document.cookie.length;

	return unescape(document.cookie.substring(b, e));
}

function setZoom() {

	/* upvalue zoom, fix */

	/* wait */
	if(document == null || document.body == null || document.body.parentElement.style == null) {
		setTimeout(setZoom, 10);
		return;
	}

	/* do! */
	if (fix) {
		document.body.parentElement.style.zoom = null;
		zoomFix(zoom);
	} else {
		zoomFix();
		document.body.parentElement.style.zoom = zoom + "%";
	}

	/* store & notify */
	setCookie("x-autozoom",	zoom + (fix?"t":"f"), zoomPath);
	chrome.extension.sendRequest({zoom:zoom});
}

/* listen to zoom requests */
chrome.extension.onRequest.addListener(
	function (msg, sender, sendResponse) {
		if(msg.zoom) {
			zoom = msg.zoom;
			fix  = msg.fix;
			setZoom();
		}
		if(msg.test) {
			zoomTest(msg.test);
		}
		sendResponse({zoom:zoom, fix:fix, fixname:zoomFixName}); /* return current value */
	}
);

/* keyboard support */
window.addEventListener("keypress", function(e) {
	/* e.preventDefault();	*/
	/* e.stopPropagation(); */
	if (e.ctrlKey) switch(e.keyCode) {
	case 27: /* [ */
		zoom -= 10;
		if (zoom < 10) zoom = 10;
		setZoom();
		break;
	case 28: /* \ */
		zoom = 100;
		setZoom();
		break;
	case 29: /* ] */
		zoom += 10;
		setZoom();
		break;
	default:
	} 
}, false);


/* init */
var zoom = parseInt(getCookie("x-autozoom"));
var fix =  (getCookie("x-autozoom-fix") == "true") || /t$/.test(getCookie("x-autozoom"));	/* Text | Full */
if (zoom) setZoom()
else chrome.extension.sendRequest({}, function(response) {
	zoom = parseInt(response.zoom) || 100;
	setZoom();
});

/* todo: remove this after 2010-03-01 */
document.cookie = "x-autozoom-fix=;path=/;expires=Mon, 01 Feb 2010 00:00:00 GMT"

})();
