window.addEvent("domready", function() { 
	
	Forum.init();
	
	autoPopulate.init();
	FieldFocus.init();	
	Weather.init();
	GalleryViews.init();
	EditCollapsible.init();
	StatusControl.init();
	
	AdvancedSearch.init();
	
	if($("register-first-name")){
		Register.init();
	}
	
	var usertips = $$("div.content a img");
	
	if(usertips){
	    //console.log("Usertips");
		//var url = "dummies/ajax-tooltip-user.html";
		var url = "/Templates/Pages/Tooltips/GeneralTooltipPage.aspx";
		Tooltips.init(usertips, "tooltipid-", url);
	}
	
	if($("feed-pictures")){	
		var url = "/Templates/Pages/Tooltips/ImageTooltipPage.aspx";
		Tooltips.init($$("div#feed-pictures table a"), "picture-", url);
		var picbrowse = new PictureBrowser($("feed-pictures"));
	}
	
	if($("gallery")){
		//console.log("Gallery!");
		var url = "/Templates/Pages/Tooltips/GalleryTooltipPage.aspx";
		Tooltips.init(usertips, "tooltipid-", url);
		var tip = $$("div.content span a img");
		
		if (tip.length == 0) {
			tip = $$("div.content a img");
		}
		Tooltips.init(tip, "galleryentry-", url);
	}
	
//	console.log("Meep");
//	if($$("farm-item")){
//		console.log("Farm item!");
//		var url = "/Templates/Pages/Tooltips/FarmTooltipPage.aspx";
//		var tip = $$("div.content span a img");
//		Tooltips.init(tip, "tooltipid-", url);
//	}
	
	if($("weekly")){
		var tabs = new TabControl($("weekly"));
	}
	
	if($("profile-intro-complete")){
		var bar = new ProfileProgressBar($("profile-intro-complete"));
	}
	
	var biglinks = $$("div.farm-list div.farm-item, div.group-list div.group-item, div.grow-blog-list div.grow-blog-item, div.blog-list div.blog-item, div.thread-list div.thread-item");
	biglinks.each(function(el){
		var biglink = new BigLink(el, true, true);
	});
});

var BigLink = new Class({
	initialize: function(el, link, hover){
		this.el = el;
		if(link){
			this.el.addClass("link");
			this.el.addEvent("click", this.click.bind(this));
		}
		
		if(hover){
			this.el.addEvent("mouseenter", this.over.bind(this));
			this.el.addEvent("mouseleave", this.out.bind(this));
		}
	},
	
	click: function(){
		var a = this.el.getElement("a");
		if(a){
			window.location = a;
		}
	},
	
	over: function(){
		this.el.addClass("over");
	},
	
	out: function(){
		this.el.removeClass("over");
	}
});

var GalleryViews = {
	init: function(){
		var galleries = $$("div.gallery-view");
		
		galleries.each(function(el){
			var url = "dummies/ajax-tooltip-picture.html";
			Tooltips.init(el.getElements("table a"), "picture-", url);
			
			if(el.getElement("div.gallery-view-browser")){
				if(el.hasClass("multi-rows")){
					var opt = new Object();
					opt.widthIncrement = 440;
					opt.multiRows = true;
					var picbrowse = new PictureBrowser(el, opt);
				}else{
					var picbrowse = new PictureBrowser(el);
				}
			}
		});
	}
}

var Tooltips = {
	init: function(tips, replace, url){
		var tooltip = new Tooltip();
		var req;
		//console.log("Tooltips.init");
		tips.each(function(el){
			
			if(el.get("tag") == "img") el = el.getParent();
			
			var prefix = el.get("class");
			if(prefix.contains(replace)){
				el.addEvent("mouseenter", function(e){
					
					tooltip.set("");
					var requestGet;
					
					if (replace == "galleryentry-"){
						var info = prefix.replace(replace, "");
						info = info.split("-");
						requestGet = {"toolTipGalleryEntityId": info[0], "toolTipGalleryId": info[1], "toolTipGalleryMediaType": info[2]};
					}
					else
					{
						var info = prefix.replace(replace, "");
						info = info.split("-");
						
						if (info.length == 1)
						    requestGet = {"toolTipEntityId": info[0], "toolTipPage": "default"};
						else
						{
						    requestGet = {"toolTipEntityId": info[0], "toolTipPage": info[1]};
						}
					}

					req = new Request.HTML({url: url});
					req.addEvent("complete", function(tree, el, html, js){
						tooltip.tooltip.fade("hide");
						// tooltip.hide();
						tooltip.set(html);
						tooltip.show(e);
					});
					
					//req.get({"toolTipEntityId": id}); 
					//console.log(requestGet);
					req.get(requestGet); 
				});
				
				el.addEvent("mouseleave", function(){
					//console.log("mouseleave <<");
					req.removeEvents("complete");
					tooltip.hide(el);
				});
			}
		});
	}
}

var Tooltip = new Class({
	initialize: function(){
		var wrapper = "";
		var content = "";
		if($$("div.tooltip")[0]){
			var wrapper = $$("div.tooltip")[0];
			var content = $$("div.tooltip-content")[0];
		}else{
			wrapper = new Element("div", {"class": "tooltip"});
			wrapper.inject(document.body);		
			wrapper.set("tween", { duration: 200, link: "cancel" }).fade("hide");
			wrapper.addEvent("mouseenter", this.clearTimer.bind(this));
			wrapper.addEvent("mouseleave", this.hide.bind(this));
			
			var inner = new Element("div", {"class": "tooltip-inner"});
			inner.inject(wrapper);
			
			content = new Element("div", {"class": "tooltip-content"});
			content.inject(inner);
			
			var close = new Element("a", {"class": "tooltip-close", "href": "#"});
			close.set("text", "St&auml;ng");
			close.inject(wrapper);
			close.addEvent("click", this.close.bind(this));		
		}
		this.tooltip = wrapper;
		this.content = content;
	},
	
	close: function(e){
		var ev = new Event(e).stop();
		this._hidide();
	},
		
	set: function(content){
		this.content.innerHTML = content;
	},	
	
	position: function(x, y){
		this.tooltip.set("styles", {
			"left": x,
			"top": y
		});
	},
	
	show: function(e){
		this.clearTimer();
		this.tooltip.fade("out");
		this.target = $(e.target);
		this.timer = setTimeout(this._show.bind(this), 750);
	},
	
	_show: function(target){
		this.clearTimer();
		this.tooltip.fade("in");
		var pos = this.target.getPosition();
		this.position(pos.x + 30, pos.y + 20);
	},
	
	hide: function(){		
		this.clearTimer();
		this.timer = setTimeout(this._hide.bind(this), 200);
	},
	
	_hide: function(e){
		this.clearTimer();
		this.tooltip.fade("out");
	},
	
	clearTimer: function(){
		clearTimeout(this.timer);
	}
});

var ProfileProgressBar = new Class({
	prefix: "-percent",
	
	initialize: function(el){
		if(el.className.contains(this.prefix)){
			var percent = el.className.replace(this.prefix, "");
			var bar = el.getElement("span.progress-bar");
			bar.setStyle("width", percent + "%");
		}
	}
});

var FieldFocus = {
	init: function(){
		var spans = $$("span.field-blue, span.field-generic, span.field-generic-ajax, span.field-green");
		spans.each(function(el){
			var control = el.getElement("input");
			var customField = new CustomControl(el, control);
		});
		
		var selects = $$("select");
		selects.each(function(el){							  
			var customSelect = new CustomControl(el, el);
		});
		
		var textareas = $$("textarea");
		textareas.each(function(el){							  
			var customSelect = new CustomControl(el, el);
		});
	}
}

var CustomControl = new Class({
	initialize: function(el, control){
		this.el = el;
		this.control = control;
		this.control.addEvent("focus", this.focus.bind(this));
		this.control.addEvent("blur", this.blur.bind(this));
		//this.control.addEvent("keydown", this.key.bind(this));
		this.control.addEvent("keyup", this.key.bind(this));
		this.checkText();
	},
	
	key: function(e){
		this.checkText();
	},
	
	checkText: function(){
		if(this.control.disabled){ return; }
		if(this.control.value.length != 0){
			this.el.addClass("filled");
		}else{
			this.el.removeClass("filled");
		}
	},
	
	focus: function(e){
		this.el.addClass("focus");
		this.checkText();
	},
	
	blur: function(e){
		this.el.removeClass("focus");
		this.checkText();
	}
});

var NameField = new Class({
	Extends: CustomControl,
	
	initialize: function(el, control, update){
		this.parent(el, control);
		this.update = update;
		this.key();
	},
	
	key: function(){
		this.update.innerHTML = this.control.value;
		this.checkText();
	}
});

var Register = {
	init: function(){
		var firstname = $$(".register-first-name")[0];
		var firstnameControl = firstname.getElement("input");
		var firstnameUpdate = $("register-first-name");
		var firstnameCustom = new NameField(firstname, firstnameControl, firstnameUpdate);
		
		var lastname = $$(".register-last-name")[0];
		var lastnameControl = lastname.getElement("input");
		var lastnameUpdate = $("register-last-name");
		var lastnameCustom = new NameField(lastname, lastnameControl, lastnameUpdate);
	}
}

var PictureBrowser = new Class({
	controlNext: "control-next",
	controlPrev: "control-prev",
	browserWidth: 440,
	maxWidth: 440,
	widthIncrement: 110,
	multiRows: false,
	
	initialize: function(wrapper, opt){
		if(opt){
			if(opt.widthIncrement){
				this.widthIncrement = opt.widthIncrement;
			}
			if(opt.multiRows){
				this.multiRows = true;
			}
		}
			
		this.wrapper = wrapper;
		this.browser = $("feed-pictures-browser");
		if(!this.browser){
			this.browser = wrapper.getElement("div.gallery-view-browser");
		}
		this.browser.set( "tween", { duration: 400, link: "ignore", onComplete: this.complete.bind(this) } );
		
		this.browserWrapper = new Element("div", {"class" : "gallery-view-browser-wrapper" });
		this.browserWrapper.inject(this.browser.getParent(), "top");
		this.browser.inject(this.browserWrapper);
		
		var footer = this.wrapper.getElement(".box-footer");
		var controlsWrapper = new Element("div", {"class": "gallery-view-controls"});
		var controls = new Element("ul", {"class": "clearfix"});
		controlsWrapper.inject(footer);
		controls.inject(controlsWrapper);
		
		this.controlPrev = new Element("li", {"class": this.controlPrev});
		this.controlPrev.inject(controls);
		this.controlPrev.addEvent("click", this.prev.bind(this));
		
		this.controlNext = new Element("li", {"class": this.controlNext});
		this.controlNext.inject(controls);
		this.controlNext.addEvent("click", this.next.bind(this));
		
		
		if(this.multiRows){
			var tableCount = this.browser.getElements("table").length - 1;
			this.maxWidth = tableCount * this.browserWidth;
		}else{
			var cellCount = this.browser.getElements("td").length;
			this.maxWidth = cellCount * this.widthIncrement - this.browserWidth;
		}
		this.browser.setStyle("width", this.maxWidth + this.browserWidth);
		
		this.checkControls();
	},
	
	checkControls: function(){
		var left = this.browser.getStyle("margin-left").toInt();

		if(left > -this.maxWidth)
			this.controlNext.addClass("active");
		else
			this.controlNext.removeClass("active");
		
		if(left < 0)
			this.controlPrev.addClass("active");
		else
			this.controlPrev.removeClass("active");
	},
	
	next: function(){
		if(this.controlNext.hasClass("active")){
			var left = this.browser.getStyle("margin-left").toInt();
			var val = left - this.widthIncrement;
			
			if(val >= -this.maxWidth){
				this.browser.tween("margin-left", [left, val]);
			}
		}
		this.checkControls();
	},
	
	prev: function(){
		if(this.controlPrev.hasClass("active")){
			var left = this.browser.getStyle("margin-left").toInt();
			var val = left + this.widthIncrement;
			if(val <= 0){
				this.browser.tween("margin-left", [left, val]);
			}
		}
		this.checkControls();
	},
	
	complete: function(){
		this.checkControls();		
	}
});

var TabControl = new Class({
	initialize: function(parent){
		this.active = parent.getElement("div.active");
		this.menu = parent.getElement("ul");
		this.activeTab = this.menu.getElement("li.sel");
		this.items = this.menu.getElements("a");
		this.items.addEvent("click", this.click.bind(this));
	},
	
	click: function(e){
		e.stop();
		e.target.blur();
		var target = $(e.target).getParent();
		var ref = target.getProperty("href").replace("#", "");
		
		this.activeTab.removeClass("sel");
		this.activeTab = target.getParent();
		this.activeTab.addClass("sel");
		
		//var classname = target.className;		
		//this.menu.className = "tab-navigation " + classname + "-selected";
		
		this.active.removeClass("active");
		this.active = $(ref);
		this.active.addClass("active");
	}
});

var Weather = {
	init: function(){
		var weather = $("weather");
		//var weatherBig = $("weather-big");
		
		if(weather){
			var url = "dummies/ajax-weather.html";
			var control = new WeatherControl(weather, url);
		}
		
		/*if(weatherBig){
			var toggle = new WeatherBigControl(weatherBig);
			var link = $("weather-big-toggle");
			var close = $("weather-big-close");
			if(link){
				link.addEvent("click", function(e){
					e.stop();
					toggle.show();
				});
			}
			if(close){
				close.addEvent("click", function(e){
					e.stop();
					toggle.hide();
				});
			}
			var url = "dummies/ajax-weather-big.html";
			var control = new WeatherControl(weatherBig, url);
		}*/
	}
}

var WeatherControl = new Class({
	toggle: "span.weather-location-toggle",
	menu: "div.weather-locations",
	update: "div.weather-update",	
	initialize: function(el, url){
		this.toggle = el.getElement(this.toggle);
		/*this.menu = el.getElement(this.menu);
		this.update = el.getElement(this.update);
		this.url = url;*/
		//this.toggle.addEvent("click", this.show.bind(this));
		this.toggle.addEvent("mouseenter", this.onToggleOver.bind(this));
		this.toggle.addEvent("mouseleave", this.onToggleOut.bind(this));
		/*this.menu.addEvent("mouseenter", this.onMenuOver.bind(this));
		this.menu.addEvent("mouseleave", this.onMenuOut.bind(this));
		var links = this.menu.getElements("a").addEvent("click", this.onLocationClick.bind(this));
		this.timer = setTimeout(this.hide.bind(this), 3000);*/
	},	
	show: function(){
		var parent = this.toggle.getParent();
		var left = this.toggle.getPosition(parent).x;		
		this.toggle.addClass("active");
		this.menu.setStyle("left", left);
		this.menu.addClass("active");
		this.active = true;
	},	
	hide: function(){
		this.toggle.removeClass("active");
		this.menu.removeClass("active");
	},	
	onMenuOver: function(){
		clearTimeout(this.timer);
	},	
	onMenuOut: function(){
		this.timer = setTimeout(this.hide.bind(this), 1000);
	},	
	onToggleOver: function(){
		this.toggle.addClass("over");
	},	
	onToggleOut: function(){
		this.toggle.removeClass("over");
	},	
	onLocationClick: function(e){
		e.stop();
		var value = e.target.innerHTML;
		this.toggle.innerHTML = value;
		this.update.load(this.url, {"location" : value});
		this.hide();
	}
});

var WeatherBigControl = new Class({
	initialize: function(el){
		this.el = el;
		this.el.addClass("active");
		this.el.set("tween", {duration: 200});
		this.el.fade("hide");
	},	
	show: function(){
		this.el.fade("in");
		this.active = true;
	},	
	hide: function(){
		this.el.fade("out");
		this.active = false;
	},	
	toggle: function(){
		if(this.active)
			this.hide();
		else
			this.show();
	}
});

var EditCollapsible = {
	init: function(){
		var elements = $$("div.edit-collapsible");
		var i = 0;
		elements.each(function(el){
			var collapsible;
			if(el.hasClass("dynamic-checkboxes")){
				collapsible = new CheckboxCollapsible(el);
			}else{
				collapsible = new Collapsible(el);
			}
			//if(i > 0) collapsible.hide();
			collapsible.hide();
			i++
		});
	}
}

var Collapsible = new Class({
	collapsed: false,
	initialize: function(el){
		this.wrapper = el;
		this.control = this.wrapper.getElement(".collapsible-toggle");
		this.element = this.wrapper.getElement(".collapsible-box");
		this.control.addClass("active-toggle");
		this.control.addEvent("click", this.toggle.bind(this));		
		this.element.set("slide", {duration: 400, onStart: this.start.bind(this), onComplete: this.complete.bind(this)});
	},	
	toggle: function(){
		this.element.slide("toggle");
	},	
	hide: function(){
		this.control.toggleClass("collapsed-toggle");
		this.element.slide("hide");
	},	
	start: function(){		
		this.control.toggleClass("collapsed-toggle");
		var el = this.element.get("slide").wrapper;
		el.setStyle("position", "relative");
	},	
	complete: function(){		
		var el = this.element.get("slide").wrapper;
		if(el.getStyle("height").toInt() > 0){
			el.erase("style");
			el.setStyles({
				overflow: "hidden",
				margin: "0px"
			});
			//this.element.inject(el, "after");
			//el.destroy();
		}
	}
});

var CheckboxCollapsible = new Class({								   
	Extends: Collapsible,	
	initialize: function(el){
		this.parent(el);		
		this.inputs = el.getElements("input");
		this.inputs.each(function(el){
			el.addEvent("click", this.checked.bind(this));
		}.bind(this));
		this.checkFilled();
	},	
	checked: function(){
		this.checkFilled();
	},	
	checkFilled: function(){
		this.control.addClass("empty");
		this.inputs.each(function(el){
			if(el.checked){
				this.control.removeClass("empty");
			}
		}.bind(this));
	}
});

var PopBox = {
	show: function(el, popbox, centered){
		el = $(el);
		popbox = $(popbox);
		//popbox.inject(document.body);
		
		popbox.set("tween");
		popbox.fade("hide");
		popbox.setStyle("display", "block");
		var popSize = popbox.getSize();
		
		var popY = 0;
		var windowSize = $(window).getSize();
		
		if(centered){
			var screenCenter = windowSize.y / 2;
			//var screenScroll = $(window).getScroll().y;
			
			popY = screenCenter - (popSize.y / 2)/* + screenScroll*/;
			
		}else{
			if(el){
				var position = el.getPosition();
				popY = position.y - (popSize.y / 2);
			}
		}
		
		popbox.setStyle("top", popY);
		popbox.setStyle("left", (windowSize.x / 2) - (popSize.y / 2));
		
		popbox.fade("in");
		
		
		popbox.visible = true;
	},
	
	toggle: function(el, popbox, centered){
		if(popbox.visible) PopBox.close(null, popbox);
		else PopBox.show(el, popbox, centered);
	},
	close: function(el, popbox){
		el = $(el);
		if(el != null){
			if(el.hasClass("alert-close")){
				popbox = el.getParent().getParent();
			}
		}
		if(popbox != null){
			//popbox.set("tween");
			//popbox.fade("out");
			popbox.setStyle("display", "none");
			popbox.visible = false;
		}
	}
}

var StatusControl = {
	init: function(){
		var status = $("profile-intro-edit");
		var toggle = $("profile-intro-status-edit");
		var form = $("profile-intro-form");
		if(toggle && form && status){
			var link = toggle.getElement("a");
			link.addEvent("click", function(e){
				new Event(e).stop();
				form.setStyle("display", "block");
				status.setStyle("display", "none");
			});
		}
	}
}

/*
* Auto-populate function by Roger Johansson, www.456bereastreet.com
*/
var autoPopulate = {
	sInputClass:'populate',
	sHiddenClass:'structual',
	bHideLabels:false,

	init:function() {
		if (!document.getElementById || !document.createTextNode) {return;}
		//var arrInputs = Site.getElementsByClassName(document, 'input', autoPopulate.sInputClass)
		var arrInputs = $$("span.field-generic input");
		var iInputs = arrInputs.length;
		var oInput;
		for (var i=0; i<iInputs; i++) {
			oInput = arrInputs[i];
			if (oInput.type == 'text' || oInput.type == 'password'){
				if (autoPopulate.bHideLabels) { autoPopulate.hideLabel(oInput.id); }
				if ((oInput.value == '') && (oInput.title != '')) { oInput.value = oInput.title; }
				oInput.addEvent('focus', function() {
					if (this.value == this.title) {
						this.value = '';
						this.select();
					}
				});
				oInput.addEvent('blur', function() {
					if (!this.value.length) { this.value = this.title; }
				});
			}
		}
	},
	hideLabel:function(sId) {
		var arrLabels = document.getElementsByTagName('label');
		var iLabels = arrLabels.length;
		var oLabel;
		for (var i=0; i<iLabels; i++) {
			oLabel = arrLabels[i];
			if (oLabel.htmlFor == sId) {
				oLabel.className = oLabel.className + ' ' + autoPopulate.sHiddenClass;
			}
		}
	}
};

var Forum = {
	init: function(){
		Forum.loader = new Image();
		Forum.loader.src = "/Img/ajax-loader2.gif";
		Forum.loader = new Element("div", { "class": "forum-loader" }).adopt(Forum.loader).set("tween").fade("hide");
		$$("div.forum-categories").each(function(el){
			new ForumCategories(el);
		});
		Forum.update(true);
	},
	update: function(doHide){
		var filter = $("forum-filter");
		if(filter){
			var col = new Collapsible(filter);
			
			if (doHide)
			{
			    col.hide();
			}
		}
		$$("div.thread-list div.thread-item").each(function(el){
			el.addClass("link");
			el.addEvent("click", function(){
				var links = el.getElements("a");
				Forum.onAjax();
				//console.log(links[1]);
			});
			el.addEvent("mouseenter", function(){
				el.addClass("over");
			});
			el.addEvent("mouseleave", function(){
				el.removeClass("over");
			});
		});
	},
	onAjax: function(){
		var el = $("forum-updates");
		el.set("tween", { "duration": 500, onComplete: function(){
			el.empty();
			el.fade("show");
			el.adopt(Forum.loader);
			Forum.loader.fade("in");
		} }).fade("out");
	}
}
var ForumCategories = new Class({
	initialize: function(el){
		var items = el.getElements("li");
		items.each(function(el){
			el.addClass("link");
			el.addEvents({
				"mouseenter": this.enter,
				"mouseleave": this.leave,
				"click": this.click
			});
			
		}.bind(this));
	},
	enter: function(){
		this.addClass("over");
	},
	leave: function(){
		this.removeClass("over");
	},
	click: function(){
		var link = this.getElement("a");
		window.location = link;
	}
});

var AdvancedSearch = {
	init: function(){
		this.control = $$(".advanced-toggle");
		this.element = $$(".advanced");
		this.control.addClass("active");
		this.control.addEvent("click", this.toggle.bind(this));
		this.element.slide("toggle");
	},	
	toggle: function(){
		this.element.slide("toggle");
		this.control.toggleClass("show");
	}
};