/* Released: 2010-03-11 16:50:57 */

//stop js error from legacy stuff
if (typeof stopBanner == 'undefined') {
	function stopBanner(){
		logTo('Cannot find stopBanner()');
	};
}

$gJQ(document).ready(function(){
	var pdmw = new ProductDetailMediaWindow();
	pdmw.init();
});

/**
 * @class ProductDetailMediaWindow
 */
function ProductDetailMediaWindow() {
	var me = this;
	
	function _doInit() {
		if (typeof infoWindow == 'undefined') {
			logTo('Error: InfoWindow needs jQuery plugin infoWindow to be loaded.');
			return;
		}
		
		$gJQ('.benefit-list a').each(function(){
			switch($gJQ(this).attr('type')) {
				case 'image':
					$gJQ(this).click(function(e){
						e.preventDefault();
						me.loadImage(this);
					})
					.mouseenter(function(){
						//prefetch lightbox image when user hovers over link and save some loading time
						me._preFetchImage($gJQ(this).attr('href'));
					});
					break;
				case 'flash':
					$gJQ(this).click(function(e){
						e.preventDefault();
						me.loadFlash(this);
					});
					break;
				default:
			 		//do nothing and follow link
			}
		});
        $gJQ('.banner a.flash-video').each(function(){
            $gJQ(this).click(function(e){
                e.preventDefault();
                me.loadFlash(this);
            });
		});      
        $gJQ('.banner area.flash-video').each(function(){
            $gJQ(this).click(function(e){
                e.preventDefault();
                $gJQ('.banner a.flash-video').trigger('click');
            });
		});   
	}
	
	return {
		init : function() {
			_doInit();
		}
	}

}

ProductDetailMediaWindow.prototype = {
	
	_imageDimensionCache : {},
	
	_htmlChunk : {
		bodyTop : '<div class="top"><div class="tl"></div></div><div class="close"></div>',
		//footer : '<div class="btm"><div class="bl"></div></div>',
		whiteBodyMiddle : '<div class="middle"><div class="ml">',
		whiteBodyBottom : '</div></div><div class="btm"><div class="bl"></div></div>',
		grayBodyMiddle  : '<div class="gray"><div class="middle"><div class="ml">',
		grayBodyBottom  : '</div></div><div class="btm"><div class="bl"></div></div></div>'
	},
	
	loadImage : function(el) {
		var me = this;
		var html;
		var href = $gJQ(el).attr('href');
		
		me._getImageDimension(href, {onSucces:__doLoadImage, onError:__onError});
		
		function __doLoadImage(imageDimension) {
			html = me._htmlChunk.whiteBodyMiddle +
				"<img src='" + href + "' width='"+ imageDimension[0] +"' height='"+ imageDimension[1] +"'/>" + 
				me._htmlChunk.whiteBodyBottom;
			
			infoWindow(html, {htmlStart:me._htmlChunk.bodyTop}, function(){
				me._ieInfoWindowWidthFix(imageDimension[0]);
			});
		}
		
		function __onError() {
			//TODO Implement generic error image
			alert('Sorry, unable to load image...');
		}
		
	},
	
	loadFlash : function(el) {
		var properties = this._getProperties(el);	//get properties from rev-attribuut
		var xmlUrl = properties.xmlurl;	//source file for player
		var xmlVar = properties.xmlvar;	//source file for player
		
		//mandatory options
		var options = {
			flashUrl : properties.flashurl,	//actual player
			width : properties.width,
			height : properties.height,
			expressInstall : properties.expressinstall
		};
		
		//optional options
		if(properties.image)        options["image"]        = properties.image;
		if(properties.flashversion) options["flashVersion"] = properties.flashversion;
		if(xmlVar && xmlUrl) {
			options["flashVars"] = {};
			options["flashVars"][xmlVar] = xmlUrl;
		}
		
		this._loadSwf(options);
	},
	
	_loadSwf : function(opts) {
		var me = this;
		var flashSetting = {htmlReplaceId : 'infowindow_swfobject'};
		flashSetting = $gJQ.extend(flashSetting, opts);
		
		var html = me._htmlChunk.whiteBodyMiddle;
			html += "<div class='loading'>";
				html += "<div id='" + flashSetting.htmlReplaceId + "' style='width:"+ flashSetting.width +"px; height:"+ flashSetting.height +"px;'>";
				if (opts.image) {
					html += "<img src='" + opts.image + "' />"
				}
				html += "</div>";	//replacement div
			html += "</div>";	//loading
			html += me._htmlChunk.whiteBodyBottom;
		
		//create lightbox
		infoWindow(html, {htmlStart:me._htmlChunk.bodyTop}, function(){
			me._ieInfoWindowWidthFix(flashSetting.width);
		});

		//inject video player after light has been created
		new SWFLoader(flashSetting);
	},
	
	_getImageDimension : function(url, opts) {
		var me = this;
		var imageDimension = [320, 240];	//default
		
		if (me._imageDimensionCache[url]) {
			if(opts.onSucces) opts.onSucces(me._imageDimensionCache[url]);
			return;
		}
		
		$gJQ("<img />").attr('src', url).css('display', 'none').appendTo('body')
			.load(function(){
				imageDimension = [$gJQ(this).width(), $gJQ(this).height()];
				me._imageDimensionCache[url] = imageDimension;
				$gJQ(this).remove();
				if(opts.onSucces) opts.onSucces(imageDimension);
			})
			.error(function(){
				$gJQ(this).remove();
				if(opts.onError) opts.onError();
			});
		
	},
	
	_getProperties : function(el) {
		//rev="width::200;;height::200;;flashurl::http://lakdflsdafj"
		var properties = {};
		var p = $gJQ(el).attr("rev").split(";;");
		for(var i in p) {
			var re = p[i].split("==");
			properties[re[0].toLowerCase()] = re[1];
		}
		return properties;
	},
	
	_preFetchImage : function(url) {
		var me = this;
		me._getImageDimension(url, {});
	},
	
	_ieInfoWindowWidthFix : function(w) {
		//fixing IE6/7 width problem, #infowindow_content needs fixed width
		if(w && ( $gJQ.browser.msie && parseInt($gJQ.browser.version) <= 7 )) {
			var w = w;
			var middle_padding = parseInt($gJQ('#infowindow_content .middle').css('padding-left'));
			var ml_padding     = parseInt($gJQ('#infowindow_content .middle .ml').css('padding-left')) +
								 parseInt($gJQ('#infowindow_content .middle .ml').css('padding-right'));
			var padding;
			try {
				padding = middle_padding + ml_padding;
			} catch (error) {
				padding = 0;
			}
			
			w = padding + parseInt(w);		//70 = right/left padding
			$gJQ('#infowindow_content').width(w);
			$gJQ(window).trigger('resize');
		}
	}

};

/**
 * @class SWFLoader
 * @example new SWFLoader(options) 
 */
function SWFLoader(opts) {
	this.init(opts);
}

SWFLoader.prototype = {
	_defaults : {
		flashUrl : null,
		htmlReplaceId : null,
		width : 480,
		height : 272,
		flashVersion : '9.0.18',
		expressInstall : null,
		flashVars : null,
		params : {menu:'false', quality:'high', wmode:'opaque', allowscriptaccess:'always', allowfullscreen:'true'},
		attributes : null,
		callback : null
	},
	
	init : function(opts) {
		var settings = $gJQ.extend(this._defaults, opts);
		this._createVideoPlayer(settings);
	},
	
	_createVideoPlayer : function(opts) {
		opts.callback = opts.callback || onCallback;
		
		try {
			swfobject.embedSWF(	opts.flashUrl,
								opts.htmlReplaceId,
								opts.width,
								opts.height,
								opts.flashVersion,
								opts.expressInstall,
								opts.flashVars,
								opts.params,
								opts.attributes,
								opts.callback );
		}
		catch(e){ logTo(e.message) }
		
		function onCallback(e) {
			if(e && !e.succes) onError(e);
		}	
		
		function onError(e) {
			$gJQ('#'+e.id).append('<a href="http://get.adobe.com/flashplayer/" target="_BLANK"><img border="0" width="112" height="33" style="position:relative; margin-left:50%; left:-56px;" alt="Get Adobe Flash Player" src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif"></a>');
		}
	}
};
