Object.extend(String.prototype, {
  // if a string doesn't end with str it appends it
  ensureEndsWith: function(str) {
    return this.endsWith(str) ? this : this + str;
  },
  
  // makes sure that string ends with px (for setting widths and heights)
  px: function() {
    return this.ensureEndsWith('px');
  }
});

Object.extend(Number.prototype, {
  // makes sure that number ends with px (for setting widths and heights)
  px: function() {
    return this.toString().px();
  }
});

var Window = {
  // returns correct dimensions for window, had issues with prototype's sometimes. this was ganked from apple.
  size: function() {
		return {'width':960, 'height':1900, 'x':0, 'y':9};
		/*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);
		return {'width':width, 'height':height, 'x':x, 'y':y};
		*/
		//var superwin = parent.getwindowdyn();
		//return superwin;
	}
}

var FancyZoomBox = {
  borderimage : '/img/fancyzoom_box',
  closeimage : '/img/fancyzoom_close',
  loadingimage : '/img/fancyzoom_loading.gif',
  cornersizes : 35,
  closeposition : 'right',
  closemargin : '14px 14px 0 0',
  backgroundcolor : '#339933',
  contentoverflow : 0,
  darkeralpha : 0.8,
  zooming   : false,
  setup     : false,
  
  init: function(directory) {
    if (FancyZoomBox.setup) return;
    FancyZoomBox.setup = true;
    
    var ie = navigator.userAgent.match(/MSIE\s(\d)+/);
    if (ie) {
      var version = parseInt(ie[1]);
      Prototype.Browser['IE' + version.toString()] = true;
      if(version>7){
    	  Prototype.Browser['IE7'] = true;
      }
      Prototype.Browser.ltIE7 = (version < 7) ? true : false;
    }
    
    var html = '<div id="zoom" style="display:none;z-index:100001;"> \
                  <table id="zoom_table" style="border:none;border-collapse:collapse; width:100%; height:100%;background:none;"> \
                    <tbody> \
                      <tr style="border:none;"> \
                        <td class="tl" style="background-color:none;background:url(' + FancyZoomBox.borderimage + '.png) top left no-repeat; width:'+FancyZoomBox.cornersizes+'px; height:'+FancyZoomBox.cornersizes+'px; overflow:hidden; padding:0; border:none;" /> \
                        <td class="tm" style="background-color:none;background:url(' + FancyZoomBox.borderimage + '.png) top center repeat-x; height:'+FancyZoomBox.cornersizes+'px; overflow:hidden; padding:0; border:none;" /> \
                        <td class="tr" style="background-color:none;background:url(' + FancyZoomBox.borderimage + '.png) top right no-repeat; width:'+FancyZoomBox.cornersizes+'px; height:'+FancyZoomBox.cornersizes+'px; overflow:hidden; padding:0; border:none;" /> \
                      </tr> \
                      <tr style="border:none;"> \
                        <td class="ml" style="background-color:none;background:url(' + FancyZoomBox.borderimage + '.png) center left repeat-y; width:'+FancyZoomBox.cornersizes+'px; overflow:hidden; padding:0; border:none;" /> \
                        <td class="mm" style="background-color:'+FancyZoomBox.backgroundcolor+'; vertical-align:top; border:none; text-align:left; padding:0; "> \
                          <div style="position:absolute;"><div id="zoom_content" style="position:absolute;margin:-' + FancyZoomBox.contentoverflow + 'px 0 0 -' + FancyZoomBox.contentoverflow + 'px;z-index:100002"> \
                          </div></div> \
                        &nbsp;</td> \
                        <td class="mr" style="background-color:none;background:url(' + FancyZoomBox.borderimage + '.png) center right repeat-y;  width:'+FancyZoomBox.cornersizes+'px; overflow:hidden; padding:0; border:none;" /> \
                      </tr> \
                      <tr style="border:none;"> \
                        <td class="bl" style="background-color:none;background:url(' + FancyZoomBox.borderimage + '.png) bottom left no-repeat; width:'+FancyZoomBox.cornersizes+'px; height:'+FancyZoomBox.cornersizes+'px; overflow:hidden; padding:0; border:none;" /> \
                        <td class="bm" style="background-color:none;background:url(' + FancyZoomBox.borderimage + '.png) bottom center repeat-x; height:'+FancyZoomBox.cornersizes+'px; overflow:hidden; padding:0; border:none;" /> \
                        <td class="br" style="background-color:none;background:url(' + FancyZoomBox.borderimage + '.png) bottom right no-repeat; width:'+FancyZoomBox.cornersizes+'px; height:'+FancyZoomBox.cornersizes+'px; overflow:hidden; padding:0; border:none;" /> \
                      </tr> \
                    </tbody> \
                  </table> \
                  <div title="Close" id="zoom_close" style="position:absolute; top:0; ' + FancyZoomBox.closeposition + ':0;z-index:100005"> \
                    	<div id="zoom_close_btn" style="cursor:pointer; margin:' + FancyZoomBox.closemargin + ';"><img src="' + FancyZoomBox.closeimage + '.png" alt="Close" style="border:none; margin:0; padding:0;" /></div> \
                  </div> \
                </div><div id="darker" style="background:#fff;top:0px;left:0px;display:none;z-index:100000;position:absolute">&nbsp;</div>';
    
    var body  = $$('body').first();
    body.insert(html);
    
    FancyZoomBox.darker = $('darker');
    FancyZoomBox.zoom = $('zoom');
    FancyZoomBox.zoom_table = $('zoom_table');
    FancyZoomBox.zoom_close = $('zoom_close');
    FancyZoomBox.zoom_content = $('zoom_content');
    $('zoom_close_btn').observe('click', FancyZoomBox.hide);
    FancyZoomBox.middle_row = $A([$$('td.ml'), $$('td.mm'), $$('td.mr')]).flatten();
    FancyZoomBox.cells = FancyZoomBox.zoom_table.select('td');
    
    // hide zoom if click fired is not inside zoom
    $$('html').first().observe('click', function(e) {
      var click_in_zoom = e.findElement('#zoom'),
          zoom_display  = FancyZoomBox.zoom.getStyle('display');
      if (zoom_display == 'block' && !click_in_zoom) {
        FancyZoomBox.hide(e);
      }
    });

    // esc to close zoom box
    $(document).observe('keyup', function(e) {
      var zoom_display = FancyZoomBox.zoom.getStyle('display');
      if (e.keyCode == Event.KEY_ESC && zoom_display == 'block') {
        FancyZoomBox.hide(e);
      }
    });
    
    // just use gifs as ie6 and below suck
    if (Prototype.Browser.ltIE7) {
      FancyZoomBox.switchBackgroundImagesTo('gif');
    }    
  },
  
  show: function(e) {
	  	if( e.stop )
	  	{	
	  		e.stop();
	  		var element            = e.findElement('a');
	  		FancyZoomBox.curTop    = e.pointerY();
			FancyZoomBox.curLeft   = e.pointerX();
		}
	  	else
	  	{	
	  		var element            = e;
	  		var vp = element.viewportOffset();
	  		FancyZoomBox.curTop    = vp.top + document.viewport.getScrollOffsets().top;
	  		FancyZoomBox.curLeft   = vp.left;
	  	}
	  	if (FancyZoomBox.zooming) return;
		FancyZoomBox.zooming   = true;
		var related_div        = element.content_div;
		var width              = (element.zoom_width || related_div.getWidth()) + ((FancyZoomBox.cornersizes-FancyZoomBox.contentoverflow)*2);
		var height             = (element.zoom_height || related_div.getHeight()) + ((FancyZoomBox.cornersizes-FancyZoomBox.contentoverflow)*2);
		var d                  = Window.size();
		var yOffset            = document.viewport.getScrollOffsets()[1];
		// ensure that newTop is at least 0 so it doesn't hide close button
		var newTop             = Math.max((d.height/2) - (height/2) + yOffset, 0);
		var newLeft            = (d.width/2) - (width/2);
		FancyZoomBox.moveX     = -(FancyZoomBox.curLeft - newLeft);
		FancyZoomBox.moveY     = -(FancyZoomBox.curTop - newTop);
    	FancyZoomBox.zoom.hide().setStyle({
			position	: 'absolute',
			top			: FancyZoomBox.curTop.px(),
			left		: FancyZoomBox.curLeft.px()
		});
		
		FancyZoomBox.darker.hide().setStyle({
			'width'			: "100%",
			'height'		: $$('body').first().getHeight()+"px",
			'top'			: "0"
		});
		
		FancyZoomBox.fixBackgroundsForIE();
    
		new Effect.Appear(FancyZoomBox.darker, {duration: 0.2,to: FancyZoomBox.darkeralpha}),
		new Effect.Parallel([
			new Effect.Appear(FancyZoomBox.zoom, {sync:true}),
			new Effect.Move(FancyZoomBox.zoom, {x: FancyZoomBox.moveX, y: FancyZoomBox.moveY, sync: true}),
			new Effect.Morph(FancyZoomBox.zoom, {
			  style: {
			    width: width.px(),
			    height: height.px()
			  },
				sync: true,
				beforeStart: function(effect) {
				  	// middle row height must be set for IE otherwise it tries to be "logical" with the height
		    		  if (Prototype.Browser.IE) {
		    		    FancyZoomBox.middle_row.invoke('setStyle', {'height':(height-((FancyZoomBox.cornersizes)*2)).px()});
		    		  }
					 // FancyZoomBox.fixBackgroundsForIE();
				},
				afterFinish: function(effect) {
					FancyZoomBox.zoom_content.setStyle({'height':(height-((FancyZoomBox.cornersizes-FancyZoomBox.contentoverflow)*2)).px()});
					FancyZoomBox.zoom_content.setStyle({'width':(width-((FancyZoomBox.cornersizes-FancyZoomBox.contentoverflow)*2)).px()});
					FancyZoomBox.zoom_content.show();
					if(typeof(related_div)=="undefined")
					{
						FancyZoomBox.loadAjaxContent(element.load_url);
					}	
					else
					{
						FancyZoomBox.zoom_content.innerHTML = related_div.innerHTML;
					}
					FancyZoomBox.unfixBackgroundsForIE();
					FancyZoomBox.zoom_close.show();
					FancyZoomBox.zooming = false;
				}
			})
		], { duration: 0.6, delay: 0.1 });
  },
  
  loadAjaxContent: function(url) 
  {
	  FancyZoomBox.zoom_content.up('td').setStyle({
				'background'	:	''+FancyZoomBox.backgroundcolor+' url('+FancyZoomBox.loadingimage+') center center no-repeat'
			});
    	
    	new Ajax.Updater(	"zoom_content", 
							url, {
								asynchronous:true, 
								evalScripts:true, 
								parameters:{'fancyzoom':'yes'}, 
								requestHeaders:['X-Update', "zoom_content"],
								onComplete:	function( t )
								{
									FancyZoomBox.zoom_content.up('td').setStyle({
										'background'	:	''+FancyZoomBox.backgroundcolor+''
									});
								}
					});
  },
  
  hide: function(e) {
	  	if(e && e.stop) e.stop();
		if (FancyZoomBox.zooming) return;
		FancyZoomBox.zooming = true;		
		FancyZoomBox.fixBackgroundsForIE();
		new Effect.Fade(FancyZoomBox.darker, {duration: 0.2, delay:0.4});
		new Effect.Parallel([
			new Effect.Move(FancyZoomBox.zoom, {x: FancyZoomBox.moveX*-1, y: FancyZoomBox.moveY*-1, sync: true}),
			new Effect.Morph(FancyZoomBox.zoom, {
			  style: {
			    width: '1'.px(),
			    height: '1'.px()
			  },
				sync					: true,
				beforeStart: function(effect) {
					FancyZoomBox.zoom_content.hide();
					if (!Prototype.Browser.IE) {
						FancyZoomBox.zoom_content.update('');
						FancyZoomBox.zoom_content.setStyle({'height':'auto'});
					}
					FancyZoomBox.zoom_close.hide();
				},
				afterFinish: function(effect) {
					FancyZoomBox.zoom_content.update('');
					FancyZoomBox.unfixBackgroundsForIE();
					FancyZoomBox.zooming = false;
				}
			}),
			new Effect.Fade(FancyZoomBox.zoom, {sync:true})
		], { duration: 0.6, delay: 0.2 });
  },
  
  // switches the backgrounds of the cells and the close image to png's or gif's
  // fixes ie's issues with fading and appearing transparent png's with 
  // no background and ie6's craptacular handling of transparent png's
  switchBackgroundImagesTo: function(to) {
    FancyZoomBox.cells.each(function(td) {
      //var bg = td.getStyle('background-image').gsub(/\.(png|gif|none)\)$/, '.' + to + ')');
      if(td.hasClassName('mm')==false)
      {
        td.setStyle({'backgroundImage': 'url('+FancyZoomBox.borderimage+'.'+to+')'});
      }
    });
    var close_img = FancyZoomBox.zoom_close.down('img');
    //var new_img = close_img.readAttribute('src').gsub(/\.(png|gif|none)$/, '.' + to);
    close_img.writeAttribute('src', FancyZoomBox.closeimage + '.' + to);
  },
  
  // prevents the thick black border that happens when appearing or fading png in IE
	fixBackgroundsForIE: function() {
    if (Prototype.Browser.IE7) { FancyZoomBox.switchBackgroundImagesTo('gif'); }
	},
	
	// swaps back to png's for prettier shadows
	unfixBackgroundsForIE: function() {
    if (Prototype.Browser.IE7) { FancyZoomBox.switchBackgroundImagesTo('png'); }
	}
}

var FancyZoom = Class.create(
{
	initialize: function(element) 
	{
		this.assetselector = false;
		this.options = arguments.length > 1 ? arguments[1] : {};
	  	FancyZoomBox.init();
	  	this.element = $(element);
		if (this.element) 
		{
			this.element.zoom_width = this.options.width;
  			this.element.zoom_height = this.options.height;
  			var href = this.element.readAttribute('href');
		  	if( href )
		  	{
			  	if( href.substr(0,1)=="#" )
			  	{
			  		this.element.content_div = $(href.gsub(/^#/, ''));
	  				this.element.content_div.hide();
	  			}
	  			else
	  			{
	  				this.element.load_url = href;
	  				if(!this.options.width || !this.options.height)
	  				{
	  					alert("Please set the fancy-zoom's width and height for AJAX-popups!");
	  					return;
	  				}
	  			}
			  	var _this = this;
	  			this.element.observe('click', function(e){_this.handleClick(e);});
			}
  		}
	},
	
	setAssetmanager: function( _divid, _viewtype )
	{
		// divid, viewtype
		this.assetselector = true;
		this.asset_divid = _divid;
		this.asset_viewtype = _viewtype;
	},
	
	handleClick: function(e)
	{
		if( this.assetselector==true )
		{
			idForAssetSelection = this.asset_divid;
			if( this.asset_viewtype )
				viewtypeForAssetSelection = this.asset_viewtype;
			else
				viewtypeForAssetSelection = "view";
		}
		FancyZoomBox.show(e);
	},
	
	open: function()
	{
		this.handleClick(this.element);
	}
	
});

