// Common functions for the offering platform.
window.Offering = window.Offering || new function(){ // do not re-create if included twice
	var ID_POPUP = "#offering-popup";
	var ID_COOKIE = "fortumUsedEstimatePeriod";
	// -- Loading indicator image

	var indicatorId = "offering-loading-indicator-" + new Date().getTime().toString(36);
	function indicator(){ return forceRef("#" + indicatorId); }
	$(function(){
		// static HTML lets Wicket sort out relative paths, so the relative 
		// image URI is in a <link> element somewhere in an HTML file
		var LINK = "link[rel=offering-loading-indicator-img]"; 
		var link = $(LINK);
		if (link.length > 0) { 
			$(document.body).append($("<img alt='' style='display: none; position: absolute; top: 0; left: 0;'/>").attr({
				src: link.attr("href"), id: indicatorId
			}));
		}
	});
	// -- Helpers
	
	function popup(){ return forceRef(ID_POPUP); }
	this.popup = popup;
	
	function forceRef(selector) {
		var ref = $(selector);
		if (ref.length == 0) 
			throw new Error("Bad selector: " + selector);
		else return ref;
	};
	this.forceRef = forceRef;
	
	function centerAbove(bg, fg, topPos){
		var offset = bg.offset();
		if(topPos){
			fg.css({
				top: (offset.top + ((600 - fg.height()) / 2)) + "px",
				left: (offset.left + ((bg.width() - fg.width()) / 2)) + "px"
			});
		}else{
			fg.css({
				top: (offset.top + ((bg.height() - fg.height()) / 2)) + "px",
				left: (offset.left + ((bg.width() - fg.width()) / 2)) + "px"
			});
		}
	}
	
	function get_cookie(cookie_name){
  		var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
  		if ( results )
    		return ( unescape ( results[2] ) );
  		else
    		return null;
	}
	
	this.getCookie = function(){
		return get_cookie(ID_COOKIE);
	}
	
	// -- Show month/annual estimate
	
	$(function(){
		var b = $(document.body);
		var c = get_cookie(ID_COOKIE);
		if (!b.hasClass("show-monthly-cost") && !b.hasClass("show-annual-cost")){
			if(c){
				b.addClass("show-"+c+"-cost");
			}else{
				if(b.hasClass("b2b")){
					b.addClass("show-annual-cost");
				}else{
					b.addClass("show-monthly-cost");
				}
			}	
		}
	});
	
	this.estimatePeriod = function(period){
		function doSwitch(from, to){ 
			$(document.body).addClass("show-" + to + "-cost").removeClass("show-" + from + "-cost");			 
			//just a session cookie allowed for the page which sets it and the domain which sets it
			//the path must be set to allow for the wicket paths
			document.cookie = ID_COOKIE+"="+to+";"+"path=/mittkonto/";
		}
		switch (period) {
		case "monthly": doSwitch("annual", "monthly"); break;
		case "annual": doSwitch("monthly", "annual"); break;
		default: throw new Error("Bad estimate period: " + period);
		}
	}
	
	// -- Overlay
	
	function overlay(){ return forceRef("#overlayhook"); } 
	function showOverlay(){ overlay().addClass("overlay"); }
	function hideOverlay(){ overlay().removeClass("overlay"); }
	
	// -- Create popup
	
	$(function(){
		$(document.body).append(
			'<div id="offering-popup" class="popupWrapper">' +
			'<div class="top"><!--Dont remove this--></div>' +
			'<div class="middle"></div>' +
			'<div class="bottom"><!--Dont remove this--></div>' +	
			'</div>');
	});
	
	// -- Show popup
	
	var closeFuncs = [];
	this.showPopup = function showPopup(contentSelector, parent, topPosition) {
		var content = undefined;
		for (var n = parent || document.body; n; n = n.parentNode) {
			var found = $(n).find(contentSelector);
			if (found.length > 0) {
				content = found.html();
				break;
			} 
		}
		if (content === undefined)
			throw new Error("Selector not matched in hierarchy: " + contentSelector);
		showOverlay();
		popup().css("z-index", "1000").find(".middle").html(content);
		popup().find(".close").click(function(){
			Offering.hidePopup();
		});
		centerAbove(overlay(), popup().show(), topPosition);
	};
	
	this.hidePopup = function hidePopup () {
		hideOverlay();
		popup().find(".middle").html("");
		popup().hide();	
		var fns = closeFuncs;
		closeFuncs = [];
		for (var i = 0; i < fns.length; ++i) fns[i]();
	};
	
	this.onPopupClose = function onPopupClose(fn){ closeFuncs.push(fn); };
	
	$("a[rel=offering-popup]").live("click", function(e){
		// hrefs can be canonicalized, remove everything up to & incl last slash
		var selector = $(this).attr("href").replace(/^.*\/([^\/]+)/g, "$1");
		var i = selector.indexOf("#", selector);
		var selected = selector.substring(i, selector.length);
		Offering.showPopup(selected, this, false);
		e.preventDefault();
		e.stopPropagation();
		return false;
	});
	$("a[rel=account-popup]").live("click", function(e){
		// hrefs can be canonicalized, remove everything up to & incl last slash
		var selector = $(this).attr("href").replace(/^.*\/([^\/]+)/g, "$1");
		Offering.showPopup(selector, this, true);
		e.preventDefault();
		e.stopPropagation();
		return false;
	});
	
	// -- Loader
	
	var loadingDepth = 0;
	
	this.showLoading = function showLoading(id){
		forceRef("#" + id).attr("disabled", "disabled");
		if (++loadingDepth == 1) {
			showOverlay();
			centerAbove(overlay(), indicator().show());
		}
	};
	this.hideLoading = function hideLoading(id){
		forceRef("#" + id).removeAttr("disabled");
		if (--loadingDepth == 0) {
			indicator().hide();
			hideOverlay();
		}
	};
	
};