﻿/*	jQuery plugins for Aberdeen Plastics
	includes:
	* jquery.hoverIntent.minified.js
	* superfish.js
	* jquery.fancybox-1.0.0.js
	* jquery.pngFix.js
	* jquery.history
*/
/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);
/*
 * Superfish v1.4.8 - jQuery menu widget
 * Copyright (c) 2008 Joel Birch
 *
 * Dual licensed under the MIT and GPL licenses:
 * 	http://www.opensource.org/licenses/mit-license.php
 * 	http://www.gnu.org/licenses/gpl.html
 *
 * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
 */
;(function($){
$.fn.superfish = function(op){
var sf = $.fn.superfish,
c = sf.c,
$arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')),
over = function(){
var $$ = $(this), menu = getMenu($$);
clearTimeout(menu.sfTimer);
$$.showSuperfishUl().siblings().hideSuperfishUl();
},
out = function(){
var $$ = $(this), menu = getMenu($$), o = sf.op;
clearTimeout(menu.sfTimer);
menu.sfTimer=setTimeout(function(){
o.retainPath=($.inArray($$[0],o.$path)>-1);
$$.hideSuperfishUl();
if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);}
},o.delay);	
},
getMenu = function($menu){
var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
sf.op = sf.o[menu.serial];
return menu;
},
addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };

return this.each(function() {
var s = this.serial = sf.o.length;
var o = $.extend({},sf.defaults,op);
o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){
$(this).addClass([o.hoverClass,c.bcClass].join(' '))
.filter('li:has(ul)').removeClass(o.pathClass);
});
sf.o[s] = sf.op = o;
$('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
if (o.autoArrows) addArrow( $('>a:first-child',this) );
})
.not('.'+c.bcClass)
.hideSuperfishUl();
var $a = $('a',this);
$a.each(function(i){
var $li = $a.eq(i).parents('li');
$a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});
});
o.onInit.call(this);
}).each(function() {
menuClasses = [c.menuClass];
if (sf.op.dropShadows  && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass);
$(this).addClass(menuClasses.join(' '));
});
};
var sf = $.fn.superfish;
sf.o = [];
sf.op = {};
sf.IE7fix = function(){
var o = sf.op;
if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined)
this.toggleClass(sf.c.shadowClass+'-off');
};
sf.c = {
bcClass     : 'sf-breadcrumb',
menuClass   : 'sf-js-enabled',
anchorClass : 'sf-with-ul',
arrowClass  : 'sf-sub-indicator',
shadowClass : 'sf-shadow'
};
sf.defaults = {
hoverClass	: 'sfHover',
pathClass	: 'overideThisToUse',
pathLevels	: 1,
delay		: 800,
animation	: {opacity:'show'},
speed		: 'normal',
autoArrows	: true,
dropShadows : true,
disableHI	: false,		// true disables hoverIntent detection
onInit		: function(){}, // callback functions
onBeforeShow: function(){},
onShow		: function(){},
onHide		: function(){}
};
$.fn.extend({
hideSuperfishUl : function(){
var o = sf.op,
not = (o.retainPath===true) ? o.$path : '';
o.retainPath = false;
var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
.find('>ul').hide().css('visibility','hidden');
o.onHide.call($ul);
return this;
},
showSuperfishUl : function(){
var o = sf.op,
sh = sf.c.shadowClass+'-off',
$ul = this.addClass(o.hoverClass)
.find('>ul:hidden').css('visibility','visible');
sf.IE7fix.call($ul);
o.onBeforeShow.call($ul);
$ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); });
return this;
}
});
})(jQuery);
/*
 * FancyBox - simple jQuery plugin for fancy image zooming
 * Examples and documentation at: http://fancy.klade.lv/
 * Version: 1.0.0 (29/04/2008)
 * Copyright (c) 2008 Janis Skarnelis
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
 * Requires: jQuery v1.2.1 or later
*/
(function($) {
var opts = {}, 
imgPreloader = new Image, imgTypes = ['png', 'jpg', 'jpeg', 'gif'], 
loadingTimer, loadingFrame = 1;
$.fn.fancybox = function(settings) {
opts.settings = $.extend({}, $.fn.fancybox.defaults, settings);
$.fn.fancybox.init();
return this.each(function() {
var $this = $(this);
var o = $.metadata ? $.extend({}, opts.settings, $this.metadata()) : opts.settings;
$this.unbind('click').click(function() {
$.fn.fancybox.start(this, o); return false;
});
});
};
$.fn.fancybox.start = function(el, o) {
if (opts.animating) return false;
if (o.overlayShow) {
$("#fancy_wrap").prepend('<div id="fancy_overlay"></div>');
$("#fancy_overlay").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': o.overlayOpacity});
if ($.browser.msie) {
$("#fancy_wrap").prepend('<iframe id="fancy_bigIframe" scrolling="no" frameborder="0"></iframe>');
$("#fancy_bigIframe").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': 0});
}
$("#fancy_overlay").click($.fn.fancybox.close);
}
opts.itemArray = [];
opts.itemNum = 0;
if (jQuery.isFunction(o.itemLoadCallback)) {
o.itemLoadCallback.apply(this, [opts]);
var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el);
var tmp	= {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)}
for (var i = 0; i < opts.itemArray.length; i++) {
opts.itemArray[i].o = $.extend({}, o, opts.itemArray[i].o);	
if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) {
opts.itemArray[i].orig = tmp;
}
}
} else {
if (!el.rel || el.rel == '') {
var item = {url: el.href, title: el.title, o: o};
if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) {
var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el);
item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)}
}
opts.itemArray.push(item);
} else {
var arr	= $("a[@rel=" + el.rel + "]").get();
for (var i = 0; i < arr.length; i++) {
var tmp		= $.metadata ? $.extend({}, o, $(arr[i]).metadata()) : o;
var item	= {url: arr[i].href, title: arr[i].title, o: tmp};
if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) {
var c = $(arr[i]).children("img:first").length ? $(arr[i]).children("img:first") : $(el);
item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)}
}
if (arr[i].href == el.href) opts.itemNum = i;
opts.itemArray.push(item);
}
}
}
$.fn.fancybox.changeItem(opts.itemNum);
};
$.fn.fancybox.changeItem = function(n) {
$.fn.fancybox.showLoading();
opts.itemNum = n;
$("#fancy_nav").empty();
$("#fancy_outer").stop();
$("#fancy_title").hide();
$(document).unbind("keydown");
imgRegExp = imgTypes.join('|');
imgRegExp = new RegExp('\.' + imgRegExp + '$', 'i');
var url = opts.itemArray[n].url;
if (url.match(/#/)) {
var target = window.location.href.split('#')[0]; target = url.replace(target,'');
$.fn.fancybox.showItem('<div id="fancy_div">' + $(target).html() + '</div>');
$("#fancy_loading").hide();
} else if (url.match(imgRegExp)) {
$(imgPreloader).unbind('load').bind('load', function() {
$("#fancy_loading").hide();
opts.itemArray[n].o.frameWidth	= imgPreloader.width;
opts.itemArray[n].o.frameHeight	= imgPreloader.height;
$.fn.fancybox.showItem('<img id="fancy_img" src="' + imgPreloader.src + '" />');
}).attr('src', url + '?rand=' + Math.floor(Math.random() * 999999999) );
} else {
$.fn.fancybox.showItem('<iframe id="fancy_frame" onload="$.fn.fancybox.showIframe()" name="fancy_iframe' + Math.round(Math.random()*1000) + '" frameborder="0" hspace="0" src="' + url + '"></iframe>');
}
};
$.fn.fancybox.showIframe = function() {
$("#fancy_loading").hide();
$("#fancy_frame").show();
};
$.fn.fancybox.showItem = function(val) {
$.fn.fancybox.preloadNeighborImages();
var viewportPos	= $.fn.fancybox.getViewport();
var itemSize	= $.fn.fancybox.getMaxSize(viewportPos[0] - 50, viewportPos[1] - 100, opts.itemArray[opts.itemNum].o.frameWidth, opts.itemArray[opts.itemNum].o.frameHeight);
var itemLeft	= viewportPos[2] + Math.round((viewportPos[0] - itemSize[0]) / 2) - 20;
var itemTop		= viewportPos[3] + Math.round((viewportPos[1] - itemSize[1]) / 2) - 40;
var itemOpts = {
'left':		itemLeft, 
'top':		itemTop, 
'width':	itemSize[0] + 'px', 
'height':	itemSize[1] + 'px'	
}
if (opts.active) {
$('#fancy_content').fadeOut("normal", function() {
$("#fancy_content").empty();
$("#fancy_outer").animate(itemOpts, "normal", function() {
$("#fancy_content").append($(val)).fadeIn("normal");
$.fn.fancybox.updateDetails();
});
});
} else {
opts.active = true;
$("#fancy_content").empty();
if ($("#fancy_content").is(":animated")) {
console.info('animated!');
}
if (opts.itemArray[opts.itemNum].o.zoomSpeedIn > 0) {
opts.animating		= true;
itemOpts.opacity	= "show";
$("#fancy_outer").css({
'top':		opts.itemArray[opts.itemNum].orig.pos.top - 18,
'left':		opts.itemArray[opts.itemNum].orig.pos.left - 18,
'height':	opts.itemArray[opts.itemNum].orig.height,
'width':	opts.itemArray[opts.itemNum].orig.width
});
$("#fancy_content").append($(val)).show();

$("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedIn, function() {
opts.animating = false;
$.fn.fancybox.updateDetails();
});
} else {
$("#fancy_content").append($(val)).show();
$("#fancy_outer").css(itemOpts).show();
$.fn.fancybox.updateDetails();
}
}
};
$.fn.fancybox.updateDetails = function() {
$("#fancy_bg,#fancy_close").show();
if (opts.itemArray[opts.itemNum].title !== undefined && opts.itemArray[opts.itemNum].title !== '') {
$('#fancy_title div').html(opts.itemArray[opts.itemNum].title);
$('#fancy_title').show();
}
if (opts.itemArray[opts.itemNum].o.hideOnContentClick) {
$("#fancy_content").click($.fn.fancybox.close);
} else {
$("#fancy_content").unbind('click');
}
if (opts.itemNum != 0) {
$("#fancy_nav").append('<a id="fancy_left" href="javascript:;"></a>');
$('#fancy_left').click(function() {
$.fn.fancybox.changeItem(opts.itemNum - 1); return false;
});
}
if (opts.itemNum != (opts.itemArray.length - 1)) {
$("#fancy_nav").append('<a id="fancy_right" href="javascript:;"></a>');

$('#fancy_right').click(function(){
$.fn.fancybox.changeItem(opts.itemNum + 1); return false;
});
}
$(document).keydown(function(event) {
if (event.keyCode == 27) {
$.fn.fancybox.close();
} else if(event.keyCode == 37 && opts.itemNum != 0) {
$.fn.fancybox.changeItem(opts.itemNum - 1);
} else if(event.keyCode == 39 && opts.itemNum != (opts.itemArray.length - 1)) {
$.fn.fancybox.changeItem(opts.itemNum + 1);
}
});
};
$.fn.fancybox.preloadNeighborImages = function() {
if ((opts.itemArray.length - 1) > opts.itemNum) {
preloadNextImage = new Image();
preloadNextImage.src = opts.itemArray[opts.itemNum + 1].url;
}
if (opts.itemNum > 0) {
preloadPrevImage = new Image();
preloadPrevImage.src = opts.itemArray[opts.itemNum - 1].url;
}
};
$.fn.fancybox.close = function() {
if (opts.animating) return false;
$(imgPreloader).unbind('load');
$(document).unbind("keydown");
$("#fancy_loading,#fancy_title,#fancy_close,#fancy_bg").hide();
$("#fancy_nav").empty();
opts.active	= false;
if (opts.itemArray[opts.itemNum].o.zoomSpeedOut > 0) {
var itemOpts = {
'top':		opts.itemArray[opts.itemNum].orig.pos.top - 18,
'left':		opts.itemArray[opts.itemNum].orig.pos.left - 18,
'height':	opts.itemArray[opts.itemNum].orig.height,
'width':	opts.itemArray[opts.itemNum].orig.width,
'opacity':	'hide'
};
opts.animating = true;
$("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedOut, function() {
$("#fancy_content").hide().empty();
$("#fancy_overlay,#fancy_bigIframe").remove();
opts.animating = false;
});
} else {
$("#fancy_outer").hide();
$("#fancy_content").hide().empty();
$("#fancy_overlay,#fancy_bigIframe").fadeOut("fast").remove();
}
};
$.fn.fancybox.showLoading = function() {
clearInterval(loadingTimer);
var pos = $.fn.fancybox.getViewport();
$("#fancy_loading").css({'left': ((pos[0] - 40) / 2 + pos[2]), 'top': ((pos[1] - 40) / 2 + pos[3])}).show();
$("#fancy_loading").bind('click', $.fn.fancybox.close);
loadingTimer = setInterval($.fn.fancybox.animateLoading, 66);
};
$.fn.fancybox.animateLoading = function(el, o) {
if (!$("#fancy_loading").is(':visible')){
clearInterval(loadingTimer);
return;
}
$("#fancy_loading > div").css('top', (loadingFrame * -40) + 'px');
loadingFrame = (loadingFrame + 1) % 12;
};
$.fn.fancybox.init = function() {
if (!$('#fancy_wrap').length) {
$('<div id="fancy_wrap"><div id="fancy_loading"><div></div></div><div id="fancy_outer"><div id="fancy_inner"><div id="fancy_nav"></div><div id="fancy_close"></div><div id="fancy_content"></div><div id="fancy_title"></div></div></div></div>').appendTo("body");
$('<div id="fancy_bg"><div class="fancy_bg fancy_bg_n"></div><div class="fancy_bg fancy_bg_ne"></div><div class="fancy_bg fancy_bg_e"></div><div class="fancy_bg fancy_bg_se"></div><div class="fancy_bg fancy_bg_s"></div><div class="fancy_bg fancy_bg_sw"></div><div class="fancy_bg fancy_bg_w"></div><div class="fancy_bg fancy_bg_nw"></div></div>').prependTo("#fancy_inner");	
$('<table cellspacing="0" cellpadding="0" border="0"><tr><td id="fancy_title_left"></td><td id="fancy_title_main"><div></div></td><td id="fancy_title_right"></td></tr></table>').appendTo('#fancy_title');
}
if ($.browser.msie) {
$("#fancy_inner").prepend('<iframe id="fancy_freeIframe" scrolling="no" frameborder="0"></iframe>');
}
if (jQuery.fn.pngFix) $(document).pngFix();
$("#fancy_close").click($.fn.fancybox.close);
};
$.fn.fancybox.getPosition = function(el) {
var pos = el.offset();
pos.top	+= $.fn.fancybox.num(el, 'paddingTop');
pos.top	+= $.fn.fancybox.num(el, 'borderTopWidth');
pos.left += $.fn.fancybox.num(el, 'paddingLeft');
pos.left += $.fn.fancybox.num(el, 'borderLeftWidth');
return pos;
};
$.fn.fancybox.num = function (el, prop) {
return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;
};
$.fn.fancybox.getPageScroll = function() {
var xScroll, yScroll;
if (self.pageYOffset) {
yScroll = self.pageYOffset;
xScroll = self.pageXOffset;
} else if (document.documentElement && document.documentElement.scrollTop) {
yScroll = document.documentElement.scrollTop;
xScroll = document.documentElement.scrollLeft;
} else if (document.body) {
yScroll = document.body.scrollTop;
xScroll = document.body.scrollLeft;	
}
return [xScroll, yScroll]; 
};
$.fn.fancybox.getViewport = function() {
var scroll = $.fn.fancybox.getPageScroll();
return [$(window).width(), $(window).height(), scroll[0], scroll[1]];
};
$.fn.fancybox.getMaxSize = function(maxWidth, maxHeight, imageWidth, imageHeight) {
var r = Math.min(Math.min(maxWidth, imageWidth) / imageWidth, Math.min(maxHeight, imageHeight) / imageHeight);
return [Math.round(r * imageWidth), Math.round(r * imageHeight)];
};
$.fn.fancybox.defaults = {
hideOnContentClick:	false,
zoomSpeedIn:		500,
zoomSpeedOut:		500,
frameWidth:			600,
frameHeight:		400,
overlayShow:		false,
overlayOpacity:		0.4,
itemLoadCallback:	null
};
})(jQuery);
/**
 * jQuery-Plugin "pngFix"
 * Version: 1.1, 11.09.2007
 * by Andreas Eberhard, andreas.eberhard@gmail.com
 *                      http://jquery.andreaseberhard.de/
 * Copyright (c) 2007 Andreas Eberhard
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 */
(function($) {
jQuery.fn.pngFix = function(settings) {
	// Settings
	settings = jQuery.extend({
		blankgif: 'blank.gif'
	}, settings);
	var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
	var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);
	if (jQuery.browser.msie && (ie55 || ie6)) {
		//fix images with png-source
		jQuery(this).find("img[@src$=.png]").each(function() {
			jQuery(this).attr('width',jQuery(this).width());
			jQuery(this).attr('height',jQuery(this).height());
			var prevStyle = '';
			var strNewHTML = '';
			var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';
			var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : '';
			var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';
			var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';
			var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';
			var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';
			if (this.style.border) {
				prevStyle += 'border:'+this.style.border+';';
				this.style.border = '';
			}
			if (this.style.padding) {
				prevStyle += 'padding:'+this.style.padding+';';
				this.style.padding = '';
			}
			if (this.style.margin) {
				prevStyle += 'margin:'+this.style.margin+';';
				this.style.margin = '';
			}
			var imgStyle = (this.style.cssText);
			strNewHTML += '<span '+imgId+imgClass+imgTitle+imgAlt;
			strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;'+imgAlign+imgHand;
			strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;';
			strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'scale\');';
			strNewHTML += imgStyle+'"></span>';
			if (prevStyle != ''){
				strNewHTML = '<span style="position:relative;display:inline-block;'+prevStyle+imgHand+'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;'+'">' + strNewHTML + '</span>';
			}
			jQuery(this).hide();
			jQuery(this).after(strNewHTML);
		});
		// fix css background pngs
		jQuery(this).find("*").each(function(){
			var bgIMG = jQuery(this).css('background-image');
			if(bgIMG.indexOf(".png")!=-1){
				var iebg = bgIMG.split('url("')[1].split('")')[0];
				jQuery(this).css('background-image', 'none');
				jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
			}
		});
		//fix input with png-source
		jQuery(this).find("input[@src$=.png]").each(function() {
			var bgIMG = jQuery(this).attr('src');
			jQuery(this).get(0).runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + bgIMG + '\', sizingMethod=\'scale\');';
   		jQuery(this).attr('src', settings.blankgif)
		});
	}
	return jQuery;
};
})(jQuery);
/**/////////////////////////////////
/*
 * jQuery history plugin
 *
 * Copyright (c) 2006 Taku Sano (Mikage Sawatari)
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Modified by Lincoln Cooper to add Safari support and only call the callback once during initialization
 * for msie when no initial hash supplied.
 * API rewrite by Lauris Bukðis-Haberkorns
 */
(function($) {
function History()
{
	this._curHash = '';
	this._callback = function(hash){};
};
$.extend(History.prototype, {
	init: function(callback) {
		this._callback = callback;
		this._curHash = location.hash;
		if($.browser.msie) {
			// To stop the callback firing twice during initilization if no hash present
			if (this._curHash == '') {
				this._curHash = '#';
			}
			// add hidden iframe for IE
			$("body").prepend('<iframe id="jQuery_history" style="display: none;"></iframe>');
			var iframe = $("#jQuery_history")[0].contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = this._curHash;
		}
		else if ($.browser.safari) {
			// etablish back/forward stacks
			this._historyBackStack = [];
			this._historyBackStack.length = history.length;
			this._historyForwardStack = [];
			this._isFirst = true;
			this._dontCheck = false;
		}
		this._callback(this._curHash.replace(/^#/, ''));
		setInterval(this._check, 100);
	},
	add: function(hash) {
		// This makes the looping function do something
		this._historyBackStack.push(hash);
		this._historyForwardStack.length = 0; // clear forwardStack (true click occured)
		this._isFirst = true;
	},
	_check: function() {
		if($.browser.msie) {
			// On IE, check for location.hash of iframe
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
			var current_hash = iframe.location.hash;
			if(current_hash != $.history._curHash) {
				location.hash = current_hash;
				$.history._curHash = current_hash;
				$.history._callback(current_hash.replace(/^#/, ''));
			}
		} else if ($.browser.safari) {
			if (!$.history._dontCheck) {
				var historyDelta = history.length - $.history._historyBackStack.length;
				if (historyDelta) { // back or forward button has been pushed
					$.history._isFirst = false;
					if (historyDelta < 0) { // back button has been pushed
						// move items to forward stack
						for (var i = 0; i < Math.abs(historyDelta); i++) $.history._historyForwardStack.unshift($.history._historyBackStack.pop());
					} else { // forward button has been pushed
						// move items to back stack
						for (var i = 0; i < historyDelta; i++) $.history._historyBackStack.push($.history._historyForwardStack.shift());
					}
					var cachedHash = $.history._historyBackStack[$.history._historyBackStack.length - 1];
					if (cachedHash != undefined) {
						$.history._curHash = location.hash;
						$.history._callback(cachedHash);
					}
				} else if ($.history._historyBackStack[$.history._historyBackStack.length - 1] == undefined && !$.history._isFirst) {
					// back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
					// document.URL doesn't change in Safari
					if (document.URL.indexOf('#') >= 0) {
						$.history._callback(document.URL.split('#')[1]);
					} else {
						$.history._callback('');
					}
					$.history._isFirst = true;
				}
			}
		} else {
			// otherwise, check for location.hash
			var current_hash = location.hash;
			if(current_hash != $.history._curHash) {
				$.history._curHash = current_hash;
				$.history._callback(current_hash.replace(/^#/, ''));
			}
		}
	},
	load: function(hash) {
		var newhash;
		if ($.browser.safari) {
			newhash = hash;
		} else {
			newhash = '#' + hash;
			location.hash = newhash;
		}
		this._curHash = newhash;
		if ($.browser.msie) {
			var ihistory = $("#jQuery_history")[0]; // TODO: need contentDocument?
			var iframe = ihistory.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = newhash;
			this._callback(hash);
		}
		else if ($.browser.safari) {
			this._dontCheck = true;
			// Manually keep track of the history values for Safari
			this.add(hash);
			// Wait a while before allowing checking so that Safari has time to update the "history" object
			// correctly (otherwise the check loop would detect a false change in hash).
			var fn = function() {$.history._dontCheck = false;};
			window.setTimeout(fn, 200);
			this._callback(hash);
			// N.B. "location.hash=" must be the last line of code for Safari as execution stops afterwards.
			//      By explicitly using the "location.hash" command (instead of using a variable set to "location.hash") the
			//      URL in the browser and the "history" object are both updated correctly.
			location.hash = newhash;
		}
		else {
		  this._callback(hash);
		}
	}
});
$(document).ready(function() {
	$.history = new History(); // singleton instance
});
})(jQuery);
