var lastMobileFilter=-1;

var varClickAllowed=true;

function clickAllowed(b) {

	varClickAllowed = b;
	if(b) {
		document.getElementById('paramloading').style.display="none";
		document.getElementById('paramloading2').style.display="none";
		document.getElementById('paramloading3').style.display="none";
	}
	else {
		document.getElementById('paramloading').style.display="block";
		document.getElementById('paramloading2').style.display="block";
		document.getElementById('paramloading3').style.display="block";
	}
}

var Matrix = new Class({
	Implements: [Options],

	options: {
		id: 'matrix',
		imgpath: '/img',
		width: 200,
		height: 200,
		border: 4,
		show: 1				// default: show newest (1) or all (2)
	},

	initialize: function(options) {
		this.setOptions(options);

		this.options.whFactor = Math.floor(this.options.width / this.options.height);
		this.options.border2  = this.options.border * 2;

		this.container = $(this.options.id);
		this.shadow = $('loading');
		this.visible = new Array();
		this.visibleIdx = new Hash();

		this.cbShow = $$("div[name='show']");
		this.cbShow.each(function(e) {
			e.addEvent('click', function() {

				if(varClickAllowed)
					this.selectShow(e.id.substring(4));

			}.bind(this));
		}.bind(this));

		this.cbCat = $$("div[name='category']");
		this.cbCat.each(function(e) {

			this.currentCat.set(e.id, true);
			e.addEvent('click', function()
			{

				if(varClickAllowed)
				{
				var state = ! this.currentCat.get(e.id);
				this.currentCat.set(e.id, state);
				if(state) {
					e.removeClass('notsel');
				} else {
					e.addClass('notsel');
				}
				this.reloadImages();
				}
			}.bind(this));
		}.bind(this));


		$('selectMobile').addEvent('click', function()	{

			var mobile=$('selectMobile').options[$('selectMobile').selectedIndex].value;
			if(lastMobileFilter!=mobile) {
				lastMobileFilter=mobile;
				this.reloadImages();
			}

		}.bind(this));


		this.setShow(this.options.show);
	},

	currentShow: 1,
	currentCat: new Hash(),
	currentHash: '',
	tilesX:0, tilesY:0, tilesWH:0,

	setShow: function(show){
		this.currentShow = show;
	},

	addTile: function(obj) {
		if (!this.visibleIdx.has(obj.id)) {
			this.visibleIdx.set(obj.id, obj);
			this.visible.push(obj);
		}
	},
	removeTile: function(obj) {
		this.visibleIdx.erase(obj.id);
		this.visible.erase(obj);
	},
	getTile: function(id) {
		return this.visibleIdx.get(id);
	},
	hasTile: function(id) {
		return this.visibleIdx.has(id);
	},
	sortTilesByID: function() {
		this.visible.sort(function(a,b) {
			return a.id - b.id;
		});
	},
	sortTilesByName: function() {
		this.visible.sort(function(a,b) {
			return (a.title < b.title) ? -1 : ((a.title > b.title) ? 1 : 0);
		});
	},
	arrangeTiles: function() {
		this.visible.each(function(obj,pos) {
			var x = (pos % this.tilesX) * (this.tilesWH + this.options.border2) + this.options.border;
			var y = Math.floor(pos / this.tilesX) * (this.tilesWH + this.options.border2) + this.options.border;
			obj.fxIn.start({
				'top': y+'px',
				'left': x+'px'
			});
		});
	},

	showImages: function(images) {
		// Anzahl Bilder / Spalte
		this.tilesY = 0;
		this.tilesX = 0;

		while( this.tilesY * this.tilesY * this.options.whFactor < images.length) {
			this.tilesY++;
			this.tilesX = this.tilesY * this.options.whFactor;
		}
		if ((this.tilesY-1)*this.tilesX >= images.length) {
			this.tilesWH = Math.min( this.options.width / this.tilesX, this.options.height / (this.tilesY-1)) - this.options.border2;
		} else {
			this.tilesWH = Math.min( this.options.width / this.tilesX, this.options.height / this.tilesY) - this.options.border2;
		}
		this.tilesWH = Math.min(this.tilesWH, 100);
		this.tilesWH2 = Math.floor(this.tilesWH / 2);

		// Liste von zu ladenden Bildern
		var loading = new Hash();

		// Liste von Effekten
		var effects = [];

		// Alle zu löschenden Bilder ermitteln (in visible, aber nicht in images)
		this.visible.each(function(image){
			var found = false;
			for(var i=0 ; i<images.length ; ++i) {
				if (image.id == images[i].id) {
					found = true;
					break;
				}
			}
			if (!found) {

			if(this.tilesWH2<=0)this.tilesWH2=50;

				// Dispose hidden image from DOM
				image.fxOut.addEvent('complete', function() {
					image.node.dispose();
					this.removeTile(image);
				}.bind(this));
				// Hide image
				effects.push([image.fxOut, {
					'width': '0',
					'height': '0',
					'margin-top': this.tilesWH2+'px',
					'margin-left': this.tilesWH2+'px'
				}]);
			}
		}.bind(this));


		// Alle anzuzeigenden Bilder durchgehen
		images.each(function(image,pos) {
			if (this.hasTile(image.id)) {
				// Tile KNOWN - move
				var x = (pos % this.tilesX) * (this.tilesWH + this.options.border2) + this.options.border;
				var y = Math.floor(pos / this.tilesX) * (this.tilesWH + this.options.border2) + this.options.border;
				var tile = this.getTile(image.id);
				effects.push([tile.fxIn, {
					'top': y+'px',
					'left': x+'px',
					'width': this.tilesWH+'px',
					'height': this.tilesWH+'px',
					'margin-top': '0',
					'margin-left': '0'
				}]);
			} else {
				// Tile NEW - create
				var x = (pos % this.tilesX) * (this.tilesWH + this.options.border2) + this.options.border;
				var y = Math.floor(pos / this.tilesX) * (this.tilesWH + this.options.border2) + this.options.border;

				var el = new Element('div', {'id': image.id, 'class': 'tile', 'styles': {
					top:y+'px', left:x+'px', width:'0px', height:'0px', marginTop:this.tilesWH2+'px', marginLeft:this.tilesWH2+'px', border: '1px solid #dddddd'
				}});
				// var img = new Element('img', {'src': 'img/products/'+image.src, 'class':'boximg'}).inject(el);
				var img = new Element('img', {'src': 'img/spacer.gif', 'class':'boximg'}).inject(el);
				if (this.options.onClick) {
					img.setStyle('cursor', 'pointer');
					img.addEvent('click', this.options.onClick);
					img.store('prodid', image.id);
				}

				// var txt = new Element('div', {'styles': {'position':'absolute', 'top':'2px', 'left':'2px', 'text-align':'left'}}).inject(img, 'after');
				// txt.set('html', image.id);
				el.inject(this.container);

				loading.set('img/products/'+image.src, img);
				el.store('tip:text', image.title);

				var myTips = new Tips(el,{hideDelay:1,showDelay:1,className:"mytooltip"});



				var fxIn = new Fx.Morph(el, {duration: '500', transition: Fx.Transitions.Sine.easeOut});
				var fxOut = new Fx.Morph(el, {duration: '500', transition: Fx.Transitions.Sine.easeOut});
				fxIn.addEvent('start', function(node) {
					node.removeClass('hidden');
				});
				fxOut.addEvent('complete', function(node) {
					node.addClass('hidden');
				});
				this.addTile({
					'node': el,
					'fxIn': fxIn,
					'fxOut': fxOut,
					'title': image.title,
					'id': image.id
				});
				effects.push([fxIn, {
					'width': this.tilesWH+'px',
					'height': this.tilesWH+'px',
					'margin-top': '0',
					'margin-left': '0'
				}]);
			}
		}.bind(this));

		clickAllowed(false);


		// Create group for end of all effects
		var list = new Array();
		effects.each(function(i) {
			list.push(i[0]);

		});
		var group = new Group(list);
		group.addEvent('complete', function(){
		    // TODO: Buttons wieder freigeben
		    clickAllowed(true);
		});

		if (loading.getLength() > 0) {
			// preload images, start effects on complete
			new Asset.images(loading.getKeys(), {
			    onComplete: function(){
					this.shadow.setStyle('display', 'none');
					(function(){
				    	loading.each(function(v,k){
				    		v.src = k;
				    	});
						effects.each(function(i) {
							i[0].start(i[1]);
						});
					}).delay(1);
			    }.bind(this)
			});
		} else {

			// start effects immediately
			this.shadow.setStyle('display', 'none');
			(function(){
				effects.each(function(i) {
					i[0].start(i[1]);
				});
			}).delay(1);
		}


	},

	reloadImages: function(func) {
		var url = 'ajax-productlist.jsc?show='+this.currentShow;
		this.currentCat.each(function(v,k){
			if (v==true) {
				url += "&cat="+k.substring(3);
			}
		});

		var mobile=$('selectMobile').options[$('selectMobile').selectedIndex].value;

		url+="&mobile="+mobile;


		var hash = this.createHash();
		if (hash != this.currentHash) {
			this.currentHash = hash;
			try {
				SWFAddress.setValue(hash);
			} catch (ex) {}
		}

		// bei klick
		//this.shadow.setStyle('display', '');

		var request = new Request.JSON({
			url: url,
			onComplete: function(jsonObj) {
				if(func) func.bind(this);
				this.updateCheckboxes();
				this.showImages(jsonObj.products);

				if(jsonObj.products.length==0)clickAllowed(true);



			}.bind(this)
		}).send();
	},

	selectShow: function(show) {
		if (this.currentShow != show) {
			this.currentShow = show;
			this.reloadImages(this.updateCheckboxes);
		}
	},


	updateCheckboxes: function() {
		this.cbShow.each(function(e){
			if (e.id == 'show'+this.currentShow) {
				e.removeClass('inact');
			} else {
				e.addClass('inact');
			}
		}.bind(this));

		this.cbCat.each(function(e) {
			var state = this.currentCat.get(e.id);
			if(state) {
				e.removeClass('notsel');
			} else {
				e.addClass('notsel');
			}
		}.bind(this));
	},

	createHash: function(){
		var hash = (this.currentShow==1) ? '/neueste/' : '/alle/';
		this.currentCat.each(function(v,k){
			if (v==true) {
				var cid = k.substring(3);
				hash += this.options.categoryName[cid]+",";
			}
		}.bind(this));
		return hash;
	},
	parseHash: function(hash) {
		var list = hash.split("/");
		if (list[1]) {
			this.setShow((list[1] == 'alle') ? 2 : 1);
		} else {
			this.setShow(this.options.show);
		}
		this.currentCat = this.currentCat.map(function(){return false});
		if (list[2]) {
			var tmp = list[2].split(",");
			for(var i=0 ; i<tmp.length ; ++i) {
				var cid = this.options.categoryId[tmp[i]];
				if (cid) {
					this.currentCat.set('cat'+cid, true);
				}
			}
		} else {
			$H(this.options.categoryId).getValues().each(function(e){
				this.currentCat.set('cat'+e, true);
			}.bind(this));
		}
	},
	hashChanged: function(hash) {
		if (hash != this.currentHash) {
			this.currentHash = hash;
			this.parseHash(hash);
			this.reloadImages();
		}
	}

});
