// iCD Map API - Copyright (c) 2006-2009 i-CD Publishing
var flashLocation = 'icdmap';
var minFlashVersion = 8;
var currentFlashVersion;
var useDhtmlMaps=false;
var hasLoaded = "n";
var hasInitialised = false;
var top_left_x = 0;
var top_left_y = 0;
var bottom_right_x = 0;
var bottom_right_y = 0;
var lastClickedX = -1;
var lastClickedY = -1;
var flagClicked = false;
var moveCounter = 0; 
var lastMoveCounter = -1;
var msgQ = new Array();
var msgPtr = 0;
var zoomChangeNotify = -1;
var serialComSpeed = 20;
var retryTimeout=1000;
var batchCmds = "";
var semaphore=0;
var useSemaphore=false;
var useInsertTarget=false;
var insertTarget=null;
var mapDivName='icdMapDiv';

// Resizable flag
var resizable=false;

var insZoom; // set during mapinsert
var insGre;
var insGrn;
var insWidth;
var insHeight;
var mapServer='www2.mapping.192.com';
var mapGre=526256;
var mapGrn=176146;
var mapLevel=6;
var mapZoomOption='none';		// options are: auto, route, none
var mapMinZoomLevel=0;
var mapMaxZoomLevel=10;
var mapPois=new Array;
var mapRouteThickness=5;
var mapRouteColor="0xffff00";
var mapRouteAlpha=200;	
var mapRoute='';
var mapClientCode="";
var mapSearchCode="";
var mapPageName="";
var mapWidth=300;
var mapHeight=300;
var mapPoiIcon='';
var mapTxtWidth = 200;
var mapPictWidth= -1;
var mapPictHeight= -1;
var mapResized=false;
//	Used to change location to focus on the map
var mapFocusBalloon=false;
var mapFocusOnBalloon=null;
//	Used to redraw map with zoom
var mapZoomStreetLevel = 5;
var mapGeocodesChanged=false;
var mapZoomRedrawPOI=false;
var mapRedrawPois = false;
var mapSliderVisible = true;
var mapSliderVisibilityUpdate = false;
var mapJQueryNoConflict = false;
var dhtmlLocation='http://api.betamapping.192.com/';
//var dhtmlLocation='http://api.devmapping.192.com/';
//var dhtmlLocation='http://localhost.192.com/mapapi/';
var modulesURL = "http://Modules.betamapping.192.com/";
//var modulesURL = "http://Modules.devmapping.192.com/";
//var modulesURL = "http://localhost/MapModules/";

var ont_mapApiClickListener;
var ont_mapApiDoubleClickListener;
var ont_mapApiZoomInListener;
var ont_mapApiZoomOutListener;
var ont_mapApiZoomEndListener;
var ont_mapApiMoveStartListener;
var ont_mapApiMoveListener;
var ont_mapApiMoveEndListener;
var ont_mapApiDragStartListener;
var ont_mapApiDragListener;
var ont_mapApiDragEndListener;
var ont_mapApiLoadListener;
var ont_mapApiPoiClickListener;
var ont_mapApiPoiOverListener;
var ont_mapApiPoiOutListener;
var ont_mapApiPoiImageClickListener;
var ont_mapApiPoiLinkClickListener;
var ont_mapApiPoiTriggerOpenListener;
var ont_mapApiPoiTriggerCloseListener;

var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false; 
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false; 
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
var ie=document.all;
var nn6=document.getElementById&&!document.all;

// map ready to accept new poi, wait until this is 'y' before
// each addBallon call
var accepting = "n";

// domain
if(document.domain.indexOf('192.com') != -1)
{
    document.domain='192.com';
}

//setter for the flashLocation var
function setflashLocation(FlashObjLocation)
{
	flashLocation = FlashObjLocation;
}
function setDhtmlLocation(FlashObjLocation)
{
	dhtmlLocation = FlashObjLocation;
}
function setModulesURL(theURL)
{
	modulesURL = theURL;
}

// JavaScript helper required to detect Flash Player PlugIn version information 
function GetSwfVer(){ 
	// NS/Opera version >= 3 check for Flash plugin in plugin array 
	var flashVer = -1; 

	if (navigator.plugins != null && navigator.plugins.length > 0) { 
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) { 
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : ""; 
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;    
			var descArray = flashDescription.split(" "); 
			var tempArrayMajor = descArray[2].split("."); 
			var versionMajor = tempArrayMajor[0]; 
			var versionMinor = tempArrayMajor[1]; 
			if ( descArray[3] != "" ) { 
				tempArrayMinor = descArray[3].split("r"); 
			} else { 
				tempArrayMinor = descArray[4].split("r"); 
			} 
			var versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0; 
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision; 
		} 
	} 
	// MSN/WebTV 2.6 supports Flash 4 
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4; 
	// WebTV 2.5 supports Flash 3 
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3; 
	// older WebTV supports Flash 2 
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2; 
	else if ( isIE && isWin && !isOpera ) { 
		//flashVer = ControlVersion(); 
		try{
	        axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
            wver = axo.GetVariable("$version");
            wver = wver.replace(/[,]/g,'.');
            wspl = wver.split(/[ ]/);
            flashVer = wspl[1];
        }catch(err)
        {
            return -1;
        }
	}  
	return flashVer; 
}
// get major version
var fver = String(GetSwfVer());
if(fver != undefined && fver != null)
{
    var spl  = fver.split(/[.]/);
    currentFlashVersion =  spl[0];
}else{
    currentFlashVersion = 0;
}

if(currentFlashVersion < minFlashVersion)
{
	useDhtmlMaps=true;
	useSemaphore=true;
}	

function forceDhtmlMaps()
{
	useDhtmlMaps=true;
	useSemaphore=true;
}
	
// call this first
function initMapApi()
{
	if(useDhtmlMaps) {
		importPrototype();
		return;
	}

	if(hasLoaded == "n")
	{
		// retry again in a moment
		setTimeout("initMapApi()", retryTimeout);
		return;
	}

	obj = window.document.icdmap;
	if(obj == null) {
		alert("iCD Map API - cannot find object with id 'icdmap'");	
	} else {
		try {
			window.document.icdmap.SetVariable("useapi", "y");
		} catch(err) {
			// retry again in a moment
			setTimeout("initMapApi()", retryTimeout);
			return;		
		}
	}
	
	importPrototype();
	//importjQuery();
	
	// trigger once, let map set this onwards
	accepting = "y";
	
	hasInitialised = true;

	ApiTick();
	
}

function importPrototype() {
	// Create the new SCRIPT tag and put it into the DOM
	var head = document.getElementsByTagName("head").item(0);
	scriptElement = document.createElement('script');
	scriptElement.setAttribute('type','text/javascript');
	scriptElement.setAttribute('src',dhtmlLocation+"prototype.js");
	head.appendChild(scriptElement);
}

function importjQuery() {
	// Create the new SCRIPT tag and put it into the DOM
	if (typeof jQuery == 'undefined') {
		var head = document.getElementsByTagName("head").item(0);
		scriptElement = document.createElement('script');
		scriptElement.setAttribute('type','text/javascript');
		scriptElement.setAttribute('src',dhtmlLocation+"jquery-1.2.6.js");
		head.appendChild(scriptElement);
	}
}

// delver commands from the message queue
function ApiTick()
{	
	if(accepting == "y")
	{
		var _batchFlushAlready;

		while(msgQ.length > 0)
		{
			var o = msgQ.shift();
			
			//alert("q msg = "+o.cmd);
			
			switch(o.cmd)
			{
				case 'applyBatchCommands':
					if(_batchFlushAlready) break;
					_batchFlushAlready = true;

					flushBatchCmds();
					window.document.icdmap.SetVariable("processBatchCommands", "y");	
				break;

				case 'batchFlush':
					window.document.icdmap.SetVariable("batchCmds", batchCmds);
				    batchCmds = "";
				break;
			
				case 'apply':
					if(_batchFlushAlready) break;
					_batchFlushAlready = true;
				
					flushBatchCmds();
					window.document.icdmap.SetVariable("applyRequest", "y");	
				break;
				
				case 'focus':
					window.document.icdmap.SetVariable("balReq", o.bref);
					window.document.icdmap.SetVariable("focusRequest", "y");
				break;
				
				case 'bmanagerVersion':
					window.document.icdmap.SetVariable("bmanagerType", o.pBmanagerType);
				break;
				
				case 'applySegs':    
					if(_batchFlushAlready) break;
					batchFlushAlready = true;

					flushBatchCmds();
					window.document.icdmap.SetVariable("routeSeg", "apply");
				break;
				
				case 'hidepoitype': 
				    window.document.icdmap.SetVariable("poiTypeToChange", o.poiType);
				    window.document.icdmap.SetVariable("poiTypeOperation", "hide");
				
			    break;
				case 'showpoitype': 
					window.document.icdmap.SetVariable("poiTypeToChange", o.poiType);
				    window.document.icdmap.SetVariable("poiTypeOperation", "show");
			    break;

				case 'setopacityofallpoisbut':
					window.document.icdmap.SetVariable("apiSetPoiRef", o.poiRef);
				    window.document.icdmap.SetVariable("apiSetPoiAlpha", o.poiAlpha);
				    window.document.icdmap.SetVariable("poiTypeOperation", "alpha");
				break;
				case 'setopacityofallpoitypesbut':
					window.document.icdmap.SetVariable("apiSetPoiRef", o.poiRef);
				    window.document.icdmap.SetVariable("apiSetPoiAlpha", o.poiAlpha);
				    window.document.icdmap.SetVariable("poiTypeToChange", o.poiType);
				    window.document.icdmap.SetVariable("poiTypeOperation", "alpha");
				break;
					
				case 'setzoom':
					window.document.icdmap.SetVariable("apiSetZoomReq", o.zoomlev);
				break;
				case 'autozoom':
					window.document.icdmap.SetVariable("apiAutoZoomReq", "y");
				break;
				case 'zoomRoute':
					window.document.icdmap.SetVariable("apiZoomRoute", "y");
				break;
				
				case 'showzoomslider':
					window.document.icdmap.SetVariable("apiSetZoomSliderVisible", o.isvisible);
				break;
				
				case 'setgeocodegregrn':
					window.document.icdmap.SetVariable("apiSetGre", o.gre);
					window.document.icdmap.SetVariable("apiSetGrn", o.grn);
					window.document.icdmap.SetVariable("apiSetGeocodeReq", "y");
//					window.document.icdmap.SetVariable("geox", o.gre);
//					window.document.icdmap.SetVariable("geoy", o.grn);
//					window.document.icdmap.SetVariable("lastClickedGre", o.gre);
//					window.document.icdmap.SetVariable("lastClickedGrn", o.gre);
				break;
				case 'setgeocodegregrnandzoom':
					window.document.icdmap.SetVariable("apiSetGreAndZoom", o.gre);
					window.document.icdmap.SetVariable("apiSetGrnAndZoom", o.grn);
					window.document.icdmap.SetVariable("apiSetZoomLevel", o.zoomlev);
					window.document.icdmap.SetVariable("apiSetGeocodeAndZoomReq", "y");
//					window.document.icdmap.SetVariable("geox", o.gre);
//					window.document.icdmap.SetVariable("geoy", o.grn);
//					window.document.icdmap.SetVariable("lastClickedGre", o.gre);
//					window.document.icdmap.SetVariable("lastClickedGrn", o.gre);
				break;

				case 'addClickListener':
					window.document.icdmap.SetVariable("apiClickListener", o.callback);
				break;
				case 'addDoubleClickListener':
					window.document.icdmap.SetVariable("apiDoubleClickListener", o.callback);
				break;
				case 'addZoomInListener':
					window.document.icdmap.SetVariable("apiZoomInListener", o.callback);
				break;
				case 'addZoomOutListener':
					window.document.icdmap.SetVariable("apiZoomOutListener", o.callback);
				break;
				case 'addZoomEndListener':
					window.document.icdmap.SetVariable("apiZoomEndListener", o.callback);
				break;
				case 'addMoveStartListener':
					window.document.icdmap.SetVariable("apiMoveStartListener", o.callback);
				break;
				case 'addMoveListener':
					window.document.icdmap.SetVariable("apiMoveListener", o.callback);
				break;
				case 'addMoveEndListener':
					window.document.icdmap.SetVariable("apiMoveEndListener", o.callback);
				break;
				case 'addDragStartListener':
					window.document.icdmap.SetVariable("apiDragStartListener", o.callback);
				break;
				case 'addDragListener':
					window.document.icdmap.SetVariable("apiDragListener", o.callback);
				break;
				case 'addDragEndListener':
					window.document.icdmap.SetVariable("apiDragEndListener", o.callback);
				break;
				case 'addLoadListener':
					window.document.icdmap.SetVariable("apiLoadListener", o.callback);
				break;
				case 'addPoiClickListener':
					window.document.icdmap.SetVariable("apiPoiClickListener", o.callback);
				break;
				case 'addPoiOverListener':
					window.document.icdmap.SetVariable("apiPoiOverListener", o.callback);
				break;
				case 'addPoiOutListener':
					window.document.icdmap.SetVariable("apiPoiOutListener", o.callback);
				break;
				case 'addPoiImageClickListener':
					window.document.icdmap.SetVariable("apiPoiImageClickListener", o.callback);
				break;
				case 'addPoiLinkClickListener':
					window.document.icdmap.SetVariable("apiPoiLinkClickListener", o.callback);
				break;
				case 'addPoiTriggerOpenListener':
					window.document.icdmap.SetVariable("apiPoiTriggerOpenListener", o.callback);
				break;
				case 'addPoiTriggerCloseListener':
					window.document.icdmap.SetVariable("apiPoiTriggerCloseListener", o.callback);
				break;
			}
		
		}
		// await flash command to change this to yes
		accepting = "n";
	}
	
	setTimeout("ApiTick()", serialComSpeed);
}

function addBatchCmd(cmd, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12)
{
    batchCmds += cmd + 	(arg1 ? ("|" + arg1) : "|") +
					(arg2 ? ("|" + arg2) : "|") +
					(arg3 ? ("|" + arg3) : "|") +
					(arg4 ? ("|" + arg4) : "|") +
					(arg5 ? ("|" + arg5) : "|") +
					(arg6 ? ("|" + arg6) : "|") +
					(arg7 ? ("|" + arg7) : "|") +
					(arg8 ? ("|" + arg8) : "|") +
					(arg9 ? ("|" + arg9) : "|") +
					(arg10 ? ("|" + arg10) : "|") +
					(arg11 ? ("|" + arg11) : "|") +
					(arg12 ? ("|" + arg12) : "|") + "~~"; 
					
					
	//alert(batchCmds);
} 
function flushBatchCmds()
{   
	var o = new Object();
	o.cmd = 'batchFlush';
	msgQ.push(o);

}

// --------------------------------------
// simple detection that map has moved
function hasMoved()
{
	if(lastMoveCounter != moveCounter)
		return true;
	
	return false;
	
}

// once you detected a move and acted upon it, call this
// so that
function resetMoveDetection()
{
	lastMoveCounter = moveCounter;
}

//------------------------------------------
// change balloon style
function setBalloonPreferences(fillcolour, alpha, borderColor, borderThickness, txtwidth, icon, pictWidth, pictHeight, padding, cornerRounding)
{
	if(useDhtmlMaps)
	{
	    semaphore++;
	    mapPoiIcon=icon;
	    mapTxtWidth=txtwidth;
	    mapPictWidth=pictWidth;
	    mapPictHeight=pictHeight;
	    
		return;
	}
		addBatchCmd('balpref',	
			icon,    
			txtwidth,    
			pictWidth,    
			pictHeight, 
			fillcolour,
			alpha,    
			borderColor,
			borderThickness,
			padding,
			cornerRounding
		);
		
}
//------------------------------------------
// add a poi to the scene
function addBalloon(ref, type, gre, grn, heading, bodytext, linkUrl, linkName, pictUrl, linkTarget, poiLabel)
{
	var mapPois = mapGetPois();
	for(var g=0;g<mapPois.length;g++){
		if(mapPois[g].ref == ref) {
			return;
		}
	}
    linkTarget = typeof(linkTarget) != 'undefined' ? linkTarget : "_top";

    var ob = new Object;
    ob.ref = ref;
    ob.type=type;
    ob.gre=gre;
    ob.grn=grn;
    ob.heading=heading;
    ob.bodytext=bodytext;
    ob.linkUrl=linkUrl;
    ob.linkName=linkName;
    ob.pictUrl=pictUrl;
    ob.icon=mapPoiIcon;
    ob.txtwidth= mapTxtWidth;
    ob.pictwidth=mapPictWidth;
    ob.pictheight=mapPictHeight;
    ob.linkTarget = linkTarget;
    ob.poiLabel = poiLabel;
	ob.visible = true;
	ob.alpha = 100;

    mapPois.push(ob);

	if(useDhtmlMaps)
	{
	    semaphore++;
		return;
	}

		
	addBatchCmd('add',	
			ref,
			type,
			gre.toString(),
			grn.toString(),
			heading,
			bodytext,
			pictUrl,
			linkUrl,
			linkName,
			linkTarget,
			poiLabel
	);

}

// clear all poi from the scene
function clearBalloons()
{
    mapPois = null;
    mapPois = new Array;

	if(useDhtmlMaps)
	{
	    semaphore++;
		return;
	}

	addBatchCmd('clearRequest');
}

// the poi's will not appear until this is called
//  - perform multiple addBalloon() calls then call this.
function applyBalloons()
{
	if(useDhtmlMaps)
	{
	    mapZoomOption='none';
		//mapZoomRedrawPOI = true;
//		mapResized = true;
		mapRedrawPois=true;
	    semaphore++;
		return;
	}
		
	var o = new Object();
	o.cmd = 'apply';
	msgQ.push(o);
	
}

function focusBalloon(ref)
{
	if(useDhtmlMaps)
	{
	    for(i=0; i<mapPois.length; i++)
	    {
	        if (mapPois[i].ref == ref) {
				mapGre=mapPois[i].gre;	
				mapGrn=mapPois[i].grn;	
				mapFocusBalloon=true;
				mapFocusOnBalloon = ref;
//		       	mapFocusBalloonTo(mapPois[i].gre,mapPois[i].grn);
	        	break;
	        }
	    }

	    semaphore++;
		return;
	}

	var o = new Object();
	o.cmd = 'focus';
	o.bref=ref;
	msgQ.push(o);
}

// set the poi type
function setBalloonManagerVersion(v)
{
    var o = new Object();
    o.cmd = 'bmanagerVersion';
	o.pBmanagerType = v;
    msgQ.push(o);
}

// action listener functions
function addClickListener(p_CallBackFunction)
{
	ont_mapApiClickListener = p_CallBackFunction;
	var o = new Object();
	o.cmd = 'addClickListener';
	o.callback = p_CallBackFunction;
	msgQ.push(o);
}
function getClickListener()
{
	return(ont_mapApiClickListener);
}

function addDoubleClickListener(p_CallBackFunction)
{
	ont_mapApiDoubleClickListener = p_CallBackFunction;
	var o = new Object();
	o.cmd = 'addDoubleClickListener';
	o.callback = p_CallBackFunction;
	msgQ.push(o);
}
function getDoubleClickListener()
{
	return(ont_mapApiDoubleClickListener);
}

function addZoomInListener(p_CallBackFunction)
{
	ont_mapApiZoomInListener = p_CallBackFunction;
	var o = new Object();
	o.cmd = 'addZoomInListener';
	o.callback = p_CallBackFunction;
	msgQ.push(o);
}
function getZoomInListener()
{
	return(ont_mapApiZoomInListener);
}

function addZoomOutListener(p_CallBackFunction)
{
	ont_mapApiZoomOutListener = p_CallBackFunction;
	var o = new Object();
	o.cmd = 'addZoomOutListener';
	o.callback = p_CallBackFunction;
	msgQ.push(o);
}
function getZoomOutListener()
{
	return(ont_mapApiZoomOutListener);
}

function addZoomEndListener(p_CallBackFunction)
{
	ont_mapApiZoomEndListener = p_CallBackFunction;
	var o = new Object();
	o.cmd = 'addZoomEndListener';
	o.callback = p_CallBackFunction;
	msgQ.push(o);
}
function getZoomEndListener()
{
	return(ont_mapApiZoomEndListener);
}

function addMoveStartListener(p_CallBackFunction)
{
	ont_mapApiMoveStartListener = p_CallBackFunction;
	var o = new Object();
	o.cmd = 'addMoveStartListener';
	o.callback = p_CallBackFunction;
	msgQ.push(o);
}

function addMoveListener(p_CallBackFunction)
{
	ont_mapApiMoveListener = p_CallBackFunction;
	var o = new Object();
	o.cmd = 'addMoveListener';
	o.callback = p_CallBackFunction;
	msgQ.push(o);
}

function addMoveEndListener(p_CallBackFunction)
{
	ont_mapApiMoveEndListener = p_CallBackFunction;
	var o = new Object();
	o.cmd = 'addMoveEndListener';
	o.callback = p_CallBackFunction;
	msgQ.push(o);
}

function addDragStartListener(p_CallBackFunction)
{
	ont_mapApiDragStartListener = p_CallBackFunction;
	var o = new Object();
	o.cmd = 'addDragStartListener';
	o.callback = p_CallBackFunction;
	msgQ.push(o);
}

function addDragListener(p_CallBackFunction)
{
	ont_mapApiDragListener = p_CallBackFunction;
	var o = new Object();
	o.cmd = 'addDragListener';
	o.callback = p_CallBackFunction;
	msgQ.push(o);
}

function addDragEndListener(p_CallBackFunction)
{
	ont_mapApiDragEndListener = p_CallBackFunction;
	var o = new Object();
	o.cmd = 'addDragEndListener';
	o.callback = p_CallBackFunction;
	msgQ.push(o);
}

function addLoadListener(p_CallBackFunction)
{
	ont_mapApiLoadListener = p_CallBackFunction;
	var o = new Object();
	o.cmd = 'addLoadListener';
	o.callback = p_CallBackFunction;
	msgQ.push(o);
}

function addPoiClickListener(p_CallBackFunction)
{
	ont_mapApiPoiClickListener = p_CallBackFunction;
	var o = new Object();
	o.cmd = 'apiPoiClickListener';
	o.callback = p_CallBackFunction;
	msgQ.push(o);
}
function getPoiClickListener()
{
	return(ont_mapApiPoiClickListener);
}

function addPoiOverListener(p_CallBackFunction)
{
	ont_mapApiPoiOverListener = p_CallBackFunction;
	var o = new Object();
	o.cmd = 'addPoiOverListener';
	o.callback = p_CallBackFunction;
	msgQ.push(o);
}
function getPoiOverListener()
{
	return(ont_mapApiPoiOverListener);
}

function addPoiOutListener(p_CallBackFunction)
{
	ont_mapApiPoiOutListener = p_CallBackFunction;
	var o = new Object();
	o.cmd = 'addPoiOutListener';
	o.callback = p_CallBackFunction;
	msgQ.push(o);
}
function getPoiOutListener()
{
	return(ont_mapApiPoiOutListener);
}

function addPoiImageClickListener(p_CallBackFunction)
{
	ont_mapApiPoiImageClickListener = p_CallBackFunction;
	var o = new Object();
	o.cmd = 'addPoiImageClickListener';
	o.callback = p_CallBackFunction;
	msgQ.push(o);
}
function getPoiImageClickListener()
{
	return(ont_mapApiPoiImageClickListener);
}

function addPoiLinkClickListener(p_CallBackFunction)
{
	ont_mapApiPoiLinkClickListener = p_CallBackFunction;
	var o = new Object();
	o.cmd = 'addPoiLinkClickListener';
	o.callback = p_CallBackFunction;
	msgQ.push(o);
}
function getPoiLinkClickListener()
{
	return(ont_mapApiPoiLinkClickListener);
}

function addPoiTriggerOpenListener(p_CallBackFunction)
{
	ont_mapApiPoiTriggerOpenListener = p_CallBackFunction;
	var o = new Object();
	o.cmd = 'addPoiTriggerOpenListener';
	o.callback = p_CallBackFunction;
	msgQ.push(o);
}
function getPoiTriggerOpenListener()
{
	return(ont_mapApiPoiTriggerOpenListener);
}

function addPoiTriggerCloseListener(p_CallBackFunction)
{
	ont_mapApiPoiTriggerCloseListener = p_CallBackFunction;
	var o = new Object();
	o.cmd = 'addPoiTriggerCloseListener';
	o.callback = p_CallBackFunction;
	msgQ.push(o);
}
function getPoiTriggerCloseListener()
{
	return(ont_mapApiPoiTriggerCloseListener);
}

//------------------------------------------
// functions to get the viewable area
function getX1()
{
	return top_left_x;	
}

function getY1()
{
	return top_left_y;	
}

function getX2()
{
	return bottom_right_x;	
}

function getY2()
{
	return bottom_right_y;	
}

// functions to get the last clicked position in gre/grn
function hasClicked()
{
	if(flagClicked == true)
	{
		flagClicked=false;
		return true;
	
	}
	return false;	
}

function getLastClickedX()
{
	return lastClickedX;
}
function getLastClickedY()
{
	return lastClickedY;
}

//------------------------------------------
// function to detect if map has moved or zoomed
function getMoveCounter()
{
	if(useDhtmlMaps)
	{
	    semaphore++;
		return;
	}
		
	obj = document.getElementById("icdmap");
	return obj.GetVariable("moveCounter");	
		
}

//------------------------------------------
function hidePoiType(type)
{
	for(var i = 0; i < mapPois.length; i++) {
		if(mapPois[i].type == type) {
			mapPois[i].visible = false;
		}	
	}
	
	if(useDhtmlMaps)
	{
		mapRedrawPois=true;
	    semaphore++;
		return;
	}
		
    var o = new Object();
	o.cmd = 'hidepoitype';
	o.poiType = type;
	msgQ.push(o);
}

function clearPoiType(type,start) {
	var i = typeof(start) == 'undefined' ? 0 : start;
	for(var x = i; x < mapPois.length; x++) {
		if(mapPois[x].type == type) {
			mapPois.splice(x,1);
			clearPoiType(type,x);
			if(typeof(start) != 'undefined')
				return;
			else {
				if(useDhtmlMaps) {
					mapRedrawPois = true;
					semaphore++;
					return;
				}
			}
		}
	}

	addBatchCmd('clearpoitype', type);
}

function showPoiType(type)
{
	for(var i = 0; i < mapPois.length; i++) {
		if(mapPois[i].type == type)
			mapPois[i].visible = true;	
	}
	
	if(useDhtmlMaps)
	{
		mapRedrawPois=true;
	    semaphore++;
		return;
	}
		
    var o = new Object();
	o.cmd = 'showpoitype';
	o.poiType = type;
	msgQ.push(o);
}

function setPoiColor(pRef, pType, pColor)
{
	for(var i = 0; i < mapPois.length; i++) {
		if(mapPois[i].type == pType) {
			if(mapPois[i].ref != pRef) {
				mapPois[i].color = pColor;
			}
		}
	}

	if(useDhtmlMaps)
	{
		mapRedrawPois=true;
	    semaphore++;
		return;
	}

	addBatchCmd('setPoiColor',	
			pRef,
			pType,
			pColor
	);

}

function applyBatchCommands()
{
	if(useDhtmlMaps)
	{
	    semaphore++;
		return;
	}
		
    var o = new Object();
	o.cmd = 'applyBatchCommands';
	msgQ.push(o);
}

function setOpacityOfAllPoisBut(pAlpha, pRef)
{
	for(var i = 0; i < mapPois.length; i++) {
		if(mapPois[i].ref != pRef) {
			mapPois[i].alpha = pAlpha;
		}
	}

	if(useDhtmlMaps)
	{
		mapRedrawPois=true;
	    semaphore++;
		return;
	}

    var o = new Object();
	o.cmd = 'setopacityofallpoisbut';
	o.poiAlpha = pAlpha;
	o.poiRef = pRef;
	msgQ.push(o);
}

function setOpacityOfAllPoiTypesBut(pAlpha, pRef, pType)
{
	for(var i = 0; i < mapPois.length; i++) {
		if(mapPois[i].type == pType) {
			if(mapPois[i].ref != pRef) {
				mapPois[i].alpha = 1/pAlpha;
			}
		}
	}

	if(useDhtmlMaps)
	{
		mapRedrawPois=true;
	    semaphore++;
		return;
	}

    var o = new Object();
	o.cmd = 'setopacityofallpoitypesbut';
	o.poiAlpha = pAlpha;
	o.poiType = pType;
	o.poiRef = pRef;
	msgQ.push(o);
}

//------------------------------------------
function setGreGrn(pgre, pgrn)
{
	if(useDhtmlMaps)
	{
	    mapGre = pgre;
	    insGre = Number(mapGre);
	    mapGrn = pgrn;
	    insGrn = Number(mapGre);
	    mapGeocodesChanged = true;
	    semaphore++;
		return;
	}
		
	var o = new Object();
	o.cmd = 'setgeocodegregrn';
	o.gre = pgre;
	o.grn = pgrn;
	msgQ.push(o);
	
}

function setGreGrnAndZoom(pgre, pgrn, pzoom)
{
	if(useDhtmlMaps)
	{
	    mapGre = pgre;
	    insGre = Number(mapGre);
	    mapGrn = pgrn;
	    insGrn = Number(mapGre);
	    mapLevel=pzoom;
	    mapGeocodesChanged = true;
	    semaphore++;
		return;
	}
		
	var o = new Object();
	o.cmd = 'setgeocodegregrnandzoom';
	o.gre = pgre;
	o.grn = pgrn;
	o.zoomlev = pzoom;
	msgQ.push(o);
}

function setZoom(level)
{
	if(useDhtmlMaps)
	{
	    mapLevel=level;
	    semaphore++;
		return;
	}
		
	var o = new Object();
	o.cmd = 'setzoom';
	o.zoomlev = level;
	msgQ.push(o);
}

function autoZoom()
{
	if(useDhtmlMaps)
	{
	    mapZoomOption='auto';
		mapRedrawPois = true;
	    semaphore++;
		return;
	}
		
	var o = new Object();
	o.cmd = 'autozoom';
	msgQ.push(o);
}

function getZoom()
{
	return zoomChangeNotify;
}

//------------------------------------------
var hasDelayedFocus=false;
var zzf_oldsz;
var delayed_id;
var zzf_newz;

function setZoomThenFocusBalloon(level, ref)
{
	if(useDhtmlMaps)
	{
	    semaphore++;
		return;
	}
		
	if(false == hasDelayedFocus)
	{
//		if (level == getZoom()) {
//			setZoom(9);
//		}
		focusBalloon(ref);

//	    for(i=0; i<mapPois.length; i++)
//	    {
//	        if (mapPois[i].ref == ref) {
//				window.document.icdmap.SetVariable("_root.geox", mapPois[i].gre);
//				window.document.icdmap.SetVariable("_root.geoy", mapPois[i].grn);
//				window.document.icdmap.SetVariable("_root.geossx", mapPois[i].gre);
//				window.document.icdmap.SetVariable("_root.geossy", mapPois[i].grn);
//				window.document.icdmap.SetVariable("_root.lastClickedGre", mapPois[i].gre);
//				window.document.icdmap.SetVariable("_root.lastClickedGrn", mapPois[i].grn);
//				window.document.icdmap.SetVariable("_root.gre", mapPois[i].gre);
//				window.document.icdmap.SetVariable("_root.grn", mapPois[i].grn);
//			}
//		}
		
		setZoom(level);
		delayed_id=ref;
		zzf_newz=level;
		zzf_oldsz=getZoom();
		setTimeout("zzf_delayCheckReady()", 500);
		hasDelayedFocus=true;
	}else{
		focusBalloon(ref);
	}
}

function zzf_delayCheckReady()
{
	var isready=false;
	if(zzf_oldsz==zzf_newz) { isready = true };
	if(getZoom() == zzf_newz) { isready = true };
	if(isready)
	{
		focusBalloon(delayed_id);
		zzf_newz = getZoom();
		setTimeout("zzf_zoomMonitor()", 500);
		
	}else{
		setTimeout("zzf_delayCheckReady()", 500);
	}
}
function zzf_zoomMonitor()
{
	// detect a change in zoom and reset
	if(getZoom() != zzf_newz) { hasDelayedFocus=false };
	setTimeout("zzf_zoomMonitor()", 500);
}

//------------------------------------------
function showZoomSlider(isVisible)
{
	if(useDhtmlMaps)
	{
		if(isVisible != mapSliderVisible) {
			mapSliderVisibilityUpdate = true;
			mapSliderVisible = isVisible;
		}
	    semaphore++;
		return;
	}
		
	var o = new Object();
	o.cmd = 'showzoomslider';
	o.isvisible = isVisible;
	msgQ.push(o);
}

//------------------------------------------
// route planner api

// 
function clearRoute()
{
	if(useDhtmlMaps)
	{
	    mapRoute='';
	    semaphore++;
		return;
	}
		
	addBatchCmd('clearRoute');
}
function addRouteSegment(roadName, x1, y1, x2, y2, color, thickness, alpha)
{
	if(useDhtmlMaps)
	{
	    if(mapRoute!='')
	        mapRoute = mapRoute+x1+','+y1;
	    else
	        mapRoute = mapRoute+','+x2+','+y2;    
	    semaphore++;
		return;
	}
		
	addBatchCmd('addSeg', roadName, x1, y1, x2, y2, color, thickness, alpha);
}
function setRoutePreferences(color, thickness, alpha)
{
	if(useDhtmlMaps)
	{
	    semaphore++;
		return;
	}
		
	addBatchCmd('routePref', color, thickness, alpha);
}

function addRoutePart(desc, action, name, rpoints)
{
	if(useDhtmlMaps)
	{
	    if(rpoints != "undefined" && rpoints != "")
	    {
	        if(mapRoute=='')
	            mapRoute = rpoints;
	        else
	            mapRoute = mapRoute+','+rpoints; 
	    }
	    semaphore++;
		return;
	}
		
	addBatchCmd('addRoute', desc, action, name, rpoints);
}

function applyRoute()
{
	if(useDhtmlMaps)
	{
	    semaphore++;
		return;
	}
		
    var o = new Object();
	o.cmd = 'applySegs';
	msgQ.push(o);
}

function autoZoomOnRoute()
{
	if(useDhtmlMaps)
	{
	    mapZoomOption='route';
	    semaphore++;
		return;
	}
		
    var o = new Object();
	o.cmd = 'zoomRoute';
	msgQ.push(o);
}
//------------------------------------------

// Check this flag to see if the map is ready to accept messages via the API
function isAccepting() {
	return (useDhtmlMaps ? true : accepting=="y");
}
// Check this flag to see if the dependency libraries have been loaded
function isDependenciesLoaded() {
	if (typeof jQuery != 'undefined') {
		if (mapJQueryNoConflict == false)
		{
			jQuery.noConflict();
			mapJQueryNoConflict = true;
			return (false);
		}
	}
	return typeof(Prototype) != 'undefined';
}
// Helper function to check both of the above in one call. Don't use this if there's no map on the page, as isAccepting() will always be false
function isApiReady() {
	return isAccepting() && isDependenciesLoaded();
}
/*
function icdmap_myMapReady()                
{
	hasLoaded = 'y';
  	accepting = 'y';
}
*/
// messages from the flash map
var isInternetExplorer = navigator.appName.indexOf("Microsoft") != -1;
function icdmap_DoFSCommand(command, args)                
{
var icdmapObj = isInternetExplorer ? document.all.icdmap : document.icdmap;
//alert(command+"="+args);

  var sargs=args.split("=");
  
  var cmd = sargs[0];
  switch (cmd)
  {
	case "hasLoaded":	
		hasLoaded = sargs[1];
		break;
	case 'accepting':
	  	accepting = sargs[1];
		break;
	case 'top_left_x': 
	  	top_left_x = sargs[1];
		break;
	case 'top_left_y':
		top_left_y = sargs[1];
		break;
  	case 'bottom_right_x':
	  	bottom_right_x = sargs[1];
		break;
  	case 'bottom_right_y':
	  	bottom_right_y = sargs[1];
		break;
	case 'moveCounter':
		moveCounter = sargs[1];
		break;
	case 'clickedX':
		lastClickedX = sargs[1];
		break;
	case 'clickedY':
		lastClickedY = sargs[1];
		break;
	case 'clicked':
		flagClicked = true;
		break;
	case 'zoomchange':
		zoomChangeNotify = sargs[1];
		break;
	
	}  
}

// Hook for Internet Explorer.
if (navigator.appName && navigator.appName.indexOf("Microsoft") != -1 && navigator.userAgent.indexOf("Windows") != -1 && navigator.userAgent.indexOf("Windows 3.1") == -1) {
    document.write('<script language=\"VBScript\"\>\n');
    document.write('On Error Resume Next\n');
    document.write('Sub icdmap_FSCommand(ByVal command, ByVal args)\n');
    document.write('	Call icdmap_DoFSCommand(command, args)\n');
    document.write('End Sub\n');
    document.write('</script\>\n');
}

//v1.0
//Copyright 2006 Adobe Systems, Inc. All rights reserved.
var movieName = "";
var addUrlParams = "";

function map_AddExtension(src, ext)
{
	if (src.indexOf('?') != -1)
	{
		var v=src.replace(/\?/, ext+'?');
		return v;
	}
	else
	{
		return src + ext;
	}
}

function map_Generateobj(objAttrs, params, embedAttrs) 
{ 
	var str = '<object ';
	for (var i in objAttrs)
	str += i + '="' + objAttrs[i] + '" ';
	str += '>';

//	str += '----------';

	for (var i in params)
	str += '<param name="' + i + '" value="' + params[i] + '" />\n';
	str += '<embed ';
	
//	str += '----------';

	for (var i in embedAttrs)
	str += i + '="' + embedAttrs[i] + '" ';
	str += ' ></embed>\n</object>';

//	alert(str);

    if(!useInsertTarget)
    {
		if (resizable.toString() == "false") {
			document.write('<div id ="'+mapDivName+'" style="width: '+mapWidth+'px; height:'+mapHeight+'px">');
		}
		else {
			document.write('<div id ="'+mapDivName+'">');
		}
	    document.write(str);
		document.write('</div>');
	}else{
	    var targetdiv= nn6 ? document.getElementById(insertTarget) : document.all[insertTarget];
	    targetdiv.innerHTML = str;
	}
}

// change the way the map is inserted into html
function mapSetInsertTarget(target)
{
    useInsertTarget=true;
    insertTarget=target;
}

function mapInsert(){
		
	var def = new Array('id','icdmap','codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0','title','192.com Maps','src',flashLocation,'quality','best', 'scale', 'noScale', 'pluginspage','http://www.macromedia.com/go/getflashplayer','name','icdmap','swliveconnect','true', 'allowScriptAccess', 'always');
	for(x=0;x<arguments.length;x++)
	{
		def.push(arguments[x])
	}
	
	var ret = 
	map_GetArgs
	(  def, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
	, "application/x-shockwave-flash"
	);
	
	// add url params
	var q = movieName+'.swf?'+addUrlParams;
	ret.embedAttrs["src"] = q;
	ret.params["movie"] = q;

    // set some default api vars based on mapinsert values
	if(useDhtmlMaps) {
		//insZoom++;
		mapchangelev=mapLevel=insZoom;
    	zoomChangeNotify=insZoom;
	}else {
    	zoomChangeNotify=insZoom;
    }
    var scale = getScale(insZoom);
    var ghw=(insWidth/2)*scale;
    var ghh=(insHeight/2)*scale;
    top_left_x = insGre - ghw;
    bottom_right_x = insGre + ghw;
    top_left_y = insGrn + ghh;
    bottom_right_y = insGrn - ghh;
    
	// divert for static maps 
	if(useDhtmlMaps)
	{		
		mapInsertDhtml();
 		return;	
	}
	
	map_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function mapInsertDhtml()
{

    var str = '<iframe id="icdmapframe" name="icdmapfr" src="'+dhtmlLocation+'mapchild.html" width="100%" height="100%" scrolling="no"> </iframe>';
	
    if(!useInsertTarget)
    {
	    document.write(str);
	}else{
	    var targetdiv= nn6 ? document.getElementById(insertTarget) : document.all[insertTarget];
	    targetdiv.innerHTML = str;
//	    loadXMLDoc(dhtmlLocation+"mapchild.html");
	}
}
function map_SW_RunContent(){
	var ret = 
	map_GetArgs
	(  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
	, null
);
map_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function map_GetArgs(args, ext, srcParamName, classid, mimeType){

	var ret = new Object();
	ret.embedAttrs = new Object();
	ret.params = new Object();
	ret.objAttrs = new Object();
	for (var i=0; i < args.length; i=i+2){
		var currArg = args[i].toLowerCase();

		switch (currArg){ 
			case "classid":
			break;
			case "pluginspage":
			case "swliveconnect":

			case "name":
			ret.embedAttrs[args[i]] = args[i+1];
			break;
			case "src":
			//case "movie":   
			//var q = map_AddExtension(args[i+1], ext);
			//ret.embedAttrs["src"] = q;
			//ret.params[srcParamName] = q;
			movieName = args[i+1];

			break;
			case 'scale':
			ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];

			break;
			case "onafterupdate":
			case "onbeforeupdate":
			case "onblur":
			case "oncellchange":
			case "onclick":
			case "ondblClick":
			case "ondrag":
			case "ondragend":
			case "ondragenter":
			case "ondragleave":
			case "ondragover":
			case "ondrop":
			case "onfinish":
			case "onfocus":
			case "onhelp":
			case "onmousedown":
			case "onmouseup":
			case "onmouseover":
			case "onmousemove":
			case "onmouseout":
			case "onkeypress":
			case "onkeydown":
			case "onkeyup":
			case "onload":
			case "onlosecapture":
			case "onpropertychange":
			case "onreadystatechange":
			case "onrowsdelete":
			case "onrowenter":
			case "onrowexit":
			case "onrowsinserted":
			case "onstart":
			case "onscroll":
			case "onbeforeeditfocus":
			case "onactivate":
			case "onbeforedeactivate":
			case "ondeactivate":
			case "type":
			case "codebase":
			ret.objAttrs[args[i]] = args[i+1];
			break;
			case "tileserver":
			    addUrlParams += args[i] + '=' + args[i+1] + '&';
			    mapServer = args[i+1];
			    break;
			case "tileserverport":
			    addUrlParams += args[i] + '=' + args[i+1] + '&';
			    mapServer += args[i+1];
			    break;
			case "mapdiv":
				mapDivName = args[i+1];
				break;
			case "resizable":
				resizable = args[i+1];
				break;
			case "slidervisible":
			case "searchcode":
			    addUrlParams += args[i] + '=' + args[i+1] + '&';
			    mapSearchCode = args[i+1];
			    break;
			case "clientcode":
			    addUrlParams += args[i] + '=' + args[i+1] + '&';
			    mapClientCode = args[i+1];
			    break;
			case "pagename":
			    addUrlParams += args[i] + '=' + args[i+1] + '&';
			    mapPageName = args[i+1];
			    
			    break;
			case "zoom":
			    addUrlParams += args[i] + '=' + args[i+1] + '&';
			    mapLevel = args[i+1];
			    //insZoom=Number(mapLevel);
				insZoom=mapLevel;
			    break;
			case "minzoomlevel":
				addUrlParams += args[i] + '=' + args[i+1] + '&';
				if (Number(args[i+1]) >= 0)
					mapMinZoomLevel = args[i+1];
				break;
			case "maxzoomlevel":
				addUrlParams += args[i] + '=' + args[i+1] + '&';
				if (Number(args[i+1]) >= 0)
					mapMaxZoomLevel = args[i+1];
				break;
			case "maptypenormal":
				addUrlParams += args[i] + '=' + args[i+1] + '&';
				mapMinZoomLevel = 5;
				mapMaxZoomLevel = 10;
				break;
			case "maptypesatellite":
				addUrlParams += args[i] + '=' + args[i+1] + '&';
				mapMinZoomLevel = 0;
				mapMaxZoomLevel = 4;
				break;
			case "gre":
			    addUrlParams += args[i] + '=' + args[i+1] + '&';
			    mapGre = args[i+1];
			    insGre = Number(mapGre);
			    break;
			case "grn":
			    addUrlParams += args[i] + '=' + args[i+1] + '&';
			    mapGrn = args[i+1];
			    insGrn = Number(mapGrn);
			    break;
			case "routeenhserver":
			    addUrlParams += args[i] + '=' + args[i+1] + '&';
			    break;
			 case "width":
				mapWidth = Number(args[i+1]);
				ret.embedAttrs['width'] = ret.objAttrs['width'] = "100%";
				ret.embedAttrs['swidth'] = ret.objAttrs['swidth'] = args[i+1];
				insWidth = mapWidth;
                break;
            case "height":
				mapHeight = Number(args[i+1]);
				ret.embedAttrs['height'] = ret.objAttrs['height'] = "100%";
				ret.embedAttrs['sheight'] = ret.objAttrs['sheight'] = args[i+1];
				insHeight = mapHeight;
                break; 
			case "align":
			case "vspace": 
			case "hspace":
			case "class":
			case "wmode":
				ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
				break;			
			case "title":
			case "accesskey":
			//case "name":
			case "id":
			case "tabindex":
				ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
				break;
			default:
				ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
				addUrlParams += args[i] + '=' + args[i+1] + '&';
		}
	}
	ret.objAttrs["classid"] = classid;
	
	if (mapMinZoomLevel > mapMaxZoomLevel) {
		mapMinZoomLevel = 0;
		mapMaxZoomLevel = 10;
	}
	
	if (mimeType) ret.embedAttrs["type"] = mimeType;
	return ret;
}

function getMetresPerPixel(izlev) {
	var _lev = (typeof(izlev) == 'undefined' || izlev.constructor != Number) ? getZoom() : izlev;
	return getScale(_lev*1);
}

function getScale(izlev) {
	switch(izlev) {
		case 0:
		return 0.04;
		case 1:
		return 0.125;
		case 2:
		return 0.25;
		case 3:
		return 0.5;
		case 4:
		return 1.0;
		case 5:
		return 1.666;
		case 6:
		return 8.333;
		case 7:
		return 41.666;
		case 8:
		return 208.333;
		case 9:
		return 868.055;
		case 10:
		return 4340.277;
	}

	return 1.0;
}

// DHTML maps section
var mapmovex=0;
var mapmovey=0;
var mapchangelev=mapLevel;

// user functions
function mapMove(dx, dy)
{
	mapmovex = dx;
	mapmovey = dy;	
}

function mapChangeLevel(lev)
{
	mapchangelev=lev;
}
function mapResize()
{
    mapResized=true;
}
function mapFocusBalloonTo(x,y)
{
	mapGre=x;	
	mapGrn=y;	
	mapFocusBalloon=true;
}
// non user functions
function mapGetServer()
{
	return mapServer;	
}
function mapGetGre()
{
	return mapGre;	
}
function mapGetGrn()
{
	return mapGrn;	
}
function mapGetPois()
{
	return mapPois;	
}
function mapGetRoute()
{
	return mapRoute;	
}
function mapGetLevel()
{
	return mapLevel;	
}
function mapGetZoomOption()
{
	return mapZoomOption;	
}
function mapGetMinZoomLevel()
{
	return mapMinZoomLevel;	
}
function mapGetMaxZoomLevel()
{
	return mapMaxZoomLevel;	
}
function mapGetClientCode()
{
	return mapClientCode;	
}
function mapGetSearchCode()
{
	return mapSearchCode;	
}
function mapGetPageName()
{
	return mapPageName;	
}
function mapGetRouteThickness()
{
	return mapRouteThickness;	
}
function mapGetRouteColor()
{
	return mapRouteColor;	
}
function mapGetRouteAlpha()
{
	return mapRouteAlpha;	
}
function mapGetMoveX()
{
	return mapmovex;
}
function mapSetMoveX(x)
{
	mapmovex=x;
}
function mapGetMoveY()
{
	return mapmovey;
}
function mapSetMoveY(y)
{
	mapmovey=y;
}
function mapSetGre(x)
{
	mapGre=x;	
}
function mapSetGrn(y)
{
	mapGrn=y;	
}
function mapSetLevel(l)
{
	mapLevel=l;	
}
function mapGetSemaphore()
{
    return semaphore;
}
function mapGetUseSemaphore()
{
    return useSemaphore;
}
function mapNotifyMoved()
{
    moveCounter++;
}
function mapNotifyPosition(x1,y1,x2,y2,zoom)
{
    top_left_x=x1;
    top_left_y=y1;
    bottom_right_x=x2;
    bottom_right_y=y2;   
    zoomChangeNotify=zoom;
	// added to support setZoom in AJAX
	mapchangelev=mapLevel=zoom;
}

function mapHasGeocodesChanged()
{
	if (mapGeocodesChanged)
	{
		mapGeocodesChanged=false;
		return true;
	}
	return false;
}
function mapHasResized()
{
    if(mapResized)
    {
        mapResized=false;
        return true;
    }
    return false;
}
function mapHasFocusBalloonChanged()
{
    if(mapFocusBalloon)
    {
		mapFocusBalloon=false;
		return true;
	}
	return false;
}
function mapGetZoomRedrawPOI()
{
    if(mapZoomRedrawPOI)
    {
		mapZoomRedrawPOI=false;
		return true;
	}
	return false;
}
function mapGetFocusOnBalloon()
{
    for(i=0; i<mapPois.length; i++)
    {
        if (mapPois[i].ref == mapFocusOnBalloon) {
        	return mapPois[i];
        }
    }
	return null;
}


// ajax

function loadXMLDoc(url)
{
	// branch for native XMLHttpRequest object
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
		req.onreadystatechange = processReqChange;
		req.open("GET", url, true);
		req.send(null);
		// branch for IE/Windows ActiveX version
	} else if (window.ActiveXObject) {
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			req.onreadystatechange = processReqChange;
			req.open("GET", url, true);
			req.send();
		}
	}
}

function processReqChange()
{
	// only if req shows "complete"
	if (req.readyState == 4) {
		// only if "OK"
		if (req.status == 200) {
		    var targetdiv= nn6 ? document.getElementById(insertTarget) : document.all[insertTarget];
		    targetdiv.innerHTML = req.responseText;
//			if(document.getElementById) {
//				document.getElementById('icdmapframe').innerHTML = req.responseText;
//			}
		} else {
			alert("There was a problem retrieving the XML data:\n" + req.statusText);
			// if local test then for some reason it will return status=0
		    var targetdiv= nn6 ? document.getElementById(insertTarget) : document.all[insertTarget];
		    targetdiv.innerHTML = req.responseText;
		}
	}
}

///////////////////////////////
// JSON AJAX
///////////////////////////////

function Ping() {}
Ping.prototype = {
	init : function(fullUrl,success,failure) {
		this._imguri=fullUrl+"?time="+(new Date()).getTime();
		this._timer=null;
		this._success=success;
		this._failure=failure;
		this._imgPreload=null;
		this._imgPreload = new Image();
		this._imgPreload.onload = this.success.bind(this);
		this._imgPreload.onerror = this.failure.bind(this);
		this._imgPreload.id = (new Date()).getTime();
		this._imgPreload.src = this._imguri;
		this._timer = setTimeout(this.failure.bind(this),3000);
	},
	cleanup : function() {
		clearTimeout(this._timer);
		this._timer = null;
		this._imgPreload = null;
	},
	failure : function() {
		this.cleanup();
		this._failure('Could not verify 192.com server is up.');
	},
	success : function() {
		this.cleanup();
		this._success();
	}
}

function have4cmForLocation(callbackFn,gre,grn) {
	if(typeof(gre) == 'undefined' || gre.constructor != Number) {
		gre = mapGetGre();
	}
	if(typeof(grn) == 'undefined' || grn.constructor != Number) {
		grn = mapGetGrn();
	}
	callJsonService("have4cm","http://www2.mapping.192.com/MapService/GetSeed", {
		lev:'b1',px:gre,py:grn,sug:300,json:1,callback:callbackFn
	});
}

/*
 * Function: 	callJsonService
 * Description: Call a JSON service by using a dynamic <script> tag. In the params argument, include
 * 				an entry for the callback function if you use one. The service will be called up by
 * 				adding the tag to the DOM and your callback will be invoked once the results come back
 * 				from the server. It's an asynchronous call so will return immediately and your callback
 * 				will get the results when they're ready.
 * 				We do things this way because of cross-domain issues with the XmlHttpRequest object.
 * Args...
 * scriptId: 	The ID attribute you want to use for the generated <script> tag. Must be unique to the document
 * url: 		The URL of the service, EXCLUDING THE QUERYSTRING
 * params: 		An associative array of the parameters to be put in the querystring. For example...
 * 				{ Module: "Location.Geocode", ClientCode: "12345", callback: "geocodeComplete" }
 * 
 */
function callJsonService(scriptId,url,params) {
	if(scriptId == null || url == null || scriptId.length == 0 || url.length == 0)
		throw "scriptId and url parameters are both required.";
	var scriptElement = $(scriptId);
	if(scriptElement && scriptElement.parentNode) {
		// Remove the element as it's already in the DOM
		scriptElement.parentNode.removeChild(scriptElement);
		scriptElement = null;
	}
	// Generate the URL including the querystring if we've been passed some parameters
	var fullUrl = url;
	var first = true;
	for(var i in params) {
		// Append a ? for the first item, a & for the latter ones
		if(first) {
			fullUrl += "?";
			first = false;
		}
		else
			fullUrl += "&";
		fullUrl += i + "=" + params[i];
	}
	// Append the time to stop the browser from caching
	if(first)
		fullUrl += "?";
	else
		fullUrl += "&";
	fullUrl += (new Date()).getTime();

	// Create the new SCRIPT tag and put it into the DOM
	var head = document.getElementsByTagName("head").item(0);
	scriptElement = document.createElement('script');
	scriptElement.setAttribute('id',scriptId);
	scriptElement.setAttribute('type','text/javascript');
	scriptElement.setAttribute('src',fullUrl);
	head.appendChild(scriptElement);
	
	return false;
}

/*
 * Function: 	callSaferJsonService
 * Description:	Executes your call to callJsonService, but only if loading a test image
 * 				passes beforehand.
 * Params...
 * testImgSrc:	The URL of the test image. Usually a 1x1 GIF in the same URI of the service
 * 				you want to load your JSON from. You can use the getImgTestUrl function to
 * 				generate this if your test image is called testImg.gif.
 * callJson:	An anonymous function that will call callJsonService to load the JSON.
 * failure:		An anonymous function that will get called if the test image can't be loaded.
 * 
 * For an example, see the geocode function.
 */
function callSaferJsonService(testImgSrc,callJson,failure) {
	var pingObj = new Ping().init(testImgSrc,callJson,failure);
}

function getImgTestUrl(url) {
	return url.slice(0,url.lastIndexOf('/')+1) + "testImg.gif";
}

///////////////////////////////
// GEOCODING...
///////////////////////////////

/*
 * Function: 		geocode
 * Description:		Geocode a postcode and get hold of the GRE and GRN
 * Args...
 * postcode:		The postcode to be geocoded
 * clientCode:		Your client code
 * callback:		The name of a function (literal value) to be invoked when the geocode results
 * 					come back from the server. The method should have a signature like this:
 * 					function geocodeResults(data) { ... }
 * 					The data argument will be an associative array containing the GRE, GRN and
 * 					MATCHLEVEL. The MATCHLEVEL is a match percentage ( 0.0 <= MATCHLEVEL <= 100.0)
 * 					describing how successful the postcode match was.
 * Example:			geocode('SW6','abc','geocodeResults');
 */
var scriptCounter = 0;
function geocode(postcode,clientCode,successCallback,failureCallback) {
	if(postcode.length == 0 || clientCode.length == 0 || successCallback.length == 0 || failureCallback.length == 0) {
		throw "All parameters are required (string,string,string,string)";
	}
	var scriptId = 'geocodeScript' + (++scriptCounter).toString();
	var endPoint = modulesURL + "index.cfm";
	var params = { Module: "Location.Geocode", ClientCode: clientCode, Postcode: postcode, callback: successCallback };
	callSaferJsonService(getImgTestUrl(endPoint),
		function () { callJsonService(scriptId,endPoint,params) },
		eval(failureCallback));
}

/*
 * Function:		addBalloonFromPostcode
 * Description:		Same as addBalloon but adds the POI from a postcode instead of GRE/GRN
 * Args...
 * clientCode:		Your client code
 * failureCallback:	The name of the function to call in event of error
 * ref,type:		See addBalloon
 * postcode:		The postcode to add the POI at
 * heading,bodytext,linkUrl,linkName,pictUrl,linkTarget: See addBalloon
 */
function addBalloonFromPostcode(clientCode, failureCallback, ref, type, postcode, heading, bodytext, linkUrl, linkName, pictUrl, linkTarget) {
	var callbackName = "gcResultCb"+(new Date()).getTime();
	var successFnBody = "";
	successFnBody = "if(geocodeResult.MATCHLEVEL > 0){addBalloon(\""+ref+"\",\""+type+"\",geocodeResult.GRE,geocodeResult.GRN,\""+heading+"\",\""+bodytext+"\",\""+linkUrl+"\",\""+linkName+"\",\""+pictUrl+"\",\""+linkTarget+"\");}";
	window[callbackName] = new Function("geocodeResult",successFnBody);
	geocode(postcode,clientCode,callbackName,failureCallback);
}
