// -------------------------------------------------------------------
// Madgex Limited
// Copyright (c) 2007 Madgex Limited. All Rights Reserved.
// More Location Popup, version 1.0
// Mark Bedser
// 18 June 2007
// Updated: Dragdrop, centering
// -------------------------------------------------------------------


function Inherit( base, derived )
{
	for ( var i in base.prototype )
	{
		eval( 'derived.prototype.' + i + '= base.prototype.' + i )
	}
}

function createXMLHttpRequest() {
   try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
   try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
   try { return new XMLHttpRequest(); } catch(e) {}
   // alert("XMLHttpRequest not supported");
   return null;
}

function Request( URL, Action, Data )
{
	var me = this; 
	
	if ( this.constructor != Request )
		me = arguments[arguments.length-1]


	me.URL = URL;
	me.Action = Action;
	me.Data = Data;
	me.TimeoutMilliseconds = 10000;
	me._Request = createXMLHttpRequest();
	// the below is necessary as otherwise the Request.prototype.Handler() method loses it's "this" reference.
	me._Handler = function () { me.Handler(); }
	me._Tick = function () { me.Tick(); }
	me._Timeout = function () { me.Timeout(); };

	me._ResponseReceived = false;
	me._TimedOut = false;

}

// Don't override this function, override ProcessResponse instead
Request.prototype.Handler = function ()
{
	if ( !this._TimedOut )
	{
		switch ( this._Request.readyState )
		{
			case 0:
				break;
			case 1:
//				window.status = "Receiving data (1)...";
				break;
			case 2:
//				window.status = "Receiving data (2)...";
				break;
			case 3:
//				window.status = "Receiving data (3)...";
				break;
			case 4:
//				window.status = "Processing data...";
				this._ResponseReceived = true;
				// Potential for asynch overlap here so check timedout again
				if ( !this._TimedOut )
				{
					this.ProcessResponse();
				}
				else
					this._ResponseReceived = false;	
				break;
			default:
				break;			
		}	
	}
}

Request.prototype.Timeout = function ()
{
	if ( ! this._ResponseReceived )
	{
		this._TimedOut = true;
		// Should check the status length first and reset if necessary
	}
}

Request.prototype.Tick = function ()
{
	if ( ! this._ResponseReceived && ! this._TimedOut )
	{
		// Should check the status length first and reset if necessary
		window.setTimeout( this._Tick, 1000 );
	}
}

Request.prototype.ProcessResponse = function ()
{
	alert( this._Request.responseBody );
}

Request.prototype.Send = function ()
{
	this._Request.open(this.Action, this.URL, true);
	this._Request.onreadystatechange = this._Handler;
	this._Request.send(this.Data);
	this._ResponseReceived = false;
	window.setTimeout( this._Tick, 1000 );
	window.setTimeout( this._Timeout, this.TimeoutMilliseconds );
}

function GetLocations( URL )
{
	var me = this;

	if ( this.constructor != GetLocations  )
		me = arguments[arguments.length-1];

	Request( URL, "GET", null, me );
	
	me.getScrollTop = function() {
		return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
	}
	
	me.ProcessResponse = function()
    {

	    var obj = document.getElementById( this.id );
	    
	    
	    var div = document.createElement( 'div' );
	    div.setAttribute('id','morelocationspopupdiv');
	    div.setAttribute('z-index',100);
	    div.style.position = 'absolute';
	    div.style.display = 'none';
	    
		var iframe = document.createElement( 'iframe' );
		iframe.setAttribute('id','MapSurfaceIframe');
		iframe.setAttribute('src','blank.htm');
		iframe.setAttribute('frameborder','no');
		iframe.style.margin = 0;
		iframe.style.position = 'absolute';
	    iframe.style.top = '0px';
	    iframe.style.left = '0px';
    	
	    var div2 = document.createElement( 'div' );
	    div2.setAttribute('id','morelocationscontentdiv');
	    div2.style.position = 'absolute';
	    div2.style.top = '0px';
	    div2.style.left = '0px';
	    div2.innerHTML = this._Request.responseText ;
	    
	    document.body.appendChild( div );
	    me.BuildShadows( div );
	    div.appendChild( iframe );
	    div.appendChild( div2 );
    	
	    // Add dom_drag functionilty
	    Drag.init(div, div);
	    link = document.getElementById( 'morelocationslink' );
	    
	    
	    // Display
	    div.style.display = 'block';
	    
	    div.style.top = ( me.findPos( link )[1] + 10 ).toString() + 'px';
	    div.style.left = ((document.body.offsetWidth/2) - (div2.offsetWidth/2)) + 'px';	
	    
	    iframe.setAttribute('width',div2.offsetWidth + 'px');
		iframe.setAttribute('height',div2.offsetHeight + 'px');
		
		me.DisplayShadows( div2 ); 
		
		
		///----------------------------------------------
		var viewportwidth;
        var viewportheight;
         
        if (typeof window.innerWidth != 'undefined')
        {
            viewportwidth = window.innerWidth,
            viewportheight = window.innerHeight
        }
        else if (typeof document.documentElement != 'undefined'
             && typeof document.documentElement.clientWidth !=
             'undefined' && document.documentElement.clientWidth != 0)
        {
            viewportwidth = document.documentElement.clientWidth,
            viewportheight = document.documentElement.clientHeight
        }
        else
        {    
            viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
            viewportheight = document.getElementsByTagName('body')[0].clientHeight
        }
        
		// Edge detection
		d = me.findPos( link )[1] - me.getScrollTop();
		if( d + div2.offsetHeight > viewportheight )
		{
		    e = viewportheight - (d + div2.offsetHeight);
		    f = me.findPos( link )[1] + e;
		    div.style.top = f + 'px'; 
		}
		    
		
    }
    
    me.BuildShadows = function( div ){
        for (var i=0; i < 4; i++)
            this.BuildShadow( i, div );
    }
    
    me.BuildShadow = function( id, div ){
        var sdiv = document.createElement( 'div' );
	    sdiv.setAttribute('id','shadow'+ id );
	    sdiv.style.position = 'absolute';
	    sdiv.style.backgroundColor = '#000000';
	    sdiv.appendChild( document.createTextNode( '&nbsp;' ) );
	    div.appendChild( sdiv );
    }
   
    me.DisplayShadows = function( contentdiv ){
        var shadowOffSet = 1;
        var width = contentdiv.offsetWidth;
        var height = contentdiv.offsetHeight;

        me.DisplayShadow( 0, shadowOffSet, width, height );
        me.DisplayShadow( 1, shadowOffSet * 2, width, height );
        me.DisplayShadow( 2, shadowOffSet * 3, width, height );
        me.DisplayShadow( 3, shadowOffSet * 4, width, height );
    }

    me.DisplayShadow = function(id,offset,width,height){
        div = document.getElementById( 'shadow' + id );
        div.className = 'shadow';
        div.style.top = offset + 'px';
        div.style.left = offset + 'px';
        div.style.width = width + 'px';
        div.style.height = height + 'px';
        div.style.display = 'block';
    }
    
    me.findPos = function(obj) {
	    var curleft = curtop = 0;
	    if (obj.offsetParent) {
		    curleft = obj.offsetLeft
		    curtop = obj.offsetTop
		    while (obj = obj.offsetParent) {
			    curleft += obj.offsetLeft
			    curtop += obj.offsetTop
		    }
	    }
	    return [curleft,curtop];
    }
    
    
	
	// dom-drag.js
	// 10.28.2001
	// www.youngpup.net
	var Drag = {

		obj : null,

		init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
		{
			o.onmousedown    = Drag.start;

			o.hmode            = bSwapHorzRef ? false : true ;
			o.vmode            = bSwapVertRef ? false : true ;

			o.root = oRoot && oRoot != null ? oRoot : o ;

			if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
			if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
			if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
			if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

			o.minX    = typeof minX != 'undefined' ? minX : null;
			o.minY    = typeof minY != 'undefined' ? minY : null;
			o.maxX    = typeof maxX != 'undefined' ? maxX : null;
			o.maxY    = typeof maxY != 'undefined' ? maxY : null;

			o.xMapper = fXMapper ? fXMapper : null;
			o.yMapper = fYMapper ? fYMapper : null;

			o.root.onDragStart    = new Function();
			o.root.onDragEnd    = new Function();
			o.root.onDrag        = new Function();
		},

		start : function(e)
		{
			var o = Drag.obj = this;
			e = Drag.fixE(e);
			var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
			var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
			o.root.onDragStart(x, y);

			o.lastMouseX    = e.clientX;
			o.lastMouseY    = e.clientY;

			if (o.hmode) {
				if (o.minX != null)    o.minMouseX    = e.clientX - x + o.minX;
				if (o.maxX != null)    o.maxMouseX    = o.minMouseX + o.maxX - o.minX;
			} else {
				if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
				if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
			}

			if (o.vmode) {
				if (o.minY != null)    o.minMouseY    = e.clientY - y + o.minY;
				if (o.maxY != null)    o.maxMouseY    = o.minMouseY + o.maxY - o.minY;
			} else {
				if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
				if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
			}

			document.onmousemove = Drag.drag;
			document.onmouseup = Drag.end;

			return false;
		},

		drag : function(e)
		{
			e = Drag.fixE(e);
			var o = Drag.obj;

			var ey    = e.clientY;
			var ex    = e.clientX;
			var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
			var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
			var nx, ny;

			if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
			if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
			if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
			if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

			nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
			ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

			if (o.xMapper)        nx = o.xMapper(y)
			else if (o.yMapper)    ny = o.yMapper(x)

			Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
			Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
			Drag.obj.lastMouseX    = ex;
			Drag.obj.lastMouseY    = ey;

			Drag.obj.root.onDrag(nx, ny);
			return false;
		},

		end : function()
		{
			document.onmousemove = null;
			document.onmouseup   = null;
			Drag.obj.root.onDragEnd(    parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]), 
										parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
			Drag.obj = null;
		},

		fixE : function(e)
		{
			if (typeof e == 'undefined') e = window.event;
			if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
			if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
			return e;
		}
	};
	
	
}

Inherit( Request, GetLocations )


function EnhanceLocationLink()
{
    // Supports basic DOM and Ajax
    if( document.getElementById && createXMLHttpRequest() != null )
    {
        //sURL = document.location.href;
        //sURL = sURL.substr(0, sURL.length - 5);
        //sURL = sURL + '/morelocationsajax/';

	    var el = document.getElementById( 'morelocationslink' );
    	
	    if (el != null)
	        el.setAttribute('href','javascript:PopLocations(\'' + MoreLocationsUrl +'\')' );
	        
	 }
}

var bOpen = false;

function PopLocations(sURL)
{
     if( document.getElementById && createXMLHttpRequest() != null )
    {
	    if ( !bOpen )
	    {
		    bOpen = true;
		    var	g = new GetLocations( sURL );
		    g.Send();
	    }
	}
}

function closemorelocations()
{

    var el = document.getElementById( 'morelocationspopupdiv' );
	
    if (el != null)
        document.body.removeChild(el);
	
    bOpen = false;
	
}


YAHOO.util.Event.onDOMReady(EnhanceLocationLink);