SolnaStad.ratingBar = function(el) {
	this.el = $(el);

	//Get elements and data
	this.percentInt = parseInt(this.el.find('.percent-data').text(), 10);
	this.maxInt = this.el.find('.max').text();
	this.average = this.el.find('.average');
	this.averageInt = this.average.text().match("[0-9]+");

	//Create elements
	this.ratingBarEl = $('<div class="rating-bar">');
	if (this.el.hasClass('raw-rating-inline')) {
		this.ratingBarEl.addClass('rating-bar-inline');
	}
	this.ratingEl = $('<div class="rating">');
	this.averageEl = $('<div>', {
		className: 'average',
		title: this.average.attr('title')
	});

	//Modify document
	this.el.before(this.ratingBarEl);
	this.ratingBarEl.prepend(this.ratingEl, this.averageEl);
	this.average.remove();

	//Calculate lengths
	this.ratingWidth = this.percentInt + '%';
	this.ratingEl.css('width', this.ratingWidth);
	this.averageEl.css('left', this.averageInt + '%');

};

SolnaStad.expandLinks = function(el, linkText, linkTextAfter) {

	var t = this;
	this.el = el;
	this.lt = linkText; //Link text
	this.lta = linkTextAfter; //Link text after
	this.mc = this.el.find('.m-c'); //Module content
	this.hc = this.mc.find('.hidden-content'); //Hidden content (to be expanded)
	this.exl = $('<a href="#" class="read-more-block-link">'+ this.lt +'</a>'); //Expand link
	this.v = false; //Visibility of expanded block

	this.exl.click(function(e) {
		e.preventDefault();
		if (t.v) {
			t.hc.slideUp();
			t.exl.text(t.lt);
			t.v = false;
		} else {
			t.hc.slideDown();
			t.exl.text(t.lta);
			t.v = true;
		}
	});

	this.hc.hide();
	this.mc.after(this.exl);

};

SolnaStad.SelectableQuestions = function (el, maxChecked) {
	var t = this;
	this.el = el;
	this.checkboxes = this.el.find('input[type=checkbox]');
	maxChecked = maxChecked || 4;

	function controlChecked () {
		t.checkedCheckboxes = t.checkboxes.filter(':checked');
		if (t.checkedCheckboxes.length == maxChecked) {
			t.checkboxes.not(t.checkedCheckboxes).attr('disabled','disabled');
		} else {
			t.checkboxes.attr('disabled','');
		}
	}

	this.checkboxes.click(function(){
		controlChecked();
	});

	controlChecked();

};

SolnaStad.ExpandTable = function (el) {

	var t = this;
	this.el = $(el);
	this.expandLink = $('<a class="expand-link" href="#">');
	this.expandLinkTextBefore = 'Visa alla frågor';
	this.expandLinkTextAfter = 'Visa inte frågor';
	this.firstCell = this.el.find('td.first');
	this.hiddenRows = this.el.nextUntil('.expand-parent');

	this.expandLink.text(this.expandLinkTextBefore);
	this.firstCell.append(this.expandLink);
	this.hiddenRows.hide();
	this.visible = false;

	this.expandLink.click(function(e) {
		e.preventDefault();
		t.expandLink.toggleClass('expand-link-expanded');
		if (t.visible) {
			t.expandLink.text(t.expandLinkTextBefore);
			t.hiddenRows.hide();
			t.visible = false;
		} else {
			t.expandLink.text(t.expandLinkTextAfter);
			t.hiddenRows.show();
			t.visible = true;
		}
	});
};

SolnaStad.FancyCheckBox = function (input, callback) {
	var self = this;

	this.enabled = true;

	this.callback = callback;

	this.input = input;
	this.input.blur(function () {
		self.checked ? self.uncheck() : self.check();
	});

	this.label = this.input.getLabel();
	this.label.bind({
		mouseover: function () {
			self.focus();
		},
		mouseout: function () {
			self.blur();
		},
		click: function (e) {
			e.preventDefault();
			self.checked ? self.uncheck() : self.check();
		}
	});

	this.checkboxImage = $('<span>', {
		className: 'fancy-checkbox'
	});
	this.checkboxTarget = $('<a>', {
		href: '#',
		click: function (e) {
			e.preventDefault();
			e.stopPropagation();
			self.checked ? self.uncheck() : self.check();
		},
		mouseover: function () {
			self.focus();
		},
		mouseout: function () {
			self.blur();
		},
		focus: function () {
			self.focus();
		},
		blur: function () {
			self.blur();
		}
	});
	this.label.append(this.checkboxImage.append(this.checkboxTarget));
	this.input.attr('checked') ? this.check() : this.uncheck();
};

SolnaStad.FancyCheckBox.prototype = {
	focus: function () {
		this.checkboxImage.addClass('fancy-checkbox-hover');
	},
	blur: function () {
		this.checkboxImage.removeClass('fancy-checkbox-hover');
	},
	check: function () {
		if (this.enabled) {
			this.checked = true;
			this.input.attr('checked', true);
			this.checkboxImage.addClass('fancy-checkbox-checked');
			if (typeof this.callback == 'function') {
				this.callback.call(this);
			}
		}
	},
	uncheck: function () {
		if (this.enabled) {
			this.checked = false;
			this.input.attr('checked', false);
			this.checkboxImage.removeClass('fancy-checkbox-checked');
			if (typeof this.callback == 'function') {
				this.callback.call(this);
			}
		}
	},
	disable: function () {
		this.checkboxImage.addClass('fancy-checkbox-disabled');
		this.enabled = false;
	},
	enable: function () {
		this.checkboxImage.removeClass('fancy-checkbox-disabled');
		this.enabled = true;
	}
};

SolnaStad.MapListItem = function (element, poi) {
	var t = this;

	this.element = element;
	this.poi = poi;
	this.hidden = true;
	this.content = this.element.find('.infowindow-content:first');

	// Hide item content
	this.content.hide();

	// Toggle content and infowindow on click
	this.element.find('h3 a:first').click(function (e) {
		e.preventDefault();
		t.toggle();
	});
};
SolnaStad.MapListItem.prototype = {
	toggle: function () {
		this.hidden ? this.show() : this.hide();
	},
	show: function () {
		this.content.slideDown('fast');
		this.element.addClass('item-expanded');
		this.poi.centerOn();
		this.poi.showInfoWindow();
		this.hidden = false;
	},
	hide: function () {
		this.content.slideUp('fast');
		this.element.removeClass('item-expanded');
		this.poi.hideInfoWindow();
		this.hidden = true;
	}
};

// Initialize when document is ready
$(function() {

	//Create rating bars
	var rawRatings = $('.raw-rating');
	if (rawRatings.length) {
		rawRatings.each(function() {
			this.ratingBar = new SolnaStad.ratingBar(this);
		});
	}

	if (!($.browser.msie && $.browser.version < 7)) {
		// Create sticky table headers (unless IE6 or below)
		$('.comp-table thead').stickyTableHeaders();
	}

	//Hide rows in tables, add expand link
	var expandParent = $('.expand-parent');
	if (expandParent.length) {
		expandParent.each(function() {
			this.expansion = new SolnaStad.ExpandTable(this);
		});
	}

	// MAP PAGE
	if ($('#comp-map').length) {
		// Fetch map container
		var mapContainer = $('#mapcontainer');
		// Create new map instance
		var map = new SolnaStad.Map(mapContainer);
		// Observe event when a POI is added
		map.addObserver('poiAdded', function (poi, element) {
			var item = new SolnaStad.MapListItem(element, poi);
			poi.addObservers({
				'markerClick': function (poi) {
					item.show();
				},
				'infoWindowClose': function (poi) {
					item.hide();
				}
			});
		});
		map.parseItemList($('#map-coords'));
	}

	//Create dialog boxes
	$('.dialog-link').openAsDialog({
		hijackForms: false
	});

	//Add expand link to some modules
	var contactInfoModule = $('#m-contactinfo');
	if (contactInfoModule.find('.hidden-content').length) {
		var contactInfoExpand = new SolnaStad.expandLinks(contactInfoModule,'Visa fler kontaktuppgifter','Visa färre kontaktuppgifter');
	}

	var checkboxes = [];
	function toggleButtons() {
		var checkedBoxes = $.grep(checkboxes, function (cb) { return cb.checked; });
		$.each(checkboxes, function () {
			var parent = this.input.closest('.select-to-compare');
			var btn = parent.find('.button:first');
			var notice = parent.find('.comparison-notice:first').css('visibility', 'hidden');

			if (checkedBoxes.length >= 5) {
				if (this.checked) {
					this.enable();
					btn.show();
				}
				else {
					this.disable();
					btn.hide();
					notice.text('Du kan jämföra maximalt fem utförare åt gången.').css('visibility', '');
				}
			}
			else {
				this.enable();
				if (checkedBoxes.length >= 2) {
					if (this.checked) {
						btn.show();
					} else {
						btn.hide();
					}
				}
				else {
					if (this.checked) {
						notice.text('Välj två eller fler utförare för att kunna jämföra.').css('visibility', '');
					}
					btn.hide();
				}
			}
		});
	}
	$('.select-to-compare').each(function () {
		checkboxes.push(new SolnaStad.FancyCheckBox($(this).find('input[type=checkbox]:first'), toggleButtons));
	});

	toggleButtons();

});
