/**
 * @author Micke
 */
var t; //timer
var popupinfo; //popup container
var ajax = new ajaxObj();
var mapContainer;
var boothlist;
var boothData;
var cssRules = new cssObj();
var notIe = !/*@cc_on!@*/false;

window.addEvent("domready", function() {
	mapContainer = document.getElementById('mapcontainer');
	boothlist = document.getElementById('map').getElementsByTagName('div');
	ajax.request(
		"boothdata.php",
//		"data.js",
		function(r){
			//success

			artistData = new Artists(r.responseText);
			boothData = artistData.getBoothData();
			initPopupinfo();
			initBooths();
			renderCategories(cssRules);
			renderArtists(cssRules);
			cssRules.showAll();
		},
		function(r){
			//failure
			alert('Could not collect data');
		}
	);
});
 
String.prototype.capitalize = function(){
	return this.replace(/\w+/g, function(a){
		return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
	});
};

/* Description: Ajax request wrapper
 * 
 */
function ajaxObj(){
	function getNewHTTPObject()
	{
		var xmlhttp;

		/*@cc_on
			@if (@_jscript_version >= 5)
				try{
					xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
				}
				catch (e){
					try{
						xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
					}
					catch (E){
						xmlhttp = false;
					}
				}
			@else
				xmlhttp = false;
		@end @*/

        /** Every other browser on the planet */
		if (!xmlhttp && typeof XMLHttpRequest != 'undefined'){
			try	{
				xmlhttp = new XMLHttpRequest();
			}
			catch (e){
				xmlhttp = false;
			}
		}
		
		return xmlhttp;
	}

	this.request = function(url, success, failure){
		var xmlHttp = getNewHTTPObject();
		xmlHttp.onreadystatechange=function()
		{
			if(xmlHttp.readyState==4){
				if (xmlHttp.status == 200) {
					success(xmlHttp);
				}
				else {
					failure(xmlHttp);
				}
			}
		}
		xmlHttp.open("GET",url,true);
		xmlHttp.send(null);
	};	
}


function cssObj(){
	var mediumlist = [ 'all', 'wood', 'pottery', 'glass', 'clothing', 'framed', 'photography', 'miscellaneous', 'jewelry', 'metal', 'fabric', 'seasonal', 'leather' ];
	
	//private		
	function getMediumClasses(){
		var cssRules;
		if (cssRules = document.styleSheets[0].rules) {
			cssRules = document.styleSheets[0].rules;
		}
		else{
			cssRules = document.styleSheets[0].cssRules;
		}
		var clsArray = [];
			
		for (i = 0; i < cssRules.length; i++) {
			var str = cssRules[i].selectorText.split(/^div\./)[1];
			if (mediumlist.toString().indexOf(str) > -1) {
				clsArray.push(cssRules[i]);
			}
		}
		
		return clsArray;
	}
	
	function hide(cls){
		cls.style.opacity = 0.2;
		cls.style.filter = "alpha(opacity=20)";
		cls.style.border
		cls.style.borderWidth = '0px';
	}

	function show(cls){
		cls.style.opacity = 1;
		cls.style.filter = "alpha(opacity=100)";
		cls.style.borderWidth = '1px';
	}
	
	//public
	this.cssRules = getMediumClasses();
		
	this.find = function(searchStr) {
		for (i=0; i<this.cssRules.length; i++) {
			if (this.cssRules[i].selectorText === "div." + searchStr) {
				return this.cssRules[i];
			}
		}
		return '';
	}
	
	this.show = function(medium){
		show(this.find(medium));
	}

	this.showOnly = function(cls_str){
		var shown_cls_txt = this.find(cls_str).selectorText;
		for (var i = 0; i < this.cssRules.length; i++) {
			if(this.cssRules[i].selectorText ==  shown_cls_txt ){
				show(this.cssRules[i]);
			}
			else {
				hide(this.cssRules[i])
			}
		}
	}

	this.showAll = function(){
		for (var i = 0; i < this.cssRules.length; i++) {
			show(this.cssRules[i]);
		}
	}

	this.hide = function(medium){
		hide(this.find(medium));
	}
	
	this.hideAll = function(){
		for (var i = 0; i < this.cssRules.length; i++) {
			hide(this.cssRules[i])
		}
	}
	
	this.getCategores = function(){
		return mediumlist
	};
	
};

function Artists(t){
	var shown = [];
	var bData = [];
	var artistMapping = [];
	var m = eval("{" + t + "}");
		
	function clear(boothNum){
		if (notIe) {
			boothlist[boothNum - 1].style.removeProperty('opacity');
			boothlist[boothNum - 1].style.removeProperty('filter');
			boothlist[boothNum - 1].style.removeProperty('border');
			boothlist[boothNum - 1].style.removeProperty('padding');
			boothlist[boothNum - 1].style.removeProperty('z-index');
			boothlist[boothNum - 1].style.removeProperty('margin');
		}
		else {
			boothlist[boothNum - 1].className = boothlist[boothNum - 1].className.replace(/ selected/, '');
		}
	}
	
	m.clearAll = function(){
		while(shown.length > 0 ){
			clear(shown.pop());
		}
	}
	
	m.show = function(boothNum){
		boothlist[boothNum - 1].onclick();

		if (notIe) {
			var o = boothlist[boothNum - 1];
			o.style.zIndex = 100;
			o.set('morph', {
				duration: 75
			});
			o.morph({
				'padding': 10,
				'margin-top': -10,
				'margin-left': -10,
				'border-width': 2
			});
			delete o;
		}
		else {
			boothlist[boothNum - 1].className += " selected";
		}
		shown.push(boothNum);
	}
	
	m.getBoothData = function(){
		if (bData.length == 0) {
			for (var i = 0; i < boothlist.length; i++) {
				bData[i] = [];
			}
			for (var i = 0; i < m.length; i++) {
				bData[ m[i].booth-1 ].push(m[i]);
			}
		}
		
		return bData;
	}
	
	m.getById = function(id){
		if (artistMapping.length == 0) {
			for(var i = 0; i < m.length; i++){
				artistMapping[ m[i].id ] = i;
			}
		}
		
		return m[artistMapping[id]];
	}
	
	return m;
}

function artistContainer(){
	function imageContainer(){
		var uid;
		var pic;
		
		var tmpImg = new Image;
		var thumb = new Image(100,100);
		thumb.src="images/loading.gif";

		tmpImg.onload = function(){
			var w = Math.round((tmpImg.width / tmpImg.height) * 100);
			thumb.src = tmpImg.src;
			thumb.morph({
				height: 100,
				width: w
			});
		};

		var imageCnt = document.createElement('div');
		imageCnt.className = 'image';
		imageCnt.src = function(src){ tmpImg.src = src; }
		imageCnt.appendChild(thumb);
		
		imageCnt.img = function(){
			return thumb;
		}
		
		imageCnt.set = function(id, n){
			uid = id;
			pic = n;
			
			tmpImg.src = 'http://www.tidefest.org/register/img/usr/small/'+ id +'_'+ n +'_small.jpg';
			//link.href = "";//'http://www.tidefest.org/register/img/usr/medium/'+ id +'_'+ n +'_medium.jpg';
		}
		
		imageCnt.onclick = function(){
			var imgs = [];
			for (var n = 0; n < 3; n++) {
				imgs[n] = ['http://www.tidefest.org/register/img/usr/medium/' + uid + '_' + n + '_medium.jpg'];
			}
			Slimbox.open(imgs,pic);
			popupinfo.keepOpen();
		}

		return imageCnt;
	}

	var artistCnt = document.createElement('div');
	artistCnt.className = 'artist';
	
	var artist = document.createElement('h1');
	artist.className = 'artist';

	var clearbr = document.createElement('br');
	clearbr.className = "clear";
	
	var artCnt = document.createElement('div');
	artCnt.className = 'art';

	var images = [];
	images.push(new imageContainer());
	images.push(new imageContainer());
	images.push(new imageContainer());
	
	artistCnt.appendChild(artist);
	artCnt.appendChild(images[0]);
	artCnt.appendChild(images[1]);
	artCnt.appendChild(images[2]);
	artCnt.appendChild(clearbr);
	artistCnt.appendChild(artCnt);
	
	artistCnt.img = function(i){
		return images[i];
	}
	
	artistCnt.setName = function(str){
		artist.innerHTML = str;
	};
	
	return artistCnt;
}

function openInfo(baseElement){
	clearTimeout(t);
	var boothdata = boothData[baseElement.boothNum-1];

	popupinfo.innerHTML = "";
	if (!boothdata[0]) {
		popupinfo.close();
		return;
	}
	
	popupinfo.setClass(boothdata);
	
	artistData.clearAll();
	artistData.show(baseElement.boothNum);

	var infoClose = document.createElement('div');
	infoClose.appendChild(document.createTextNode('Close'));
	infoClose.className = 'boothinfo-close';
	infoClose.onclick = function(){
		popupinfo.close();
	}
	popupinfo.appendChild(infoClose);
	
	for(var i = 0; i < boothdata.length; i++){
		var art = new artistContainer();
		art.setName(boothdata[i].name + ' (' + boothdata[i].booth + ')');
		popupinfo.appendChild(art);
		
		for (var j = 0; j < 3; j++) {
			
			art.img(j).set(boothdata[i].id, j);
			
		}
		
	}
	
	popupinfo.open(baseElement.boothNum);
	
	var modTop = baseElement.offsetTop - popupinfo.offsetHeight - 20;
	var modLeft = baseElement.offsetLeft + Math.ceil(baseElement.offsetWidth * 0.5) - Math.ceil(popupinfo.offsetWidth * 0.5);

	var bTop = 0;
	var bLeft = 0;


	
	if (modLeft < 0 && modLeft > (-1 * popupinfo.offsetWidth * 0.4)) {
		modLeft = 0;			
	}
	
	if (modTop < 0 && modLeft < 0) {
		bLeft = baseElement.offsetLeft + baseElement.offsetWidth + 30;
		bTop = 0;
	}
	else if (modTop < 0) {
		bTop = baseElement.offsetTop + baseElement.offsetHeight + 30;
		bLeft = modLeft;
	}
	else if (modLeft < 0) {
		bTop = modTop;
		bLeft = baseElement.offsetLeft + baseElement.offsetWidth + 30;
	}
	else {
		bTop = modTop;
		bLeft = modLeft;
	}
	
	popupinfo.set('morph', {duration: 'short', transition: 'quad:in:out'});
	popupinfo.morph({
		left: bLeft,
		top: bTop
	});
	/*
	popupinfo.style.left = bLeft + "px";
	popupinfo.style.top = bTop + "px";
	*/
}

function renderCategories(cssObj){
	var id = "categories"
	var placeholder = document.getElementById(id);
	if (!placeholder) {
		var el = document.createElement("div");
		el.id=id;
		mapContainer.appendChild(el);
		placeholder = el;
	}
		
	var list = cssObj.getCategores();
	for (var i = 0; i < list.length; i++) {
		var d = document.createElement('div');
		d.category = list[i];
		d.className = list[i];
		
		var dText = document.createTextNode(list[i].capitalize());
		
		if (list[i] == 'all') {
			d.onclick = function(){
				artistData.clearAll();
				cssObj.showAll();
			}
		}
		else {
			d.onclick = function(){
				artistData.clearAll();
				cssObj.showOnly(this.category);
			}
		}
		
		d.appendChild(dText);
		placeholder.appendChild(d);
	}
}

function renderArtists(cssObj){
	var id = "artists"
	var placeholder = document.getElementById(id);
	if (!placeholder) {
		var el = document.createElement("div");
		el.id=id;
		mapContainer.appendChild(el);
		placeholder = el;
	}
	
	var list = artistData;
	for (var i = 0; i < list.length; i++) {
		var d = document.createElement('div');
		d.boothNum = list[i].booth;
		d.className = list[i].medium;
		
		var dText = document.createTextNode(list[i].name);
		
		d.onclick = function(){
			//cssObj.hideAll();
			artistData.clearAll();
			artistData.show(this.boothNum);
		}
		
		d.appendChild(dText);
		placeholder.appendChild(d);
	}	
}

function initBooths(){
	for (var i = 0; i < boothlist.length; i++) {
		boothlist[i].onclick = popupinfo.startOpen;
		boothlist[i].onmouseover = popupinfo.startOpen;
		boothlist[i].onmouseout = popupinfo.startClose;
		boothlist[i].boothNum = i+1;
		if (boothData[i][0]) {
			boothlist[i].className = boothlist[i].className + " " + boothData[i][0].medium;
		}
	}		
}

function initPopupinfo(){
	function onOpenTimeout(el){
		return function(){
			if ( popupinfo.isOpen != el.boothNum) {
				clearTimeout(t);
				openInfo(el);
			}
		}
	}
	
	function close(){
		artistData.clearAll();
		clearTimeout(t);
		popupinfo.set('opacity',0);
		popupinfo.style.display = "none";
		popupinfo.isOpen = false;
	}

	function open(boothNum){
		popupinfo.isOpen = boothNum;
		popupinfo.style.display = "block";
		var myFx = new Fx.Tween(popupinfo);
		if (popupinfo.get('opacity') != 1) {
			myFx.start('opacity',0,1);
		}
	}
	
	popupinfo = document.getElementById("boothinfo");

	popupinfo.isOpen = false;
	
	popupinfo.onmouseover = function(){ clearTimeout(t); }
	popupinfo.onmouseout = function(){ popupinfo.startClose(); }

	popupinfo.startOpen = function(){
		clearTimeout(t);
		t = setTimeout( onOpenTimeout(this), 200);
	}
	popupinfo.startClose = function(){
		clearTimeout(t);
		t = setTimeout( function(){
			if (popupinfo.isOpen) {
				close();
			}
		}, 200);
	}
	popupinfo.keepOpen = function(){
		clearTimeout(t);
	}
	popupinfo.open = function(boothNum){
		open(boothNum);
	}
	popupinfo.close = function(){
		close();
	}
	popupinfo.setClass = function(o){
		//popupinfo.style.removeProperty('background-color');
		//popupinfo.style.backgroundColor = cssRules.find(o[0].medium).style.backgroundColor;
	}
}
