
RedSquare.PopupBuilder = Base.extend
({
	constructor: function(linkClassName, windowName, options, linksById)
	{
		if (linkClassName && linkClassName != '')
			this.links = $$("a." + linkClassName);
		else if (linksById)
			this.links = linksById;
		else
		{
			// assume ALL links on the page
			this.links = $A(document.getElementsByTagName('a'));
		}
		
		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();
		}

		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));
         }
     }
});
