/**
 * Ny Teknik
 */

// Twingly settings 
var tw_noConflict = true; // Important to avoid conflict with $-function
var tw_toplistUrl = "http://www.nyteknik.se";
var tw_skipDefaultCss = true;
var tw_language = "swedish";
var tw_postLimit = 5;
var tw_useToolTip = false;
var tw_onComplete = function() {
	var twingly = $$("twingly");
	if (twingly) {
		if (tw_numberOfPosts == 0) {
			twingly.setStyle("display", "none");
		} else {
			twingly.setStyle("left", "0px");
		}
	}
};


var NyTeknik = function() {
	return {	
		init: function() {
			Talentum.addAnchors.init([
				{element: ".teaser", include: ["P", "IMG"], exclude: [".poll"]},
				{element: ".subteaser", include: ["P", "IMG"]},
				{element: ".pullteaser", include: ["P", "IMG"]},
				{element: ".small-teaser", include: ["P", "IMG"]},
				{element: ".blog-teaser", include: ["IMG"]}
			]);
			Talentum.print.init();
			Talentum.mediaplayer.init();
			Talentum.recommend.init();
			Talentum.zoom.init();
			Talentum.fontSize.init();
			Talentum.popup.init();
			Talentum.comment.init();
			Talentum.reportAbuse.init();
			Talentum.userSettings.init();
			Talentum.validateForms.init();
			Talentum.slideshow.init();
			Talentum.ajaxForms.init();
			Talentum.tooltip.init();
			Talentum.stickyAd.init({
				top: "submenu"
			});
			Talentum.poll.init();
			Talentum.leiki.init();
 			Talentum.scrollingList.init([
				{ element: ".job-teaser ul", noOfItems: 3 },
				{ element: ".article .jobs ul", noOfItems: 3, duration: 1500, delay: 4000, direction: "horizontal" }
			]);
			
			NyTeknik.subscribe.init();
			NyTeknik.jobSearch.init();
			NyTeknik.sIFR.init();
			NyTeknik.accordion.init();
			NyTeknik.toggler.init();
			NyTeknik.conditionalDisplay.init();
			NyTeknik.definition.init();
			NyTeknik.autoComplete.init();
		}
	};
}();


NyTeknik.autoComplete = function() {
	var className = "auto-complete";
	var urlField = "auto-complete-url";
	var maxResultSize = 20;
	var data = [];
	var inputElms = 0;
	
	var createOutputElm = function(elm) {
		var position = Talentum.getPosition(elm);
		elm.dummyInput = $(document.body).create("input", {className: "auto-completion-input-dummy" }, true);
		elm.outputElm = $(document.body).create("ul", {className: "auto-completion-list", id: "auto-completion-list-" + inputElms }, true);
		elm.outputElm.style.display = "none";
		elm.outputElm.style.position = "absolute";
		elm.outputElm.style.left = position.x + "px";
		elm.outputElm.style.top = position.y + elm.offsetHeight + "px";
		elm.outputElm.style.width = (elm.offsetWidth-20) + "px";
		elm.dummyInput.style.position = "absolute";
		elm.dummyInput.style.left = "-9999px";
		elm.dummyInput.style.top = position.y + elm.offsetHeight + "px";
		inputElms++;

		Talentum.eventHandler.register("click", "#" + elm.outputElm.id + " li", function() {
			elm.value = this.innerHTML;
			elm.form.submit();
		});
		elm.outputElm.show = function() {
			elm.currentIndex = -1;
			elm.outputElm.style.display = "block";
			$(document).addEvent("click", elm.outputElm.hide);
			$(elm.dummyInput).addEvent("keyup", elm.outputElm.step);
		};
		elm.outputElm.hide = function() {
			elm.outputElm.style.display = "none";
			$(document).removeEvent("click", elm.outputElm.hide);		
			$(elm.dummyInput).removeEvent("keyup", elm.outputElm.step);
		};
		elm.outputElm.step = function(e) {
			if (e.keyCode == 40 || e.keyCode == 38 && elm.outputElm.style.display == "block") {
				if (e.keyCode == 40 && (elm.currentIndex < elm.resultSize-1)) {
					elm.currentIndex++;
				} else if (e.keyCode == 38 && elm.currentIndex > 0) {
					elm.currentIndex--;
				} else if (e.keyCode == 38) {
					elm.currentIndex--;
					elm.focus();
				}
				var i = 0;
				elm.outputElm.elmsByTag("li").each(function() {
					if (i == elm.currentIndex) {
						this.className = "current";
					} else {
						this.className = "";
					}
					i++;
				});
			} else if (e.keyCode == 13 && elm.outputElm.style.display == "block" && elm.currentIndex > -1) {
				elm.value = ($("#" + elm.outputElm.id + " li:nth-child(" + (elm.currentIndex+1) + ")")[0]).innerHTML;
				elm.form.submit();
			} else if (e.keyCode == 27) {
				elm.outputElm.hide();
				elm.focus();
			}
		}
	};

	var fetchData = function(elm) {
		elm.timer = null;
		elm.post(document.getElementById(urlField).value + "?mode=ajax&query=" + elm.value, function(response) {
			data = eval(response);
			elm.resultSize = 0;
			elm.outputElm.innerHTML = "";
			for (var i = 0, l = data.length; i < l && elm.resultSize < maxResultSize; i++) {
				var li = elm.outputElm.create("li", {title: data[i]}, true, data[i].substring(0, elm.value.length) + data[i].substring(elm.value.length));
				elm.resultSize++;
			}
			if (elm.resultSize > 0) {
				elm.outputElm.fadeIn();
			} else {
				elm.outputElm.hide();
			}
		});
	};

	var DOMReady = function() {
		$(".auto-complete").each(function() {
			this.setAttribute("autocomplete", "off");
			$(this).addEvent("keyup", function(e) {
				var elm = this;
				if (!elm.outputElm) createOutputElm(elm);
				if (e.keyCode == 40 || e.keyCode == 38 && elm.outputElm.style.display == "block") {
					elm.dummyInput.focus();
					elm.outputElm.step(e);
				} else if (elm.value.length > 1 && !elm.timer) {
					elm.timer = setTimeout(function() { fetchData(elm); }, 250);
				} else {
					elm.outputElm.hide();
				}
			});
		});
	};
	
	return {
		init: function() {
			Talentum.addOnDOMReady(DOMReady);
		}
	}
}();


NyTeknik.conditionalDisplay = function() {
	var DOMReady = function() {
		$(".conditional-display").each(function() {
			var show = Talentum.getClassNameValue(this, "showon");
			var hide = Talentum.getClassNameValue(this, "hideon");
			var focus = $$(Talentum.getClassNameValue(this, "focuson"));
			var elem = this;
			if ($$(show).checked) {
				elem.style.display = "block";
			}
			Talentum.eventHandler.register("click", "#" + show, function() {
				if (this.checked) {
					elem.style.display = "block";
					focus.focus();
				}
				else {
					elem.style.display = "none";
				}
				return true;
			});
			if (show != hide) {
				Talentum.eventHandler.register("click", "#" + hide, function() {
					elem.style.display = "none";
					return true;
				});
			}
		});
	};
	
	return {
		init: function() {
			Talentum.addOnDOMReady(DOMReady);
		}
	};
}();


NyTeknik.subscribe = function() {
	var formId = "job-search";
	var subscribeId = "subscribe";
	var togglerClass = "toggle-subscribe";
	var searchModeSubmitId = "search-mode-submit";
	var notice;
	var formContent;
	
	return {
		init: function() {
			Talentum.eventHandler.register("click", "." + togglerClass, function() {
				var elm = $$(subscribeId);
				if (elm != null) {
					if (elm.getStyle("display") == "block") {
						elm.setStyle("display", "none");
						$$(searchModeSubmitId).setStyle("display", "block");
						$$("subscribe-email").removeClass("required email");
					} else {
						elm.setStyle(DOMEffects.getOpacityRule(0));
						$$(searchModeSubmitId).setStyle("display", "none");
						elm.setStyle("display", "block");
						elm.fadeIn( { duration: 400, callback: function() { $$("subscribe-email").focus(); } } );
						$$("subscribe-email").addClass("required email");
					}
				}
			});
		}
	};
}();


NyTeknik.accordion = function() {
	var triggerClass = "accordion";
	var partClass = "accordion-part";
	var partTag = "div";
	var partContentClass = "accordion-part-content";
	var activePartClass = "active-accordion-part";
	var EFFECT_SLIDE = "slide";
	var accordions = 0;
	var frameRate = 30;
	var step = 25;
	
	var toggleTo = function(elm, accordionObjIndex, effect) {
		var accordion = $$("_accordion-" + accordionObjIndex);
		
		if (effect == EFFECT_SLIDE) {
			accordion.openElm = elm.elmsByClass(partContentClass)[0];
			accordion.closeElm = accordion.activeElm.elmsByClass(partContentClass)[0];
			accordion.openElm.setStyle("height", "0px");
			accordion.currentPart = accordion.activeElm;
			elm.addClass(activePartClass);
			accordion.openElmHeight = Talentum.getActualHeight(accordion.openElm);
			accordion.closeElmHeight = Talentum.getActualHeight(accordion.closeElm);

			NyTeknik.accordion.openClose(accordionObjIndex);
			accordion.activeElm = elm;
		} else {
			if (accordion.activeElm) {
				accordion.activeElm.removeClass(activePartClass);
			}
			elm.addClass(activePartClass);
			accordion.activeElm = elm;
		}
	};
	
	var getMaxHeight = function(elementsArray) {
		var maxHeight = 0;
		for (var i = 0, l = elementsArray.length; i < l; i++) {
			var elem = $(elementsArray[i]).elmsByClass(partContentClass)[0];
			maxHeight = Math.max(Talentum.getActualHeight(elem), maxHeight);
		}
		return maxHeight;
	};
	
	var DOMReady = function() {
		$("." + triggerClass).each(function() {
			var thisIndex = accordions;
			accordions++;

			var accordion = $(this);
			accordion.id = "_accordion-" + thisIndex;

			var parts = accordion.elmsByClass(partClass, partTag);
			
			accordion.targetHeight = getMaxHeight(parts);
			for (var i = 0, l = parts.length; i < l; i++) {
				var partContent = $(parts[i]).elmsByClass("accordion-part-content")[0];
				partContent.setStyle("height", accordion.targetHeight + "px");
				partContent.setStyle("display", "none");
			}
			$(parts[0]).addClass(partClass + "-first");
			$(parts[parts.length - 1]).addClass(partClass + "-last");

		 	toggleTo(parts[0], thisIndex);

			Talentum.eventHandler.register("click", "#" + accordion.id + " ." + partClass, function() {
				if (this != accordion.activeElm) {
					toggleTo($$(this), thisIndex, EFFECT_SLIDE);
				} else {
					return true;
				}
			});
		});
	};

	return {
		openClose: function(accordionObjIndex) {
			var accordion = $$("_accordion-" + accordionObjIndex);
			if (accordion.closeElmHeight <= 0) {
				clearTimeout(accordion.timer);
				accordion.currentPart.removeClass(activePartClass);
			} else {
				accordion.openElmHeight = ((accordion.openElmHeight + step) >= accordion.targetHeight) ? accordion.targetHeight : accordion.openElmHeight + step;
				accordion.closeElmHeight = ((accordion.closeElmHeight - step) <= 0) ? 0 : accordion.closeElmHeight - step;
				accordion.openElm.setStyle("height", accordion.openElmHeight + "px");
				accordion.closeElm.setStyle("height", accordion.closeElmHeight + "px");
				accordion.timer = setTimeout("NyTeknik.accordion.openClose(" + accordionObjIndex + ")", frameRate);
			}
		},

		init: function() {
			Talentum.addOnDOMReady(DOMReady);
		}
	};
}();


NyTeknik.toggler = function() {
	var togglePrefix = "toggle";
	var duration = 300;
	var DOMReady = function() {
		Talentum.eventHandler.register("click", "a." + togglePrefix, function() {
			var elmId = Talentum.getClassNameValue(this, togglePrefix);
			var elm = $$(elmId);
			if(elm.getStyle("display") != "block") {
				elm.setStyle(DOMEffects.getOpacityRule(0));
				elm.setStyle("display", "block");
				elm.fadeIn( { duration: duration } );
			} else {
				elm.setStyle("display", "none");
			}
		});
	};
	
	return {
		init: function() {
			Talentum.addOnDOMReady(DOMReady);
		}
	};
}();


NyTeknik.jobSearch = function() {
	var handleCheckBoxes = function(field) {
		if (field.type == "checkbox") {
			var fieldset = field.parentNode;
			while (fieldset && fieldset.tagName != "FIELDSET") {
				fieldset = fieldset.parentNode;
			}
			if (fieldset) {
				if ($(field).hasClass("select-all")) {
					var current = field;
					$(fieldset).cssSelect("input[type=checkbox]").each(function() {
						if (this != current) {
							this.checked = "";
						}
					});
				} else {
					$(fieldset).cssSelect(".select-all")[0].checked = "";
				}				
			}
		}
		return true;		
	};
	
	return {
		init: function() {
			Talentum.eventHandler.register("click", "fieldset.titles input", function() {
				return handleCheckBoxes(this);
			});
			Talentum.eventHandler.register("click", "fieldset.regionsandcompanies input", function() {
				return handleCheckBoxes(this);
			});
		}
	};
}();


NyTeknik.definition = function() {
	var DOMReady = function() {
		var toolTip = $$("tool-tip");
		Talentum.eventHandler.register("mouseover", ".definition", function() {
			var txt = $(this).title;
			toolTip.innerHTML = "<span>\"" + txt + "...\"</span> Läs mer i ordboken";
			pos = Talentum.getPosition(this, $(".article")[0]);
			toolTip.setStyle("position", "absolute");
			toolTip.style.display = "block";
			toolTipHeight = Talentum.getActualHeight(toolTip);
			toolTipWidth = Talentum.getActualWidth(toolTip);
			
			toolTip.setStyle("left", Math.max(0, pos.x - (toolTipWidth / 2) + 5) + "px");
			toolTip.setStyle("top", (pos.y - 3 - toolTipHeight) + "px");
		});
		Talentum.eventHandler.register("mouseout", ".definition", function() {
			toolTip.style.left = "-9999px";
			toolTip.style.top = "-9999px";
		});
	};
	
	return {
		init: function() {
			Talentum.addOnDOMReady(DOMReady);
		}
	}
}();


NyTeknik.sIFR = function() {
	var bentonSans = {
		src: "/nyteknik/static/ver02/flash/sIFR/bentonSans.swf"
	};
	
	var rgbToHex = function(value, defaultValue) {
		if (value.charAt(0) == "#") {
			return value;
		}
		var result = value.match(/^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*/);
		if (result == null) {
			return defaultValue ? defaultValue : value;
		}
		var rgb = +result[1] << 16 | +result[2] << 8 | +result[3];
		var hex = "";
		var digits = "0123456789abcdef";
		while (rgb != 0) {
			hex = digits.charAt(rgb&0xf) + hex;
			rgb >>>= 4;
		}
		while (hex.length < 6) {
			hex = "0" + hex;
		}
		return "#" + hex;
	};
	
	var DOMReady = function() {
		NyTeknik.sIFR.render();
	};

	return {
		init: function() {
			if (typeof sIFR !== "undefined") {
				sIFR.activate(bentonSans);
				Talentum.addOnDOMReady(DOMReady);
			}
		},
		render: function() {
			if (typeof sIFR !== "undefined") {
				$(".comments-grid H2", ".tags-heading H1 .heading", ".article-blog .links H2", ".article-blog .tags H2", ".blog-sidebar H2", ".box-blue H2", ".box-grey H2", ".box-definition H2", ".box-yellow H2", ".box-pink H2", ".links H2", ".article #comments H2", ".article .additional-content .links H2", "#twingly H2", ".tags H2", ".additional-content .tags H2", ".jobs H2", ".article .jobs H2", ".additional-content .jobs H2", ".article #comments H2", ".section-heading H1", ".toplists .links H2", ".prime-teaser .sup-title", ".box-jobs H2", ".job-teaser H2 SPAN", ".box-whitepaper H2").each(function() {				
					var els = [];
					els[0] = $(this);
					var color = rgbToHex(this.getStyle("color"), "#000000");
					var textAlign = this.getStyle("text-align");
					sIFR.replace(bentonSans, {
							elements: els,
							css: {".sIFR-root": {"letter-spacing": "-0.6", "color": color, "text-align": textAlign}},
							tuneHeight: -4,
							wmode: "transparent",
							ratios: [7, 1.32, 11, 1.31, 12, 1.24, 14, 1.27, 19, 1.23, 24, 1.22, 33, 1.2, 45, 1.19, 50, 1.18, 51, 1.19, 74, 1.18, 1.17]
						}
					);
				});
			}
		}
	};
}();


NyTeknik.init();

function handleJobForm(jobForm, searchAction, subscribeAction, searchErrorUrl, subscribeErrorUrl)
{
	var subscribeFields = document.getElementById('subscribe');
	var productionHostname = "nyteknik.se";
	
	//To make it work on local development environment.
	var localDirectory = window.location.hostname.indexOf(productionHostname) == -1 ? '/nyteknik' : '';
	
	if (subscribeFields.style.display == 'block')		
	{
		jobForm.action = localDirectory + subscribeAction;
		jobForm.errorUrl.value = subscribeErrorUrl;
	}
	else
	{
		jobForm.action = localDirectory + searchAction;
		jobForm.errorUrl.value = searchErrorUrl;
	}
		
	//Copy job "search word" to subscription search word. TODO: Update the SubscribeAction class to use "searchString" instead of "field(searchword)". Then remove the code below.
	document.getElementById('subscribeSearchWord').value = document.getElementById('job-search-string').value;
}
