/* Infiniti specific jQuery plugins */
(function (jQuery){
	jQuery.infiniti = {};
	/* launch popup windows from promo or specific page
	 * use with size: fullscreen,fixed
	 * with fixed, specify height, width, top, left
	 * depends on jQuery.cookie plugin when checking cookie before showing popup
	 */
    jQuery.infiniti.promoPopup = function(options) {
        options = jQuery.extend({
            url: "",
            size: "fullscreen",
            height: "auto",
            width: "auto",
            top: "0",
            left: "0",
            name: "popup",
            cookie: null,
            autofocus: false,
            extra: ""
        },
        options);
        if (options.cookie !== null && options.cookie.length > 0 && jQuery.cookie && jQuery.cookie(options.cookie) !== null && (jQuery.cookie(options.cookie).length > 0 || jQuery.cookie("nopopups") == "true")) {
            return jQuery;
        }
        var size = "";
        switch (options.size) {
        case "fullscreen":
            size = "fullscreen,type=fullWindow";
            break;
        case "fixed":
        default:
            size = "width=" + options.width + ",height=" + options.height + ",top=" + options.top + ",left=" + options.left;
        }
		//check the cookie - if no cookie value is set, or if the value isn't correct show the popup
		var myName = options.name;
		var cookieVal = jQuery.cookie(myName);
		
		if(!cookieVal){
	        var win = window.open(options.url, options.name.replace(/\s*/ig, ""), size + (options.extra.length > 0 ? "," + options.extra: ""));
	        if (!win) {
	            win = window.open('', options.name.replace(/\s*/ig, ""), size + (options.extra.length > 0 ? "," + options.extra: ""));
	            if (win) {
	                win.location.href = options.url;
	            }
	        }
	        if (options.autofocus !== null && options.autofocus && win) {
	            win.focus();
	        }
	        
	        jQuery.cookie(myName, myName)
		};
		
		return jQuery;
	};

	/* jQuery flash event handler, allows you to bind custom "flashEvent" events, which flash will pass {event: <event>, state: <state>, ...} into */
	jQuery.fn.flashEvent=function (options) {
		var $$ = jQuery(this);
		if (typeof(options)=='function') {
			$$.bind("flashEvent",options);
		} else {
			$$.trigger("flashEvent",[options]);
		}
	};

	/* Provide a "Preview" Layer on Hover for showing larger views of images and popup detail items */
	jQuery.fn.preview=function (options) {
		var $$ = jQuery(this);
		options = jQuery.extend({
				offset: {x: 10, y: 15},
				attribute: "rel",
				type: "image",
				id: "previewPluginPreviewElement",
				trigger: "hover",
				style: "simple",
				closeText: "X",
				position: "offset"
				},options);
		$$.data("preview.options",options);
		if (options.trigger=="hover") {
			$$.hover(jQuery.fn.preview.hoverIn,jQuery.fn.preview.hoverOut).mousemove(jQuery.fn.preview.mousemove);
		};
		if (options.trigger=="toggle") {
			$$.toggle(jQuery.fn.preview.hoverIn,jQuery.fn.preview.hoverOut);
		};
		
		return this;
	};
	jQuery.fn.preview.hoverIn=function(e) {
		var options = jQuery(this).data("preview.options");
		var $$ = jQuery(this);
		var preview = [];
		if (this.title.length > 0) {
			this.title = options.title ? options.title : this.title ? this.title : this.alt ? this.alt : "";
		}
		preview.push("<div id=\""+options.id+"\">");
		// close button
		if (options.trigger=="toggle") { preview.push("<a class=\"closeButton\" href=\"javascript:void(null)\">"+options.closeText+"</a>"); };
		switch(options.type) {
			case "image":
			case "img":
				var attr = $$.attr(options.attribute).split("|");
				preview.push('<table border="0" cellspacing="0" cellpadding="0"><tr><td align="center">');

				preview.push("<img src=\""+attr[0]+"\"");
				//using webdav gives incorrect dimensions- so we check to see how large it's reporting 
				if ((attr.length > 2)&&(parseInt(attr[1])>5)){
					preview.push(" width=\""+attr[1]+"\" height=\""+attr[2]+"\"");
				}

				preview.push(">");
				preview.push('</td></tr>');
				break;
			case "html":
				preview.push(jQuery($$.attr(options.attribute)).html());
				break;
		}
		if (options.style=="slideshow") {
			// add controls for prev/next
			//table elements had to be added, because webdav does not supply image width-
			//using divs, this causes a problem in ie6 where the preview window would be 100% of screen width
			//we fix this using tables...
			if (options.nextLabel.length>0) {var nextLabel=options.nextLabel} else {var nextLabel='&gt;';}
			if (options.prevLabel.length>0) {var prevLabel=options.prevLabel} else {var prevLabel='&lt;';}
						
				preview.push('<tr><td align="center"><table border="0" cellspacing="0" cellpadding="0"><tr><td valign="middle">');

				//if ((attr.length > 2)&&(parseInt(attr[1])>5)){var thisWidth="width: "+attr[1]+"px;"} else {var thisWidth="";}
				preview.push('<div class="slideshow">');	

			if ($$.data("prev")) {			
				preview.push("<img id=\"previousImg\" src=\""+cmsContext+"/img/icons/page-prev.png\" alt=\""+prevLabel+"\" />");
			} else {
				preview.push("<img id=\"previousImg\" src=\""+cmsContext+"/img/icons/page-prev-off.png\" alt=\""+prevLabel+"\" />");
			};

				preview.push('</div></td><td valign="middle">');

			if (options.ofWord) {
				var idInt=$$.data("idInt");
				preview.push('<span class="previewCounter">'+idInt+options.ofWord+$$.data("intMax")+'</span>');
			}			

				preview.push('</td><td valign="middle">');
				preview.push('<div class="slideshow">');
			if ($$.data("next")) {
				preview.push("<img id=\"nextImg\" src=\""+cmsContext+"/img/icons/page-next.png\" alt=\""+nextLabel+"\" />");				
			} else {
				preview.push("<img id=\"nextImg\" src=\""+cmsContext+"/img/icons/page-next-off.png\" alt=\""+nextLabel+"\" />");
			};
				preview.push('</div></td></tr></table></td></tr></table>');

		}
	
		if (this.title.length > 0) {
			preview.push("<p>"+this.title+"</p>");
		};
		preview.push("</div>");
		jQuery("body").append(preview.join(""));
		var $p = jQuery("#"+options.id);
		if (options.trigger=="toggle") {
			$p.get(0).triggerElement = $$;
			$p.click(function(){
					this.triggerElement.click();
			});
		};
		if (options.style=="slideshow") {
			jQuery(".slideshow img").data("triggerElement",$$);
			if (jQuery.fn.ifixpng) jQuery(".slideshow img").ifixpng();
			jQuery(".slideshow img:eq(0)").click(function() {
				jQuery(jQuery(this).data("triggerElement").click().data("prev")).click();
			});
			jQuery(".slideshow img:eq(1)").click(function() {
				jQuery(jQuery(this).data("triggerElement").click().data("next")).click();
			});
		};
		if (options.callback) { options.callback.apply(this); };
		switch (options.position) {
			case "offset":
				$p.css({"left":(e.pageX+options.offset.x)+"px","top":(e.pageY+options.offset.y)+"px"}).show();
				break;
			case "center":
				var top = jQuery(window).scrollTop()+((jQuery(window).height()-jQuery("#"+options.id).height())/2);
				var left = jQuery(window).scrollLeft()+((jQuery(window).width()-jQuery("#"+options.id).width())/2);
				$p.css({"left":left+"px","top":top+"px"}).show();
				break;
		};
	};
	jQuery.fn.preview.hoverOut=function(e) {
		var options = jQuery(this).data("preview.options");
		jQuery("#"+options.id).hide().remove();
	};
	jQuery.fn.preview.mousemove=function(e) {
		var options = jQuery(this).data("preview.options");
		jQuery("#"+options.id).css({"left":(e.pageX+options.offset.x)+"px","top":(e.pageY+options.offset.y)+"px"});
	};

	// Reload images in IE which have not loaded properly
	jQuery.fn.iefiximg=function(returnType) {
		var t = jQuery(this);
		var tcount = 0;
		if (jQuery.browser.msie && jQuery.browser.version<7) {
			t.each(function(){
				var t = jQuery(this);
				if (this.readyState == "uninitialized" || this.readyState == "loading") {
					var attempts = t.data("iefiximg_attempts");
					attempts = !!attempts ? parseInt(attempts,10) : 0;
					if (attempts < 3) {
						if (!this.src || (this.src && this.src.indexOf("metrics")==-1)) {
							t.removeClass("gImgPNG");
							t.iunfixpng();
							var clon = t.clone(true);
							t.replaceWith(clon);
							t = clon;
							t.ifixpng();
						}
						t.data("iefiximg_attempts",attempts+1);
						tcount++;
					}
				};
			});
		};
		return returnType == "count" ? tcount : t;
	};
	jQuery.iefiximg=function(iteration) {
			if (jQuery("img").iefiximg("count") > 0 && !!iteration) {
				setTimeout(function(){ jQuery.iefiximg(iteration); }, iteration);
			};
		return jQuery;
	};
})(jQuery);

/*
 * jQuery ifixpng plugin
 * (previously known as pngfix)
 * with another plugin
 * Version 1.9  (27/09/2007)
 * @requires jQuery v1.1.3 or above
 *
 * Examples at: http://jquery.khurshid.com
 * Copyright (c) 2007 Kush M.
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */

 /**
  *
  * @example
  *
  * optional if location of pixel.gif if different to default which is images/pixel.gif
  * jQuery.ifixpng('media/pixel.gif');
  *
  * jQuery('img[@src$=.png], #panel').ifixpng();
  *
  * @apply hack to all png images and #panel which icluded png img in its css
  *
  * @name ifixpng
  * @type jQuery
  * @cat Plugins/Image
  * @return jQuery
  * @author jQuery Community
  */

(function(jQuery) {

	/**
	 * helper variables and function
	 */
	jQuery.ifixpng = function(customPixel) {
		jQuery.ifixpng.pixel = customPixel;
	};

	jQuery.ifixpng.getPixel = function() {
		return jQuery.ifixpng.pixel || (typeof(cmsContext)!="undefined"?cmsContext:cmsContext=(document.location.pathname.indexOf("/author")==0?"/author":"")) + '/img/global/spacer.gif';
	};

	var hack = {
		ltie7  : jQuery.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent),
		filter : function(src,method) {
			return "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod='"+method+"',src='"+src+"')";
		}
	};

	/**
	 * Applies ie png hack to selected dom elements
	 *
	 * jQuery('img[@src$=.png]').ifixpng();
	 * @desc apply hack to all images with png extensions
	 *
	 * jQuery('#panel, img[@src$=.png]').ifixpng();
	 * @desc apply hack to element #panel and all images with png extensions
	 *
	 * @name ifixpng
	 */

	jQuery.fn.ifixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = jQuery(this);
			var base = jQuery('base').attr('href'); // need to use this in case you are using rewriting urls
			if ($$.is('img') || $$.is('input')) { // hack image tags present in dom
				if ($$.attr('src')) {
					if ($$.attr('src').match(/.*\.png([?].*)?$/i)) { // make sure it is png image
						// use source tag value if set
						var source = (base && $$.attr('src').substring(0,1)!='/') ? base + $$.attr('src') : $$.attr('src');
						// apply filter
						var w = $$.width();
						var h = $$.height();
						if (w == 0) w = $$.attr("width");
						if (h == 0) h = $$.attr("height");
						if (w == 0) w = "auto";
						if (h == 0) h = "auto";
						$$.css({filter:hack.filter(source,"image"), width: w, height: h})
						  .attr({src:jQuery.ifixpng.getPixel()})
						  .positionFix();
					}
				}
			} else { // hack png css properties present inside css
				var image = $$.css('backgroundImage');
				if (image.match(/^url\(["']?(.*\.png([?].*)?)["']?\)$/i)) {
					image = RegExp.$1;
					$$.css({backgroundImage:'none', filter:hack.filter(image,"scale")})
					  .children().positionFix();
				}
			}
		});
	} : function() { return this; };

	/**
	 * Removes any png hack that may have been applied previously
	 *
	 * jQuery('img[@src$=.png]').iunfixpng();
	 * @desc revert hack on all images with png extensions
	 *
	 * jQuery('#panel, img[@src$=.png]').iunfixpng();
	 * @desc revert hack on element #panel and all images with png extensions
	 *
	 * @name iunfixpng
	 */

	jQuery.fn.iunfixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = jQuery(this);
			var src = $$.css('filter');
			if (src.match(/src=["']?(.*\.png([?].*)?)["']?/i)) { // get img source from filter
				src = RegExp.$1;
				if ($$.is('img') || $$.is('input')) {
					$$.attr({src:src}).css({filter:''});
				} else {
					$$.css({filter:'', background:'url('+src+')'});
				}
			}
		});
	} : function() { return this; };

	/**
	 * positions selected item relatively
	 */

	jQuery.fn.positionFix = function() {
		return this.each(function() {
			var $$ = jQuery(this);
			var position = $$.css('position');
			if (position != 'absolute' && position != 'relative') {
				$$.css({position:'relative'});
			}
		});
	};

})(jQuery);

/**
 * jQuery.Preload
 * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com
 * Dual licensed under MIT and GPL.
 * Date: 3/12/2008
 *
 * @projectDescription Multifunctional preloader
 * @author Ariel Flesler
 * @version 1.0.7
 *
 * @id jQuery.preload
 * @param {String, jQuery, Array< String, <a>, <link>, <img> >} original Collection of sources to preload
 * @param {Object} settings Hash of settings.
 *
 * @id jQuery.fn.preload
 * @param {Object} settings Hash of settings.
 * @return {jQuery} Returns the same jQuery object, for chaining.
 *
 * @example Link Mode:
 *	$.preload( '#images a' );
 *
 * @example Rollover Mode:
 *	$.preload( '#images img', {
 *		find:/\.(gif|jpg)/,
 *		replace:'_over.$1'
 *	});
 *
 * @example Src Mode:
 *	$.preload( [ 'red', 'blue', 'yellow' ], {
 *		base:'images/colors/',
 *		ext:'.jpg'
 *	});
 *
 * @example Placeholder Mode:
 *	$.preload( '#images img', {
 *		placeholder:'placeholder.jpg',
 *		notFound:'notfound.jpg'
 *	});
 *
 * @example Placeholder+Rollover Mode(High res):
 *	$.preload( '#images img', {
 *		placeholder:true,
 *		find:/\.(gif|jpg)/,
 *		replace:'_high.$1'
 *	});
 */
;(function( $ ){

	var $preload = $.preload = function( original, settings ){
		/* if( original.split )//selector
			original = $(original); */

		if (typeof(original)=='undefined') { return original; }

		settings = $.extend( {}, $preload.defaults, settings );
		var sources = $.map( original, function( source ){
			if( !source ) {
				return; } //skip
			if( source.split )//URL Mode
				{ return settings.base + source + settings.ext; }
			var url = source.src || source.href;//save the original source
			if( typeof settings.placeholder == 'string' && source.src )//Placeholder Mode, if it's an image, set it.
				{ source.src = settings.placeholder; }
			if (settings.rel)
				{ url = source.rel; }
			if( url && settings.find )//Rollover mode
				{ url = url.replace( settings.find, settings.replace ); }
			return url || null;//skip if empty string
		});

		var data = {
			loaded:0,//how many were loaded successfully
			failed:0,//how many urls failed
			next:0,//which one's the next image to load (index)
			done:0,//how many urls were tried
			//found:false,//whether the last one was successful
			total:sources.length//how many images are being preloaded overall
		};
		
		if( !data.total ) {//nothing to preload
			return finish();
		}
		var imgs = '<img/>',//ensure one
			thres = settings.threshold;//save a copy
		
		while( --thres > 0 ) {//it could be oddly negative
			imgs += '<img/>'; }
		imgs = $(imgs).load(handler).error(handler).bind('abort',handler).each(fetch);
		
		function handler( e ){
			data.found = e.type == 'load';
			data.image = this.src;
			var orig = data.original = original[this.index];
			data[data.found?'loaded':'failed']++;
			data.done++;
			if( settings.placeholder && orig.src ) {//special case when on placeholder mode
				orig.src = data.found ? data.image : settings.notFound || orig.src;
			}
			if( settings.onComplete ) {
				settings.onComplete( data );
			}
			if( data.done < data.total ) { //let's continue
				fetch( 0, this );
			} else{//we are finished
				if( imgs.unbind )//sometimes IE gets here before finishing line 84
					imgs.unbind('load').unbind('error').unbind('abort');//cleanup
				imgs = null;
				finish();
			}
		};
		function fetch( i, img, retry ){
			if( $.browser.msie && data.next && data.next % $preload.gap == 0 && !retry ){//IE problem, can't preload more than 15
				setTimeout(function(){ fetch( i, img, true ); }, 0);
				return false;
			}
			if( data.next == data.total ) return false;//no more to fetch
			img.index = data.next;//save it, we'll need it.
			img.src = sources[data.next++];
			if( settings.onRequest ){
				data.image = img.src;
				data.original = original[data.next-1];
				settings.onRequest( data );
			}
		};
		function finish(){
			if( settings.onFinish ) {
				settings.onFinish( data );
			}
		};
	};

	// each time we load this amount and it's IE, we must rest for a while, make it lower if you get stack overflow.
	$preload.gap = 14; 

	$preload.defaults = {
		threshold:2,//how many images to load simultaneously
		base:'',//URL mode: a base url can be specified, it is prepended to all string urls
		ext:'',//URL mode:same as base, but it's appended after the original url.
		replace:''//Rollover mode: replacement (can be left empty)
		/*
		find:null,//Rollover mode: a string or regex for the replacement
		notFound:''//Placeholder Mode: Optional url of an image to use when the original wasn't found
		placeholder:'',//Placeholder Mode: url of an image to set while loading
		onRequest:function( data ){ ... },//callback called every time a new url is requested
		onComplete:function( data ){ ... },//callback called every time a response is received(successful or not)
		onFinish:function( data ){ ... }//callback called after all the images were loaded(or failed)
		*/
	};

	$.fn.preload = function( settings ){
		$preload( this, settings );
		return this;
	};

})( jQuery );
jQuery(document).ready(function(){jQuery.iefiximg(5000);});
