/*** Function Chains ***/

var chainDomLoaded = new CodeCompany.FunctionChain('domLoaded');
var chainPostTransition = new CodeCompany.FunctionChain('postTransition');
var chainWindowLoaded = new CodeCompany.FunctionChain('windowLoaded');

document.observe('dom:loaded', chainDomLoaded.executeChain.bind(chainDomLoaded));
Event.observe(window, 'load', chainWindowLoaded.executeChain.bind(chainWindowLoaded));


/*** Site Class ***/

var Site = Class.create({
	initialize: function(options) {
		this.options = Object.extend({
			logEnabled: true,
			useConsoleLog: true,
			logElementId: 'logwindow'
		},options || {});

		// Cowardly refuse to use console.log if it doesn't exist
		if (this.options.useConsoleLog && Object.isUndefined(console)) {
			this.options.useConsoleLog = false;
		}
	},
	log: function(str) {
		if (!this.options.logEnabled) { return; }
		if (this.options.useConsoleLog) {
			console.log(str);
			return;
		}
		// Try logging to an element
		var logElement = $(this.options.logElementId);
		if (logElement!=null) {
			logElement.insert(str+'<br />');
			logElement.scrollTop = logElement.scrollHeight;
		}
	}
});

var site = new Site({
	logEnabled: (window.location.search.match(/[?&]nolog/)===null) && ((window.location.hostname.match(/test/)!==null) || (window.location.search.match(/[?&]log/i)!==null))
});


/*** Logging ***/

if (site.options.logEnabled && !site.options.useConsoleLog) {
	chainDomLoaded.addFunction(function(){
		var body = $$('BODY').first();
		body.insert('<div class="logwindow" id="logwindow"></div>');
	},'Adding logwindow');
}

// Make sure calls to console.log doesn't break Javascript
if (Object.isUndefined(console)) {
	var console = { log: function(str) { site.log(str+' via console.log()'); }};
}


/*** HoverObserver ***/

var HoverObserver = Class.create({
	initialize: function(options) {
		this.options = Object.extend({
			'elementSelector':		'.hoverable',
			'className':			'hover',
			'startEvent':			'mouseenter',
			'stopEvent':			'mouseleave'
		},options || {});
		var elements = 0;
		$$(this.options.elementSelector).each(function(element){
			Event.observe(element, this.options.startEvent, this.onStart.bindAsEventListener(this,element));
			Event.observe(element, this.options.stopEvent, this.onStop.bindAsEventListener(this,element));
			elements++;
		},this);
		site.log('HoverObserver is observing '+elements+' elements selected by "'+this.options.elementSelector+'"');
	},
	onStart: function(event,element) { element.addClassName(this.options.className); },
	onStop: function(event,element) { element.removeClassName(this.options.className); }
});

chainDomLoaded.addFunction(function(){
	// Observe mouse-enter/leave
	new HoverObserver();
},'HoverObserver');


/*** Window Resizer - Fixes background images ***/

var WindowResizer = Class.create({
	log: function(str) {
		site.log('[WindowResizer] '+str);
	},
	initialize: function() {
		// .maincontainer -> .maincontainerstretcher -> .maincontainerinner
		this.initialized = false;
		this.stretcherElement = $('maincontainerstretcher');
		if (null===this.stretcherElement) {
			this.log('Initialized without #maincontainerstretcher');
			return;
		}
		this.innerElement = $('maincontainerinner');
		if (null===this.innerElement) {
			this.log('Initialized without #maincontainerinner');
			return;
		}
		this.layerElements = $$('DIV.pagebackground');
		this.initialized = true;
		this.resize();
		Event.observe(window, 'resize',this.onResize.bindAsEventListener(this));
	},
	resize: function() {
		if (!this.initialized) {
			this.log('Call to resize() without proper initialization');
			return;
		}

		// Height of viewport
		var viewport = document.viewport.getDimensions();
		var viewportHeight = viewport['height'];

		// Height of inner element
		var innerHeight = this.innerElement.getHeight();

		// Set height of stretcher + layers
		var height = Math.max(viewportHeight,innerHeight);
		this.log('Resizing to height '+height);
		var heightStr = ''+height+'px';

		if (Prototype.Browser.IE) {
			this.stretcherElement.style.height = heightStr;
			this.layerElements.each(function(element){ element.style.height = heightStr; });
		} else {
			this.stretcherElement.style.minHeight = heightStr;
			this.layerElements.each(function(element){ element.style.minHeight = heightStr; });
		}
	},
	onResize: function(e) {
		this.resize();
	}
});

// Make sure windowResizer is globally accessible
var windowResizer;
chainWindowLoaded.addFunction(function(){
	windowResizer = new WindowResizer();
	document.observe("contentrefresh",function(){
		if (!Object.isUndefined(site)) { site.log('"contentrefresh" event triggered on document'); }
		windowResizer.resize();
	});
},'WindowResizer',100);



/*** Image Map ***/

chainPostTransition.addFunction(function(){
	new CodeCompany.ImageMapLoader();
},'ImageMap');


/*** Fancy Transition ***/

var Transition = Class.create({
	log: function(str) {
		if (!Object.isUndefined(site)) { site.log('Transition: '+str); }
	},
	initialize: function(options) {
		this.log('Initialize');
		this.options = options;
		this.blurredDiv = $(this.options.blurred);
		this.sharpDiv = $(this.options.sharp);
		this.contentDiv = $(this.options.content);

		// Markup sanity check
		if (undefined==this.sharpDiv) { return; }

		// Identify current and last background
		var currentBackground = this.sharpDiv.select('IMG')[0].src;
		var lastBackground = CodeCompany.Cookie.read('lastbg');

		// Explicitly disabled?
		var body = $$('BODY')[0];
		var disabled = body.hasClassName('notransition');

		// Show slow or fast?
		if (disabled || (currentBackground==lastBackground)) {
			this.showfast();
		} else {
			this.showslow();
		}

		CodeCompany.Cookie.write('lastbg',currentBackground);
	},
	showfast: function() {
		this.log('Fast transition');
		this.blurredDiv.show();
		this.contentDiv.show();
		this.aftershow();
	},
	showslow: function() {
		this.log('Slow transition');
		this.contentDiv.addClassName('transitioning');
		this.sharpDiv.appear({duration:0.5,afterFinish:this.showslowStage1.bind(this)});
	},
	showslowStage1: function() {
		setTimeout(this.showslowStage2.bind(this),2*1000); /* 2 seconds */
	},
	showslowStage2: function() {
		this.blurredDiv.appear({duration:1.5});
		this.contentDiv.appear({duration:0.3,afterFinish:this.showslowStage3.bind(this)});
	},
	showslowStage3: function() {
		this.contentDiv.removeClassName('transitioning');
		this.aftershow();
	},
	aftershow: function() {
		chainPostTransition.executeChain();
	}
});	


/*** ? ***/

function fixProductLinksPosition() {
	var source = $('produktlinks');
	var destination = $('prodlinksplaceholder');
	if (source==null || destination==null) { return; }
	destination.replace(source);
}


/*** Hook on chains ***/

chainDomLoaded.addFunction(function(){
	fixProductLinksPosition();
},'FixProductLinksPosition');

chainWindowLoaded.addFunction(function(){
	new Transition({
		sharp: 'layer1',
		blurred: 'layer2',
		content: 'layer3'
	});
},'Transition');

chainPostTransition.addFunction(function(){
	$$('.forsideartikel_bottomimage').each(function(element){
		var imagelayer = element.select('.imagelayer').first();
		if (!imagelayer) { return; }
		var linklayer = element.select('.linklayer').first();
		if (!linklayer) { return; }

		// site.log('ImageLayer: '+imagelayer.getWidth()+'x'+imagelayer.getHeight());
		// site.log('LinkLayer: '+linklayer.getWidth()+'x'+linklayer.getHeight());

		var width = imagelayer.getWidth();
		var height = imagelayer.getHeight();

		var tmp;
		if ((tmp=linklayer.getWidth())>width) { width=tmp; }
		if ((tmp=linklayer.getHeight())>height) { height=tmp; }

		site.log('Setting element '+element.toString()+' to '+width+'x'+height);

		// Set main container size
		element.style.height = height+'px';
		element.style.width = width+'px';

		// Set linklayer size
		linklayer.style.height = height+'px';
		linklayer.style.width = width+'px';

		// Set imagelayer size
		imagelayer.style.height = height+'px';
		imagelayer.style.width = width+'px';

	});
},'LinkImage Tweak');

chainPostTransition.addFunction(function(){
	var sslEnabled = document.location.protocol=='https:';
	var urlprefix = document.location.protocol+'//';
	
	// Yahoo Tracking
	var yahooUrl = urlprefix+'d.yimg.com/mi/eu/ywa.js';
	LazyLoader.load(yahooUrl,function(){
		try {
			if (undefined===YWA) {
				site.log('Yahoo tracking script did not provide YWA object.');
				return;
			}
			var YWATracker = YWA.getTracker("10001510305370");
			//YWATracker.setDocumentName("");
			//YWATracker.setDocumentGroup("");
			YWATracker.submit(); 
			site.log('Yahoo tracking loaded');
		} catch(err) {
			site.log('Yahoo tracking failed');
		}
	});
	
	// Globase Tracking
	var globaseUrl = urlprefix+'pagetracking.globase.com/tracking.php?guid=b516476c';
	LazyLoader.load(globaseUrl,function(){
		site.log('Globase tracking loaded');
	});

	// Google Analytics Tracking
	var googleUrl = urlprefix + (sslEnabled?'ssl':'www') + '.google-analytics.com/ga.js';
	LazyLoader.load(googleUrl,function(){
		try {
			var pageTracker = _gat._getTracker("UA-12685907-1");
			pageTracker._initData();
			pageTracker._trackPageview();
			site.log('Google tracking loaded');
		} catch(err) {
			site.log('Google tracking failed');
		}
	});

},'Tracking');

chainPostTransition.addFunction(function(){
	new CodeCompany.ImageFrames();
},'ImageFrames');


