RedSquare.PopupBuilder = Class.create();

RedSquare.PopupBuilder.prototype = 
{
	initialize: function(linkClassName, windowName, options)
	{
		this.links = $A(document.getElementsByClassName(linkClassName));
		
		this.windowName = windowName;
		this.options = options;
		
		this.setup();
	},
	
	setup: function()
	{
		this.processOptions();
		
		this.links.each
		(
		 	function(element)
			{
				Event.observe(element, 'click', this.linkOnClick.bindAsEventListener(this));

				// fix for safari
				element.onclick = function() { return false };
			}
			.bind(this)
			
		)
	},
	
	linkOnClick: function(event)
	{
		var element = Event.element(event);
		
		// find the actual link element (in the case of an image or span or something inside the link firing the event)
		
		var pf = new RedSquare.ParentFinder(element);
		
		var link;
		
		if (link = pf.findTag('a'))
		{
			this.window = window.open(link.href, this.windowName, this.options);
			this.window.focus();
			link.blur();
		}

		Event.stop(event);
		return false;
	},
	
	processOptions: function()
     {
         var matches;
         var width;
         var height;

         // first, check if a width is available
         matches = this.options.match(/width=([\d]+)/);

         if (matches)
         {
             width = parseInt(matches[1]);

             // replace any references to "c" as left value with screen center
             this.options = this.options.replace(/left\=c/, 'left=' + ((screen.availWidth - width) / 2));
         }

         // first, check if a width is available
         matches = this.options.match(/height=([\d]+)/);

         if (matches)
         {
             height = parseInt(matches[1]);

             // replace any references to "c" as top value with screen center
             this.options = this.options.replace(/top\=c/, 'top=' + ((screen.availHeight - height) / 2));
         }
     }
}
