﻿/**
 * @author Jeremy.Manoto
 */

	jQuery.expr[':'].containsIgnoreCase = function(e,i,m){return jQuery(e).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;};


	$(document).ready(function() {

	    IE6_Init();

	    JQuery_Init();

	    ShortArticle_Init();

	    Promo_Init();
		
	    DiFR_Init();

	    Navigation_Init();

	    LatestNews_Init();

	    AddThis_Init();

	    Sitemap_Init();
		
	    Footer_Init();

	});


	/**
	 * JQuery Initialisation
	 */
	function JQuery_Init() {
		
		/**
		 * Setup default loggin method
		 * @param {Object} message
		 */
		$.log = function(message) {
			if (window.console) {
				//console.debug(message);
			}
		}
		
		if ($(".flash_slideshow").length > 0)
		{
			$("img.hero_image").remove();
			$(".flash_slideshow").show();
		}
	}
	
	
	function IE6_Init() {
		
	}

	
	/**
	 * Initialize the superfish navigation
	 */
	function Navigation_Init() {
		
		//Home page link
		$("h1.logo").click(function() {
			window.location = (VirtualDirectory == "") ? "/" : VirtualDirectory;

		});

		$(".header .search button.submit").click(function() {
		    //perform google site search
		    var searchString = $(".header #txtSearch").val();
		    window.location = VirtualDirectory + "/search?q=" + searchString;		    
		});

		$(".header .search #txtSearch").keyup(function(e) {
		    if (e.keyCode == 13) {
		        $(".header .search button.submit").click();
		    }
		});
		
		$(".header .registration button.submit").click(function() {
		    var emailString = $(".header #txtEmailRegistration").val();
		    window.location = VirtualDirectory + "/about/contact?e=" + emailString;		    
		});
		
		$(".header .registration #txtEmailRegistration").keyup(function(e) {
		    if (e.keyCode == 13) {
		        $(".header .registration button.submit").click();
		    }
		});
		
		$(".navigation ul").supersubs({
			minWidth:	8,
			extraWidth:	0
		}).superfish();
		
		//Sustain the highlight for the parent section while hovering over subpages
		$(".navigation ul li ul").hover(function() {
			$(this).prev("a").addClass("hover");
		}, function() {
			$(this).prev("a").removeClass("hover");
			
		});


		
		$(".sub-navigation li.highlight").parent().prev().addClass("parent-highlight");
	}

	
	/**
	 * Latest News Initialization
	 */
	function LatestNews_Init() {

		$(".latest-news").DeepCarousel();
		
	}
	
	function ShortArticle_Init() {
		$(".short-article").DeepShortArticle();
		
		$(".span-6 .short-article:odd").addClass("last");
	}
	
	
	function Promo_Init() {
	    $(".promo:not(.promo-share)").DeepHover();
		
		//$(".production-listitem .thumb").DeepHover({ useOverlay: false});
		$(".video-gallery").DeepHover();
		$(".image-gallery").DeepHover();
		$(".audio-player").DeepHover();
		
	}
	
	
	function ProductionDetails_Init() {
		
		$(".production.panel-details").DeepTabCopy();
	}
	
	function ProductionCalendar_Init() {
		//calendar = new Calendar($(".calendar"));
	}

	function AddThis_Init() {
	    var addthis_config = {
	        username: "bellshakespeare"
	    }

	}

	function Sitemap_Init() {
	    $("#cms-tree div.wrapper").click(function() {
	        window.location = $(this).find("div.page-path").text();
	    });
	}
	
	function DiFR_Init() {
	
		$(".difr, .html-block h2, .html-block h3, .promo h3, .html-block h1, .html-block h4").DiFR({
		    DiFRPath: VirtualDirectory + "/services/difr.ashx"
		});
	
	
		$(".short-article h3").DiFR({
		    DiFRPath: VirtualDirectory + "/services/difr.ashx",
		    spacing: "normal",
		    kerning: "-1"
		});
		
		
		$(".navigation .top-menu span").DiFR({
			DiFRPath: VirtualDirectory + "/services/difr.ashx",
			rollover:true
		});
	
		/*$(".navigation .top-level span").DiFR({
		    DiFRPath: VirtualDirectory + "/services/difr.ashx",
		    kerning: "3",
		    rollover:true
		});*/		
	}
	
	
	function Footer_Init() {
		$(".dsq-widget-item").each(function() {
			var item = $(this);
			var link = item.find(".dsq-widget-meta a:first");
			
			item.click(function() {
				window.location = link.attr("href");
			})
		});
		
	}
	
	
	/***********************************************************************
	 * Plugins!!
	 */
	
	
		$.fn.DeepPromo = function(options) {
			var defaults = {
				hoverOpacity:	.7,
				defaulOpacity:	1
			}
			
			// Extend/Combine options with our defaults
			var opts = $.extend({}, defaults, options);
			
			return this.each(function() {
				var container = $(this);
				
				if (container.find("a").length > 0) {
					container.hover(function(){
						$(this).stop(true, false).animate({
							opacity: opts.hoverOpacity
						});
					}, function(){
						$(this).stop(true, false).animate({
							opacity: opts.defaulOpacity
						});
					});
				}
				
			});
		}


		$.fn.DeepHover = function(options) {
		    var defaults = {
		        hoverOpacity: .7,
		        defaultOpacity: .999,
		        useOverlay: false,
		        overlayColor: "#F0EBE8"
		    }

		    // Extend/Combine options with our defaults
		    var opts = $.extend({}, defaults, options);

            // Force IE to use the overlay method
		    if ($.browser.msie) {
		        opts.useOverlay = true;
		        opts.defaultOpacity = 1 - opts.defaultOpacity;
		        opts.hoverOpacity = 1 - opts.hoverOpacity;
		    }

		    return this.each(function() {
		        var container = $(this);

		        if (opts.useOverlay) {

		            var width = container.outerWidth();
		            var height = container.outerHeight();

		            // Generate Overlay
		            var overlay = jQuery("<div class='hoverOverlay'></div>");
		            overlay.css({ position: "absolute", width: width, height: height, backgroundColor: opts.overlayColor, cursor: "pointer", opacity: opts.defaultOpacity });
		            container.css({ position: "relative" });
		            container.prepend(overlay);

		            overlay.hover(function() {
		                //var overlay = container.find(".hoverOverlay");
		                $(this).stop(true, false).animate({
		                    opacity: opts.hoverOpacity
		                });
		            }, function() {
		                //var overlay = container.find(".hoverOverlay");
		                $(this).stop(true, false).animate({
		                    opacity: opts.defaultOpacity
		                });
		            })

		            // Assign click event to overlay (if anchor tag exists within container)
		            var link = container.find("a[href]").attr("href");
		            overlay.click(function() {
		                window.location.href = link;
		            });




		        } else {
		            container.hover(function() {
		                $(this).stop(true, false).animate({
		                    opacity: opts.hoverOpacity
		                });
		            }, function() {
		                $(this).stop(true, false).animate({
		                    opacity: opts.defaultOpacity
		                });
		            });

		        }

		    });
		}
	
	
	
		//Declare Scroller Plugin
		$.fn.DeepCarousel = function(options) {
			
			//Plugin Defaults
			var defaults = {
				viewPort:		".viewport",	//The viewport css (Not Needed??)
				itemContainer:	".items",		
				itemSelector:	".item",		//Selector for each item to scroll
				nextSelector: 	".next",		//Selector for the next button
				prevSelector: 	".prev",		//Selector for the prev button
				autoScroll:		false, 			//Not Implemented Yet!
				scrollInterval:	10
			}
			
			// Extend/Combine options with our defaults
			var opts = $.extend({}, defaults, options);
			
			var indexTracker = "currentIndex";
		
			return this.each(function() {
				var container = $(this);
				
				//Count the number of items
				var numItems = container.find(opts.itemSelector).length;
				
				//Set the width of the items
				var itemWidth = container.find(opts.itemSelector + ":first").outerWidth();
				var itemHeight = container.find(opts.itemSelector + ":first").outerHeight();
				container.find(opts.itemContainer).css("width", numItems * itemWidth + "px");
				
				//Set the height of the viewport
				//container.find(opts.viewPort).css("height", itemHeight + "px");
				
				//Set the index counter to track which one is currently visible.
				//Store in the itemContainer data
				container.find(opts.itemContainer).data(indexTracker, 1);
				
				
				//Definition of Scroll animation
				container.Scroll = function(directionAmount) {
					//$.log(container);
					
					var currentIndex = parseInt(container.find(opts.itemContainer).data(indexTracker));
					//$.log("currentIndex: " + currentIndex);
					
					var nextIndex = currentIndex + directionAmount;
					//TODO: Check if nextIndex is valid
					if (nextIndex > 0 && nextIndex <= numItems) {
					
						var nextSelector = opts.itemSelector + ":nth-child(" + (nextIndex) + ")";
						var nextItem = container.find(nextSelector);
						//$.log(nextItem);
						var nextHeight = nextItem.outerHeight();
						//$.log("nextHeight: " + nextHeight);
						
						container.find(opts.viewPort).animate({
							scrollLeft: (nextIndex - 1) * itemWidth
						});
						
						container.find(opts.itemContainer).data(indexTracker, nextIndex);
					}
	
				};
				
				
				
				//Set the click event for the next selector.
				//Scrolls the items
				container.find(opts.nextSelector).click(function() {
					
					container.Scroll(1);

				});
				
				//Set the click event for the prev selector
				container.find(opts.prevSelector).click(function() {
					
					container.Scroll(-1);

				})

				
			});
			
		}

		//Plugin for Short Article module
		$.fn.DeepShortArticle = function(options) {
			//Plugin Defaults
			var defaults = {
				toShowSelector:		".copy",
				toHideSelector:		".thumb"
			}
			
			// Extend/Combine options with our defaults
			var opts = $.extend({}, defaults, options);
			
			
			return this.each(function() {
				var container = $(this);
				
				container.containerHeight = container.outerHeight({margin: "true"});
				container.containerWidth = container.outerWidth({margin: "true"});
				//container.css({ height: container.containerHeight + "px"});
				
				container.toHide = container.find(opts.toHideSelector);
				container.toShow = container.find(opts.toShowSelector);
				var containerHeight = container.toShow.offset().top - container.offset().top;
				//alert(containerHeight);
				container.css({ height: containerHeight + "px"});
				container.toShow.show();
				
				//Determine the hiding elements full height for storage.
				container.toHideHeight;
				container.toHideWidth;
				container.toHide.each(function() {
					var hide = $(this);
					container.toHideHeight = hide.outerHeight({margin: "true"});
					container.toHideWidth = hide.outerWidth({margin: "true"});
					hide.data("fullHeight", container.toHideHeight);
					hide.data("fullWidth", container.toHideWidth);
				});
				container.toShow.each(function() {
					var show = $(this);
					container.toShowHeight = show.outerHeight({margin: "true"});
					container.toShowWidth = show.outerWidth({margin: "true"});
					show.data("fullHeight", container.toShowHeight);
					show.data("fullWidth", container.toShowWidth);
				})
				
				var copy = $.trim(container.find(".copy").text());
				if (copy.length > 0) {
					container.hover(function(){
						container.toHide.stop(true, false).animate({
							top: "-" + (container.toHideHeight) + "px",
							marginBottom: "-" + (container.toHideHeight - 3) + "px"
						}, "normal", "swing");
					}, function(){
						container.toHide.stop(true, false).animate({
							top: "0px",
							marginBottom: "3px"
						}, "normal", "swing");
					});
				}
				

			});
			
			
		}
		
		
		$.fn.DeepTabCopy = function(options) {
			var defaults = {
				defaultTab:		1, //Index of panel to show
				highlightClass:	"highlight"
			};
			
			var opts = $.extend({}, defaults, options);
			
			return this.each(function() {
				
				
				var container = $(this);
				
				var copyArea = container.find(".copy-area");
				
				var defaultTab = container.find("li").eq(opts.defaultTab - 1);
				copyArea.html(defaultTab.find(".copy").html());
				defaultTab.addClass(opts.highlightClass);
				
				// Set click/activate event handler
				container.find(".heading").click(function() {
					
					container.find("." + opts.highlightClass).removeClass(opts.highlightClass);
					
					var item = $(this).parent();
					var copy = item.find(".copy").html();
					
					copyArea.html(copy);
					
					item.addClass(opts.highlightClass);
				});
				
				
			});
		}
		
		
		
		
		$.fn.DeepScroll = function(options) {
			var defaults = {
				scrollUpClass:			"scroll-up",
				scrollContentClass:		"scroll-content",
				scrollDownClass:		"scroll-down"
			}
			
			var opts = $.extend({}, defaults, options);
			
			return this.each(function() {
				
				var container = $(this);
				var scrollContent = container.find("." + opts.scrollContentClass);
				var scrollUpElement = container.find("." + opts.scrollUpClass);
				var scrollDownElement = container.find("." + opts.scrollDownClass);
				
			})
		}
		
		
		var Calendar = base2.Base.extend({
			constructor: function(container) {
				this.container = $(container);
				this.scrollableArea = this.container.find(".scrollable");
				this.scrollable = null;
				
				this.setScrollableArea();
				
				this.setFilterEvents();
				
				this.setDefaultDate();
			},
			
			setScrollableArea: function() {
				this.scrollable = new Scrollable(this.scrollableArea);
			},
			
			setDefaultDate: function() {
				
				var container = this.container;
				var scrollableArea = this.scrollableArea;
				var scrollable = this.scrollable;
				
				var currentDate = new Date();
				//console.log("Current Date: " + currentDate);
				var currentMonth = currentDate.getMonth() + 1;
				var currentYear = currentDate.getFullYear();
				var currentDay = currentDate.getDate();
				//console.log("Year:" + currentYear + " | Month:" + currentMonth + " | Day:" + currentDay);
				
				//debugger;
				var targetDate = + parseInt(currentYear + "" + padZero(currentMonth,2) + "" + padZero(currentDay,2));
				var target = scrollableArea.find("." + targetDate);
				if (target.length == 0) {
					
					var counter = 0;
					var limit = 7;
					for (counter = 0; counter <= limit; counter++) {
						targetDate = targetDate + 1;
						var target = scrollableArea.find("." + targetDate)
						
						if (target.length > 0) {
							//target.css({ background: "red" });
							break;
						}
					}
				}
				
				var targetOffset = target.offset();
				
				var overlayLabelHeight = 24;
				var scrollTo = targetOffset.top - scrollable.scrollContent.offset().top + scrollable.scrollContent.scrollTop() - overlayLabelHeight;
				
				var scrollWrapper = scrollableArea.find(".scroll-wrapper");
				
				//console.debug("scrollAreaHeight: " + scrollWrapper.outerHeight()  +  " | targetTop: " + targetOffset.top + " | targetScrollTop: " + target.scrollTop() + " | currentScrollTop: " + scrollable.scrollContent.scrollTop() + " | scrollTo: " + scrollTo);
				
				
				var currentTop = scrollable.scrollContent.scrollTop();
				//console.debug("currentTop: " + currentTop);
				var scrollSpeed = Math.abs(scrollTo - currentTop);
				
				//console.debug("Scrolling From: " + currentTop + " | Scrolling To:" + scrollTo);
				
				scrollable.scrollContent.stop(true, false).animate({
					scrollTop: scrollTo
				}, scrollSpeed * 1.3, "swing", function(){
					scrollable.updateGroupLabel();
				});
				 
				
				
				
			},
		
			setFilterEvents: function() {
				var selectLocation = this.container.find(".filter .location");
				var selectTime = this.container.find(".filter .time");
				
				var container = this.container;
				var scrollableArea = this.scrollableArea;
				var scrollable = this.scrollable;
				
				selectLocation.change(function() {
					var locationClass = $(this).val();
					var items = container.find(".item");
					var groups = container.find(".group");
					var locationLabels = container.find("h5");
					
					if (locationClass != "") {
						items.not("." + locationClass).hide();
						container.find(".item." + locationClass).show();
						
						locationLabels.not("." + locationClass).hide();
						container.find("h5." + locationClass).show();
						
						
					} else {
						items.show();
						locationLabels.show();
					}
					
					var scrollWrapper = scrollableArea.find(".scroll-wrapper");
					var scrollBottom = scrollWrapper.offset().top + scrollWrapper.outerHeight();

					//if (scrollBottom < scrollableArea.offset().top) {
						scrollable.scrollContent.animate({scrollTop: 0});
					//}
					scrollable.updateGroupLabel();
					
				});
				
				selectTime.change(function() {
					var timeClass = $(this).val();
					var groups = container.find(".group");
					
					var target = container.find("." + timeClass);
					var targetOffset = target.offset();
					var scrollTo = targetOffset.top - scrollable.scrollContent.offset().top + scrollable.scrollContent.scrollTop();
					
					var scrollWrapper = scrollableArea.find(".scroll-wrapper");
					
					//console.debug("scrollAreaHeight: " + scrollWrapper.outerHeight()  +  " | targetTop: " + targetOffset.top + " | targetScrollTop: " + target.scrollTop() + " | currentScrollTop: " + scrollable.scrollContent.scrollTop() + " | scrollTo: " + scrollTo);
					
				
					var currentTop = scrollable.scrollContent.scrollTop();
					//console.debug("currentTop: " + currentTop);
					var scrollSpeed = Math.abs(scrollTo - currentTop);
					
					//console.debug("Scrolling From: " + currentTop + " | Scrolling To:" + scrollTo);
					
					scrollable.scrollContent.stop(true, false).animate({scrollTop: scrollTo}, scrollSpeed * 1.3, "swing", function() {
						scrollable.updateGroupLabel();
					});
					

				});
			}
		});
		
		
		
		/**
		 * Addes Scrollable events to a DOM structure
		 * @param {Object} container jQuery DOM container
		 */
		var Scrollable = base2.Base.extend({
		    constructor: function(container) {

		        this.container = $(container);
		        this.scrollContent = this.container.find(".scroll-content");
		        this.scrollUpElement = this.container.find(".scroll-up");
		        this.scrollDownElement = this.container.find(".scroll-down");

		        //this.container.css({ border: "4px solid #000"});
		        this.interval = null;
		        this.groups = this.container.find(".group .label");

		        this.bindEvents();
		        this.updateGroupLabel();

		    },
		    scrollDown: function() {
		        var currentTop = this.scrollContent.scrollTop();
		        var scrollTo = this.scrollContent.children(".scroll-wrapper").height() - this.scrollContent.height();

		        var scrollSpeed = Math.abs(scrollTo - currentTop);
		        this.scrollContent.animate({ scrollTop: scrollTo }, scrollSpeed * 2);

		    },
		    scrollUp: function() {
		        var currentTop = this.scrollContent.scrollTop();
		        var scrollTo = 0;

		        this.scrollContent.animate({ scrollTop: scrollTo }, currentTop * 2);

		    },
		    scrollStop: function() {
		        this.scrollContent.stop();

		    },
		    updateGroupLabel: function() {
		        var container = this.container;
		        var groups = container.find(".group");
		        var groupLabels = container.find(".group .label");
		        var numGroups = groups.length;


		        var sticky = container.find(".sticky");
		        var stickyLeft = sticky.find(".left");
		        var stickyRight = sticky.find(".right");

		        var stickyOffset = sticky.offset();

		        var maxGroupOffset = -1;
		        var groupIndex = 0;

		        var currentLabel;

		        var group = groups.eq(0);
		        var groupOffset = group.offset();
		        for (i = 0; i < numGroups; i++) {
		            group = groups.eq(i);
		            groupOffset = group.offset();

		            if (groupOffset.top <= stickyOffset.top) {
		                maxGroupOffset = groupOffset.top;
		                groupIndex = i;
		            }
		        }

		        currentLabel = groupLabels.eq(groupIndex);
		        sticky.html(currentLabel.html());


		    },
		    scrollDetect: function() {

		        var container = this.container;
		        var groups = container.find(".group");
		        var groupLabels = container.find(".group .label");
		        var numGroups = groups.length;



		        var sticky = container.find(".sticky");
		        var stickyLeft = sticky.find(".left");
		        var stickyRight = sticky.find(".right");

		        var stickyOffset = sticky.offset();
		        //stickyLeft.text(stickyOffset.top + "(" + numGroups + ")");

		        var maxGroupOffset = 0;
		        var groupIndex = 0;

		        var currentLabel;

		        var group = groups.eq(0);
		        var groupOffset = group.offset();
		        this.interval = setInterval(function() {
		            for (i = 0; i < numGroups; i++) {
		                group = groups.eq(i);
		                groupOffset = group.offset();

		                if (groupOffset.top < stickyOffset.top && groupOffset.top > maxGroupOffset) {
		                    maxGroupOffset = groupOffset.top;
		                    groupIndex = i;
		                }
		            }

		            //console.debug(groupIndex);
		            currentLabel = groupLabels.eq(groupIndex);
		            sticky.html(currentLabel.html());
		            //					stickyLeft.text()
		            //					stickyRight.text(groups.eq(groupIndex).find(".label .left").text());
		        }, 30);
		    },
		    scrollUndetect: function() {
		        clearInterval(this.interval);
		    },
		    bindEvents: function() {
		        var scrollable = this;

		        this.scrollUpElement.live("mousedown", function() {
		            //scrollable.scrollDetect();
		            scrollable.scrollUp();

		        }).live("mouseup", function() {
		            scrollable.scrollStop();
		            //scrollable.scrollUndetect();
		            scrollable.updateGroupLabel();

		        }).mouseout(function() {
		            //scrollable.scrollStop();	
		            //scrollable.scrollUndetect();
		            //scrollable.updateGroupLabel();
		        });

		        this.scrollDownElement.live("mousedown", function() {
		            //scrollable.scrollDetect();
		        scrollable.scrollDown();
		        enableDocumentSelection(false);

		        }).live("mouseup", function() {

		        scrollable.scrollStop();
		        enableDocumentSelection(true);
		            //scrollable.scrollUndetect();
		            scrollable.updateGroupLabel();

		        }).mouseout(function() {
		            //scrollable.scrollStop();
		            //scrollable.scrollUndetect();
		            //scrollable.updateGroupLabel();

		        });
		    }
		});
		
		
		
		
		//DiFR
		$.fn.DiFR = function(options) {
			//Plugin Defaults
			var defaults = {
				color:				"000000",
				spacing:			"normal",
				style:				"normal",
				size:				"16",
				kerning:			"normal",
				backgroundColor:	"transparent",
				rollover:			false,
				rolloverColor:		"0000EE",
				rolloverClass:		"hover",
				asBackground:		false,
				lineHeight:			16,
				cacheXmlPath:		VirtualDirectory + "/_config/difr-cache.xml",
				cacheImagePath:		"/images/difr/",
				DiFRPath:			VirtualDirectory + "/services/difr.ashx"
			};
			
			// Extend/Combine options with our defaults
			var opts = $.extend({}, defaults, options);
			
			var init = function(initOptions) {
				defaults = $.extend(defaults, initOptions);
			}
			
			var randomnumber=Math.floor(Math.random()*11009343)
			var cacheXml =  fnLoadXml(opts.cacheXmlPath + "?t=" + randomnumber);
			
			var selector = this.selector;
			
			var tmp = 1;
			
			return this.each(function() {
				
				var item = $(this);
				//item.hide();
				var content = $.trim(item.html());
				
				//Remove strong|em tags
				content = content.replace("<strong>", "");
				content = content.replace("</strong>", "");
				content = content.replace("<em>", "");
				content = content.replace("</em>", "");
				content = content.replace("'", "%27");
				
				
				if (item.css("text-transform") == "uppercase") content = content.toUpperCase();
				
				var font = {};
				
				font.size = item.css("font-size").replace("px", "");
				
				var familyComma = item.css("font-family").indexOf(",");
				if (familyComma > -1) {
					font.family = item.css("font-family").substr(0, familyComma);				
				}
				else {
					font.family = item.css("font-family").replace('"', "");
				}
				
				font.color = item.css("color");
					if (!$.browser.msie) font.color = rgbToHex(font.color);
				font.color = font.color.replace("#", "");
				
				
				if (options.kerning) font.kerning = options.kerning;
				else font.kerning = item.css("letter-spacing").replace("px", "");
				if (font.kerning == "normal") font.kerning = 0;
				
				font.lineHeight = item.css("line-height").replace("px", "");
				if (font.lineHeight == "normal") font.lineHeight = opts.lineHeight;
				
				font.style = item.css("font-weight");
				if (font.style == "normal") font.style = "regular";
				try {if (parseInt(font.style) > 100) font.style = "bold" } catch (e) {}
				
				
				font.wordSpacing = item.css("word-spacing").replace("px", "");
				if (font.wordSpacing == 0) font.wordSpacing = opts.spacing;
				
				if (opts.rollover)
				{
					if (!$.browser.msie) opts.rolloverColor = rgbToHex(item.css("outline-color")).replace("#", "");
					else opts.rolloverColor = item.css("outline-color").replace("#", "");
				}
				
				/************
				 * Check the cache xml
				 */
				cacheFileName = fnCompressString(removeAll(removeAll(content, " "), ".") + font.size + font.color + font.lineHeight + font.style + font.kerning);
				
				if (opts.rollover)
				{
					cacheFileName += "_" + opts.rolloverColor;	
				}
				
				cacheFileName = cacheFileName.toUpperCase();
				cacheFileName = removeAll(cacheFileName, "<BR>");
				cacheFileName = removeAll(cacheFileName, "<BR />");
				cacheFileName = removeAll(cacheFileName, ".");
				cacheFileName = removeAll(cacheFileName, ",");
				cacheFileName = removeAll(cacheFileName, "'");
				cacheFileName = removeAll(cacheFileName, "’");
				cacheFileName = removeAll(cacheFileName, "&");
				
				var isCached = false;
								
//				alert($(cacheXml).find("difr-images").length);
				/*
				$(cacheXml).find("image").each(function() {
					//alert($(this).attr("file"));
					
					if ($(this).attr("file") == cacheFileName) {
					    cacheWidth = parseFloat($(this).attr("w"));
					    cacheHeight = parseFloat($(this).attr("h"));
					    isCached = true;
					}
				    });
		*/
				
				var cachedImage = $(cacheXml).find("image[file=" + cacheFileName + "]");
				
				if (cachedImage.length > 0) {
					isCached = true;
					cacheWidth = parseFloat(cachedImage.attr("w"));
					cacheHeight = parseFloat(cachedImage.attr("h"));
				}
				
				
				var difrSource = new String();
				if (isCached) {
					difrSource = VirtualDirectory + opts.cacheImagePath + cacheFileName + ".png";
					
				}
				else {
					//alert(cacheFileName);
				
					/************
					 * Make the Request to DiFR backend
					 */
					difrSource = opts.DiFRPath + "?text=" + encodeURIComponent(content) +
								"&font=" +								font.family +
								"&style=" +								font.style +
								"&size=" +								font.size +
								"&color=" +								font.color +
								"&backgroundColor=" +					opts.backgroundColor +
								"&lineheight=" +						font.lineHeight +
								"&kerning=" +							font.kerning +
								"&spacing=" +							font.wordSpacing +
								"&withRollover=" +						opts.rollover +
								((opts.rollover) ? "&rolloverColor=" + opts.rolloverColor : "");
				}
				
				var image = new Image()
				image.src = difrSource;
				
				

				
				item.empty().append("<span style='display: none'>" + content + "</span>");
				if (opts.rollover) {
					
					runOnLoad(function(){
						var rolloverHeight = 0;
						rolloverHeight = parseFloat(image.height) / 2;
						
						item.css({
							background: "transparent url(" + difrSource + ") no-repeat",
							display: "block",
							height: rolloverHeight + "px",
							width: image.width + "px"
						});
						item.hover(function(){
							var hoverShift = rolloverHeight;
							
							if ($.browser.msie && $.browser.version == "6.0")
							{
								hoverShift = hoverShift - 1;
							}
								
							item.css("background-position", "0 -" + hoverShift + "px");
						}, function(){
							item.css("background-position", "0 0");
						})
					});
				} else {
					item.append(image);
				}
				
				item.show();
				
				
			});
		};
		
		
/*********************************************
* HELPERS
**********************************************/

function padZero(number, length) {
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
   
    return str;
}


function rgbToHex(rgb) {
	var rgbvals = /rgb\((.+),(.+),(.+)\)/i.exec(rgb);
	var rval = parseInt(rgbvals[1]);
	var gval = parseInt(rgbvals[2]);
	var bval = parseInt(rgbvals[3]);

	return '#' + (getRGBzeros(rval.toString(16)) + getRGBzeros(gval.toString(16)) + getRGBzeros(bval.toString(16))).toUpperCase();

}
function fnLoadXml(sURL){
    var returnXml;
    
    var xResponse = $.ajax({
        type: "GET",
        url: sURL,
        dataType: "XML",
        async: false
    });
    
    return xResponse.responseXML;
}

function parseXml(xml) {  
  if ($.browser.msie) {  
    var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");  
    xmlDoc.loadXML(xml);  
    xml = xmlDoc;  
  }  
  return xml;  
}

function getRGBzeros(scolorVal) {
	if (scolorVal.length < 2) {
		scolorVal = "0" + scolorVal;
	}
	return scolorVal;
}
function fnCompressString(strIn){

//was using hashing, found it was overkill - oliver

    strIn = removeAll(strIn);
    strIn = removeAll(strIn,"'");
    strIn = removeAll(strIn,":");
    strIn = removeAll(strIn,"&COPY;");
    strIn = removeAll(strIn,"&AMP;");
    strIn = removeAll(strIn,";");
    strIn = removeAll(strIn,"#");
    strIn = removeAll(strIn,"?");
    strIn = removeAll(strIn,"%20");
    strIn = removeAll(strIn,"�");
    strIn = removeAll(strIn,"&");
    strIn = removeAll(strIn,",");
    
    return strIn;    
}

function removeAll(strIn, reStr){
    var strReturn = "";
    strArr = strIn.split(reStr);
    for(var i = 0;i<strArr.length;i++)
    {
       strReturn = strReturn + strArr[i].replace(reStr,"");
    }
    return strReturn;
}



function enableDocumentSelection(enable) {
    if (enable) {
        document.onselectstart = _original_onselectstart;
    }
    else {
        _original_onselectstart = document.onselectstart;
        document.onselectstart = function() { return false; }
    }
}