// Global variables
var buttonsDistill, contentDivDistill;
var buttonsProduct, contentDivProduct;
var imageHolder;

// Same domain policy
document.domain = 'bundabergrum.com.au';

// Code to run when DOM is ready
window.addEvent("domready", function() {	

	if (bundyReadCookie('bundyGateway') == null) {
		window.location = '/gateway.htm';
	}

	pageActions();
	
	// Handles login box transitions.
	if ($("loginPane") != null) {
		var loginBoxFx = new Fx.Slide($("loginPane"), { transition: Fx.Transitions.Quad.easeInOut } ).hide();
	}

	// Clear default texts on focus, restore default texts on blur
	if ($("loginPane") != null) {
		[$("email"), $("password")].each( function(el) {
			el.addEvent("focus", function(e) {
				if (this.value == "Email" || this.value == "Password") this.value = "";
			});
			el.addEvent("blur", function(e) {
				if (!this.value) {
					if (e.target == $("email"))
						this.value = "Email";
					else 
						this.value = "Password";
				}				
			});
		});
	}
	
	if (loginBoxFx != null) {
		$("loginButton").addEvent("click", function(e) {
			e = new Event(e);										
			loginBoxFx.toggle();
			e.stop();
		});		
	}

	if ($("flvDiv") != null) {
		var defaultBundyFlv = $$(".flvLink")[0].getAttribute("href");
		var initUrl = (queryString("load")) ? queryString("load") : null;
		if ($chk(initUrl)) {
			defaultBundyFlv = initUrl;
		}
		var flash = new BundyFlash({
			swfPath: "/flash/flvPlayer.swf",
			links: $$(".flvLink"),
			flvDiv: $("flvDiv"),
			defaultFlv: defaultBundyFlv
		});
	}
	
	if (contentDivProduct != null) {
		contentDivProduct.fade("hide");
		preLoadProductImages();
	};
	
	// add the bookmark
	if ($('bookmarker')) {
	  $('bookmarker').addEvent("click", addToFavorites());
	};
	
	// implement Capture CMS content (try on DOM ready and 2 seconds later)
	implementCaptureContent(1);
	setTimeout("implementCaptureContent(2)", 2000);
	setTimeout("implementCaptureContent(3)", 5000);

	// check if user is logged in
	checkLoginStatus();
	
	// If TickerVertical ul exists create a Ticker object to generate scrolling effect
	if ($("TickerVertical") != null) {
		var hor = new Ticker("TickerVertical", {speed: 1000, delay: 4000, direction: 'horizontal'});

		// 2009-07-09 Thierry: For some reason, fixes news ticker not working in IE6 
		$('newsTicker').getElement('.latestNews_I').setStyle('background', 'none');

	} else if ($("newsTicker") != null) {
		attemptToStartNewsTicker();
	}
});

// Creates new Ticker object
function attemptToStartNewsTicker()
{
	if ($("TickerVertical") != null) {
		var hor = new Ticker("TickerVertical", {speed: 1000, delay: 4000, direction: 'horizontal'});
	} else {
		setTimeout("attemptToStartNewsTicker()", 1000);
	}
}

// Retrieves content from Capture CMS and implements it on page
function implementCaptureContent(attempt)
{
	$$('iframe').each(function(el) {
			if (el.hasClass('captureModule')) {
				var alias = el.get('name');
				if (alias != '') {
					var moduleContent = '';
					if (window.frames[alias].document != null
					&& typeof(window.frames[alias].document.getElementById(alias)) != 'undefined'
					&& window.frames[alias].document.getElementById(alias) != null) {
						moduleContent = window.frames[alias].document.getElementById(alias).innerHTML;
					}
					if (moduleContent != '' || attempt == 3) {
						var parentEl = el.getParent();
						var iframeRegExp = new RegExp("<iframe[^>]+name=[\'\"]?" + alias + "[\\\s\\\S]*?<\/iframe>", "i");
						parentEl.innerHTML = parentEl.innerHTML.replace(iframeRegExp, moduleContent);
					}
				}
			}
	});
}

// Validates contact us form
function validateContactUsForm()
{
	var subjectValue = document.getElementById('subject').value;
	var firstNameValue = document.getElementById('firstName').value;
	var lastNameValue = document.getElementById('lastName').value;
	var emailAddressValue = document.getElementById('emailAddress').value;
	var enquiryDetailsValue = document.getElementById('enquiryDetails').value;

	if (subjectValue == '') {
		alert('Please select the subject of your enquiry');
	} else if (firstNameValue == '' || firstNameValue == 'First name *') {
		alert('Please enter your first name');
	} else if (lastNameValue == '' || lastNameValue == 'Last name *') {
		alert('Please enter your last name');
	} else if (!emailAddressValue.match(/^([a-zA-Z0-9]|-|_|\.)+@([a-zA-Z0-9]|-|_|\.)+\.[a-zA-Z]{2,4}$/gi)) {
		alert('Please enter a valid email address');
	} else if (enquiryDetailsValue == '' || enquiryDetailsValue == 'Tell us about your enquiry *') {
		alert('Please enter the details of your enquiry');
	} else {
		return true;
	}

	return false;
}

// Checks if user is logged in
function checkLoginStatus()
{
	var cookieBundySignedIn = readCookieValue('bundySignedIn');
	var cookieBundyUserFirstName = readCookieValue('bundyUserFirstName');
	
	if (cookieBundySignedIn == 'true' && cookieBundyUserFirstName != false) {
		$$("li.members").setStyle('display', 'none');
		showSignoutPane(cookieBundyUserFirstName);
	}
}

// Displays welcome message and signout options in main navigation
function showSignoutPane(userFirstName)
{
	var signinPane = document.getElementById('signinPane');
	var signoutPane = document.getElementById('signoutPane');
	var welcomeMessageUserName = document.getElementById('welcomeMessageUserName');

	welcomeMessageUserName.innerHTML = userFirstName;
	
	signinPane.style.display = 'none';
	signoutPane.style.display = 'block';
}

// Retrieves value of a cookie
function readCookieValue(name)
{
	if (document.cookie != '') {
		var cookieName = name + "=";
		
		var cookieArray = document.cookie.split(';');
	
		for (var i in cookieArray) {
	
			var cookiePair = cookieArray[i];

			if (typeof(cookiePair) == 'string') {
				
				while (cookiePair.charAt(0) == ' ') {
					cookiePair = cookiePair.substring(1, cookiePair.length);
				}
		
				if (cookiePair.indexOf(cookieName) == 0) {
					var cookieValue = cookiePair.substring(cookieName.length, cookiePair.length);

					return cookieValue;
				}
			}
		}
	}

	return false;
}

// Ticker news class
var Ticker = new Class({
	setOptions: function(options) {
		this.options = Object.extend({
			speed: 5000,
			delay: 5000,
			direction: 'vertical',
			onComplete: Class.empty,
			onStart: Class.empty
		}, options || {});
	},
	initialize: function(el,options){
		this.setOptions(options);
		this.el = $(el);			
		this.items = this.el.getElements('li');
		var w = 0;
		var h = 0;
		if(this.options.direction.toLowerCase()=='horizontal') {
			h = this.el.getSize().y;
			this.items.each(function(li,index) {
				w += li.getSize().x;
			});
		} else {
			w = this.el.getSize().x;
			this.items.each(function(li,index) {
				h += li.getSize().y;
			});
		}
		this.el.setStyles({
			position: 'absolute',
			top: 0,
			left: 0,
			width: w,
			height: h
		});
		this.fx = new Fx.Morph(this.el,{duration:this.options.speed,onComplete:function() {
			var i = (this.current===0)?this.items.length:this.current;
			this.items[i-1].injectInside(this.el);
			this.el.setStyles({
				left:0,
				top:0
			});
		}.bind(this)});
		this.current = 0;
		this.next();
	},
	next: function() {
		this.current++;
		if (this.current >= this.items.length)
			this.current = 0;
		var pos = this.items[this.current];
		this.fx.start({
			top: -pos.offsetTop,
			left: -pos.offsetLeft
		});
		this.next.bind(this).delay(this.options.delay+this.options.speed);
	}
});

/* Client-side access to querystring name=value pairs
	Version 1.3
	28 May 2008
	
	License (Simplified BSD):
	http://adamv.com/dev/javascript/qslicense.txt
*/
function queryString(key) {
	qs = window.location.search.substring(1);
	keys = qs.split("&");
	for (i=0; i < keys.length; i++) {
		ft = keys[i].split("=");
		if (ft[0] == key)
			return ft[1];
	}
	
	return false;
}

var initUrl = (queryString("load")) ? queryString("load") : null;
var initContent;

function pageActions() {
	if ($chk(initUrl)) {
		// Find the page. If there's an error, continue as per normal load.
		var ajaxRequest = new Request({
			url: initUrl,
			method: "get",
			onSuccess: function(response) {			
				initContent = response;
				pageLoad(true);
			},
			onFailure: function() { pageLoad(false); }
		}).send();
	} else {		
		pageLoad(false);
	}
}

function pageLoad(isForced) {
	if ($("productPage")) {
		productsAjax(isForced);
	} else if ($("distilleryPage")) {
		distillBackground = $("heroHome");
		if (distillBackground != null) {
			if (isForced) {
				distilleryAjax("/distillery/heroTour.htm", isForced);
			} else {
				$("btnEnterDistillery").addEvent("click", function(evt) {
					evt.stop();
					distilleryAjax(this.getAttribute("href"));
				});
			}
		}
	}
}

function distilleryAjax(url, isForced) {
	var ajaxRequest = new Request({
		url: url,
		method: "get",
		onSuccess: function(response) {
			distillBackground.fade("hide");
			distillBackground.getParent().set("html",response);
					
			// when the contents of the tour page is loaded
			// we can click on the buttons of distillery to
			// see the content of each step
			buttonsDistill = $$("div.disSteps a");
			contentDivDistill = $$("div.distilleryDetails")[0];
//			contentDivDistill.setStyle("display","none");

			if (isForced) {
				// Auto-begin next step
				loadContent(initContent, "distill");
			}

			buttonsDistill.each(function(el) {	
				el.addEvent("click", function(evt) {						  
					evt.stop();			
					var ajaxRequest = new Request({
						url: this.getAttribute("href"),
						method: "get",
						onSuccess: function(response) {
							contentDivDistill.setStyle("display", "block");
							loadContent(response, "distill");
						},
						onFailure: function() {
							loadContent("<p>Error loading AJAX content</p>");
						}
					}).send();
				});
			});

		if (contentDivDistill != null)
				contentDivDistill.fade("hide");
		},
		onFailure: function() {
			distillBackground.getParent().innerHTML = "<p>Error loading AJAX content</p>";
		}
	}).send();
}

function productsAjax(isForced) {
	buttonsProduct = $$("div.prodItem a");
	contentDivProduct = $$("div.productDetails")[0];	
	contentDivProduct.fade("hide");
	buttonsProduct.each(function(el) {
		el.addEvent("click", function(evt) {									  
			evt.stop();
			var ajaxRequest = new Request({
				url: this.getAttribute("href"),
				method: "get",
				onSuccess: function(response) {
					loadContent(response, "product");
				},
				onFailure: function() {
					loadContent("<p>Error loading AJAX content</p>", "product");
				}
			}).send();
		});
	});
	
	if (isForced) {
		loadContent(initContent, "product");
	}
}
	
// Pre-load product images
function preLoadProductImages() {
	images = [
                '/images/product_bundyReserveBG.jpg',
		'/images/product_bundyRumBG.jpg',
		'/images/product_bundyLiqueur.jpg',
		'/images/product_bundyLimited.jpg',
		'/images/product_bundyOPRumBG.jpg',
		'/images/product_bundyRedBG.jpg',
		'/images/product_bundyAndCola.jpg',
		'/images/product_dryAndLime.jpg',
		'/images/product_darkAndStormy.jpg'
	];
	
	new Asset.images(images).each(function(image,index) {
		$$("div.preloaded").innerHTML += image;
	});
	$$("div.preloaded").set("html", "");
}

// load content from ajax request
function loadContent(html, content) {
	if (content == "distill") {
		contentDivDistill.setStyle("display", "block");
		contentDivDistill.set('html', html);
		
		$$(".stepDetailImage1").setStyle('display', 'none');
		$$(".stepDetailImage2").setStyle('display', 'none');
		$$(".stepDetailImage3").setStyle('display', 'none');
		$$(".stepDetailImage4").setStyle('display', 'none');
		$$(".stepDetailImage5").setStyle('display', 'none');

		makePrevBtns();
		makeNextBtns();

		makeCloseBtns(content);
		contentDivDistill.fade("in");
	} else {
		contentDivProduct.set("html", html);

		makeCheckoutBtns(content);
		makeCloseBtns(content);	
		contentDivProduct.fade("in");
	}

}

function closeContent(evt, content) {
	evt.stop();
	if (content == "distill"){
		$$("div.distilleryDetails")[0].fade("out");
	} else {
		$$("div.productDetails")[0].fade("out");
	}
	
}

// close the pop up content
function makeCloseBtns(content) {
	$$(".closeBtn").each(function(cl) {
		cl.addEvent("click", function(evt) {
			closeContent(evt, content);	
		});
    }.bind(this));
}

// make checkout buttons
function makeCheckoutBtns(content) {
	$$(".checkoutBtn").each(function(cb) {
		cb.addEvent("click", function(evt) {
			closeContent(evt, content);
			evt.stop();
			var ajaxRequest = new Request({
				url: this.getAttribute("href"),
				method: "get",
				onSuccess: function(response) {
					loadContent(response, "product");
				},
				onFailure: function() {
					loadContent("<p>Error loading AJAX content</p>", "product");
				}
			}).send();
		});
		}.bind(this));
}

// to load next image 
function nextImage(evt) {
	evt.stop();

	changeImage(1);
}

// to load previous image 
function prevImage(evt) {
	evt.stop();
	changeImage(-1);	
}

// Added to decrease code footprint!
function changeImage(direction) {
	var imageTotal = $("imageTotal").get("html");
	var imageCurrent = $("imageCurrent").get("html");
	imageHolder = $$("div.stepDetailImage img");
	if (direction < 0) {
		imageCurrent = (imageCurrent > 1) ? --imageCurrent : imageTotal;
	} else {
		imageCurrent = (imageCurrent < imageTotal) ? ++imageCurrent : 1;
	}
	var image = ".stepDetailImage"+imageCurrent;	
	
	$$("div.imageName p").set("html", $$(image+" img").get("alt"));
	$$(".stepDetailImage").set("html", $$(image).get("html"));
	$("imageCurrent").set("html", imageCurrent);
}

// make button to load next image 
function makeNextBtns() {
	
	$$(".nextBtn").each(function(cl) {
		cl.addEvent("click", function(evt) { nextImage(evt); });
    }.bind(this));
	
}

// make button to load previous image 
function makePrevBtns() {
	$$(".prevBtn").each(function(cl) {
		cl.addEvent("click", function(evt) { prevImage(evt); });
    }.bind(this));
}

// load flash content in bundyBear.htm
var BundyFlash = new Class({
	Implements: [Options, Events],
	options: {
		links: [],
		flvDiv: null,
		swfPath: "",
		autoplay: false,
		defaultFlv: "",
		so: null
	},
	initialize: function(options) {
		this.setOptions(options);
		if ($chk(this.options.defaultFlv))
			this.loadFlv(this.options.defaultFlv, this.options.autoPlay);		
		this.options.links.each(function(el) {
			el.addEvent("click", function(evt) {
				evt.stop();
				if (el.getAttribute("href") != '#') {
					window.location.href = "#";
					this.loadFlv(el.getAttribute("href"));
				}
			}.bind(this));
		}.bind(this));
	},
	loadFlv: function(flvToPlay, autoPlay) {
		this.options.so = new Swiff(this.options.swfPath, {
			id: "bundyFlash",
			width: 600,
			height: 345,
			container: this.options.flvDiv,
			params: {
				wmode: "opaque",
				bgcolor: "#000000"
			},
			vars: {
				flvToPlay: flvToPlay,
				autoStart: autoPlay,
				startImage: '/images/flvLanding.jpg'
}
		});		

	}
});

/* 
*  Copyright 2006-2007 Dynamic Site Solutions.
*  Free use of this script is permitted for non-commercial applications,
*  subject to the requirement that this comment block be kept and not be
*  altered.  The data and executable parts of the script may be changed
*  as needed.  Dynamic Site Solutions makes no warranty regarding fitness
*  of use or correct function of the script.  Terms for use of this script
*  in commercial applications may be negotiated; for this, or for other
*  questions, contact "license-info@dynamicsitesolutions.com".
*
*  Script by: Dynamic Site Solutions -- http://www.dynamicsitesolutions.com/
*  Last Updated: 2007-06-17
*/

//IE5+/Win, Firefox, Netscape 6+, Opera 7+, Safari, Konqueror 3, IE5/Mac, iCab 3
var addBookmarkObj = {
  linkText:'Bookmark This Page',
  addTextLink:function(parId){
    var a=addBookmarkObj.makeLink(parId);
    if(!a) return;
    a.appendChild(document.createTextNode(addBookmarkObj.linkText));
  },
  addImageLink:function(parId,imgPath){
    if(!imgPath || isEmpty(imgPath)) return;
    var a=addBookmarkObj.makeLink(parId);
    if(!a) return;
    var img = document.createElement('img');
    img.title = img.alt = addBookmarkObj.linkText;
    img.src = imgPath;
    a.appendChild(img);
  },
  makeLink:function(parId) {
    if(!document.getElementById || !document.createTextNode) return null;
    parId=((typeof(parId)=='string')&&!isEmpty(parId))
      ?parId:'addBookmarkContainer';
    var cont=document.getElementById(parId);
    if(!cont) return null;
    var a=document.createElement('a');
    a.href=location.href;
    if(window.opera) {
      a.rel='sidebar'; // this makes it work in Opera 7+
    } else {
      // this doesn't work in Opera 7+ if the link has an onclick handler,
      // so we only add it if the browser isn't Opera.
      a.onclick=function() {
        addBookmarkObj.exec(this.href,this.title);
        return false;
      }
    }
    a.title=document.title;
    return cont.appendChild(a);
  },
  exec:function(url, title) {
    // user agent sniffing is bad in general, but this is one of the times 
    // when it's really necessary
    var ua=navigator.userAgent.toLowerCase();
    var isKonq=(ua.indexOf('konqueror')!=-1);
    var isSafari=(ua.indexOf('webkit')!=-1);
    var isMac=(ua.indexOf('mac')!=-1);
    var buttonStr=isMac?'Command/Cmd':'CTRL';

    if(window.external && (!document.createTextNode ||
      (typeof(window.external.AddFavorite)=='unknown'))) {
        // IE4/Win generates an error when you
        // execute "typeof(window.external.AddFavorite)"
        // In IE7 the page must be from a web server, not directly from a local 
        // file system, otherwise, you will get a permission denied error.
        window.external.AddFavorite(url, title); // IE/Win
    } else if(isKonq) {
      alert('You need to press CTRL + B to bookmark our site.');
    } else if(window.opera) {
      void(0); // do nothing here (Opera 7+)
    } else if(window.home || isSafari) { // Firefox, Netscape, Safari, iCab
      alert('You need to press '+buttonStr+' + D to bookmark our site.');
    } else if(!window.print || isMac) { // IE5/Mac and Safari 1.0
      alert('You need to press Command/Cmd + D to bookmark our site.');    
    } else {
      alert('In order to bookmark this site you need to do so manually '+
        'through your browser.');
    }
  }
}

function isEmpty(s){return ((s=='')||/^\s*$/.test(s));}

function dss_addEvent(el,etype,fn) {
  if(el.addEventListener && (!window.opera || opera.version) &&
  (etype!='load')) {
    el.addEventListener(etype,fn,false);
  } else if(el.attachEvent) {
    el.attachEvent('on'+etype,fn);
  } else {
    if(typeof(fn) != "function") return;
    if(typeof(window.earlyNS4)=='undefined') {
      // to prevent this function from crashing Netscape versions before 4.02
      window.earlyNS4=((navigator.appName.toLowerCase()=='netscape')&&
      (parseFloat(navigator.appVersion)<4.02)&&document.layers);
    }
    if((typeof(el['on'+etype])=="function")&&!window.earlyNS4) {
      var tempFunc = el['on'+etype];
      el['on'+etype]=function(e){
        var a=tempFunc(e),b=fn(e);
        a=(typeof(a)=='undefined')?true:a;
        b=(typeof(b)=='undefined')?true:b;
        return (a&&b);
      }
    } else {
      el['on'+etype]=fn;
    }
  }
}

dss_addEvent(window,'load',addBookmarkObj.addTextLink);

// to make multiple links, do something like this:
/*
dss_addEvent(window,'load',function(){
  var f=addBookmarkObj.addTextLink;
  f();
  f('otherContainerID');
});
*/

// below is an example of how to make an image link with this
// the first parameter is the ID. If you pass an empty string it defaults to
// 'addBookmarkContainer'.
/*
dss_addEvent(window,'load',function(){
  addBookmarkObj.addImageLink('','/images/add-bookmark.jpg');
});
*/

/**/
	// IE5.5+ PNG Alpha Fix v2.0 Alpha: Background Tiling Support
// (c) 2008 Angus Turnbull http://www.twinhelix.com

// This is licensed under the GNU LGPL, version 2.1 or later.
// For details, see: http://creativecommons.org/licenses/LGPL/2.1/
var IEPNGFix = window.IEPNGFix || {};
IEPNGFix.tileBG = function(elm, pngSrc, ready) {
	// Params: A reference to a DOM element, the PNG src file pathname, and a
	// hidden "ready-to-run" passed when called back after image preloading.
	var data = this.data[elm.uniqueID],
		elmW = Math.max(elm.clientWidth, elm.scrollWidth),
		elmH = Math.max(elm.clientHeight, elm.scrollHeight),
		bgX = elm.currentStyle.backgroundPositionX,
		bgY = elm.currentStyle.backgroundPositionY,
		bgR = elm.currentStyle.backgroundRepeat;

	// Cache of DIVs created per element, and image preloader/data.
	if (!data.tiles) {
		data.tiles = {
			elm: elm,
			src: '',
			cache: [],
			img: new Image(),
			old: {}
		};
	}
	var tiles = data.tiles,
		pngW = tiles.img.width,
		pngH = tiles.img.height;

	if (pngSrc) {
		if (!ready && pngSrc != tiles.src) {
			// New image? Preload it with a callback to detect dimensions.
			tiles.img.onload = function() {
				this.onload = null;
				IEPNGFix.tileBG(elm, pngSrc, 1);
			};
			return tiles.img.src = pngSrc;
		}
	} else {
		// No image?
		if (tiles.src) ready = 1;
		pngW = pngH = 0;
	}
	tiles.src = pngSrc;

	if (!ready && elmW == tiles.old.w && elmH == tiles.old.h &&
		bgX == tiles.old.x && bgY == tiles.old.y && bgR == tiles.old.r) {
		return;
	}

	// Convert English and percentage positions to pixels.
	var pos = {
			top: '0%',
			left: '0%',
			center: '50%',
			bottom: '100%',
			right: '100%'
		},
		x,
		y,
		pc;
	x = pos[bgX] || bgX;
	y = pos[bgY] || bgY;
	if (pc = x.match(/(\d+)%/)) {
		x = Math.round((elmW - pngW) * (parseInt(pc[1]) / 100));
	}
	if (pc = y.match(/(\d+)%/)) {
		y = Math.round((elmH - pngH) * (parseInt(pc[1]) / 100));
	}
	x = parseInt(x);
	y = parseInt(y);

	// Handle backgroundRepeat.
	var repeatX = { 'repeat': 1, 'repeat-x': 1 }[bgR],
		repeatY = { 'repeat': 1, 'repeat-y': 1 }[bgR];
	if (repeatX) {
		x %= pngW;
		if (x > 0) x -= pngW;
	}
	if (repeatY) {
		y %= pngH;
		if (y > 0) y -= pngH;
	}

	// Go!
	this.hook.enabled = 0;
	if (!({ relative: 1, absolute: 1 }[elm.currentStyle.position])) {
		elm.style.position = 'relative';
	}
	var count = 0,
		xPos,
		maxX = repeatX ? elmW : x + 0.1,
		yPos,
		maxY = repeatY ? elmH : y + 0.1,
		d,
		s,
		isNew;
	if (pngW && pngH) {
		for (xPos = x; xPos < maxX; xPos += pngW) {
			for (yPos = y; yPos < maxY; yPos += pngH) {
				isNew = 0;
				if (!tiles.cache[count]) {
					tiles.cache[count] = document.createElement('div');
					isNew = 1;
				}
				var clipR = (xPos + pngW > elmW ? elmW - xPos : pngW),
					clipB = (yPos + pngH > elmH ? elmH - yPos : pngH);
				d = tiles.cache[count];
				s = d.style;
				s.behavior = 'none';
				s.left = xPos + 'px';
				s.top = yPos + 'px';
				s.width = clipR + 'px';
				s.height = clipB + 'px';
				s.clip = 'rect(' +
					(yPos < 0 ? 0 - yPos : 0) + 'px,' +
					clipR + 'px,' +
					clipB + 'px,' +
					(xPos < 0 ? 0 - xPos : 0) + 'px)';
				s.display = 'block';
				if (isNew) {
					s.position = 'absolute';
					s.zIndex = -999;
					if (elm.firstChild) {
						elm.insertBefore(d, elm.firstChild);
					} else {
						elm.appendChild(d);
					}
				}
				this.fix(d, pngSrc, 0);
				count++;
			}
		}
	}
	while (count < tiles.cache.length) {
		this.fix(tiles.cache[count], '', 0);
		tiles.cache[count++].style.display = 'none';
	}

	this.hook.enabled = 1;

	// Cache so updates are infrequent.
	tiles.old = {
		w: elmW,
		h: elmH,
		x: bgX,
		y: bgY,
		r: bgR
	};
};
IEPNGFix.update = function() {
	// Update all PNG backgrounds.
	for (var i in IEPNGFix.data) {
		var t = IEPNGFix.data[i].tiles;
		if (t && t.elm && t.src) {
			IEPNGFix.tileBG(t.elm, t.src);
		}
	}
};
IEPNGFix.update.timer = 0;
if (window.attachEvent && !window.opera) {
	window.attachEvent('onresize', function() {
		clearTimeout(IEPNGFix.update.timer);
		IEPNGFix.update.timer = setTimeout(IEPNGFix.update, 100);
	});
}

function bundyReadCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i=0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	
	return null;
}