/*
	PopupHandler.js

	registers popup onclick handlers for links of a specific class
*/

// class name of links to add the popup handling to
var _POPUP_CLASS_NAME= "popup";

// class name of popup images
var _POPUP_CLASS_NAME_IMAGE= "popupImage";

// magic string to mimic the target="_blank" attribute
var _POPUP_BLANK= "_blank";

// default name of the popup window
var _POPUP_NAME= "shopsonic_popup";


// register the popup handler with the loader object
if (window.loader)
{
	window.loader.add(_registerPopupOnClickHandler);
}
else
{
	window.onload= _registerPopupOnClickHandler;
}


// register the popup onclick handlers for links that have the specified
// class name
function _registerPopupOnClickHandler()
{
	// regular expression to match the popup dimensions specified in the class
	var dimensions= new RegExp("w(\\d+)xh(\\d+)$");

	// loop over all the links in the document
	for (var i= 0; i < document.links.length; i++)
	{
		var l= document.links[i];

		// if the class name contains our target class
		if (l.className.indexOf(_POPUP_CLASS_NAME) > -1)
		{
			// is this a popup image?
			if (l.className.indexOf(_POPUP_CLASS_NAME_IMAGE) > -1)
			{
				l.isImagePopup= true;
			}

			// are we told to mimic the target="_blank" attribute?
			if (l.className.indexOf(_POPUP_BLANK) > -1)
			{
				l.targetBlank= true;
			}

			// if not, we might be specifying dimensions in the class
			else
			{
				// does the class name contain popup window dimensions?
				var result= l.className.match(dimensions);

				// if so, assign them as properties of the link
				if (result != null)
				{
					l.popupWidth= result[1];
					l.popupHeight= result[2];
				}
			}

			// let the link target know it's a popup
			l.search+= ((l.search.indexOf('?') > -1) ? "&" : "?") + "popup=1";

			// register the onclick function for this link
			l.onclick= new Function("", "return popupOnClickHandler(this);");
		}
	}
}


// the popup onclick handler itself
function popupOnClickHandler(ilink)
{
	var newUrl= ilink.href;

	var opts= "";

	if (!ilink.targetBlank)
	{
		var w= (ilink.popupWidth) ? ilink.popupWidth : 750;
		var h= (ilink.popupHeight) ? ilink.popupHeight : 540;

		opts=
			"width=" + w + ",height=" + h + ",location=no,menubar=no,toolbar=no,dependent=yes,resizable=" +
			((ilink.isImagePopup) ? "no,scrollbars=no" : "yes,scrollbars=yes");

		newUrl+= ((ilink.href.indexOf('?') > -1) ? "&" : "?") + "width=" + w + "&height=" + h;
	}

	var myWin= window.open(newUrl, _POPUP_NAME, opts);

	return false;
}

