var aru = new Array();
var kosar_timer = false;
var kosar = 0;

var aru_class = Class.create();
aru_class.prototype = {
	initialize: function(attr) {
		Object.extend(this, attr || { });
		if (typeof(this.id) == "undefined") return false;
		this.div_id = "aru_kosar_" + this.id;
		this.kosar_last = this.kosarban;
		this.kosar_last_s = new Array();
		this.div = $(this.div_id);
		this.incofus = false;
		window.onmousemove = this.kosar_autosave.bindAsEventListener(this);
		
		this.error_messages();
		this.error_max = this.kosarban;	
		
		this.loading = false;
		$$("div a.photo").each(function(aruimg) {
			new FancyZoom(aruimg)
		});
	},
	
	kosar_autosave: function() {
			if (this.kosarban != this.kosar_last) {
				this.infocus = false;
				this.kosar_mod(0, false, true, this.skey);
			}		
	},
	
	kosar_ajax_post: function(response) {
		$(this.div_id + "_loading").style.display = "none";
		this.loading = false;
		arken_ajax_post(response);
		this.error_messages();
		new Effect.Opacity(this.div, {from: 0.4, to: 1, duration: 0.5});
	},
	
	error_messages: function(show, vh) {
		if (show && $(this.div_id + "_" + show)) {
			if (vh == 1 && $(this.div_id + "_" + show).style.display == "none") {
				new Effect.BlindDown($(this.div_id + "_" + show), {duration: 0.3});
			}
			if (vh != 1 && $(this.div_id + "_" + show).style.display != "none") {
				new Effect.BlindUp($(this.div_id + "_" + show), {duration: 0.3});
			}
		}
		if (this.error_max != this.kosarban) {
			this.error_max = this.kosarban;
			if (this.max == this.kosarban) {
				new Effect.BlindDown($(this.div_id + "_max"), {duration: 0.3});
			} else if ($(this.div_id + "_max").style.display != "none") {
				new Effect.BlindUp($(this.div_id + "_max"), {duration: 0.3});
			}
		}
	},

	select_spec: function(sid, skey) {
		$(this.div_id + "_loading").style.display = "block";
		this.loading = true;
		new Effect.Opacity(this.div, {from: 1, to: 0.4, duration: 0});
		var url = "/json/console/";
		var date = new Date();
		var params = "aruid=" + this.id + "&sid=" + sid + "&skey=" + skey + "&time=" + date.getTime();
		new Ajax.Request(url, {
			method: "post",
			postBody: params,
			onSuccess: this.kosar_ajax_post.bind(this)
		});
	},
	
	kosar_send: function() {
		$(this.div_id + "_loading").style.display = "block";
		this.loading = true;
		new Effect.Opacity(this.div, {from: 1, to: 0.4, duration: 0});
		var url = "/json/console/";
		var date = new Date();
		var params = "aruid=" + this.id + "&me=" + this.kosarban + "&time=" + date.getTime();
		if (this.skey) {
			params += "&skey=" + this.skey;
		}
		if (kosar == 1) {
			params += "&kosar=1";
		}
		new Ajax.Request(url, {
			method: "post",
			postBody: params,
			onSuccess: this.kosar_ajax_post.bind(this)
		});
		kosar_timer = false;
	},
	
	parse_skey: function(skey) {
		if(typeof(this.k_spec) != "object") return;
		this.skey = skey;		
		this.kosarban = 0;
		this.kosar_last = 0;
		this.k_spec.each(function(ks) {
			if (ks[0] == skey) {
				this.kosarban = ks[1];
				if (this.kosar_last_s[skey]) {
					this.kosar_last = this.kosar_last_s[skey];
				} else { 
					this.kosar_last = ks[1];
					this.kosar_last_s[skey] = ks[1];
				}
			}
		}.bind(this));
	},
	
	kosar_mod: function(me, set, notimer, skey) {
		if (this.loading == true) {
			return false;
		}
		if (skey) {
			if (kosar_timer != false && skey != this.skey) {
				this.kosar_send();
				return false;
			}
			this.parse_skey(skey);
		}
		if (set == true) {
			this.kosarban = me;
		} else {
			this.kosarban = this.kosarban * 1 + me;
		}
		this.kosarban = this.kosarban.toFixed(2) * 1;
		if (this.kosarban <= 0) {
			this.kosarban = 0;
			notimer = true;
		}
		if (this.kosarban > this.max) {
			this.kosarban = this.max;
		}
		
		this.error_messages();

		var input = $$("#" + this.div_id + " input");
		if (input[0]) {
			var i;
			var osszdb = 0;			
			if (skey) {
				input.each(function (inp) {
					if (inp.id.indexOf("_input" + skey) > 0) i = inp;
				});
				this.k_spec.each(function(ks) {
					if (ks[0] == skey) ks[1] = this.kosarban;
					osszdb += ks[1];
				}.bind(this));
				
			} else {
				i = input[0];
				osszdb = this.kosarban;
			}
			$$("#" + this.div_id + " span.aru_reszosszeg_num")[0].innerHTML = trim(pont(osszdb * this.ar));
			if (this.infocus == true) {
				return false;
			}
			if (i) {
				i.value = this.kosarban;
			}
		}
		if (this.kosarban == this.kosar_last) return;
		this.kosar_last = this.kosarban;
		if (skey) this.kosar_last_s[skey] = this.kosarban;
		
		if (notimer != true) {
			if (kosar_timer !== false) clearTimeout(kosar_timer);
			kosar_timer = setTimeout(this.kosar_send.bind(this), 800);
		} else {
			this.kosar_send();
		}
	},
	
	kosar_keycheck: function(e, inp) {
		if (this.kme == Math.floor(this.kme)) {
			if ((e.charCode < 48 || e.charCode > 57) && e.charCode != 0) return false;
		} else {
			var pont = e.charCode == 46 || e.charCode == 44 ? true : false;
			if (pont === true && inp.value.lastIndexOf(".") >= 0) return false;
			if ((e.charCode < 48 || e.charCode > 57) && e.charCode != 0 && pont !== true) return false;
		}
		return true;
	},
	
	kosar_valuecheck: function(e, inp) {
		var skey = inp.id.replace(this.div_id + "_input", "");
		if (skey) {
			this.parse_skey(skey);
		}
		
		var k;
		this.infocus = true;
		if (this.kme == Math.floor(this.kme)) {
			k = Math.floor(inp.value);
		} else {
			k = inp.value.replace(",", ".");
		}
		inp.value = k;
		if (k == "") k = 0;
		
		if (e.keyCode == 38 && this.max > k) {
			this.kosar_mod(this.kme, false, false, skey);
			inp.value = this.kosarban;
			return;
		}
		if (e.keyCode == 40 && k > 0) {
			this.kosar_mod(this.kme * -1, false, false, skey);
			inp.value = this.kosarban;
			return;
		}

		if (k > this.max) {
			inp.value = this.max;
		}
		
		this.kosar_mod(k, true, false, skey);
	},
	
	leiras: function(a) {
		if (!$("aru_leiras_" + this.id)) return;
		if (a == 1) {
			new Effect.Appear("aru_leiras_" + this.id, {duration: 0.8});
		} else {
			new Effect.Fade("aru_leiras_" + this.id, {duration: 0.3});
		}
		$("aru_leiras0_" + this.id).style.display = a == 1 ? "block" : "none";
		$("aru_leiras1_" + this.id).style.display = a == 0 ? "block" : "none";
	}
}

var kepek = function(a) {
	page_load("console", false, "images=" + a);
}

var leirasok = function(a) {
	if (a != 0 && a != 1) return;
	var url = "/json/console/";
	var params = "leirasok=" + a;
	new Ajax.Request(url, {
		method: "post",
		postBody: params
	});
	$$("#body div.aru_elem").each(function(div) {
		var d = div.id.split("_");
		if (d[1] && aru[d[1]]) {
			aru[d[1]].leiras(a);
		}
	});
	$("leirasok0").style.display = a == 0 ? "none" : "inline";
	$("leirasok1").style.display = a == 0 ? "inline" : "none";
}

var arken_morph_inner = function(element, innerhtml, mtime) {
	if ($(element.id + "_morph")) {
		var h1 = $(element.id + "_morph").getHeight();
		element.removeChild($(element.id + "_morph"));
	} else {
		var h1 = element.getHeight();
		var pt = element.getStyle("padding-top").replace("px", "");
		var pb = element.getStyle("padding-bottom").replace("px", "");
		h1 = h1 - pt - pb;
	}
	var e = document.createElement("div");
	e.id = element.id + "_morph";
	e.style.overflow = "hidden";
	element.innerHTML = "";
	element.appendChild(e);
	e.innerHTML = innerhtml;
	var h2 = e.getHeight();
	new dropliciousMenu();
	if (h1 < h2) {
		e.style.display = "none";
	}
	if (h2 < h1) {
		e.style.display = "none";
		new Effect.Appear(e, {from: 0, to: 1, duration: 1.2});
	}
	element.style.height = h1 + "px";
	if (h1 != h2) {
		new Effect.Morph(element, {
			style: "height: " + h2 + "px",
			duration: mtime,
			afterFinish: function(){
				e.style.height = h2 + "px";
				if (h2 > h1) {
					new Effect.Appear(e, {
						from: 0,
						to: 1,
						duration: 1.2
					});
				}
			}
		});
	}
}

var arken_ajax_post = function(response) {
	var json = response.responseText.evalJSON();
	json.html.each(function(a) {
		if ($(a.target)) {
			a.html = a.html.replace(/\\/g, "");
			if (a.morph != 0) {
				arken_morph_inner($(a.target), a.html, a.morph);
			} else {
				$(a.target).innerHTML = a.html;
				if (typeof(dropliciousMenu) == "function") {
					new dropliciousMenu();
				}
			}
		}
	});
	check_links();
	if (json.javascript) {
		eval(json.javascript);
	}
//	check_links();
}


var kereses_key = function(e) {
	if ($("kereses2")) {
		$("kereses2").value = $("kereses").value;
	}
	if (e.keyCode == 13) kereses();
}

var kereses = function() {
	var s = $F("kereses");
	if (!s) return false;
	s = escape(s);
	s = s.replace("/", " ");
	window.location.href = "/#kereses," + s + ",1";
//	saved_location = window.location.href = window.location.protocol + "//" + window.location.host + "/#kereses/1/" + escape(q);
//	page_load("kereses/1", false, "q=" + s);
}

var page_load = function(page, attr, postdata) {
	$("body").innerHTML = "<div style='margin: 60px auto; width: 32px'><img src='http://images.arken.hu/1/0/loading2.gif'/></div>";
	$$("body")[0].scrollTo();
	var url = "/json/" + page;
	if (attr) url += "/" + attr;
	var params = postdata ? postdata : "";
	new Ajax.Request(url, {
		method: "post",
		postBody: params, 
		onSuccess: arken_ajax_post
	});
}

var prev_page = "";
var check_links = function() {
	$$("a").each(function(a){
		var reg = /http\:\/\/([^\/]+)\/([ka])([0-9]+)\/?(.*)?$/;
		if (reg.match(a.href)) {
			var r = reg.exec(a.href);
			var p = "";
			a.observe('click', function(event){
				if (r[4] == Math.floor(r[4])) p = ","+r[4];
				a.href = '/#' + r[2] + r[3] + p;
			});
		}
		var reg = /http\:\/\/([^\/]+)\/kosar\/?([0-9]+)?/;
		if (reg.match(a.href)) {
			var r = reg.exec(a.href);
			var p = "";
			a.observe('click', function(event){
				if (r[2]) p = ","+r[2];
				a.href = '/#kosar' + p;
			});
		}
		var reg = /http\:\/\/([^\/]+)\/kereses\/?([^\/]+)?\/?([0-9]+)/;
		if (reg.match(a.href)) {
			var r = reg.exec(a.href);
			var p = "";
			a.observe('click', function(event){
				if (r[2]) p = ","+r[2];
				if (r[3]) p += ","+r[3];
				a.href = '/#kereses' + p;
			});
		}
	});
	$$("#body div.aru_mekedv img").each(function(i) {
		i.observe('mouseover', function(event) {
			mekedv_help = $(i.id.replace("aru_mekedv_ikon_", "aru_mekedv_help_"));
			if (!mekedv_help) return;
			
			mekedv_help.style.left = (mouseX - mekedv_help.getWidth() - 5) + "px";
			mekedv_help.style.top = (mouseY - mekedv_help.getHeight() - 5) + "px";
			mekedv_help.style.display = "block";
		});
		i.observe('mouseout', function(event) {
			if (!mekedv_help) return;
			mekedv_help.style.display = "none";
			mekedv_help = false;
		});
	});
	
	$$("a.lang").each(function(i) {
		if (!i.default_href) i.default_href=i.href;
		i.href = i.default_href + document.location.hash;
	})
	
	if (typeof gapi == "undefined") return;
	gapi.plusone.go("body");
	FB.XFBML.parse($("root"));	
}

var mouseX, mouseY, mekedv_help;
function getcords(e){
        mouseX = Event.pointerX(e);
        mouseY = Event.pointerY(e);
        if (!mekedv_help) return;
		mekedv_help.style.left = (mouseX - mekedv_help.getWidth() - 5) + "px";
		mekedv_help.style.top = (mouseY - mekedv_help.getHeight() - 5) + "px";
}
Event.observe(document, 'mousemove', getcords);

var getsubcats_inprog = false;
var getsubcats = function(id, a) {
	$("kategoriak").style.height = "";
	if ($("kategoriak_morph")) $("kategoriak_morph").style.height = "";
	if (getsubcats_inprog === true) return;
	a.className = "kat_blind_wait";
	getsubcats_inprog = true;
	var kat = $("kat_" + id);
	if (!$("kat_" + id + "_s")) {
		kat.innerHTML += "<div style='display: none' id='kat_" + id + "_s'></div>";
		new Ajax.Request("/json/alkat/" + id, {
			method: "post",
			onSuccess: arken_ajax_post,
			onFailure: function() {
				getsubcats_inprog = false;
				a.style.className = "kat_blind_open";
			}
		});
		return;
	}
	getsubcats_show(id);
}

var getsubcats_show = function(id) {
	if (!$("kat_" + id + "_s")) return;
	//$("butt_" + id).innerHTML = "";
	var d = $("kat_" + id + "_s");
	
	if (d.style.display == "none") { 
		// blinddown glitch fix part 1
		d.style.display = "block";
		d.style.height = d.getDimensions().height + "px";
		d.style.display = "none";
		Effect.BlindDown("kat_" + id + "_s", {
			afterFinish: function() {
				getsubcats_inprog = false;
				// blinddown glitch fix part 2
				d.style.height = "";
				$("butt_" + id).className = "kat_blind_close";
			}
		});
	} else {
		Effect.BlindUp("kat_" + id + "_s", {
			afterFinish: function() {
				getsubcats_inprog = false;
				$("butt_" + id).className = "kat_blind_open";
			}
		});
	}
}

var saved_location = window.location.href;
var load_page = function(hash) {
	hash = hash.replace("#", "");
	var reg = /k([0-9]+),?([0-9]+)?$/;
	if (reg.match(hash)) {
		var r = reg.exec(hash);
		var attr = r[1] + "/";
		attr += r[2] ? r[2] : 1;
		prev_page = hash;
		page_load("kat", attr);
		return;
	}
	var reg = /a([0-9]+)/;
	if (reg.match(hash)) {
		var aid = reg.exec(hash)[1];
		prev_page = hash;
		page_load("aru", aid);
		return;
	}
	var reg = /kosar,?([0-9]+)?/;
	if (reg.match(hash)) {
		var r = reg.exec(hash);
		var attr = r[1] ? r[1] : 1;
		page_load("kosar", attr);
		return;
	}
	var reg = /kereses,?([^\,]+)?\,?([0-9]+)?/;
	if (reg.match(hash)) {
		var r = reg.exec(hash);
		if (r[1]) {
		        r[1] = unescape(r[1]);
			r[1] = r[1].replace("/", " ");
		}
		var attr = r[1] ? r[1] : "";
		if (r[2]) {
		        attr += "/" + r[2];
		}
		page_load("kereses", attr);
		return;
	}
	window.location.href = saved_location;
}

setInterval(function(){
	if (saved_location == window.location.href) return;
	saved_location = window.location.href;
	load_page(window.location.hash);
}, 100);

document.observe('dom:loaded', function(){
	new dropliciousMenu();
	if (window.location.hash) {
		var h = window.location.hash.replace("#", "");
		load_page(window.location.hash);
	}
	check_links();
});

window.fbAsyncInit = function() {
 if (!FB) return;

 FB.init({status: true, cookie: true, xfbml: true});

 FB.Event.subscribe('edge.create', function(href, widget) {
        var reg = /\/a([0-9]+)/;
        var id = reg.exec(href)[1];
        if (!id) return;
        new Ajax.Request("/like/fb/a/" + id);
 });
 FB.Event.subscribe('edge.remove', function(href, widget) {
        var reg = /\/a([0-9]+)/;
        var id = reg.exec(href)[1];
        if (!id) return;
        new Ajax.Request("/like/fb/r/" + id);
 });
};
arken_gplusone = function(g) {
        if (!g.state || !g.href) return;
        var reg = /\/a([0-9]+)/;
        var id = reg.exec(g.href)[1];
        if (!id) return;
	if (g.state == "on") {
                new Ajax.Request("/like/g/a/" + id);
	}
	if (g.state == "off") {
                new Ajax.Request("/like/g/r/" + id);
	}
}


// Select mod
// Depends on Droplicious v.3.0 Created May 21, 2009

var dropliciousMenu = Class.create({
	showingUpDuration: 0.3,
	hidingDuration: 0.1,
	hideDelay: 0.9,
	initialize: function(){
		$$("a.drops").invoke('observe', 'mousemove', this.linkMouseOver.bind(this));
		$$("a.drops").invoke('observe', 'mouseout', this.linkMouseOut.bind(this));
		$$("ul.licious").invoke('observe', 'mousemove', this.submenuMouseOver.bind(this));
		$$("ul.licious").invoke('observe', 'mouseout', this.submenuMouseOut.bind(this));
		$$("ul.k_val_lista").each(function(ul_parent) {
			if (ul_parent.dSetup == 1) return;
			ul_parent.dSetup = 1;
			ul_parent.parentNode.style.width = ul_parent.getWidth()+2 + "px";
			var target_height = 0;
			var ul = ul_parent.select("ul")[0];
			var a_parent = ul_parent.select("a")[0];
			if (ul.getWidth() < (a_parent.getWidth() - 2)) {
				ul.style.width = (a_parent.getWidth() - 2) + "px";
			}
			$A(ul.select("a")).each(function(a) {
				var cnt = 1;
				var backup = a.innerHTML;
				if (target_height == 0) {
					a.innerHTML = "i";
					target_height = a.getHeight();
				}
				a.innerHTML = backup + " i";
				while (a.getHeight() > target_height) {
					cnt++;
					if (cnt > 50) return false;
					ul.style.width = ul.getWidth() + 3 + "px";
					if (a_parent.style.width < ul.getWidth() - 25) {
						a_parent.style.width = ul.getWidth() - 25 + "px";
					}
				}
				a.innerHTML = backup;
			});
			ul.style.display = "none";
		});
	},
	showUpEffect: function(e, effectDuration){
		if(!e.visible()){
			new Effect.BlindDown(e, {
				duration: effectDuration,
				queue: {
					position: 'end',
					scope: e.identify(),
					limit: 2
				}
			});
		}
	},
	hidingEffect: function(e, effectDuration){
		new Effect.BlindUp(e, {
			duration: effectDuration,
			queue: {
				position: 'end',
				scope: e.identify(),
				limit: 2
			}
		});
	},
	linkMouseOut: function(e){
		var dropElement = e.element().next();		
		if (dropElement && dropElement.hasClassName('active')){
			this.setDelayedHide(dropElement);
		}
	},
	linkMouseOver: function(e){
		var dropElement = e.element().next();
		if(!dropElement){
			return;
		}
		dropElement.parentNode.absolutize();
		if (!dropElement.hasClassName('hidding')){
			dropElement.removeClassName('waitingtohide');
		}
		if (!dropElement.hasClassName('active')){
			dropElement.addClassName('active');
			this.showUpEffect(dropElement, this.showingUpDuration);
		}
	},
	submenuMouseOut: function(e){
		var dropElement = e.findElement("ul");	
		if (dropElement && dropElement.hasClassName('active')){
			this.setDelayedHide(dropElement);
		}
	},
	submenuMouseOver: function(e){
		var dropElement = e.findElement("ul");	
		if (dropElement && !dropElement.hasClassName('hidding')){
			dropElement.removeClassName('waitingtohide');
		}
	},
	setDelayedHide: function(e){
		e.addClassName('waitingtohide')
		if(!e.hasClassName('hidding')){
			if (!e.hasClassName('hiddingtimerset')){	
				e.addClassName('hiddingtimerset');
				(function(obj, e){ obj.delayedHide(e); }).delay(this.hideDelay, this, e);
			}
		}
	},
	delayedHide: function(e){
		e.removeClassName('hiddingtimerset');
		if (e.hasClassName('waitingtohide')){
			this.hidingEffect(e, this.hidingDuration);
			e.addClassName('hidding');
			(function(e){
				e.removeClassName('waitingtohide');
				e.removeClassName('hidding');
				e.removeClassName('active');
				e.parentNode.relativize();
			}).delay(this.hidingDuration, e);
		}
	}
});

// fancyzoom
Object.extend(String.prototype, {
  ensureEndsWith: function(str) {
    return this.endsWith(str) ? this : this + str;
  },
  px: function() {
    return this.ensureEndsWith('px');
  }
});

Object.extend(Number.prototype, {
  px: function() {
    return this.toString().px();
  }
});

var Window = {
  size: function() {
		var width  = window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth);
		var height = window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight);
		var x      = window.pageXOffset || (window.document.documentElement.scrollLeft || window.document.body.scrollLeft);
		var y      = window.pageYOffset || (window.document.documentElement.scrollTop || window.document.body.scrollTop);
		return {'width':width, 'height':height, 'x':x, 'y':y}
	}
}

var FancyZoomBox = {
  directory : 'http://kvtimages.arken.hu/1/0/fancy',
  zooming   : false,
  setup     : false,
  
  init: function(directory) {
    if (FancyZoomBox.setup) return;
    FancyZoomBox.setup = true;
    
    var ie = navigator.userAgent.match(/MSIE\s(\d)+/);
    if (ie) {
      var version = parseInt(ie[1]);
      Prototype.Browser['IE' + version.toString()] = true;
      Prototype.Browser.ltIE7 = (version < 7) ? true : false;
    }
    
    var html = '<div id="zoom" style="display:none;"> \
                  <table id="zoom_table" style="border-collapse:collapse; width:100%; height:100%;"> \
                    <tbody> \
                      <tr> \
                        <td class="tl" style="background:url(' + FancyZoomBox.directory + '/tl.png) 0 0 no-repeat; width:20px; height:20px; overflow:hidden;" /> \
                        <td class="tm" style="background:url(' + FancyZoomBox.directory + '/tm.png) 0 0 repeat-x; height:20px; overflow:hidden;" /> \
                        <td class="tr" style="background:url(' + FancyZoomBox.directory + '/tr.png) 100% 0 no-repeat; width:20px; height:20px; overflow:hidden;" /> \
                      </tr> \
                      <tr> \
                        <td class="ml" style="background:url(' + FancyZoomBox.directory + '/ml.png) 0 0 repeat-y; width:20px; overflow:hidden;" /> \
                        <td class="mm" style="background:#fff; vertical-align:top; padding:10px;"> \
                          <div id="zoom_content"> \
                          </div> \
                        </td> \
                        <td class="mr" style="background:url(' + FancyZoomBox.directory + '/mr.png) 100% 0 repeat-y;  width:20px; overflow:hidden;" /> \
                      </tr> \
                      <tr> \
                        <td class="bl" style="background:url(' + FancyZoomBox.directory + '/bl.png) 0 100% no-repeat; width:20px; height:20px; overflow:hidden;" /> \
                        <td class="bm" style="background:url(' + FancyZoomBox.directory + '/bm.png) 0 100% repeat-x; height:20px; overflow:hidden;" /> \
                        <td class="br" style="background:url(' + FancyZoomBox.directory + '/br.png) 100% 100% no-repeat; width:20px; height:20px; overflow:hidden;" /> \
                      </tr> \
                    </tbody> \
                  </table> \
                </div>';
    var body  = $$('body').first();
    body.insert(html);
    
    FancyZoomBox.zoom = $('zoom');
    FancyZoomBox.zoom_table = $('zoom_table');
    FancyZoomBox.zoom_content = $('zoom_content');
    FancyZoomBox.zoom_table.observe('click', FancyZoomBox.hide);
    FancyZoomBox.middle_row = $A([$$('td.ml'), $$('td.mm'), $$('td.mr')]).flatten();
    FancyZoomBox.cells = FancyZoomBox.zoom_table.select('td');
    
    $$('html').first().observe('click', function(e) {
      var click_in_zoom = e.findElement('#zoom'),
          zoom_display  = FancyZoomBox.zoom.getStyle('display');
      if (zoom_display == 'block' && !click_in_zoom) {
        FancyZoomBox.hide(e);
      }
    });

    $(document).observe('keyup', function(e) {
      var zoom_display = FancyZoomBox.zoom.getStyle('display');
      if (e.keyCode == Event.KEY_ESC && zoom_display == 'block') {
        FancyZoomBox.hide(e);
      }
    });
    
    if (Prototype.Browser.ltIE7) {
      FancyZoomBox.switchBackgroundImagesTo('gif');
    }    
  },
  
  show: function(e) {
  	new Effect.Opacity("body", {from: 1, to: 0.3, duration: 1});
    e.stop();
		if (FancyZoomBox.zooming) return;
		FancyZoomBox.zooming   = true;
		var element            = e.findElement('a');
		var related_div        = element.content_div;
		var width              = (element.zoom_width || related_div.getWidth()) + 60;
		var height             = (element.zoom_height || related_div.getHeight()) + 60;
		var d                  = Window.size();
		var yOffset            = document.viewport.getScrollOffsets()[1];
		var newTop             = Math.max((d.height/2) - (height/2) + yOffset, 0);
		var newLeft            = (d.width/2) - (width/2);
		FancyZoomBox.curTop    = e.pointerY();
		FancyZoomBox.curLeft   = e.pointerX();
		FancyZoomBox.moveX     = -(FancyZoomBox.curLeft - newLeft);
		FancyZoomBox.moveY     = -(FancyZoomBox.curTop - newTop);
    FancyZoomBox.zoom.hide().setStyle({
			position	: 'absolute',
			top				: FancyZoomBox.curTop.px(),
			left			: FancyZoomBox.curLeft.px()
		});
    
		new Effect.Parallel([
			new Effect.Appear(FancyZoomBox.zoom, {sync:true}),
			new Effect.Move(FancyZoomBox.zoom, {x: FancyZoomBox.moveX, y: FancyZoomBox.moveY, sync: true}),
			new Effect.Morph(FancyZoomBox.zoom, {
			  style: {
			    width: width.px(),
			    height: height.px()
			  },
				sync: true,
				beforeStart: function(effect) {
    		  if (Prototype.Browser.IE) {
    		    FancyZoomBox.middle_row.invoke('setStyle', {height:(height-40).px()});
    		  }
					FancyZoomBox.fixBackgroundsForIE();
				},
				afterFinish: function(effect) {
				  FancyZoomBox.zoom_content.innerHTML = related_div.innerHTML;
					FancyZoomBox.unfixBackgroundsForIE();
					FancyZoomBox.zooming = false;
				}
			})
		], { duration: 0.5 });
  },
  
  hide: function(e) {
   	new Effect.Opacity("body", {from: 0.3, to: 1, duration: 1});
	
    e.stop();
		if (FancyZoomBox.zooming) return;
		FancyZoomBox.zooming = true;		
		new Effect.Parallel([
			new Effect.Move(FancyZoomBox.zoom, {x: FancyZoomBox.moveX*-1, y: FancyZoomBox.moveY*-1, sync: true}),
			new Effect.Morph(FancyZoomBox.zoom, {
			  style: {
			    width: '1'.px(),
			    height: '1'.px()
			  },
				sync					: true,
				beforeStart: function(effect) {
					FancyZoomBox.fixBackgroundsForIE();
					FancyZoomBox.zoom_content.innerHTML = '';
				},
				afterFinish: function(effect) {
					FancyZoomBox.unfixBackgroundsForIE();
					FancyZoomBox.zooming = false;
				}
			}),
			new Effect.Fade(FancyZoomBox.zoom, {sync:true})
		], { duration: 0.5 });
  },
  
  switchBackgroundImagesTo: function(to) {
    FancyZoomBox.cells.each(function(td) {
      var bg = td.getStyle('background-image').gsub(/\.(png|gif|none)\)$/, '.' + to + ')');
      td.setStyle('background-image: ' + bg);
    });
  },
  
 	fixBackgroundsForIE: function() {
    if (Prototype.Browser.IE7) { FancyZoomBox.switchBackgroundImagesTo('gif'); }
	},
	
	unfixBackgroundsForIE: function() {
    if (Prototype.Browser.IE7) { FancyZoomBox.switchBackgroundImagesTo('png'); }
	}
}

var FancyZoom = Class.create({
	initialize: function(element) {
	  this.options = arguments.length > 1 ? arguments[1] : {};
	  FancyZoomBox.init();
	  this.element = $(element);
		if (this.element) {
		  this.element.content_div = $(this.element.readAttribute('href').gsub(/^#/, ''));
  		this.element.content_div.hide();
  		this.element.zoom_width = this.options.width;
  		this.element.zoom_height = this.options.height;
      this.element.observe('click', FancyZoomBox.show);
		}
	}
});
