﻿/*

	IHI
	JavaScript functions
	
	Author: Tysn - Creuna Danmark A/S / www.creuna.dk
	Copyright: 2009, Creuna Danmark A/S. All rights resevered

-----------------------------------------------------------------------*/

if (typeof Ihi == 'undefined')
{
	var Ihi = {};
}

Ihi.initialize = function()
{
	//if ($j('#content .tabs ul.tabToggler li').length > 1)
	//{
	//	this.Tabs.initialize();
	//}
	
	if ($j.browser.msie && $j.browser.version < 7)
	{
		// Fix IE6 bugs
		this.fixIe6BoxBugs();
	}
}

Ihi.fixIe6BoxBugs = function()
{
	$j('.mypageBox i.tr').each(function(i) {
		$j(this).css('height', $j(this).parent().height() + 1);
	});
	$j('.mypageBox i.bl').each(function(i) {
		$j(this).css('width', $j(this).parent().width());
	});
}

Ihi.ShowHide = function(e)
{
	var elm = $j(e);
	
	if (elm.css('display') == 'none')
		elm.fadeIn(400);
	else
		elm.fadeOut(400);
}

Ihi.Tabs = 
{
	initialize: function()
	{
		var elements = $j('#content .tabs');
		
		return this.selectDefaultTab(elements.tabs());
	},
	
	selectDefaultTab: function(tab)
	{
		var regex = new RegExp("[#]([^$]*)");
		var href = regex.exec(location.href);
		
		if (href && href[1])
		{
			var anchor = href[1].split('tab')[1] - 1;
			
			if (anchor != '')
			{
				tab.tabs("select", anchor);
			}
		}
	}
}

/*

	Creuna lightweight cBox
	
	Author: Creuna Danmark A/S / www.creuna.dk
	Copyright: 2009, Creuna Danmark A/S. All rights resevered

-----------------------------------------------------------------------*/

var cBox = {
	
	options:
	{
		height: 500,
		width: 833,
		bottomPadding: 1,
		loading: '',
		
		hideDuration: 500,
		hideAnimation: function(element)
		{
			$j(element).hide();
			//.fadeOut(cBox.options.hideDuration)
		},
		
		showDuration: 1,
		showAnimation: function(element)
		{
			$j(element).fadeIn(cBox.options.showDuration)
		},
		
		updateDuration: 400,
		shadow: true,
		frameOffsetTop: 100,
		frameOffsetBottom: 50
	},
	
	initialize: function()
	{
		if($j('.cBox').length > 0)
		{
			this.build();
		}
		
		// Bind event to all click's
		$j(document.body).click(function(e)
		{
			var $target = $j(e.target);
			if ($target.length)
			{
				// Prevent default click if eventHandler is true
				if (cBox.eventHandler($target) == true)
				{
					e.preventDefault();
				}
			}
		});
	},
	
	eventHandler: function(target)
	{
		var $element = $j(target);
		
		if ($element.hasClass('cBoxClose'))
		{
			cBox.hide();
			
			return true;
		}
		else if ($element.hasClass('cBoxUpdate'))
		{
			cBox.updateIframe($element);
			
			return true;
		}
		
		return false;
	},
	
	build: function()
	{
		var documentHeight = $j(document).height();
		
		// Build html
		$j('<div id="cBox"><div class="overlay"></div><div class="frame"><a href="#" class="close"></a></div></div>')
			.appendTo("body");
			
		$j('<div class="wrapper"><h1 class="title"></h1><div class="content"></div><div class="loading"><div>' + cBox.options.loading + '</div></div></div>')
			.appendTo("#cBox .frame");
		
		if ($j.browser.msie)
		{
			$j('#cBox')
				.prepend('<iframe id="ieIframe" scrolling="no" frameborder="0"></iframe>')
				
				.find('#ieIframe')
					.css({
						'width': $j(window).width(),
						'height': documentHeight,
						'opacity': 0
					})
		}
		
		if (this.options.shadow)
		{
			$j('<div class="shadow"><div class="n"></div><div class="ne"></div><div class="nw"></div><div class="e"></div><div class="se"></div><div class="s"></div><div class="sw"></div><div class="w"></div></div>')
				.appendTo('#cBox .frame');
		}
		
		$j('#cBox')
			// Set document to 100% height
			.css('height', documentHeight)
			
			// Add close click event
			.find('.close').unbind('click').click(function(e)
			{
				cBox.hide();
				
				// Prevent anchor scrolling
				e.preventDefault();
			});
		
		// Hide if escaped is clicked
		$j(document).keyup(function(event)
		{
			if (event.keyCode == 27)
			{
            	cBox.hide();
            }
		});
		
		// Resize document background when resizing
		$j(window).resize(function()
		{
			cBox.resizeDocumentHeight('resize', false);
		});
		
		return this.findBoxes();
	},
	
	findBoxes: function()
	{
		/* Find all elements with classname cBox
		   and bind 'show' click event */
		
		$j('a.cBox').each(function(i)
		{
			$j(this).unbind('click').click(function(e)
			{
				cBox.show(this);
				
				e.preventDefault();
			});
		});
	},
	
	show: function(element)
	{
		// Make sure box is build
		if ($j('body > #cBox').length < 1)
		{
			this.build();
		}
		
		var href = element.href || element;
		var query = href.replace(/^[^\?]+\??/,'');
		var params = this.parseQuery(query);
		var documentOffsetTop = $j(document).scrollTop();
		
		var height = params['h'] || this.options.height;
		var width = params['w'] || this.options.width;
		var title = params['t'];
		
		if (typeof title != 'undefined')
		{
			$j('#cBox .wrapper h1.title')
				.html(decodeURI(title))
				.show();
		}
		
		$j('#cBox')
			.find('.content')
				.css('height', height + 'px')
				.end()
			
			.find('.loading div')
				.css('margin-top', (height-65) / 2)
				.end()
			
			.find('.loading')
				.css({
					'height': height - 5 + 'px',
					'width': width - 6 + 'px'
				})
				.show()
				.end()
			
			.find('.frame')
				.css({
					'top': documentOffsetTop + this.options.frameOffsetTop,
					'width': width + 'px'
				});
		
		this.options.showAnimation($j('#cBox'));
		
		setTimeout(function()
		{
			$j('#cBox .content')
				.append(cBox.appendIframe(href));
		}, (this.options.showDuration + 50) );
	},
	
	appendIframe: function(href)
	{
		var id = 'iframeContent' + Math.round(Math.random() * 1000);
		
		return "<iframe frameborder='0' hspace='0' src='" + href + "' id='" + id + "' name='" + id + "' onload='cBox.showIframe(this);' style='width:100%;'></iframe>";
	},
	
	hide: function()
	{
		// Hide cBox
		
		var topWindow = $j('body', top.document);
		
		this.options.hideAnimation(topWindow.find('#cBox'));
		
		setTimeout(function()
		{
			topWindow.find('#cBox')
				.find('.content')
				.empty();
		}, (this.options.hideDuration) );
	},
	
	resizeDocumentHeight: function(newHeight, fromIframe)
	{
		// Set calculated document height on cBox 
		
		var currentDocument = (fromIframe) ? top.document : document;
		var topDocHeight = $j('body', currentDocument).height();
		var topBox = $j('#cBox', currentDocument);
		
		// If the window is resized
		if (newHeight == 'resize')
		{
			if (topDocHeight > topBox.height())
			{
				topBox.css('height', topDocHeight);
			}
		}
		
		// If iframe is larger then the box, set the new height on box
		else if (newHeight > topBox.height())
		{
			topBox.css('height', newHeight);
		}
		
		// If the box is larger then document height
		else if (topBox.height() > topDocHeight)
		{
			topBox.css('height', topBox.height());
		}
		
		// Just set the new height
		else
		{
			topBox.css('height', topDocHeight);
		}
	},
	
	resizeIframe: function()
	{
		// Resize the iframe from within the iframe
		
		// Height of iframe content + 6px border from stylesheet
		var innerHeight = $j('body', document).height() + 6;
		
		$j('#cBox .content', top.document)
			.stop()
			.animate({
				height: innerHeight
			}, this.options.updateDuration, function()
			{
				// Calculate height from top + offset from bottom
				
				// Get position from element
				var position = $j('#cBox .frame', top.document).offset();

				// Resize document after animating the box
				cBox.resizeDocumentHeight(innerHeight + position.top + cBox.options.frameOffsetBottom, true);
			})
			.find('iframe')
				.height(innerHeight);
	},
	
	showIframe: function(f)
	{
		// Display the iframe after loading
		
		var innerDocument = (f.contentDocument) ? f.contentDocument : f.contentWindow.document;
		var innerHeight = innerDocument.body.scrollHeight + cBox.options.bottomPadding;
		f = (f.style) ? f.style : f;
		
		// Set height on iframe
		f.height = innerHeight + 'px';
		
		// Height of iframe content + 6px border from stylesheet
		var iframeHeight = innerHeight + 6;
		
		// Offset for cBox + default offset value from top
		var scrollTop = $j(document).scrollTop() + this.options.frameOffsetTop;
		
		// Calculate height's + offset from bottom
		var documentHeight = iframeHeight + scrollTop + this.options.frameOffsetBottom;
		
		// Resize document before animating the box
		this.resizeDocumentHeight(documentHeight, false);
		
		
		// Show the Iframe and hide loading and title
		$j('#cBox')
			.find('.content')
				.animate({
					height: innerHeight
				}, this.options.updateDuration)
				.end()
			
			.find('.loading')
				.hide()
				.css({
					'height': innerHeight - 5 + 'px'
				})
				.end()
			
			.find('.loading div')
				.css('margin-top', (innerHeight-65) / 2)
				.end()
			
			.find('.wrapper h1.title')
				.hide()
				.end()
			
			.find('.content')
				.show();
	},
	
	updateIframe: function(element)
	{
		var topWindow = $j('body', top.document);
		var href = (typeof element == 'string') ? element : element.attr('href');
		var query = href.replace(/^[^\?]+\??/,'');
		var params = this.parseQuery(query);
		
		var headline = topWindow.find('#cBox .wrapper h1.title');
		var newWidth = params['w'];
		var oldWidth = topWindow.find('#cBox .loading').width() + 6;
		var newTitle = params['t'];
		
		// Replace title when loading
		if (typeof newTitle != 'undefined')
		{
			topWindow.find('#cBox')
				.find('.loading')
				.show()
				.end()
				
				.find('.wrapper h1.title')
					.html(decodeURI(newTitle))
					.show();
		}
		
		
		// Resize frame and loading width
		if (newWidth && oldWidth != newWidth)
		{
			topWindow.find('#cBox')
				.find('.loading')
					.animate({
						width: newWidth - 6 + 'px'
					}, this.options.updateDuration)
					.end()
			
				.find('.frame')
					.animate({
						width: newWidth + 'px'
					}, this.options.updateDuration);
			
			setTimeout(function()
			{
				topWindow.find('#cBox') // jQuery bug: when .find('#cBox .content') is used, it finds to many elements
					.find('.content')
					.html(cBox.appendIframe(href));
			}, (this.options.updateDuration + 50) );
		}
		
		// Keep the original width
		else
		{
			topWindow.find('#cBox')
				.find('.content')
				.html(this.appendIframe(href));
		}
	},
	
	parseQuery: function (query)
	{
		var params = {};
		if ( ! query ) {return params;}
		var pairs = query.split(/[;&]/);
		var length = pairs.length;
		for ( var i = 0; i < length; i++ )
		{
			var keyVal = pairs[i].split('=');
			if ( ! keyVal || keyVal.length != 2 ) {continue;}
			
			var key = unescape( keyVal[0] );
			var val = keyVal[1];
			val = val.replace(/\+/g, ' ');
			params[key] = val;
		}
		
		return params;
	}
	
};

var $j = jQuery.noConflict();

$j(document).ready(function()
{
	Ihi.initialize();
	cBox.initialize();
});

// Plugin's
$j.fn.delay = function(time, callback)
{
	jQuery.fx.step.delay = function(){};
	return this.animate({delay:1}, time, callback);
} 
