var PopupBox = Class.create();
PopupBox.clickHandler = function(link) {
	if(link.href.match(/#/)) {
		element = $(link.href.split('#')[1]);
		if(!!Object.isElement(element)) {
			//popupbox.loading();
			popupbox.start(element.clone(), {header:link.title});
		}
		else 
			return true;
	}
	else if(link.href.match(/\.jpg|png|gif$/i)) {
		popupbox.loading();
		image = new Image();
    image.onload = function() {
      popupbox.start('<div class="text-center"><img src="' + image.src + '" /></div>',{header:link.title});
			image.onload = function() {};
    }
    image.src = link.href
	}
	else {
		//popupbox.loading();		
		new Ajax.Request(link.href, {
		  method: 'get',
		  onSuccess: function(transport) {
		    popupbox.start(transport.responseText,{header:link.title});
			}, 
			onFailure: function(transport) {
				popupbox.start("<strong>Document not found.</strong>");
			}
		});	
	}
	return false;
}

PopupBox.prototype = {
  settings : {
    loading_image : '/images/popupbox/loading.gif',
    close_image   : '/images/popupbox/closelabel.gif',
		effectDuration: 0.4,
    html: '\
  <div id="popupbox" style="display:none;"> \
    <div class="popup"> \
      <table> \
        <tbody> \
          <tr> \
            <td class="tl border"/><td class="b border"/><td class="tr border"/> \
          </tr> \
          <tr> \
            <td class="b border"/> \
            <td id="popup_body"> \
              <div id="popup_header"></div> \
							<div id="popup_content"> \
              </div> \
              <div id="popup_footer"> \
                <a href="#" id="popup_close"> \
                  <img id="popup_close_image" /> \
                </a> \
              </div> \
							<div id="popup_loading" style="display:none"> \
								<img id="popup_loading_image" /> \
							</div> \
            </td> \
            <td class="b border"/> \
          </tr> \
          <tr> \
            <td class="bl border"/><td class="b border"/><td class="br border"/> \
          </tr> \
        </tbody> \
      </table> \
    </div> \
  </div>'
  },
	initialize: function() {
		if (this.initialized) {
      return true
    } else {
      this.initialized = true
    }
    $$('body').first().insert(this.settings.html);

    var cache_images = [];
		new Array(this.settings.loading_image, this.settings.close_image).each(function(i){
			cache_images.push(new Image().src=i);
		});
		$$('.popup .border').each(function(e) {
			if(e.getStyle("background-image") && e.getStyle("background-image").match(/url\((.+)\)/) != null)
				cache_images.push(new Image().src=e.getStyle("background-image").match(/url\((.+)\)/)[1]);
		});
		$('popup_close_image').writeAttribute({src:this.settings.close_image});
		$('popup_close').onclick = function(){popupbox.close();return false;};
		$('popup_loading_image').writeAttribute({src:this.settings.loading_image});
		
		// borrowed from lightbox
		var anchors = document.getElementsByTagName('a');
		var areas = document.getElementsByTagName('area');

		// loop through all anchor tags 
		for (var i=0; i<anchors.length; i++){
			var anchor = anchors[i];
			
			var relAttribute = String(anchor.getAttribute('rel'));
			
			// use the string.match() method to catch 'popup' references in the rel attribute
			if (anchor.getAttribute('href') && (relAttribute.toLowerCase().match('popup'))){
				anchor.onclick = function () {return PopupBox.clickHandler(this);}
			}
		}

		// loop through all area tags
		// todo: combine anchor & area tag loops
		for (var i=0; i< areas.length; i++){
			var area = areas[i];
			
			var relAttribute = String(area.getAttribute('rel'));
			
			// use the string.match() method to catch 'popup' references in the rel attribute
			if (area.getAttribute('href') && (relAttribute.toLowerCase().match('popup'))){
				area.onclick = function () {return PopupBox.clickHandler(this);}
			}
		}
	},
	loading: function() {
    this.clearPopup();
    $('popup_content').hide();
		$('popup_footer').hide();
		$('popup_loading').show();
		
		scroll_offsets = document.viewport.getScrollOffsets();
    $('popupbox').setStyle({top:	(scroll_offsets[1] + 100) + "px", left: scroll_offsets[0] + "px"}).show();
	},
	
	close: function() {
		new Effect.Fade( 'popupbox', { duration:this.settings.effectDuration });
		return false;
	},
	show: function(content, options) {
		$('popup_loading').hide();
		$("popup_content").update(content);
		$("popup_content").childElements().each(Element.show);
		 
		if(typeof options.header == "string" && !options.header.empty) {
			$("popup_header").update(options.header);
			new Effect.Appear( "popup_header", { duration:this.settings.effectDuration });
		}
		else {
			$("popup_header").hide();
		}
		
		scroll_offsets = document.viewport.getScrollOffsets();
	  $('popupbox').setStyle({top:	(scroll_offsets[1] + 100) + "px", left: scroll_offsets[0] + "px"});
	
		new Effect.Parallel([
				new Effect.Appear( "popupbox", { duration:this.settings.effectDuration }),
				new Effect.Appear( "popup_content", { duration:this.settings.effectDuration }),
				new Effect.Appear( "popup_footer", { duration:this.settings.effectDuration }),
				new Effect.Fade("popup_loading", { duration:this.settings.effectDuration })
			]
		);
	},
	start: function(content,options) {
		this.clearPopup();
		//this.loading();
		Object.isFunction(content) ? content.call() : this.show(content,options);
	},
	clearPopup: function() {
		$("popup_content").update("");
		$("popup_header").update("");
	},
	adjustSize: function() {
		
	}
}
Element.addMethods( {
	clone: function(element) {
	  var clone = new Element(element.tagName);
	  $A(element.attributes).each(function(attribute) { 
			if( attribute.name != 'style' && attribute.name != "id" ) 
			clone[attribute.name] = attribute.value; }
			);
		clone.addClassName(element.className);
	  clone.setStyle( element.getStyles() );
	  clone.update(element.innerHTML);

	  return clone;
	} 
} );
document.observe('dom:loaded', function() {
	popupbox = new PopupBox();
});
