var r = r || function(data) {console.log(data)};
var appObject = function(vars) {
	return {
		vars: vars || { },
		ui: { },
		i18n: { },
		extend: function(vars) {this.vars = jQuery.extend(this.vars, vars || { })}
		};
}

var tedx = tedx || new appObject();

tedx.locker = {
	indexes: {},
	locked: function(index) {return this.indexes[index];},
	lock: function(index) {return this.indexes[index] ? false : this.indexes[index] = true;},
	unlock: function(index) {this.indexes[index] = false;}
}

tedx.getHash = function(str, map) {
	pos = str.indexOf("#");
	hash = pos > -1 ? str.substr(pos + 1) : "";

	if (!map)
		return hash;

	hash = hash.split("/");
	array = {};

	for (var i = 0; i < hash.length; i++) {
		if (!hash[i])
			continue;

		pos = hash[i].indexOf(":");

		if (pos > -1)
			array[hash[i].substr(0, pos)] = hash[i].substr(pos + 1);
		else
			array[hash[i]] = 1
	}

	return array;
}

tedx.getHeight = function(element) {
	position = element.css("position");
	left = element.css("left");
	height = element.css({position: "absolute", left: -9999}).show().outerHeight();
	element.css({position: position || "static", left: left || 0}).hide();
	return height;
}

tedx.scrollTo = function(element, speed, offset, easing) {
	scroll = (element instanceof jQuery ? element.offset().top - (offset || 10) : 0);
	jQ('html, body').animate({scrollTop: scroll > 0 ? scroll : 0}, speed || 200, easing || "swing");
}

tedx.getXhr = function() {
	return jQuery.browser.msie && jQuery.browser.version < 7 ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
}

tedx.removeAccents = function(string, lowercase) {
	clearedString = (lowercase ? string.toLowerCase() : string)
		.replace(/[àáâãäå]/g, "a")
		.replace(/[č]/g,"c")
		.replace(/[ď]/g,"d")
		.replace(/[èéêë]/g,"e")
		.replace(/[ìíîï]/g,"i")
		.replace(/[ľĺ]/g,"l")
		.replace(/[ň]/g,"n")
		.replace(/[òóôõö]/g,"o")
		.replace(/[ŕ]/g,"r")
		.replace(/[š]/g,"s")
		.replace(/[ť]/g,"t")
		.replace(/[ùúûü]/g,"u")
		.replace(/[ýÿ]/g,"y")
		.replace(/[ž]/g,"z");

	if (!lowercase)
		clearedString = clearedString
			.replace(/[ÀÁÂÃÄÅ]/g, "A")
			.replace(/[Č]/g,"C")
			.replace(/[Ď]/g,"D")
			.replace(/[ÈÉÊË]/g,"E")
			.replace(/[ÌÍÎÏ]/g,"I")
			.replace(/[ĽĹ]/g,"L")
			.replace(/[Ň]/g,"N")
			.replace(/[ÒÓÔÕÖ]/g,"O")
			.replace(/[Ŕ]/g,"R")
			.replace(/[Š]/g,"S")
			.replace(/[Ť]/g,"T")
			.replace(/[ÙÚÛÜ]/g,"U")
			.replace(/[ÝŸ]/g,"Y")
			.replace(/[Ž]/g,"Z");

	return clearedString;
	}

tedx.makeLoading = function(text, parent) {
	return jQuery('<div class="loading">').appendTo(parent || jQuery("body")).html(text || "Loading");
}

tedx.Fcb = new function() {

	var vars = {
		appId: '207897485906359',
		status: null
		}


	function init(callback) {
		if (vars.status) {
			callback(vars.status);
			return;
		}

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

		FB.getLoginStatus(function(response) {
			vars.status = response;

			if (callback)
				callback(response);
		});
	}


	function login(callback) {
		if (vars.status.session && callback) {
			callback(vars.status);
			return;
		}

		FB.login(function(response) {
			vars.status = response;

			if (callback)
				callback(response);
		});

	}


	this.init = init;
	this.login = login;

}


jQuery.fn.getUrlHash = function(map) {
	return tedx.getHash(jQ(this).attr("href"), map || false);
}



///  "Sachovnica"   ////////////////////////////////////////////////////////////

tedx.chess = new appObject({
	styles: ["black", "justred", "brick", "darkred", "gray", "lightgray", "darkgray"],
	rows: 3,
	columns: 12,
	size: 76,
	space: 4,
	participants: [],
	text: [],
	i18n: {}
});


tedx.chess.init = function(vars) {
	this.vars = jQuery.extend(this.vars, vars);
	var self = this;

	this.ui.board = jQuery('div.chessboard');
	this.ui.cells = jQuery();

	for (var i = 0; i < this.vars.rows; i++) {
		row = jQuery('<div class="row">').appendTo(this.ui.board);

		for (var j = 0; j < this.vars.columns; j++) {
			this.ui.cells = this.ui.cells.add(jQuery('<div class="cell">').appendTo(row));
		}
	}

	this.ui.randomer = this.ui.cells.last();

	this.ui.randomer.append(jQuery('<div class="randomer">')).click(function() {
		if (!tedx.locker.lock("chess"))
			return false;

		jQuery.post("participants/ajaxGetParticipants", {amount: self.ui.participants.length}, function(response) {
			if (response) {
				self.randomCells(cells, response);
			}
		}, "json");

		return false;
	});

	jQuery.each(this.vars.text, function() {
		self.write(this[0], this[1], this[2]);
	});

	jQuery.each(this.ui.cells.filter(":empty"), function(index) {
		jQuery(this).append(tedx.chess.createFace(self.vars.participants[index]));
	});

	this.ui.participants = this.ui.cells.find(".face");

}

tedx.chess.randomCells = function(cells, data) {
	var self = this;

	var shrinkCell = function(index, callback) {
		halfsize = self.vars.size / 2;

		self.ui.participants.eq(index).animate({width: 0, height: 0, top: halfsize, left: halfsize, opacity: 0}, {
			duration: 100,
			complete: function() {
				if (callback) callback(index);
			}
		});
	}


	var growCell = function(index, callback) {
		halfsize = self.vars.size / 2;

		self.ui.participants.eq(index).css({position: "absolute", top: halfsize, left: halfsize, width: 0, height: 0, opacity:0})
			.animate({top: 0, left: 0, width: self.vars.size, height: self.vars.size, opacity: 1}, {
				duration: 100,
				complete: function() {
					if (callback) callback(index);
				}
			});
	}

	var handleCell = function(index) {
		if (index > self.ui.participants.length) {
			self.ui.participants = self.ui.cells.find(".face")
			tedx.locker.unlock("chess");
			return;
		}

		shrinkCell(index, function(index) {
			self.ui.participants.eq(index).replaceWith(tedx.chess.createFace(data[index]));
			growCell(index);
		});

		setTimeout(function() {
			handleCell(index + 1);
		}, 100)
	}

	this.ui.participants.sort(function() {return Math.random() > 0.5 ? 1 : -1});
	handleCell(0);

}

tedx.chess.write = function(row, column, text, instant) {
	instant = instant || true;
	row = row || 0;
	column = column || 0;

	cells = this.ui.board.find("div.row").eq(row).find("div.cell");

	for (var i = 0; i < text.length; i++) {
		if ((pos = i + column) > cells)
			break;

		if (text[i].match(/\s/))
			continue;

		cells.eq(pos).empty().append(jQ('<div class="letter">')
			.addClass(this.vars.styles[Math.round(Math.random() * (this.vars.styles.length - 1))])
			.html(text[i]));

	}
}

tedx.chess.createFace = function(participant) {
	var self = this;
	var face = jQuery('<div class="face">');
	var text = jQuery('<div class="face-text">');

	if (!participant)
		return face;

	face.append(
		jQuery('<div class="image">').append(
			jQuery('<img>').attr({
				src: "data/participants/" + ( parseInt(participant.image, 10) ? participant.participant_id : '0' ) + "_thumb.jpg",
				alt: participant.name
			}).css({
                position: "relative",
				width: ( parseInt(participant.image_orientation, 10) ? "auto" : self.vars.size ),
				height: ( parseInt(participant.image_orientation, 10) ? self.vars.size : "auto" )
			}).css({
				left: (parseFloat(participant.image_offset_x) * 100) + "%",
				top: (parseFloat(participant.image_offset_y) * 100) + "%"
			})
		)
	);

	if (participant.topics.length > 2) {
		participant.topics = participant.topics.substr(1, participant.topics.length - 2).split(",").join(", ");
	} else {
		participant.topics = ""
	}

	text.css({position: "absolute", height: self.vars.size, zIndex: 999}).append(
		jQuery('<p class="bold">').html(participant.name),
		jQuery('<p style="display:none">').html(participant.topics)
	);

	face.hover(function() {
		element = jQuery(this)
		offset = element.offset();
		width = self.vars.size * 2 + self.vars.space;

		if (element.parents("div.cell").index() + 3 > self.vars.columns)
			offset.left -= (width + self.vars.space);
		else
			offset.left += self.vars.size + self.vars.space;

		text.css({left: offset.left, top: offset.top, width: width}).appendTo("body").show();

	}, function() {

		text.fadeOut(150);

	});

	return face;
}



///  Videa  ////////////////////////////////////////////////////////////////////


tedx.videos = new appObject({perPage: 10, currentPage: 0, pages: 0});

tedx.videos.init = function(lang) {
	var self = this;

	this.vars.lang = lang;

	this.ui.filtered = jQ('<div>');
	this.ui.displayed = jQ('<div>');

	this.ui.yearsList = jQ('.-jQ-years').find("a");
	this.ui.tagsList = jQ('.-jQ-tags').find("a");

	this.ui.videoListPage = jQ('.-jQ-videoListPage');
	this.ui.videoTheatrePage = jQ('.-jQ-videoTheatrePage');

	this.ui.pager = jQ('div.pager');
	this.ui.videoList = jQ('div.video-list');
	this.ui.videos = this.ui.videoList.find('div.video-box');

	this.ui.videos.each(function() {
		jQ(this).appendTo(self.ui.displayed).show();
		jQ(this).find("a.preview").click(function() {
			self.openVideo(tedx.getHash(jQ(this).attr("href"), true).video);
			//return false;
		});
	});

	this.ui.yearsList.add(this.ui.tagsList).click(function() {
		thisElement = jQ(this);

		thisElement.parents("ul").find("a").removeClass("checked");
		thisElement.addClass("checked");

		self.filter();

		return false;
	});

	this.filter();

	// kompatibilita so starym formatom linkov
	if ((play = tedx.getHash(window.location.href, true).play)) {
		jQuery.get('videos/urlCompabilityConvertor/video:' + play, { }, function(response) { 
			if (response != "0")
				window.location.hash = "/video:" + response;
			
			self.openVideo(response);
		});
	} 

	else if ((video = tedx.getHash(window.location.href, true).video)) {
		this.openVideo(video);
	}

}

tedx.videos.filter = function() {
	var years = [];
	var tags = [];
	var self = this;

	this.ui.videos.appendTo(this.ui.filtered);

	var year = tedx.getHash(this.ui.yearsList.filter(".checked").attr("href"));
	var tag = tedx.getHash(this.ui.tagsList.filter(".checked").attr("href"));

	jQ.each(this.ui.videos, function() {
		thisElement = jQ(this);
		elementYear = thisElement.find("input[name=year]").val();
		elementTags = thisElement.find("input[name=tags]").val().split(",");
		condition = true;

		if (year != "all" && elementYear != year)
			condition = false;

		if (tag != "all" && elementTags.indexOf(tag) == -1)
			condition = false;

		thisElement.appendTo( condition ? self.ui.displayed : self.ui.filtered);
	});

	this.vars.pages = Math.ceil(this.ui.displayed.children().length / this.vars.perPage);

	this.refreshPager();
	this.listPage(0);
}

tedx.videos.refreshPager = function() {
	var self = this;

	this.ui.pager.empty();

	if (this.vars.pages > 1) {
		for (var i = 0; i < this.vars.pages; i++) {
			jQ('<a>').attr("href", "#" + i).addClass(!i ? "selected" : "").html(i + 1).appendTo(this.ui.pager).click(function() {
				self.listPage(tedx.getHash(jQ(this).attr("href")));
				self.ui.pager.find("a").removeClass("selected");
				jQ(this).addClass("selected");
				return false;
			});
		}
	}
}

tedx.videos.listPage = function(number) {
	this.ui.videoList.empty();

	if (number > this.vars.pages)
		number = this.vars.pages;

	this.vars.currentPage = number;
	start = number * this.vars.perPage;

	for (var i = 0; i < this.vars.perPage; i++) {
		this.ui.displayed.children().eq(start + i).clone(true).appendTo(this.ui.videoList);
	}
}

tedx.videos.openVideo = function(videoID) {
	var self = this;

	var openVideo = function() {
		self.vars.openedTheatre = true;
		jQ.post(self.vars.lang + "/videos/view/video:" + videoID, {}, function(response) {
			if (response != "0")
				self.ui.videoTheatrePage.empty().append(response).fadeIn();
		});

	}

	if (!this.vars.openedTheatre)
		this.ui.videoListPage.fadeOut(openVideo);
	else
		this.ui.videoTheatrePage.fadeOut(openVideo);
}

tedx.videos.closeVideo = function() {
	var self = this;

	if (this.vars.openedTheatre) {
		this.ui.videoTheatrePage.fadeOut(function() {
			jQ(this).empty();
			self.ui.videoListPage.fadeIn(function() {
				self.vars.openedTheatre = false;
			});
		});
	}

}



tedx.teaserRow = new appObject();

tedx.teaserRow.init = function() {

	var self = this;
	var showMoreTimer;

	this.ui.box = jQ('div.videorow');
	this.ui.more = this.ui.box.find('div.more');
	this.videos = this.ui.box.find(".video a");

	var showMoreSlideIn = function() {
		link = self.ui.more.find("a").stop().css({top: -30});
		self.ui.more.show();
		link.animate({top: 0}, 200);
	}

	var showMoreSlideOut = function() {
		link = self.ui.more.find("a").stop().animate({top: -30}, 200, function() {self.ui.more.hide();});
	}

	this.ui.box.hover(function() {showMoreTime = setTimeout(showMoreSlideIn, 1000)}, function() {clearTimeout(showMoreTime), showMoreSlideOut()});

}



tedx.liveView = new appObject();

tedx.liveView.init = function(activeLang) {
	var self = this;

	this.ui.liveView = jQ('.-jQ-liveView');
	this.ui.liveViewLauncher = this.ui.liveView.find('.-jQ-liveViewLauncher');
	this.ui.liveViewTheatre = this.ui.liveView.find('.theatre');
	this.ui.body = jQ("body");

	this.bindLauncher(true);


	// inicializacia prehravca

	function createPlayer(videoLang) {
        var flashvars = {
			streamer: "rtmp://86.110.225.152/tedx&file=tedxba_" + videoLang + ".sdp",
			title: "TEDxBratislava 2011 LiveView",
			image: "http://www.tedxbratislava.sk/gfx/images/liew-view-player-" + videoLang + ".png"
		};

		var params = {
		  menu: "false",
		  allowscriptaccess: "always",
		  allowfullscreen: "true"
		};

		swfobject.embedSWF("/lib/jwplayer/player.swf", videoLang + "-live-view-player", "636", "357", "9.0.0", "expressInstall.swf", flashvars, params);
	}


	function switchLangStream(lang, autoplay) {
		//if ((playing = jQuery("[id$=-live-view-player]:visible")).length)
			//playing[0].sendEvent("stop");

		jQuery("[id$=-live-view-player-holder]").hide();
		jQuery("#" + lang + "-live-view-player-holder").show();

		if (autoplay)
		    setTimeout(function() {jQuery("#" + lang + "-live-view-player")[0].sendEvent("play")}, 500);
	}


    createPlayer("sk");
    createPlayer("en");

	switchLangStream(activeLang, false);


	jQuery("div.theatre div.languages a").click(function() {
		lang = (pos = (href = jQuery(this).attr("href")).indexOf("#")) > -1 ? href.substr(pos + 1) : null;

		switchLangStream(lang, true);

		return false;
	});

}

tedx.liveView.open = function() {
	var self = this;

	this.vars.fog = new this.Fog(function() {self.close();return true}, 300);
	height = tedx.getHeight(this.ui.liveViewTheatre);

	this.ui.liveView.css({top: -height}).animate({top: 0}, function() {tedx.scrollTo(null, 0);});
	this.ui.body.animate({paddingTop: "+=" + height});
	this.ui.liveViewTheatre.show();

	this.unbindLauncher();
}

tedx.liveView.close = function() {
	this.vars.fog.remove();

	height = this.ui.liveView.height();
	this.ui.liveView.animate({top: -height});
	this.ui.body.animate({paddingTop: 0});

	this.bindLauncher();
}

tedx.liveView.bindLauncher = function(firstTime) {
	var self = this;

	this.ui.liveViewLauncher.css({backgroundPosition: ""}).unbind('click').click(function() {
		self.open();
		return false;
	});

	if (!firstTime) {
		this.ui.liveViewLauncher.find(".open").css({top: 40, opacity: 0}).show().animate({top: 0, opacity: 1});
		this.ui.liveViewLauncher.find(".close").animate({top: -40, opacity: 0}, function() {jQ(this).hide()});
	}
}

tedx.liveView.unbindLauncher = function() {
	var self = this;

	this.ui.liveViewLauncher.css({backgroundPosition: "50% 100%"}).unbind('click').click(function() {
		self.close();
		return false;
	});

	this.ui.liveViewLauncher.find(".close").css({top: 40, opacity: 0}).show().animate({top: 0, opacity: 1});
	this.ui.liveViewLauncher.find(".open").animate({top: -40, opacity: 0}, function() {jQ(this).hide()});
}

tedx.liveView.Fog = function(onClick, zIndex) {
	var onClick = onClick || function() {return true;}
	var fog;

	var create = function() {
		fog = jQ('<div>')
			.css({position: "fixed", top: 0, left: 0, width: "100%", height: "100%", background: "#000", opacity: 0.5, zIndex: zIndex || 999})
			.hide()
			.appendTo("body")
			.click(function() {if (onClick()) remove()})
			.fadeIn(200);
	}

	var remove = function() {
		fog.stop().fadeOut(200, function() {jQ(this).remove()});
	}

	create();

	this.remove = remove;
}



tedx.participants = new appObject({cols: 6, rows: 5, spacing: 3, size: 99});

tedx.participants.init = function(participants, vars) {
	jQuery.extend(this.vars, vars);

	var self = this;
	var boxes = this.getBoxes();
	var participants = participants || {}

	this.ui.holder = jQuery("div.module-participants div.participants-holder");
	this.ui.faces = jQuery();

	for (var i = 0; i < boxes.length; i++)
		this.ui.faces = this.ui.faces.add(this.renderFace(boxes[i], participants[i]));

	this.ui.faces.appendTo(this.ui.holder);
	this.ui.holder.css({height: (this.vars.size + this.vars.spacing) * this.vars.rows});

}

tedx.participants.getNewFaces = function(tag) {
	var self = this;
	var boxes = this.getBoxes();
	var faces = jQuery();

	if (!tedx.locker.lock("participants.animation"))
		return;

	function showingHandler(index) {
		if (!(element = faces.eq(index || 0)).length) {
			self.ui.faces.remove();
			self.ui.faces = faces;

			tedx.locker.unlock("participants.animation");
			return;
		}

		element.fadeIn(120);

		setTimeout(function() {showingHandler(++index);}, 60)
	}

	function hidingHandler(index) {
		if (!(element = self.ui.faces.eq(index || 0)).length)
			return;

		element.fadeOut(120);

		setTimeout(function() {hidingHandler(++index);}, 60)
	}

	function replaceFaces(participants) {
		for (var i = 0; i < boxes.length; i++)
			faces = faces.add(self.renderFace(boxes[i], participants[i]));

		self.ui.faces.sort(function() {return 0.5 - Math.random();});
		faces.sort(function() {return 0.5 - Math.random();}).hide().appendTo(self.ui.holder);

		hidingHandler(0);

		setTimeout(function() {showingHandler(0)}, 300);
	}


	function rotateRandomer(angle) {
        angle = (angle || 0);

		if (angle < 360)
			setTimeout((function(a) {return function() {rotateRandomer(a)}})(angle + 10), 15);
		else
		    angle = 0;

		jQuery("div.randomer div").css({
			"-ms-transform": "rotate(-" + angle + "deg)",
			"-webkit-transform": "rotate(-" + angle + "deg)",
			"-moz-transform": "rotate(-" + angle + "deg)"
		});
	}


	jQuery.post("participants/ajaxGetParticipants", {amount: boxes.length, tag: tag || null}, function(response) {
		replaceFaces(response);
	}, "json");


	rotateRandomer();

}

tedx.participants.fixTopics = function(topics) {
	function trim(str, character) {
		while (str.substr(0, character.length) == character)
			str = str.substr(character.length);

		while (str.substr(-character.length) == character)
			str = str.substr(0, str.length - character.length);

		return str;
	}

	topics = trim(topics, "{");
	topics = trim(topics, "}");
	topics = topics.split(",");

	jQuery.each(topics, function(key, val) {
		topics[key] = trim(topics[key], '"');
		topics[key] = trim(topics[key], '"');
		topics[key] = jQuery.trim(topics[key]);
	});

	return topics.join(', ');
}

tedx.participants.renderFace = function(box, participant) {
	var self = this;

	var element = jQuery('<div class="face">').css({
		top: box.row * (this.vars.size + this.vars.spacing),
		left: box.col * (this.vars.size + this.vars.spacing),
		width: this.vars.size + (box.large ? this.vars.size + this.vars.spacing : 0),
		height: this.vars.size + (box.large ? this.vars.size + this.vars.spacing : 0)
	});

	if (!participant)
		return element;

	participant.topics = self.fixTopics(participant.topics);

	element.append(
		jQuery('<img>').attr({
			src: "data/participants/" + participant.participant_id + (!box.large ? "_thumb" : "") + ".jpg",
			alt: participant.name
		}).css({
			position: "absolute",
			width: parseInt(participant.image_orientation, 10) ? "auto" : "100%",
			height: parseInt(participant.image_orientation, 10) ? "100%" : "auto",
			top: (participant.image_offset_y || 0) + "%",
			left: (participant.image_offset_x || 0) + "%",
			opacity: participant.not_highlighted ? "0.3" : ""
		})
	);

	element.hover(function() {
		jQuery(this).stop().css({opacity: 0.75});
	}, function() {
		jQuery(this).animate({opacity: 1}, 200);
	})

	element.click(function() {
		self.showDetail(participant);
	});

	return element;
}

tedx.participants.getBoxes = function() {
	boxes = [];
	row = 0;
	col = 0;
	mines = {"0": {}}
	large = false;

	while (row < this.vars.rows) {
		if (!mines[row + 1])
			mines[row + 1] = {};

		if (!mines[row][col]) {
			lastRow = (row == this.vars.rows - 1);
			lastColumn = (col == this.vars.cols - 1);

			notUnderLarge = (!row || mines[row - 1][col] < 3);
			notUnderDiagonalLarge = (!row || mines[row - 1][col + 1] < 2)
			notNexToLarge = (!col || mines[row][col - 1] < 3);

			if (Math.random() < 0.5 && !lastRow && !lastColumn && notUnderLarge && notNexToLarge && notUnderDiagonalLarge) {

				large = true;
				mines[row][col] = 2;
				mines[row][col + 1] = 3;
				mines[row + 1][col] = 3;
				mines[row + 1][col + 1] = 2;

			} else {

				large = false;
				mines[row][col] = 1

			}

			boxes.push({
				large: large,
				row: row,
				col: col
				});
		}

		if (++col >= this.vars.cols) {
			col = 0;
			row++;
		}
	}

	return boxes;
}

tedx.participants.changeStatus = function(element, participant_id) {
	element = element instanceof jQuery ? element : jQuery(element);

	jQuery.post("participants/adminChangeStatus", {ajax: true, participant_id: participant_id}, function(response) {
		if (response == 1)
			element.find("span").attr("class", "submitted").html("POTVRDENÝ");
		else
			element.find("span").attr("class", "not-submitted").html("NEPOTVRDENÝ");
	});

	return false;
}

tedx.participants.showDetail = function(participant) {
	var self = this;
	var holder = jQuery('<div>');
	var element = jQuery('<div class="participant-detail">')
	var clicks = 0;

	function close() {
		element.remove();
		holder.fadeOut(200, function() {jQuery(this).remove()});
		jQuery(window).unbind('.participants.detail');
	}

	holder.css({position: "absolute", width: "100%", height: "100%", top: 0, left: 0, background: "rgba(255,255,255, 0.7)"})
		.hide()
		.appendTo(self.ui.holder)
		.fadeIn(200);

	element.appendTo(self.ui.holder).append(
		jQuery('<div class="close">').html("X").click(function() {close()}),
		jQuery('<img>').attr({
			src: "data/participants/" + participant.participant_id + "_thumb.jpg",
			alt: participant.name
		}),
		jQuery('<div class="holder">').append(
			jQuery('<h3>').html(participant.name),
			jQuery('<h4>').html(self.i18n.myTopics), jQuery('<p>').html(participant.topics),
			( participant.about_who ? jQuery('<h4>').html(self.i18n.aboutWho).add(jQuery('<p>').html(participant.about_who)) : null ),
			( participant.about_why ? jQuery('<h4>').html(self.i18n.aboutWhy).add(jQuery('<p>').html(participant.about_why)) : null )
		)
	);

	jQuery(window).bind('click.participants.detail', function(e) {
		if (clicks++ && !jQuery(e.target).parents().andSelf().filter(element).length)
		    close();
	});

	jQuery(window).bind('keyup.participants.detail', function(e) {
		if (e.keyCode == 27)
			close();
	});

}



tedx.register = new appObject({maxChars: 500});

tedx.register.init = function() {
	var self = this;

	this.ui.form =				jQuery('form[name=registration]');
	this.ui.onCompany =			jQuery('input[name=company]');
	this.ui.topics =			jQuery('input[name=topic\\[\\]]');
	this.ui.picture =			jQuery("div.profile-picture");
	this.ui.pictureButtons =	jQuery("div.profile-picture div.buttons-holder");

	this.ui.textAreas =			this.ui.form.find("textarea.with-max-chars");
	this.ui.price =				this.ui.form.find("input[name=price]");
	this.ui.customPrice =		this.ui.form.find("input[name=custom_price]");
	this.ui.shirt =				this.ui.form.find("select[name=shirt]");

	this.ui.shirtSexHolder =	this.ui.form.find(".-jQ-sex");
	this.ui.uploadInput =		this.ui.form.find(".-jQ-uploadInput");
	this.ui.facebookLauncher =	this.ui.form.find(".-jQ-facebookLauncher");


	function isLast(element) {
		return element.parent().find("input[type=text]").last().filter(element).length > 0;
	}


	function count(element) {
		return element.parent().find("input[type=text]").length;
	}


	function topicsBlur() {
		element = jQ(this);

		if (!isLast(element) && !jQ.trim(element.val()).length) {
			jQ(this).remove();
		}
	}


	function topicsKeyUp() {
		element = jQ(this);

		if (isLast(element) && jQ.trim(element.val()).length && count(element) < 3) {
			jQ('<input type="text" name="topic[]" class="input">')
				.autocomplete({source: self.vars.topics, delay: 100, minLength: 1})
				.blur(topicsBlur)
				.keyup(topicsKeyUp)
				.insertAfter(element);
		}
	}


	function checkSupportability() {
		showInSupporters = jQuery("input[name=show_in_supporters]");

		if (self.ui.price.filter(":checked").val() > 50)
			showInSupporters.removeAttr("disabled").parent().css({opacity: 1.0});
		else
			showInSupporters.attr("disabled", true).parent().css({opacity: 0.5});
	}


	function recountRemainingChars(element) {
		length = element.val().length;

		if (length > self.vars.maxChars) {
			element.val(element.val().substr(0,500));
			length = self.vars.maxChars;
			}

		maxCharLabel = element.siblings(".max-chars");
		maxCharLabel.html(maxCharLabel.html().replace(/^\d+/, self.vars.maxChars - length));
	}


	function handlePhoto(imageUrl) {
		new tedx.register.Framer({
			parent: self.ui.picture,
			imageUrl: imageUrl
			});
	}


	this.ui.price.click(function() {
		checkSupportability();
	})

	this.ui.price.filter(":last").click(function() {
		self.ui.customPrice.focus();
	})

	this.ui.customPrice.keyup(function() {
		self.ui.price.filter(":last").val(jQuery(this).val());
		checkSupportability();
	});

	this.ui.onCompany.click(function() {
		if (jQ(this).filter(":checked").length)
			jQ(".-jQ-company").show();
		else
			jQ(".-jQ-company").hide();
	});

	this.ui.textAreas.attr({maxlength: this.vars.maxChars}).keyup(function() {
		recountRemainingChars(jQuery(this));
	});

	this.ui.shirt.change(function() {
		if (!jQuery(this).val())
			self.ui.shirtSexHolder.hide();
		else
			self.ui.shirtSexHolder.show();
	})

	this.ui.form.submit(function() {
		return self.checkForm();
	});

	this.ui.topics
		.autocomplete({source: this.vars.topics, delay: 100, minLength: 1})
		.keyup(topicsKeyUp)
		.blur(topicsBlur);


	tedx.Fcb.init();
	checkSupportability();


	new tedx.register.Uploader({
		input: this.ui.uploadInput,
		onSuccess: handlePhoto,
		onFailure: function() {
			var error;

			error = jQuery('<div class="error">').appendTo(self.ui.picture).append(
				jQuery('<p>').html(tedx.register.i18n.uploadError),
				jQuery('<a href="#">').html(tedx.register.i18n.tryAgain).click(function() {
					error.remove();
					self.ui.pictureButtons.show();
					return false;
				})
			);
		}
	});

	new tedx.register.FacebookPhoto({
		launcher: this.ui.facebookLauncher,
		onSuccess: handlePhoto,
		onFailure: function() {
			var error;

			error = jQuery('<div class="error">').appendTo(self.ui.picture).append(
				jQuery('<p>').html(tedx.register.i18n.facebookError),
				jQuery('<a href="#">').html(tedx.register.i18n.tryAgain).click(function() {
					error.remove();
					self.ui.pictureButtons.show();
					return false;
				})
			)
		}
	});




}

tedx.register.checkForm = function() {
	var self = this;
	var errors = [];

	var fixElement = function(element) {
		if (!(element instanceof jQuery))
			element = self.ui.form.find('[name=' + element + ']');

		return element;
	}


	var checkVal = function(element, type) {
		var element = fixElement(element);
		var type = type || "text";

		value = jQ.trim(element.val());


		switch (type) {
			case "email":
				valid = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(value);
				break;
			case "checkbox":
				valid = element.filter(":checked").length > 0
				break;
			case "number":
				valid = !isNaN(parseInt(value));
				break;
			case "text":
			default:
				valid = value.length > 0
				break;
		}

		return valid;
	}

	var checkError = function(element, type) {
		var element = fixElement(element)

		if(!checkVal(element, type))
			errors.push(element);
	}


	this.ui.form.find(".error").removeClass("error");


	checkError("name");
	checkError("surname");
	checkError("email", "email");

	if (checkVal("company", "checkbox")) {
		checkError("company_name");
		checkError("company_ico");
		checkError("company_dic");
		checkError("company_address");
	}

	checkError('topic\\[\\]');
	checkError("i_agree_with_terms", "checkbox");

	if (parseFloat(this.ui.price.filter(":checked").val().replace(",", "."), 10) < 50.0)
		errors.push(jQuery("[name=custom_price]"));

	if (errors.length) {
		jQ.each(errors, function() {
			this.parents("div.field").add(this.parents("label")).addClass("error");
		});

		element = this.ui.form.find(".error").eq(0).find("input,textarea");

		tedx.scrollTo(element, 300, 50);

		return false;

	} else {

		return true;

	}

};

tedx.register.Framer = function(o) {
	var self = this;

	this.vars = jQuery.extend({
		parent: jQuery(),
		imageUrl: "",
		size: 167
		}, o);

	this.dom = {
		holder: jQuery('<div class="photoFramer">'),
		frame: jQuery('<div class="frame">'),
		image: jQuery('<img>'),
		imageOffsetX: jQuery('<input type="hidden" name="image_offset_x" value="0">'),
		imageOffsetY: jQuery('<input type="hidden" name="image_offset_y" value="0">'),
		imageName: jQuery('<input type="hidden" name="image_name" value="">')
		};



	function makeMovable() {
		self.dom.image
			.attr(self.dom.image.width() > self.dom.image.height() ? {height: self.vars.size} : {width: self.vars.size})

		self.dom.image
			.css({position: "absolute", top: 0, left: 0, cursor: "move"})
			.bind('mousedown.photoFramer', function(e) {
				var start = {
					offset: jQuery(this).position(),
					mouse: {left: e.pageX, top: e.pageY},
					cursor: jQuery('body').css("cursor"),
					image: {
						width: self.dom.image.width(),
						height: self.dom.image.height()
						}
					}

				var ghost = self.dom.image.clone()
					.css({opacity: 0.4, left: start.offset.left, top: start.offset.top, zIndex: 0})
					.prependTo(self.dom.holder);

				jQuery('body').css("cursor", "move");

				jQuery(window).bind('mousemove.photoFramer', function(e) {
					position = {
						left: start.offset.left + (e.pageX - start.mouse.left),
						top: start.offset.top + (e.pageY - start.mouse.top)
						}

					position.left = position.left > 0 ? 0 : ( position.left < (a = self.vars.size - start.image.width) ? a : position.left );
					position.top = position.top > 0 ? 0 : ( position.top < (a = self.vars.size - start.image.height) ? a : position.top );

					self.dom.image.css(position);
					ghost.css(position);

					return false;
				});

				jQuery(window).bind('mouseup.photoFramer', function(e) {
					jQuery(window).unbind('.photoFramer');
					jQuery('body').css("cursor", start.cursor);

					ghost.remove();

					offset = self.dom.image.position();

					self.dom.imageOffsetX.val(Math.round((offset.left / self.dom.image.width()) * 1000) / 1000);
					self.dom.imageOffsetY.val(Math.round((offset.top / self.dom.image.height()) * 1000) / 1000);
				});

				return false;
		});
	}


	this.vars.parent.find(".photoFramer").remove();

	this.dom.holder
		.css({position: "relative", display: "inline-block", width: this.vars.size, height: this.vars.size, border: "1px solid #000"})
		.appendTo(this.vars.parent);

	this.dom.frame
		.css({position: "relative", display: "inline-block", width: this.vars.size, height: this.vars.size, overflow: "hidden"})
		.appendTo(this.dom.holder);

	this.dom.image
		.attr({src: this.vars.imageUrl})
		.appendTo(this.dom.frame)
		.load(makeMovable);

	this.dom.imageOffsetX.appendTo(this.dom.holder);
	this.dom.imageOffsetY.appendTo(this.dom.holder);
	this.dom.imageName.val(this.vars.imageUrl.substr(this.vars.imageUrl.lastIndexOf("/") + 1)).appendTo(this.dom.holder);

}

tedx.register.Uploader = function(o) {
	var self = this;

	this.vars = jQuery.extend({
		input: jQuery(),
		onStart: function() {  },
		onSuccess: function() {  }, //tedx.registration.photoFramer.init(xhr.responseText, jQuery(".image-source-tab-upload"));
		onFailure: function() {  } //holder.append(jQuery('<div class="upload-error">').html('{"Participants:upload_error"|t}'));
		},o);

	this.dom = {
		holder: tedx.register.ui.picture
		}


	function startUpload() {
		var xhr = tedx.getXhr();

		self.vars.uploadingFile = self.vars.input[0].files[0];

		if (!self.vars.uploadingFile)
			return;

		tedx.register.ui.pictureButtons.hide();

		self.dom.loading = tedx.makeLoading(tedx.register.i18n.uploadLoading, self.dom.holder);
		self.dom.holder.find(".upload-error").remove();

		self.vars.onStart(self);

		xhr.onreadystatechange = function(response) {
			if (this.readyState == 4) {
				self.dom.loading.remove();
				self.vars.uploadingFile = null;

				if (xhr.responseText != "0")
					self.vars.onSuccess(xhr.responseText, self);
				else
					self.vars.onFailure(self);
			}
		}

		xhr.open("POST", 'participants/uploadPhoto?file=' + encodeURIComponent(self.vars.uploadingFile.fileName), true);
		xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
		xhr.setRequestHeader("X-File-Name", encodeURIComponent(self.vars.uploadingFile.fileName));
		xhr.setRequestHeader("Content-Type", "application/octet-stream");
		xhr.send(self.vars.uploadingFile);
	}


	this.vars.input.bind('change.photoUploader', function() {
		startUpload();
	});

}

tedx.register.FacebookPhoto = function(o) {
	var self = this;

	this.vars = jQuery.extend({
		launcher: jQuery(),
		onSuccess: function() {  },
		onFailure: function() {  }
		}, o);

	this.dom = {
		holder: tedx.register.ui.picture
	}

	this.vars.launcher.click(function() {
		self.dom.loader = tedx.makeLoading(tedx.register.i18n.facebookLoading, self.dom.holder);

		tedx.register.ui.pictureButtons.hide();

		tedx.Fcb.login(function(status) {
			jQuery.post("participants/getFacebookPhoto", {user: status.session.uid, token: status.session.access_token}, function(response) {
				self.dom.loader.remove();

				if (response != "0")
					self.vars.onSuccess(response, self);
				else
					self.vars.onFailure(self);
			});
		});

		return false;
	});
}


tedx.tagCloud = function(target, items, callback) {
	var o = {
		minFontSize: 10,
		maxFontSize: 20
		}

	jQuery.each(items, function() {
		if (!o.max || o.max < this.amount)
			o.max = this.amount;
	});

	target.addClass("tag-cloud");

	jQuery.each(items, function() {
		jQuery('<span class="tag-cloud-item">')
			.html(this.topic)
			.css({
				position: "relative",
				display: "inline-block",
				fontSize: (size = (this.amount / o.max) * o.maxFontSize) < o.minFontSize ? o.minFontSize : size
				})
			.click((function(item) {return function() {callback.call(this, item)}})(this))
			.appendTo(target);
	});

}
