var MagicFolder = new Class({
	Implements: Options,
	options: {
		cardLanguage:'us',
		cards:[],
		startPage:0,
		cardsPerPage:9,
		imgURL:'http://beta.gatherer.wizards.com/Handlers/Image.ashx',
		imgURLold:'http://www.wizards.com/global/images/magic/',
	},
	
	/****** PUBLIC ******/
	initialize: function(options){
		this.setOptions(options);
		this.cards = [];
		this.cardsOriginal = [];
		this.pages = [];
		this.currentPage = -2;
		this.animationInProgress = false;
		$('filter').addEvent('submit',function(e){
			new Event(e).stop();
			this.filterCards([
				{'field':'name','value':$('search').get('value')},
				{'field':'color','value':$('colorfilter').get('value')},
				{'field':'rarity','value':$('rarityfilter').get('value')},
				{'field':'edition','value':$('editionfilter').get('value')},
				{'field':'count','value':$('countfilter').get('value')}
			]);
		}.bind(this));
		new Element('div',{'id':'cardcontainer'}).inject(document.body);
		this.initCards(this.options.cards);
		this.show(this.options.startPage);
	},
	
	initCards:function(newCards){
		var colorfilter = new Hash();
		var rarityfilter = new Hash();
		var editionfilter = new Hash();
		newCards.sort(function(a,b){return (a.color>b.color ? 1:(a.color==b.color ? 0:-1));}).each(function(card,index){
			if(card.name.trim() == "") return;
			if($defined(card.color)) {
				if(colorfilter.get(card.color.toLowerCase()) == null) colorfilter.set(card.color.toLowerCase(),1);
				else colorfilter.set(card.color.toLowerCase(),colorfilter.get(card.color.toLowerCase())+1);
			}
			if($defined(card.rarity)) {
				if(rarityfilter.get(card.rarity.toLowerCase()) == null) rarityfilter.set(card.rarity.toLowerCase(),1);
				else rarityfilter.set(card.rarity.toLowerCase(),rarityfilter.get(card.rarity.toLowerCase())+1);
			}
			if(editionfilter.get(card.edition.toLowerCase()) == null) editionfilter.set(card.edition.toLowerCase(),1);
			else editionfilter.set(card.edition.toLowerCase(),editionfilter.get(card.edition.toLowerCase())+1);
			this.cards.include(card);
			this.cardsOriginal.include(card);
		},this);
		new Element('option',{'value':''}).appendText('all colors').inject($('colorfilter').empty());
		new Element('option',{'value':''}).appendText('all rarities').inject($('rarityfilter').empty());
		new Element('option',{'value':''}).appendText('all editions').inject($('editionfilter').empty());
		colorfilter.getKeys().sort().each(function(filter){new Element('option',{'value':'^'+filter+'$'}).set('text',filter.toUpperCase()+' ('+colorfilter.get(filter)+')').inject($('colorfilter'))});
		rarityfilter.getKeys().sort().each(function(filter){new Element('option',{'value':'^'+filter+'$'}).set('text',filter.toUpperCase()+' ('+rarityfilter.get(filter)+')').inject($('rarityfilter'))});
		editionfilter.getKeys().sort().each(function(filter){new Element('option',{'value':'^'+filter+'$','style':'background:url('+this.options.imgURL+'?type=symbol&size=small&set='+this.fixEdition(filter)+') left center no-repeat;height:22px;padding:8px 0 0 42px'}).set('text',filter.toUpperCase()+' ('+editionfilter.get(filter)+')').inject($('editionfilter'))},this);
		this.updateSubnav();
	},
	
	filterCards:function(filters){
		var newCards = [];
		this.cardsOriginal.each(function(card){
			var passed = true;
			filters.each(function(filter){
				if(filter.value == "") return;
				if(card[filter.field].toString().test(filter.value,'i') == false) passed = false;
			})
			if(passed) newCards.include(card);
		});
		this.cards = newCards;
		this.currentPage = -2;
		this.updateSubnav();
		this.show(0);
	},
	
	show:function(pageToShow){
		//console.log('show '+pageToShow);
		if(!this.animationInProgress) {
			var totalPages = Math.floor(this.cards.length/this.options.cardsPerPage)+1;
			pageToShow = (pageToShow+totalPages) % totalPages;
			if(pageToShow == this.currentPage + 1) {
				this.pageAdd(pageToShow+1,4);
				this.pageShift(-1);
			} else if(pageToShow == this.currentPage - 1) {
				this.pageAdd(pageToShow,1);
				this.pageShift(+1);
			} else if(pageToShow < this.currentPage) {
				this.pageAdd(pageToShow,0);
				if((pageToShow+1) <= totalPages) this.pageAdd(pageToShow+1,1);
				this.pageShift(+2);
			} else if(pageToShow > this.currentPage) {
				this.pageAdd(pageToShow,4);
				if((pageToShow+1) <= totalPages) this.pageAdd(pageToShow+1,5);
				this.pageShift(-2);
			}
			this.currentPage = pageToShow;
			this.slider.set(pageToShow+1);
		}
	},
	
	nextPage:function(){this.show(this.currentPage == Math.floor((this.cards.length-1)/this.options.cardsPerPage)-1 ? 0 : this.currentPage+1);},
	
	prevPage:function(){this.show(this.currentPage == 0 ? Math.floor((this.cards.length-1)/this.options.cardsPerPage)-1 : this.currentPage-1);},



	/****** PRIVATE ******/
	pageAdd:function(pageNumber,position){
		if($defined(this.pages[position])) this.pages.erase(this.pages[position]);
		this.pages[position] = new Element('div',{'class':'page','id':'page'+pageNumber});
		for(var x = (pageNumber*this.options.cardsPerPage);x<Math.min(this.options.cardsPerPage*pageNumber+this.options.cardsPerPage,this.cards.length);x++) {
			var card = this.cards[x];
			card.name = card.name.replace(/([^ ])\/([^ ])/g,'$1 / $2');
			var cardImage = card.name.replace(/[^a-z0-9-,\' ]/ig,'');
			var cardBox = new Element('div',{'class':'card'}).grab(this.buildLabel(card));
			cardImage = new Element('img',{'src':this.options.imgURL+'?type=card&set='+this.fixEdition(card.edition)+'&name='+cardImage,'id':'card'+x,'alt':card.name}).addEvent('error',function(event){
				console.log(this.get('src'));
				this.set('src','images/back.jpg');
			}).inject(cardBox,'top');
			if(card.edition.test('^([4-9]e|un|rv)$','i')) cardImage.addClass('white');
			else if(card.edition.test('^(uh|ug)$','i')) cardImage.addClass('silver');
			cardBox.inject(this.pages[position]).addEvent('mouseenter',function(e){
				this.clone().setStyles({'left':this.getPosition().x,'top':this.getPosition().y}).addClass('full').addEvent('mouseleave',function(e){
					this.dispose();
				}).inject($('cardcontainer').empty());
			});
		}
		this.pages[position].inject($('cardfolder')).setStyle('left',-740+370*position);
	},
	
	pageShift:function(shiftBy){
		var options = {};
		var newPages = [];
		var oldPages = [];
		var x = 0;
		this.pages.each(function(page,index){
			options[x] = {left:[page.getStyle('left').toInt(),-740+370*(index+shiftBy)]};
			x++;
			if((index+shiftBy)>=2 && (index+shiftBy)<=3) newPages[index+shiftBy] = page;
			else oldPages.include(page);
		});
		this.animationInProgress = true;
		$('cardcontainer').empty();
		var shiftFx = new Fx.Elements(this.pages,{wait:true,duration:300,onComplete:function(event){
			oldPages.each(function(page,index){page.dispose()});
			this.pages = newPages;
			this.animationInProgress = false;
		}.bind(this)}).start(options);
	},
	
	updateSubnav:function(){
		$('subnav').empty();
		var links = new Element('span',{'class':'links'}).inject($('subnav').set('text',this.cards.length+' of '+this.cardsOriginal.length+' cards'),'top');
		var knob = new Element('div',{'class':'slider'}).set('text',0).setStyle('width',Math.max(100/Math.max(Math.floor(this.cards.length/this.options.cardsPerPage),1),8)+'%').inject(links);
		this.slider = new Slider(links,knob,{
			range:[1,Math.max(Math.floor(this.cards.length/this.options.cardsPerPage),1)],
			onChange:function(value){if($defined(value)) knob.set('text',value)},
			onComplete:function(value){if(this.currentPage != value.toInt()-1 && value.toInt()>=0) this.show(value.toInt()-1)}.bind(this)
		});
	},
	
	buildLabel:function(card){
		label = new Element('span',{'class':'label'});
		var count = card.count - ($defined(card.foil) ? card.foil : 0);
		var comment = "";
		if($defined(card.comment) && card.comment.toLowerCase().match(/(\d+)x ?(ger|us|jap|rus|esp)( foil)?/ig)) {
			card.comment.toLowerCase().match(/(\d+)x ?(ger|us|jap|rus|esp)( foil)?/ig).each(function(substr,ind){
				var subcount = substr.replace(/^(\d+)x.*$/i,'$1').toInt();
				count = count-subcount;
				comment = new Element('span',{'class':'icon_'+substr.replace(/^\d+x ?(.*)$/i,'$1')}).set('text',subcount+'x').inject(label,'bottom');
			});
		}
		if(count>0) new Element('span',{'class':'icon_'+this.options.cardLanguage}).set('text',count+'x').inject(label,'top');
		if(card.foil>0) new Element('span',{'class':'icon_'+this.options.cardLanguage+' foil'}).set('text',card.foil+'x').inject(label,'top');
		label.grab(new Element('br'),'top').appendText(card.name,'top');
		label.grab(new Element('div',{'class':'edition','style':'background-image:url('+this.options.imgURL+'?type=symbol&size=small&set='+this.fixEdition(card.edition)+'&rarity='+(card.rarity ? card.rarity : 'r')+');'}).set('html','&nbsp;'),'top');
		return label;
	},
	
	fixEdition:function(edition){
		switch(edition.toLowerCase()){
			case 'fd':edition='5dn';break;
			case 'ud':edition='cg';break;
			case 'us':edition='uz';break;
			case 'ul':edition='gu';break;
			case 'on':edition='ons';break;
			case 'mr':edition='mrd';break;
			case 'gp':edition='gpt';break;
			case 'sh':edition='st';break;
			case 'st':edition='p3';break;
			case 'py':edition='pr';break;
			case 'cs':edition='csp';break;
			case 'tp':edition='te';break;
			case 'to':edition='tor';break;
			case 'ds':edition='dst';break;
			case 'ju':edition='jud';break;
			case 'sc':edition='scg';break;
			case 'pre':edition='general';break;
			case 'fnm':edition='general';break;
			case 'le':edition='lgn';break;
			case '8e':edition='8ed';break;
			case '9e':edition='9ed';break;
			case 'r':edition='3e';break;
			case 'b':edition='2e';break;
			case 'a':edition='1e';break;
		}
		return edition;
	}
});

