mapApplication = Class.create();
mapApplication.prototype = {

	initialize: function(conf) {
		this.is_debug = false;
		this.waitPanel = new YAHOO.widget.Panel("wait",{
			width: "240px",
			fixedcenter: true,
			close: false,
			draggable: false,
			zindex:4,
			modal: true,
			visible: false
		});

		this.waitPanel.setHeader("Loading, please wait...");
		this.waitPanel.setBody('<img src=\"http://l.yimg.com/a/i/us/per/gr/gp/rel_interstitial_loading.gif\"/>');
		this.waitPanel.setFooter("Initializing interface");
		this.waitPanel.render(document.body);
		this.waitPanel.show();
		this.conf = {};
		Object.extend(this.conf, conf);
		this.setupSpaces();
		this.waitPanel.setFooter("Setting up SVG");
		this.setupSVG();
		this.repaint();
	},

	setupSVG: function() {
		//top.svgLoaded = this.svgReady.bind(this);
		//this.frameWork.setStatus("Waiting for SVG Download");
		//	width = $(this.rightPanel).getWidth() - 370;
		//	height = $(this.rightPanel).getHeight() - 50;
		width = $(this.rightPanel).getWidth() - 370;
		height = $(this.rightPanel).getHeight() - 50;
		if (width < 1 || width < 0) {
			width = 959 - 360;
			height = 700 - 50;
		}

		var svgembed = '<embed name="_mySvg" id="_mySvg" src="data/map.svg" width="' + width + '" height="' + height + '" pluginspage="http://www.adobe.com/svg/viewer/install/" wmode="transparent"></embed>';
		embed = document.createElement('EMBED');
		embed.name = "_svg";
		embed.id = "_svg";
		embed.src = 'data/map.svg';
		embed.width = width + "px";
		embed.height = height + "px";
		embed.pluginspace = "http://www.adobe.com/svg/viewer/install/";
		embed.wmode = "transparent";
		self.svgLoaded = this.svgLoaded.bind(this);
		this.rightPanel.appendChild(embed);
		this.svgEmbed = embed;

	},

	svgLoaded: function(svg) {
		this.svgDoc = svg;
		if (!this.downloading) {
			this.downloading = true;
			this.downloadData();
		}
	},

	downloadData: function() {
		//this.waitPanel.hide();
		this.waitPanel.setFooter("Loading XML data...");
		onSuccess = this.readXMLData.bind(this);
		onFailure = this.dataError.bind(this);
		var loader = new Ajax.Request(this.conf.dataUrl, {
			method: 'GET',
			onSuccess: onSuccess,
			onFailure: onFailure,
			onComplete: function(transport) {
				if (200 == transport.status || transport.status == 304) {
					onFailure(transport);
				}
			}

		});
		this.waitPanel.setFooter("Downloading XML data...");
	},

	readXMLData: function(transport) {

		this.waitPanel.setFooter("Parsing XML data...");
		xml = transport.responseXML;
		this.citta = [];
		this.cittaById = [];
		this.cittaXML = xml.getElementsByTagName('citta');
		for (i = 0; i < this.cittaXML.length; i++) {
			o = this.cittaXML[i];
			this.citta[this.citta.length] = {
				x: o.getAttribute('x'),
				y: o.getAttribute('y'),
				name: o.getAttribute('name'),
				rec: o.getAttribute('rec'),
				id: o.getAttribute('idCITTA')
			};
			this.cittaById[o.getAttribute('idCITTA')] = {
				x: o.getAttribute('x'),
				y: o.getAttribute('y'),
				name: o.getAttribute('name'),
				rec: o.getAttribute('rec'),
				id: o.getAttribute('idCITTA'),
				count: i
			};
			//console.log(this.citta[this.citta.length - 1]);
		}
		this.eventiXML = xml.getElementsByTagName('evento');
		this.eventi = [];
		this.svgHideImageGroup();
		for (i = 0; i < this.eventiXML.length; i++) {
			o = this.eventiXML[i];
			this.debug('Creating ev');
			ev = {
				idEvento: o.getAttribute('idEvento'),
				name: o.getAttribute('name'),
				image: o.getAttribute('image'),
				myImage: this.appendSvgImage(o.getAttribute('image')),
				annoFine: o.getAttribute('annoFine'),
				annoInizio: o.getAttribute('annoInizio'),
				yearline: o.getAttribute('yearline'),
				fasiCSI: []
			};

			fasi = o.getElementsByTagName('fasiCSIeventiCollegateEvento');
			for (y = 0; y < fasi.length; y++) {
				f = fasi[y];
				id = f.getAttribute('idfasiCSIeventi');
				name = f.getAttribute('name');
				com = f.getElementsByTagName('comment')[0];
				col = f.getElementsByTagName('color')[0];
				color = null;
				comment = null;
				if (col && col.firstChild && col.firstChild.nodeValue) {
					color = col.firstChild.nodeValue;
				}
				if (com && com.firstChild && com.firstChild.nodeValue) {
					comment = com.firstChild.nodeValue;
				}
				cai = [];
				cais = f.getElementsByTagName('CAIcollegatiFasiCSIeventi');
				for (z = 0; z < cais.length; z++) {
					v = cais[z].firstChild.nodeValue;

					cai[cai.length] = v.substring(1);
				}

				ev.fasiCSI[ev.fasiCSI.length] = {
					id: id,
					name: name,
					comment: comment,
					color: color,
					cai: cai
				};
			}
			this.eventi[this.eventi.length] = ev;
		}
		this.debug('Done creating events');

		this.caiXML = xml.getElementsByTagName('CAI');
		this.cai = [];
		this.caiById = [];

		for (i = 0; i < this.caiXML.length; i++) {
			c = this.caiXML[i];
			cittaXML = this.caiXML[i].getElementsByTagName('fasiCittaCAIcollegateCAI');
			citta = [];
			for( y = 0; y < cittaXML.length; y++) {
				citta[citta.length] = {
					id: cittaXML[y].getAttribute('CITTAcollegateFasiCittaCAI')
				};
			}
			o = {
				name: c.getAttribute('name'),
				id: c.getAttribute('idCAI'),
				citta: citta
			};

			this.cai[i] = o;
			this.caiById[c.getAttribute('idCAI')] = o;
		}

		//console.log(this.eventi);
		this.dataParsed();
	},

	svgHideImageGroup: function() {
		this.debug('Hiding group');
		this.svgDoc.getElementById("bgImage").setAttributeNS(null, "display", "none");
		this.debug('Hidden');
	},

	svgShowImageGroup: function() {
		this.debug('Showing group');
		this.svgDoc.getElementById("bgImage").setAttributeNS(null, "display", "block");
		this.debug('Shown');
	},

	svgMakeImageVisible: function(image) {
		this.debug('Making visible');
		chlds = this.svgDoc.getElementById("bgImage").getElementsByTagName('image');
		this.debug('There are ' + chlds.length + " children");
		for (i = 0; i < chlds.length; i++) {
			this.debug('Child');
			c = chlds[i];
			if (!c) {
				c = chlds.item(i);
			}
			try {
				c.setAttributeNS(null, "display", "none");
			} catch(e) {
				this.debug(e.message);
			}
			this.debug('Done child');
		}
		this.debug('Make');
		this.debug('Making visible ' + image.getAttributeNS('http://www.w3.org/1999/xlink','href'));
		image.setAttributeNS(null, "display", "block");
	},

	appendSvgImage: function(imageurl) {
		//alert('adding');
		this.svgns = "http://www.w3.org/2000/svg";
		this.xlinkNS = "http://www.w3.org/1999/xlink";
		var image = this.svgDoc.createElementNS(this.svgns,"image");
		image.setAttributeNS(null,"x","-10");
		image.setAttributeNS(null,"y","-10");
		image.setAttributeNS(null,"width","445");
		image.setAttributeNS(null,"height","520");
		image.setAttributeNS(null,"overflow","visible");
		image.setAttributeNS(null,"opacity","1");
		image.setAttributeNS(this.xlinkNS,"href",this.conf.mapsBasePath + imageurl);
		image.setAttributeNS(null,"id","bgRasterImage");
		this.debug(image);
		this.svgDoc.getElementById("bgImage").appendChild(image);
		this.debug('About to append image...');
		return image;
		//this.svgDoc.getElementById("bgImage").appendChild(image);
	},

	removeSvgImage: function() {
		this.svgDoc.getElementById("bgImage").setAttributeNS(null, "display", "none");
		/*
		//alert('removing');
		if (!this.svgDoc) { return; }
		var el = this.svgDoc.getElementById("bgImage");
		if (!el) { return; }
		if (el.firstChild) {
		im = this.svgDoc.getElementById('bgRasterImage');
		if (im) {
		//alert('Removing');
		el.removeChild(im);
		} else {
		//alert('no im!');
		}
		}
		*/
	},

	hideAllSvgImages: function() {
		chlds = this.svgDoc.getElementById("bgImage").getElementsByTagName('image');
		for (i = 0; i < chlds.length; i++) {
			c = chlds[i];
			c.setAttributeNS(null, "display", "none");
		}
	},

	showSvgImage: function(el) {
		this.svgDoc.getElementById("bgImage").setAttributeNS(null, "display", "block");
		el.setAttributeNS(null,'display','block');
		//console.log('Attribute set');
	},

	dataParsed: function() {
		this.waitPanel.setFooter("Making fisheye list ...");
		this.bullets = [];
		//console.log( this.svgDoc );
		ul = document.createElement('UL');
		for (var i = 0; i < this.citta.length; i++) {
			li = document.createElement('LI');
			//console.log(this.citta[i]);
			li.setAttribute('rec',this.citta[i].rec);
			li.setAttribute('x',this.citta[i].x);
			li.setAttribute('y',this.citta[i].y);
			li.innerHTML = this.citta[i].name;
			//console.log(li);
			//console.log('Making bullet', this.citta[i]);
			this.bullets[this.bullets.length] = new svgBullet( this.svgDoc, this.citta[i]);
			//console.log(this.bullets[this.bullets.length -1]);
			ul.appendChild(li);
		}
		this.citiesList = ul;
		this.geoPanel.appendChild(ul);
		this.tenbyten = new TenByTen ( this.citiesList, {
			overFunction: this.overCity.bind (this),
			outFunction: this.outCity.bind (this),
			leftClickFunction: this.conf.leftCityClick
		});
		this.goYear(this.conf.sliderStart);
		mode = document.location;
		//mode = mode > 0;

		switch(mode.toString().indexOf('=hist') > 0) {
			case true:
			this.switchToHist();
			break;

			default:
			this.switchToGeo();
			break;
		}
		this.waitPanel.hide();
	},

	overCity: function(ten) {
		this.debug('Overcity and...' + ten.hilighted);
		var li = ten.innerNodes[ten.hilighted];
		this.bullets[ ten.hilighted ].hilight('red');
	},

	outCity: function(ten) {
		this.debug('Outcity and...' + ten.hilighted);
		var li = ten.innerNodes[ten.hilighted];
		if (this.bullets[ten.hilighted]) {
			this.debug('Unhilighting...' + ten.hilighted);
			this.bullets[ten.hilighted].unhilight();
		}
	},

	dataError: function(e) {
		this.waitPanel.setFooter("Error loading XML data...");
		this.waitPanel.setBody('<img src="http://www.amp.york.ac.uk/internal/research/intsys/common/images/warning.jpg" align="left">' + " <br/><br/>&nbsp;Unrecoverable error");

	},

	setupSpaces: function() {
		this.body = document.getElementsByTagName('body')[0];
		Event.observe(document.onresize ? document : window, "resize", this.repaint.bind(this));
		if (this.is_debug) {
			this.createDebugPanel();
		}
		this.createLeftPanel();
		this.createRightPanel();

		this.repaint();
	},

	createDebugPanel: function() {
		if (window.console !== undefined) {
			if (console.log) { return; }
		}
		db = document.createElement('DIV');
		db.className = 'debug';
		this.debugPanel = db;
		this.body.appendChild(this.debugPanel);
	},

	debug: function(m) {
		if (this.is_debug) {
			if (window.console) {
				if (console.log) {
					console.log(m);
				}
			} else {
				this.debugPanel.innerHTML = m + "<br/>" + this.debugPanel.innerHTML;
			}
		}
	},

	createLeftPanel: function() {
		lp = document.createElement('DIV');
		lp.className = 'leftPanel';
		this.body.appendChild(lp);

		gb = document.createElement('BUTTON');
		gb.innerHTML = 'Geografia';
		gb.className = 'switchbutton inactive';
		lp.appendChild(gb);

		hb = document.createElement('BUTTON');
		hb.innerHTML = 'Storia';
		hb.className = 'switchbutton inactive';
		lp.appendChild(hb);

		gp = document.createElement('DIV');
		gp.className = 'geoPanel';
		lp.appendChild(gp);

		hp = document.createElement('DIV');
		hp.className = 'histPanel';
		lp.appendChild(hp);

		hdp = document.createElement('DIV');
		hdp.className = 'histDetailPanel';
		lp.appendChild(hdp);



		$(gb).observe('click', this.switchToGeo.bind(this));
		$(hb).observe('click', this.switchToHist.bind(this));

		this.geoButton = gb;
		this.histButton = hb;
		this.leftPanel = lp;
		this.geoPanel = gp;
		this.histPanel = hp;
		this.histDetailPanel = hdp;
	},

	createRightPanel: function() {




		rp = document.createElement('DIV');
		rp.className = 'rightPanel';
		this.body.appendChild(rp);
		this.rightPanel = rp;

		yp = document.createElement('DIV');
		yp.className = 'yearDisplay';
		yp.innerHTML = '&nbsp;';


		hs = document.createElement('DIV');
		hs.className = 'yui-h-slider slider';
		hs.id = "slider-bg";



		hsp = document.createElement('DIV');
		hsp.id = "slider-thumb";
		hsp.className = "yui-slider-thumb";

		img = document.createElement('IMG');
		img.src = "assets/thumb-n.gif";

		hs.appendChild(hsp);
		hsp.appendChild(img);

		this.sliderPanel = hs;
		this.sliderHandle = hsp;
		this.sliderImage = img;

		this.yearPanel = yp;

		this.rightPanel.appendChild(yp);
		this.rightPanel.appendChild(hs);

		this.setupSlider();

	},

	setupSlider: function() {

		//compute slider length and ticks
		offs = this.conf.sliderOffsets;
		mylength = 0;
		ticks = [];

		for (i = 0; i < offs.length; i++) {
			o = offs[i];
			switch(o.t) {
				case 'd':
				mylength = mylength + o.p;
				ticks[ticks.length] = o.p;
				break;

				case 'c':
				mylength = mylength + o.p;
				for (y = 0; y < o.p; y++) {
					ticks[ticks.length] = 1;
				}
				break;
			}
		}


		this.sliderPanel.style.width = mylength + "px";
		this.slider = YAHOO.widget.Slider.getHorizSlider(this.sliderPanel.id, this.sliderHandle.id, 0, mylength, ticks);
		this.slider.animate = true;
		this.slider.subscribe("slideEnd", this.slideEnd.bind(this));
		this.slider.subscribe( "change", this.slideChange.bind(this));


	},

	computeYear: function(offset) {
		var year = this.conf.sliderStart;
		var start = 0;
		var end = 0;
		for (var i = 0; i < this.conf.sliderOffsets.length; i++) {
			var o = this.conf.sliderOffsets[i];
			start = end;
			end = start + o.p;
			if (offset >= start &&  offset < end) {
				switch(o.t) {

					case "c":
					var ypp = o.y / o.p;
					myyear = parseInt(((offset - start) * ypp) + year,10);
					break;

					case "d":
					myyear = year;
					break;

				}

				break;
			}

			year = year + o.y;
		}

		return myyear;
	},

	slideChange: function() {
		var offset = this.slider.getValue();
		year = this.computeYear(offset);
		this.yearPanel.innerHTML = year;
	},

	slideEnd: function() {

		var offset = this.slider.getValue();
		this.currentYear = this.computeYear(offset);
		this.goYear(this.currentYear);

	},

	goYear: function(year) {
		this.yearPanel.innerHTML = year;
		this.currentImage = null;
		this.cleanDiv(this.histPanel);
		//alert('Removing in go year');
		//this.removeSvgImage();
		this.switchToHist();
		foundEv = null;
		for (i = 0; i < this.eventi.length; i++) {
			ev = this.eventi[i];
			if (ev.annoInizio == year) {
				foundEv = ev;
				foundEvId = i;
				break;
			}
		}


		if (!foundEv) {
			this.waitPanel.setFooter("Inconsistend data!");
			this.waitPanel.setBody('<img src="http://www.amp.york.ac.uk/internal/research/intsys/common/images/warning.jpg" align="left">' + " <br/><br/>&nbsp;Unrecoverable error");
			return;
		}


		title = document.createElement('DIV');
		title.className = 'eventName';
		title.innerHTML = foundEv.name;
		this.histPanel.appendChild(title);

		reigns = document.createElement('UL');
		reigns.className = 'reignsList';

		for (i = 0; i < foundEv.fasiCSI.length; i++) {
			r = foundEv.fasiCSI[i];
			li = document.createElement('li');
			li.innerHTML = r.name;
			li.className = 'reignsReign';
			li.style.color = r.color;
			li.reignId = i;
			li.eventId = foundEvId;
			$(li).observe('click',this.reignClick.bind(this));
			//Extended Mode
			if (true) {

			}
			reigns.appendChild(li);
		}

		this.histPanel.appendChild(reigns);

		if (foundEv.image.length > 0) {
			this.currentImage = foundEv.image;
			//this.appendSvgImage(foundEv.image);
			this.svgMakeImageVisible(foundEv.myImage);
			this.currentImageDom = foundEv.myImage;
		} else {
			this.currentImage = null;
		}

	},

	reignClick: function(e) {
		if (!e.target) {
			return false;
		}
		tg = e.target;
		r = tg.reignId;
		ev = tg.eventId;
		ev = this.eventi[ev];
		r = ev.fasiCSI[r];
		this.cleanDiv(this.histDetailPanel);
		this.switchToDetail();

		backto = document.createElement('DIV');
		backto.className = 'backToReign';
		backto.innerHTML = this.conf.backToTheList;
		$(backto).observe('click',this.switchToHist.bind(this));
		this.histDetailPanel.appendChild(backto);

		title = document.createElement('DIV');
		title.className = 'reignName';
		title.innerHTML = this.conf.contestoIstituzionaleStoricoLabel + r.name;
		this.histDetailPanel.appendChild(title);

		if (r.comment && r.comment.length > 0) {
			comment = document.createElement('DIV');
			comment.className = 'reignComment';
			comment.innerHTML = r.comment;
			this.histDetailPanel.appendChild(comment);
		}

		cai = this.caiById[r.cai[0]];
		if (cai.name) {
			titleCAI = document.createElement('DIV');
			titleCAI.className = 'caiName';
			titleCAI.innerHTML = this.conf.contestoIstituzionaleArchivisticoLabel;
			this.histDetailPanel.appendChild(titleCAI);

			caidiv = document.createElement('DIV');
			caidiv.className = 'caiDesc';

			caidiv.innerHTML = cai.name;
			func = function(ev) {
				this.conf.leftCaiClick(cai);
			}.bind(this);
			$(caidiv).observe('click',func);
			this.histDetailPanel.appendChild(caidiv);

			if (cai.citta.length > 0) {
				div = document.createElement('DIV');
				div.innerHTML = this.conf.archiviDiStato;
				div.className = 'archiviInfo';

				ul = document.createElement('UL');
				ul.className = 'archiviList';
				for (i = 0; i < cai.citta.length; i++) {
					c = this.cittaById[cai.citta[i].id];
					li = document.createElement('LI');
					li.innerHTML = c.name;
					li.setAttribute('rec',c.rec);
					li.c_equiv = c.count;

					this.bullets[ c.count ].setColor('red');
					this.bullets[ c.count ].show();
					cfunc = function(ev) {
						t = ev.target;
						this.conf.leftCityClick(t);
					}.bind(this);
					$(li).observe('click',cfunc);
					overfunc = function(ev) {
						t = ev.target;
						this.debug('Hilight...' + t.c_equiv);
						this.bullets[ t.c_equiv].hilight();
					}.bind(this);

					outfunc = function(ev) {
						t = ev.target;
						this.debug('Unhilight...' + t.c_equiv);
						this.bullets[ t.c_equiv ].unhilight();

					}.bind(this);
					$(li).observe('mouseover',overfunc);
					$(li).observe('mouseout',outfunc);
					ul.appendChild(li);
				}
				this.histDetailPanel.appendChild(div);
				this.histDetailPanel.appendChild(ul);
			}

		}

		backto2 = document.createElement('DIV');
		backto2.className = 'backToReign';
		backto2.innerHTML = this.conf.backToTheList;
		$(backto2).observe('click',this.switchToHist.bind(this));
		this.histDetailPanel.appendChild(backto2);


		//console.log(this.caiById[r.cai[0]]);
		this.switchToDetail();
	},

	cleanDiv: function(div) {
		while(div.lastChild) {
			this.cleanDiv(div.lastChild);
			div.removeChild(div.lastChild);
		}
	},

	switchToGeo: function() {
		//alert('Removing in switch to geo');

		//this.removeSvgImage();
		this.svgHideImageGroup();
		this.histButton.className = "switchbutton inactive";
		this.geoButton.className = "switchbutton active";
		this.histPanel.style.display = 'none';
		this.histDetailPanel.style.display = 'none';
		this.geoPanel.style.display = 'block';
		this.sliderPanel.style.visibility = 'hidden';
		this.yearPanel.style.visibility = 'hidden';
		if (this.bullets && this.bullets.length > 0) {
			for ( i = 0; i < this.bullets.length; i++) {
				this.bullets[i].setColor('black');
				this.bullets[i].unhilight();
				this.bullets[i].show();
			}
		}
	},

	switchToHist: function() {
		this.svgShowImageGroup();
		this.histButton.className = "switchbutton active";
		this.geoButton.className = "switchbutton inactive";
		this.geoPanel.style.display = 'none';
		this.histDetailPanel.style.display = 'none';
		this.histPanel.style.display = 'block';
		this.sliderPanel.style.visibility = 'visible';
		this.yearPanel.style.visibility = 'visible';
		if (this.bullets && this.bullets.length > 0) {
			for ( i = 0; i < this.bullets.length; i++) {
				this.bullets[i].setColor('black');
				this.bullets[i].unhilight();
				this.bullets[i].hide();
			}
		}
	},

	switchToDetail: function() {
		//alert('Removing in switch to detail');
		this.svgHideImageGroup();
		//this.removeSvgImage();
		this.histButton.className = "switchbutton active";
		this.geoButton.className = "switchbutton inactive";
		this.geoPanel.style.display = 'none';
		this.histPanel.style.display = 'none';
		this.histDetailPanel.style.display = 'block';
		this.sliderPanel.style.visibility = 'visible';
	},

	repaint: function() {
		try{

			//Temporary fix for IE showing Iframe Borders!



			var dimensions = document.viewport.getDimensions();

			//this.maxX = dimensions.width;
			this.maxX = dimensions.width;
			this.maxY = dimensions.height;
			if (this.maxY < 1 || this.maxY < 1) {
				this.maxX = 959;
				this.maxY = 700;
			}
			//	this.maxY = dimensions.height;
			//		alert(this.maxX);
			this.leftPanel.style.height = this.maxY + "px";
			this.leftPanel.style.width = 350 + "px";
			this.rightPanel.style.height = this.maxY + "px";
			this.rightPanel.style.width = this.maxX - 360 + "px";
			if (this.svgEmbed) {
				this.svgEmbed.width = this.maxX - 10 - 360;
				this.svgEmbed.height = this.maxY - 50;
			}
			this.geoPanel.style.height = this.maxY - 31 + "px";
			this.histPanel.style.height = this.maxY - 31 + "px";
			this.histDetailPanel.style.height = this.maxY - 31 + "px";
		}
		catch(e) {
		}
	}
};