(function(jQuery) {
	jQuery.fn.mgclightbox = function(settings) {
		settings = jQuery.extend({
		}, settings);
		var $group = this;
		if(typeof STATIC_ASSET_DOMAIN_LOGIC==="undefined"){
			STATIC_ASSET_DOMAIN_LOGIC=function(p){return p;};
		}

	//lightbox
		$group.each(function(){
		
			var $this = jQuery(this);
			var flashReg = /\.swf$/i;
			var imageReg = /(\.gif$)|(\.jpg$)|(\.png$)/i;
			var contentHref = $this.attr("href");
			var contentType = null;
			var cacheHeight = null;
			var cacheWidth = null;
			if(flashReg.test(contentHref)||$this.hasClass("lb_flash")){
				contentType = 'flash';
			}else if(imageReg.test(contentHref)||$this.hasClass("lb_image")){
				contentType = 'image';
			}else if($this.hasClass("lb_iframe")){
				contentType = 'iframe';
			}
			if(contentType=='image'&&!$this.hasClass("button")){
				$this.prepend('<span class="zoom"></span>')
			}

			$this.click(function(){
				
				$group.removeClass("mgclightboxed");
				$this.addClass("mgclightboxed");	
				
				jQuery('embed, object, select').css('visibility', 'hidden');
				jQuery(window).resize(lb_positionBoxes);
				
				//var $overlay = jQuery('<div id="lb-overlay"></div>');
				//var $viewer = jQuery('<div id="lb-viewer"></div>');
				//var $internal = jQuery('<div id="lb-internal"></div>');
				//var $toprow = jQuery('<div id="lb-toprow"></div>');
				//var theTitle = $this.attr("title")
				//var $titleDiv = jQuery('<div class="lightboxtitle"></div>');
				var $overlay = jQuery('<div id="lb-overlay"></div>');
				
				//var html = '<div id="lb-viewer"> \
			    //              <table id="zoom_table"> \
			    //                <tbody> \
			    //                  <tr> \
			    //                    <td class="tl">&nbsp;</td> \
			    //                    <td class="tm" id="lb-toprow">&nbsp;</td> \
			    //                    <td class="tr">&nbsp;</td> \
			    //                  </tr> \
			    //                  <tr> \
			    //                    <td class="ml">&nbsp;</td> \
			    //                    <td class="mm"> \
			    //                      <div id="lb-content"> \
			    //                      </div> \
			    //                    </td> \
			    //                    <td class="mr">&nbsp;</td> \
			    //                  </tr> \
			    //                  <tr> \
			    //                    <td class="bl">&nbsp;</td> \
			    //                    <td class="bm">&nbsp;</td> \
			    //                    <td class="br">&nbsp;</td> \
			    //                  </tr> \
			    //                </tbody> \
			    //              </table> \
			    //            </div>';
			    
			    var options   = options || {};
		  		var directory = options && options.directory ? options.directory : STATIC_ASSET_DOMAIN_LOGIC('/mentor2/images/lightbox/');
		  		var ext;
		  		if((jQuery.browser.msie)){
		  			ext = 'gif'
		  		}else{
		  			ext = 'png'
		  		}
			    var html = '<div id="lb-viewer"> \
			    			  <div id="lb-toprow"></div> \
			                  <table id="zoom_table" style="border-collapse:collapse; width:100%; height:100%;"> \
			                    <tbody> \
			                      <tr> \
			                        <td class="tl" style="background:url(' + directory + 'tl.' + ext + ') 0 0 no-repeat; width:20px !important; height:20px; overflow:hidden;" /> \
			                        <td class="tm" style="background:url(' + directory + 'tm.' + ext + ') 0 0 repeat-x; height:20px; overflow:hidden;" /> \
			                        <td class="tr" style="background:url(' + directory + 'tr.' + ext + ') 100% 0 no-repeat; width:20px; height:20px; overflow:hidden;" /> \
			                      </tr> \
			                      <tr> \
			                        <td class="ml" style="background:url(' + directory + 'ml.' + ext + ') 0 0 repeat-y; width:20px; overflow:hidden;" /> \
			                        <td class="mm" style="background:#fff; vertical-align:top; padding:10px;"> \
			                          <div id="lb-content"> \
			                          </div> \
			                        </td> \
			                        <td class="mr" style="background:url(' + directory + 'mr.' + ext + ') 100% 0 repeat-y;  width:20px; overflow:hidden;" /> \
			                      </tr> \
			                      <tr> \
			                        <td class="bl" style="background:url(' + directory + 'bl.' + ext + ') 0 100% no-repeat; width:20px; height:20px; overflow:hidden;" /> \
			                        <td class="bm" style="background:url(' + directory + 'bm.' + ext + ') 0 100% repeat-x; height:20px; overflow:hidden;" /> \
			                        <td class="br" style="background:url(' + directory + 'br.' + ext + ') 100% 100% no-repeat; width:20px; height:20px; overflow:hidden;" /> \
			                      </tr> \
			                    </tbody> \
			                  </table> \
			                </div>';
							
				jQuery('body').append(html);	
							
				var $viewer = jQuery('#lb-viewer');
				var $content = jQuery('#lb-content');
				var $toprow = jQuery('#lb-toprow');
				var $internal = jQuery('<div id="lb-internal"></div>');
				
				var theTitle = $this.attr("title")
				var $titleDiv = jQuery('<div class="lightboxtitle"></div>');
				
				
				// ensure that newTop is at least 0 so it doesn't hide close button
/*
				var newTop = Math.max((d.height/2) - (height/2) + y, 0);
				var newLeft = (d.width/2) - (width/2);
				var curTop = e.pageY;
				var curLeft = e.pageX;
*/
				var lb_positionBoxes = function(){
					var width = window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth);
					var height = window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight);
					var x = window.pageXOffset || (window.document.documentElement.scrollLeft || window.document.body.scrollLeft);
					var y = window.pageYOffset || (window.document.documentElement.scrollTop || window.document.body.scrollTop);
					var window_size = {'width':width, 'height':height, 'x':x, 'y':y}
					var d = window_size;
/*
					var lbTop = (jQuery(window).height()-$viewer.outerHeight())/2+jQuery(window).scrollTop();
					var lbLeft = (jQuery(window).width()-$viewer.outerWidth())/2+jQuery(window).scrollLeft();
*/
					var lbTop = Math.max((d.height/2) - ($viewer.outerHeight()/2) + y, 0);
					var lbLeft = (d.width/2) - ($viewer.outerWidth()/2);
					$viewer.animate({
						top: lbTop,
						left: lbLeft
					});
					$overlay.css({
						height: jQuery(document).height()+'px',
						width: jQuery(document).width()+'px'
					})
				}	
				
				jQuery(window).resize(lb_positionBoxes);
				
				var lb_closeLightbox = function(){
					$this.removeClass("mgclightboxed");	
					if(contentType=='flash'){
						if($this.hasClass("mgcswfreplacefp")){
							try {
								mgc_submitOmnitureVideoEnd()
							} catch (e) {
								// well crap - send what we have
							}
							unloadcontrol()
							flowplayer("flashreplace").unload();
						}else if($this.hasClass("mgcswfreplace")){
							try {
								mgc_submitOmnitureVideoEnd()
							} catch (e) {
								// well crap - send what we have
							}
							swfobject.removeSWF("flashreplace")
						}else{
							swfobject.removeSWF("flashreplace")
						}
					}
					$overlay.remove();
					$viewer.remove();	
					jQuery('embed, object, select').css('visibility', 'visible');
					jQuery(window).unbind('keyup',lb_escapeout)
					return false;
				}
		
				var lb_escapeout = function(e){
					if(e.keyCode==27){
						lb_closeLightbox()
					}
				}

				
				jQuery(document).keyup(lb_escapeout);
		
				var $closer = jQuery('<div id="lb-closer"><a href="#">Close (or Press the Esc Key)</a></div>').click(lb_closeLightbox);
		
				var lb_resizeBoxes = function(){
					var resizeTimeout = setTimeout(lb_resizeBoxes2,500)
				}
				var showCloseTitle = function(){}
				var lb_resizeBoxes2 = function(){
				
					$viewer.show();
					var intHeight = parseInt($internal.outerHeight(),10)
					var intWidth = parseInt($internal.outerWidth(),10)
				
					var leftAni;
					var topAni;
		
					if(cacheHeight===null){
						topAni = '-=' + intHeight/2 + 'px'
					}else{
						if((cacheHeight-intHeight)<0){
							topAni = '-=' + (intHeight-cacheHeight)/2 + 'px' 
						}else{
							topAni = '+=' + (cacheHeight-intHeight)/2 + 'px' 
						}
					}
					if(cacheWidth===null){
						leftAni = '-=' + intWidth/2 + 'px'
					}else{
						if((cacheWidth-intWidth)<0){
							leftAni = '-=' + (intWidth-cacheWidth)/2 + 'px' 
						}else{
							leftAni = '+=' + (cacheWidth-intWidth)/2 + 'px' 
						}
					}
					fixBackgroundsForIE();
					$viewer.animate({
						width: intWidth + 60 + 'px',
						height: intHeight + 60 + 'px',
						left: leftAni,
						top: topAni
					},'normal',function(){
						$internal.show();
						$internal.find("img").css('visibility', 'visible');
						//$viewer.css({background:'none'})
						if(contentType=='iframe'){
							$iframe.css({background:'#fff'})
						}
						if(($titleDiv.text()).length>0){
							$titleDiv.animate({opacity: "show"}, "slow")
						}
						$toprow.animate({opacity: "show"}, "slow")
						var showTimeout = setTimeout(showCloseTitle,1000)
						unfixBackgroundsForIE()
						var posafter = $viewer.offset()
						if(parseInt(posafter.top,10)<0){
							lb_positionBoxes()
						}
					})
				}
		
				
				if(contentType!==null){
					$overlay.css({
						position: 'absolute',
						height: jQuery(document).height()+'px',
						width: jQuery(document).width()+'px',
						background: '#ddd',
						opacity: 0,
						top: 0,
						left: 0,
						'z-index': 20001
					}).appendTo("body").fadeTo(150,.25)
			
					$viewer.css({
						position: 'absolute',
						height: '20px',
						width: '20px',
						background: 'none',
						'z-index': 20001
					}).appendTo("body").hide();
				
		
					$internal.appendTo($content).hide();
					$titleDiv.insertAfter($internal).hide();
		
					$closer.appendTo($viewer);
					
					lb_positionBoxes();
					
					//$viewer.fadeTo("fast",1);
					
					if(contentType=='flash'){
		
						// rel should be width||height||flashvars||params||attributes
						var flashwidth="500";
						var flashheight="500";
						var flashvars=false;
						var flashparams=false;
						var flashattributes=false;
						var flashpass = $this.attr("rel");
						if(flashpass.length>0){
							var flasharr = flashpass.split("||")
							jQuery.each(flasharr,function(i,n){
								switch(i){
								case 0:
		
									if(n!="false"&&n.length>0){
										flashwidth=n
									}
		
								break
								case 1:
		
									if(n!="false"&&n.length>0){
										flashheight=n
									}
		
								break
								case 2:
		
									if(n!="false"&&n.length>0){
										flashvars = {};
										var flashvarsarr = n.split("|")
										jQuery.each(flashvarsarr,function(i,n){
											var flashvarrtemp=n.split(":")
											if(flashvarrtemp.length>1){
												flashvars[flashvarrtemp[0]]=flashvarrtemp[1]
											}									
										})
									}
		
								break
								case 3:
		
									if(n!="false"&&n.length>0){
										flashparams = {};
										var flashparamsarr = n.split("|")
										jQuery.each(flashparamsarr,function(i,n){
											var flashparamsrtemp=n.split(":")
											if(flashparamsrtemp.length>1){
												flashparams[flashparamsrtemp[0]]=flashparamsrtemp[1]
											}									
										})
									}
		
								break
								case 4:
		
									if(n!="false"&&n.length>0){
										flashattributes = {};
										var flashattributesarr = n.split("|")
										jQuery.each(flashattributesarr,function(i,n){
											var flashattributestemp=n.split(":")
											if(flashattributestemp.length>1){
												flashattributes[flashattributestemp[0]]=flashattributestemp[1]
											}									
										})
									}
		
								break
								}
								
							})
						}
						if($this.hasClass("mgcswfreplace")){
							contentHref = "/mentor2/images/player.swf"
							mgcvideofilename=$this.attr("title");
						}
						if($this.hasClass("mgcswfreplacefp")){
							mgc_wasfulfilled=false;
							var nopagetagging=false;
							if($this.hasClass("nopagetagging")){
								nopagetagging=true;
							}
							if (flashwidth <= 485) {
								$content.addClass("mentor-player-compact");
							}
							//contentHref = "/mentor2/images/player.swf"
							contentHref = "/mentor2/images/flowplayer.swf"
							mgcvideofilename=$this.attr("title");
							var $flashreplace = jQuery('<div id="flashreplace" style="height:'+flashheight+'px;width:'+flashwidth+'px"></div>')
							$internal.append($flashreplace)
							var $controls = jQuery('<div id="mentor-player" class="mentor-player"></div>')
							$internal.append($controls)
/*
							var $rtmp = jQuery('<div id="rtmpInfo"></div>')
							$internal.append($rtmp)
*/
							var runflow = function(){
								var fp_clip = {}; 
								var fp_rtmp = { 
									url: '/mentor2/images/flowplayer.rtmp.swf', 
									netConnectionUrl: flashvars['streamer']
						        }
						        var fp_bwcheck = {
						            url: 'flowplayer.bwcheck.swf', 
						            rememberBitrate:false,
						 
						            // limelight uses Flash Media Servers 
						            serverType: 'fms', 
						 
						            // Use this connection for bandwidth detection 
						            netConnectionUrl: flashvars['streamer'], 
						 
						            // available bitrates for file names 
						            bitrates: [500, 800], 
						 
						            // use a customized urlPattern for file names 
						            urlPattern: '{0}-{1}k', 
						            defaultBitrate: 500
						 
						            // this method is called when the bandwidth check is done 
/*
						            onBwDone: function(url, chosenBitrate, bitrate) { 
						                var el = document.getElementById("rtmpInfo"); 
						                el.innerHTML = "Your speed is: " +bitrate+ "<br />Video file served: " +url; 
						            } 
*/
						        }
						        var fp_controls={
							        bottom:0, 
							        height:24, 
							        'z-index':1, 
							        backgroundColor: '#2d3e46', 
							        backgroundGradient: 'low', 
							        fontColor: '#ffffff',
							        timeFontColor: '#333333',
							        autoHide: 'never',
							        play:true, 
							        volume:true, 
							        mute:true, 
							        time:true, 
							        stop:false, 
							        playlist:false, 
							        fullscreen:true, 
							        scrubber: true 
						        }
						        var fp_canvas={
								    background: '#000000 url(/mentor2/images/player/logo.swf) no-repeat 45pct 45pct', 
								    backgroundGradient: [0.1, 0.2, 0.3],
								    border:'2px solid #2e5790'
						        }
						        var fp_plugins={};
						        if(flashvars['mgcbitrate']==="mgcvbitrate"){
						        	fp_plugins={
						        		controls:null,
						        		rtmp: fp_rtmp,
								        bwcheck: fp_bwcheck
								    }
								    fp_clip={
										url: flashvars['file'].replace('.flv',''), 
										provider: 'rtmp',
										urlResolvers: "bwcheck"
									}
						        }else{
						        	fp_plugins={
						        		controls:null,
						        		rtmp: fp_rtmp
								    }
								    fp_clip={
										//url: "mp4:cdc_seminar_india.f4v", 
										url: flashvars['file'].replace('.flv',''), 
										provider: 'rtmp'
									}
						        }
								if(nopagetagging===false){
									fp_clip["onBegin"]=playerReady2
								}
								flowplayer("flashreplace",contentHref,{
									canvas: fp_canvas,
									key: '#$07616e65f9d742907eb',
								    plugins: fp_plugins, 
								    clip: fp_clip
								}).controls("mentor-player", {duration: 25}); 
							}
							setTimeout(runflow,1000)
						}else{
							flashvars['streamer']='rtmpt%3A//mgraphics.fcod.llnwd.net/a3661/o33';
							$internal.append('<div id="flashreplace"></div>')
							swfobject.embedSWF(contentHref, "flashreplace", flashwidth, flashheight, "9", false, flashvars, flashparams, flashattributes)
						}
						lb_resizeBoxes();
					}
					
					if(contentType=='iframe'){
						var iframewidth=parseInt((.9*jQuery(window).width()),10);
						var iframeheight=parseInt((.9*jQuery(window).height()),10);
						var iframepass = $this.attr("rel");
						if(iframepass.length>0){
							var iframearr = iframepass.split("||")
							jQuery.each(iframearr,function(i,n){
								switch(i){
								case 0:
		
									if(n!="false"&&n.length>0){
										iframewidth=n
										if(jQuery.browser.msie===true){
											iframewidth=parseInt(n,10)+5
										}
									}
		
								break
								case 1:
		
									if(n!="false"&&n.length>0){
										iframeheight=n
										if(jQuery.browser.msie===true){
											iframeheight=parseInt(n,10)+5
										}
									}
		
								break
								}
								
							})
						}
						$iframe = jQuery('<iframe></iframe>').attr('src',contentHref)
						.attr('frameborder','0').attr('marginwidth','0').attr('marginheight','0').css({
							width: iframewidth + 'px',
							height: iframeheight + 'px'
						})
						$iframe[0].id = new Date().getTime();
						$iframe.appendTo($internal);
						$titleDiv.html(theTitle);
						lb_resizeBoxes();
					}
					
					if(contentType=='image'){
						var galleryReg = /^lightbox\[/;
						var $appendimage;
						var currImage=0;
						var theRel = $this.attr("rel");
						if(galleryReg.test(theRel)){
							var getGallReg = /(^lightbox\[)/
							var theGallery = theRel.replace(getGallReg,'')
							theGallery = theGallery.replace(/\]$/,'')
							var $galleryLinks = jQuery("a[rel='" + theRel + "']").not(".mgclbsecond");
							var gallery = [];
							var gallerytitles = [];
							var gallerySize = $galleryLinks.length;
							if(gallerySize==1){
								$appendimage = jQuery('<img src="' + contentHref + '" />').appendTo($internal)
								$titleDiv.html(theTitle);
								lb_resizeBoxes();
							}else{
		
								$galleryLinks.each(function(index){
									//if(!jQuery(this).hasClass("mgclbsecond")){
										gallery.push(jQuery(this).attr("href"))
										gallerytitles.push(jQuery(this).attr("title"))
									    var $cacheimage=jQuery("<img />")
									    $cacheimage.attr("src", jQuery(this).attr("href"));
									//}
								});
								currImage=jQuery.inArray(contentHref,gallery);
								var $prevArrow = jQuery('<div id="prevarrow"><a href="#">previous</a></div>').appendTo($toprow)
								var $nextArrow = jQuery('<div id="nextarrow"><a href="#">next</a></div>').appendTo($toprow);
								$prevArrow.find("a").click(function(){
									currImage=currImage-1
									if(currImage<0){
										currImage=gallerySize-1
									}
									cacheHeight = parseInt($internal.outerHeight(),10);
									cacheWidth = parseInt($internal.outerWidth(),10);
									$toprow.hide();
									$internal.hide().find("img").remove();
									$titleDiv.hide()
									$appendimage = jQuery('<img src="' + gallery[currImage] + '" />').css('visibility', 'hidden').appendTo($internal)
									$titleDiv.html(gallerytitles[currImage]);
									//$viewer.css({background: '#fff'})
									lb_resizeBoxes();
									return false;
								});
								$nextArrow.find("a").click(function(){
									currImage=currImage+1
									if(currImage>(gallerySize-1)){
										currImage=0
									}
									cacheHeight = parseInt($internal.outerHeight(),10);
									cacheWidth = parseInt($internal.outerWidth(),10);
									$toprow.hide()
									$internal.hide().find("img").remove();
									$titleDiv.hide()
									$appendimage = jQuery('<img src="' + gallery[currImage] + '" />').css('visibility', 'hidden').appendTo($internal)
									$titleDiv.html(gallerytitles[currImage]);
									//$viewer.css({background: '#fff'})
									lb_resizeBoxes();
									return false;
								});
								$appendimage = jQuery('<img src="' + gallery[currImage] + '" />').appendTo($internal)
								$titleDiv.html(gallerytitles[currImage]);
								lb_resizeBoxes();
							}
						}else{
							$appendimage = jQuery('<img src="' + contentHref + '" />').appendTo($internal)
							$titleDiv.html(theTitle);
							lb_resizeBoxes();
						}
					}
			
				}
				
				function switchBackgroundImagesTo(to) {
				    jQuery('#zoom_table td').each(function(i) {
				      var bg = jQuery(this).css('background-image').replace(/\.(png|gif|none)"\)$/, '.' + to + '")');
				      jQuery(this).css({'background-image':bg});
				    });
				    //alert(jQuery('#zoom_table td.tm').css('background-image'))
				    //var close_img = zoom_close.children('img');
				    //var new_img = close_img.attr('src').replace(/\.(png|gif|none)$/, '.' + to);
				    //close_img.attr('src', new_img);
				}
				  
				function fixBackgroundsForIE() {
				    if (jQuery.browser.msie && parseFloat(jQuery.browser.version) >= 7) {
				      switchBackgroundImagesTo('gif'); 
				    }
				}
				  
				function unfixBackgroundsForIE() {
				    if (jQuery.browser.msie && jQuery.browser.version >= 7) {
				      switchBackgroundImagesTo('png'); 
				    }
				}
		
				return false;
					
			
			});
		});
		return $group;
	};
})(jQuery);


