/* popup function for pages */


//$( function() {
//	$(".showHelp").click( function() {
//		showHelp(this);
//		return false;
//	});
//});

//function showHelp( el )
//{
//	var pop = new Popup( {className:"popHelp" , isSticky:true , src : el.href, anchor:el , srcContainer : ".popupHolder" });
//}

/*************************************************************************************
Generic popup class
Author: Jarrod McGuire 5/12/2008
************************************************************************************/

/*
var pop = new Popup(  featuresObj )

className (string) : Mandatory - Popup layouts are css driven, so as well as the generic layout, specific css must be defined for the popup.
src (string) : Conditional Mandatory - This is the url source of the content being produced (same server) It is loaded by ajax and inserted into the popup. It is mandatory if no html is set.
html (string) : Conditional Mandatory - This is the html of the content that is inserted into the popup. It is mandatory if no src is set.
isSticky (boolean) : Optional default false - If the popup is sticky it will remain on the page until the user clicks the "close" button
onlyOne (boolean) : Optional default is true - Specifies if there can only be one instance of a particular popup specified by the className (Probably leave this one as is)
isDraggable (boolean) : Optional default is true - Specifies whether the popup can be dragged. Looks at css of popup and finds where "cursor:move" has been set and makes the popup draggable from that position
anchor (dom object or string id) : Optional - Specifies where the popup will be anchored to on the page. If this is left out the popup will appear in the centre of the viewable window
*/



function Popup( features )
{
	if( !features.className ) 
	{
		return alert("*** Popup.create : You must specify the 'className' to be used with this popup ***");
	}
	else if( !features.src && !features.html )
	{
		return alert("*** Popup.create : You must either specify the popup 'src' or 'html' ***");
	}

	if( features.isDraggable != false ) {features.isDraggable = true;}
	if( features.onlyOne != false ) {features.onlyOne = true;}
    if( features.hasClose != false ) {features.hasClose = true;}

	this.features = features;

	this.browserIE6Below = $.browser.msie && $.browser.version*1 <= 6;
	this.id = Math.random();

	this.popupHolder = this.create( features );
	this.fill( features );
	if( !Popup.elements ) Popup.elements = {};
	if( !Popup.elements[features.className] )
	{
		Popup.elements[features.className] = {};
	}

	if( features.onlyOne )
	{
		for(var p in Popup.elements[features.className] )
		{
			Popup.elements[features.className][p].destroy();
		}
	}
	Popup.elements[features.className][ this.id ] = this;
}

function Popup_removeAll()
{
	alert(Popup.test);
}

Popup.removeAll = Popup_removeAll;

Popup.destroy = function(el)
{
    Popup.elements[ $(el).attr("type") ][el.id].destroy();
};

function Popup_genPopup( obj )
{
    var s = [];
	var popupHolder = $( '<div class="popupHolder ' + obj.className + '" type="' + obj.className + '" id="' + this.id + '"  ' + (!obj.isSticky ? "notSticky=\"true\"":"" ) + '><div class="popup"><div class="popTop"><div></div></div><div class="body"><div class="bodyInner"></div></div><span class="popBot"><span></span></span></div></div>' );

	if( this.browserIE6Below )
	{
		popupHolder.append( '<iframe class="popFrame" frameborder="0" src="javascript:false;"></iframe>' );
	}

   // popupHolder.css("left","-10000px");
	
	return popupHolder.get(0);
}

/*****************
popup functions
*****************/

function Popup_show(obj)
{
	var popupObj = this;
	if( !$.browser.msie )
	{
		$(this.popupHolder).fadeIn("slow" , showComplete );
	}
	else
	{
		$(this.popupHolder).show();
		showComplete();
	}
	
	function showComplete()
	{
		if( popupObj.features.isDraggable ){ $(popupObj.popupHolder).mousedown( Popup_startPopupDrag );}
		if( !popupObj.features.isSticky )
		{
			setTimeout( '$(document).bind( "click" , Popup_handleDocumentClick)' , 0);
		}
		
        if( obj.callback )
        {
            obj.callback();
        }		
		
	}
}

function Popup_getContent( obj )
{
	var popupObj = this;
	var popup = popupObj.popupHolder;
	if( obj.src )
	{
	    $.ajax({
	        url : obj.src,
	        dataType : "html",
	        cache:true,
	        success : function( html ) {
				var popDom = $("<div/>").append( html );
				var str = "";
				if( obj.srcContainer && popDom.is(":has(" + obj.srcContainer + ")") )
				{
					str = popDom.find(obj.srcContainer).contents();
				}
				else
				{
					if( html.match(/<body/) )
					{
						str = html.match(/<body[^>]*>([.\s\S]+)<\/body>/)[1];
					}
					else
					{
						str = popDom.contents();
					}
				}
	            if(str){loadPopup( str )}
	            else{this.error();}
	        },
	        error : function() {
	            loadPopup( obj.errorhtml || '<div class="popupError"><div class="popupErrorHeader">Popup error</div><div class="popupErrorContent"><p>Sorry, but an error occurred loading the popup</p></div></div>' );
	        }
	    }); 
	}
	else if( obj.html )
	{
		loadPopup( obj.html );
	}

    function loadPopup( str )
    {
        if( !str ) return;
        failLoad = false;
	
        $(popup)
            .find(".bodyInner")
            .append( str );
        
        if( obj.hasClose )
        {
            $(popup)
                .append('<a class="closePopup" href="#">x</a>')
                .find(".closePopup").click( function() {
			    	popupObj.destroy();
                    return false;
                });
        }


	    $("body").append( popup );
 
		var el = null;
		if( obj.anchor )
		{
			if( typeof obj.anchor == "string" )
			{
				el = document.getElement( obj.anchor );
			}
			else
			{
				el = obj.anchor;
			}
		};

		var winSize = getWindowSize();
		var winWidth = winSize[0];
		var winHeight = winSize[1];
		var winScroll = getScrollXY();
		var popWidth = popup.offsetWidth;
		var popHeight = popup.offsetHeight;

		// if there is an anchor element, use that. If not put it in the middle of the page TODO
		var offset;
		if( el )
		{
			offset = $(el).offset();
		}
		else
		{
			offset = { left:((winWidth-popWidth)/2) + winScroll[0] , top:((winHeight-popHeight)/2)+winScroll[1] };
		}
		
	    if (popupObj.browserIE6Below)
	    {
		    popup.style.height = popup.offsetHeight + "px";
		    popup.style.zoom = 1;
	    }

        $(popup).hide();

		var popRight = offset.left - winScroll[0] + popWidth;
        if( popRight - winWidth > 0 )
        {
            popup.style.left = (winWidth - popWidth - 35) + "px";
        }
        else
        {
    	    popup.style.left = offset.left + "px";
        }

		var popBottom = offset.top - winScroll[1] + popHeight;
		if( popBottom - winHeight > 0 )
		{
			popup.style.top = (winScroll[1] + winHeight - popHeight-20) + "px";
		}
		else
		{
			popup.style.top = offset.top + "px";
		}
    	
		popupObj.show(obj);
	}
}

function Popup_handleDocumentClick( e )
{
	e = window.event || e;
    var el = e.target || e.srcElement;
    if( !($(el).parents(".popupHolder[notSticky='true']").length) && !Popup.stopDoc )
    {
        $("[notSticky='true']").each( function() {
            Popup.elements[ $(this).attr("type") ][ this.id ].destroy();
        });
		$(document).unbind( "click" , Popup_handleDocumentClick );
    }
    
    Popup.stopDoc = false;
}

function Popup_startPopupDrag( e )
{	
	var target = e.target; // jquery takes care of the cross browser stuff
	if( !$(target).css("cursor").match(/move/i) ) return;
	var el = this;
	document.startX = (e.clientX||e.pageX) - el.offsetLeft;
	document.startY = (e.clientY||e.pageY) - el.offsetTop;
	document.el = el;
	
	$(document).mousemove( Popup_dragPopup );
	$(document).mouseup( Popup_stopPopupDrag );
	disableSelection( document.body );	
}

function Popup_dragPopup(e)
{
	if( !e ) e = window.event;
	try
	{
    	document.el.style.left = ( (e.clientX||e.pageX) - document.startX) + "px";
	    document.el.style.top = ( (e.clientY||e.pageY) - document.startY) + "px";
	}
	catch(e){}
}

function Popup_stopPopupDrag()
{
	$(document).unbind( "mousemove" , Popup_dragPopup );
	$(document).unbind( "mouseup" , Popup_stopPopupDrag );
	enableSelection( document.body );
}

function Popup_removePopup()
{
	var popup = this;

	Popup.elements[ this.features.className ][this.id] = null;
	delete Popup.elements[ this.features.className ][this.id];
	
	if( !$.browser.msie )
	{
        $(popup.popupHolder).fadeOut("slow" , destroyPopup )
    }
	else
	{
		destroyPopup();
	}
	
	function destroyPopup()
	{
		$(document).unbind( "click" , Popup_handleDocumentClick );
		$(popup.popupHolder).remove();
		popup.popupHolder = null;
		popup = null;
	}
}

Popup.prototype.create = Popup_genPopup;
Popup.prototype.show = Popup_show;
Popup.prototype.destroy = Popup_removePopup;
Popup.prototype.fill = Popup_getContent;

/*************************
Public helper functions
*************************/
function disableSelection(element) {
	element.onselectstart = function() {return false;};
	element.unselectable = "on";
	element.style.MozUserSelect = "none";
}

function enableSelection(element) {
	element.onselectstart = null;
	element.unselectable = "off";
	element.style.MozUserSelect = "";
}

function getWindowSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return [ myWidth , myHeight ];
}

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}
