


// addLoadEvent function
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != "function") {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

function addClickEvent(obj, func) {
	var oldonclick = obj.onclick;
	if (typeof obj.onclick != "function") {
		obj.onclick = func;
	} else {
		obj.onclick = function() {
			oldonclick();
			func();
		}
	}
}

//used on some pages that don't
//need a specific  location on the map
//to display items found
//around it :see Attraction, City, etc...
var maxLatLongCallbacks = 0; //used in PrePopulateMapLatLong()
function PrePopulateMapLatLong() {

    try {
        var oMapIDHiddenTestBox = $get("tbMapID");
        document.getElementById("lat").value = $find(oMapIDHiddenTestBox.value)._Map.GetCenter().Latitude;
        document.getElementById("long").value = $find(oMapIDHiddenTestBox.value)._Map.GetCenter().Longitude
    }
    catch (e) {
        maxLatLongCallbacks++;
        if (maxLatLongCallbacks < 6) {
            setTimeout(PrePopulateMapLatLong, 300);
        }
        else {
            maxLatLongCallbacks = 0;
            return;
        }
    }
}

//updates the camera control on the page 
function UpdateHeroCitation(sTitle, sCopyright, sArtist, sLocation, sArtistUrl) {
	try {
		document.getElementById("photocreditflashhero_title").innerHTML = sTitle;
		document.getElementById("photocreditflashhero_cite").innerHTML = '&copy;' + sCopyright;
		document.getElementById("photocreditflashhero_artist").innerHTML = sArtist;
		document.getElementById("photocreditflashhero_location").innerHTML = sLocation;

		oPar = document.getElementById("photocreditflashhero_url");
		oAnchor = oPar.getElementsByTagName('a');
		oAnchor[0].href = sArtistUrl;
		oAnchor[0].setAttribute('target', '_blank');
		//eliminates some white space, we at least need 'http' or 'www.'
		if (sArtistUrl.length > 4) {
			oPar.style.display = "inline";
		}
		else {
			oPar.style.display = "none";
		}
	}
	catch (e) {
		/* Just keeping things from crashing if this is called on the wrong page */
	}
}

/*Returns the data from the photocredit control
*The return must be in the format specified for ActionScript to recognize it
*/
function GetImageData() {

	//URL
	var links = $get('imggallery').getElementsByTagName('a');
	if (links == null) { return ''; }
	var sUrl = links[0].href;

	//TITLE
	oTitleNode = $get('photocreditphotocontrol_title');
	var sTitle = '';
	if (oTitleNode != null) {
		sTitle = oTitleNode.innerHTML;
	}

	//LOCATION
	oLocationNode = $get('photocreditphotocontrol_location');
	var sLocation = '';
	if (oLocationNode != null) {
		sLocation = oLocationNode.innerHTML;
	}

	//COPYRIGHT
	oCiteNode = $get('photocreditphotocontrol_cite');
	var sCite = '';
	if (oCiteNode != null) {
		sCite = oCiteNode.innerHTML;
	}

	//ARTIST
	oArtistNode = $get('photocreditphotocontrol_artist');
	var sArtist = '';
	if (oArtistNode != null) {
		sArtist = oArtistNode.innerHTML;
	}

	//HIEGHT
	oHieghtNode = $get('photocreditphotocontrol_hieght');
	var sHieght = '';
	if (oHieghtNode != null) {
		sHieght = oHieghtNode.innerHTML;
	}

	return '{ "url": "' + sUrl
                + '", "title": "' + sTitle
                + '", "imageHeight": ' + sHieght
                + ', "location": "' + sLocation
                + '", "copyright": "' + sCite
                + '", "artist": "' + sArtist
                + '" }'
}


/*Method called by flash piece to open the light box
*url == url of image
*title == title of the image
*rev == the HTML markup that makes up the photo credit info for the image
*iMaxWidth == the maximum width of the image
*iMaxHeight ==  the maximum hieght of the image
*
*TODO: Refactor.  This code uses a naive method to open the lightbox 
*for the photocontrol on the page.  This was done due to an 
*issue with lightbox needing an actual <a> tag on the page to attach to.
*The attachment is done when the DOM raises the 'Loaded' event
*This will eventualy need to be
*/
function ShowLightbox(url, title, rev, rel, iMaxWidth, iMaxHeight) {
	OpenLightbox(0);
}

/*Helper function to open the lightbox
*imageIndex is the 0 based index of the image tags in
*the imagegallery obect on the page.
*/
function OpenLightbox(imageIndex) {

	var links = $get('imggallery').getElementsByTagName('a');

	/*if...else block gets around the fact
	*Mozilla does not implement a .click()
	*event like IE does for anchor tags.  We have to do a 
	*programatic click here to keep lightbox.js happy
	*/
	if (window.ActiveXObject) {
		if (links != null) {
			links[imageIndex].click();
		}
	}
	else {
		var event = document.createEvent("MouseEvents");
		event.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
                            false, false, false, false, 0, null);

		if (links != null) {
			links[imageIndex].dispatchEvent(event);
		}
	}
}

/*Function will detect the browser has
*Flash version fCurrentVersion or later
*Returns true if installed, else false
*fCurrentVersion is the Major version of Flash to detect
*as a float such as 9.0 or 9.1
*/
function BrowserIsFlashCapable(fCurrentVersion) {

	var isFlashInstalled = false;
	var flashVersion = null;

	//IE, then Mozilla/Navigator
	if (window.ActiveXObject) {
		var control = null;

		try {
			control = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
		} catch (e) {
			return isFlashInstalled;
		}

		if (control) {

			version = control.GetVariable('$version').substring(4);
			version = version.split(',');
			version = parseFloat(version[0] + '.' + version[1]);

			if (version >= fCurrentVersion) {
				isFlashInstalled = true;
			}
		}
	} else {

		oPlugin = navigator.plugins["Shockwave Flash"];
		if (oPlugin == null || oPlugin == 'undefined') {
			return isFlashInstalled;
		}
		else {
			version = oPlugin.description
			version = version.split(' ');
			version = parseFloat(version[2]);

			if (version >= fCurrentVersion) {
				isFlashInstalled = true;
			}
		}
	}

	return isFlashInstalled;
}

// insert after
function insertAfter(newElement, targetElement) {
	var parent = targetElement.parentNode;
	if (parent.lastChild == targetElement) {
		parent.appendChild(newElement);
	} else {
		parent.insertBefore(newElement, targetElement.nextSibling);
	}
}

// add class
function addClass(element, value) {
	if (!element.className) {
		element.className = value;
	} else {
		var pattern = new RegExp("(^| )" + value + "( |$)");
		if (element.className.search(pattern) == -1) {
			element.className += " " + value;
		}
	}
}

// remove class
function removeClass(element, value) {
	var pattern = new RegExp("(^| )" + value + "( |$)");
	element.className = element.className.replace(pattern, "$1");
	element.className = element.className.replace(/ $/, "");
}

// show and hide items on the page

// show and hide a section
function toggleSection(id) {
	var divs = document.getElementsByTagName("div");
	for (var i = 0; i < divs.length; i++) {
		if (divs[i].className.indexOf("section") == -1) continue;
		if (divs[i].className == "section hide") {
			var spans = document.getElementById("internalnav").getElementsByTagName("span");
			for (var l = 0; l < spans.length; l++) {
				if (spans[l].className == "state") {
					spans[l].innerHTML = "- Hide"
				}
			}
			divs[i].className = "section show";
		} else {
			var spans = document.getElementById("internalnav").getElementsByTagName("span");
			for (var l = 0; l < spans.length; l++) {
				if (spans[l].className == "state") {
					spans[l].innerHTML = "+ Show"
				}
			}
			divs[i].className = "section hide";
		}
	}
}

// prepare the internal navigation to display on click

// prepare the internal navigation to display on click
function prepareInternalnav() {
	if (!document.getElementsByTagName) return false;
	if (!document.getElementById) return false;
	if (!document.getElementById("internalnav")) return false;
	var nav = document.getElementById("internalnav");
	var links = nav.getElementsByTagName("a");
	for (var i = 0; i < links.length; i++) {
		var sectionId = links[i].getAttribute("href").split("#")[1];
		if (!document.getElementById(sectionId)) continue;
		links[i].destination = sectionId;
		links[i].onclick = function() {
			toggleSection(this.destination);
			return false;
		}
	}
}

function prepareInputsForHints() {
	// TODO
	return;
	var inputs = document.getElementsByTagName("input");
	for (var i = 0; i < inputs.length; i++) {
		// test to see if the hint span exists first
		if (inputs[i].parentNode.getElementsByTagName("span")[0]) {
			// the span exists!  on focus, show the hint
			inputs[i].onfocus = function() {
				this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
			}
			// when the cursor moves away from the field, hide the hint
			inputs[i].onblur = function() {
				this.parentNode.getElementsByTagName("span")[0].style.display = "none";
			}
		}
	}
	// repeat the same tests as above for selects
	var selects = document.getElementsByTagName("select");
	for (var k = 0; k < selects.length; k++) {
		if (selects[k].parentNode.getElementsByTagName("span")[0]) {
			selects[k].onfocus = function() {
				this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
			}
			selects[k].onblur = function() {
				this.parentNode.getElementsByTagName("span")[0].style.display = "none";
			}
		}
	}
}

function externalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i = 0; i < anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") &&
       anchor.getAttribute("rel") == "external") {
			anchor.target = "_blank";
		}
	}
}
addLoadEvent(externalLinks);

// **************************************************************
//                       core dom
// **************************************************************
var Core = {};

// W3C DOM 2 Events model
if (document.addEventListener) {
	Core.addEventListener = function(target, type, listener) {
		target.addEventListener(type, listener, false);
	};

	Core.removeEventListener = function(target, type, listener) {
		target.removeEventListener(type, listener, false);
	};

	Core.preventDefault = function(event) {
		event.preventDefault();
	};

	Core.stopPropagation = function(event) {
		event.stopPropagation();
	};
}
// Internet Explorer Events model
else if (document.attachEvent) {
	Core.addEventListener = function(target, type, listener) {
		// prevent adding the same listener twice, since DOM 2 Events ignores
		// duplicates like this
		if (Core._findListener(target, type, listener) != -1) return;

		// listener2 calls listener as a method of target in one of two ways,
		// depending on what this version of IE supports, and passes it the global
		// event object as an argument
		var listener2 = function() {
			var event = window.event;

			if (Function.prototype.call) {
				listener.call(target, event);
			}
			else {
				target._currentListener = listener;
				target._currentListener(event)
				target._currentListener = null;
			}
		};

		// add listener2 using IE's attachEvent method
		target.attachEvent("on" + type, listener2);

		// create an object describing this listener so we can clean it up later
		var listenerRecord =
    {
    	target: target,
    	type: type,
    	listener: listener,
    	listener2: listener2
    };

		// get a reference to the window object containing target
		var targetDocument = target.document || target;
		var targetWindow = targetDocument.parentWindow;

		// create a unique ID for this listener
		var listenerId = "l" + Core._listenerCounter++;

		// store a record of this listener in the window object
		if (!targetWindow._allListeners) targetWindow._allListeners = {};
		targetWindow._allListeners[listenerId] = listenerRecord;

		// store this listener's ID in target
		if (!target._listeners) target._listeners = [];
		target._listeners[target._listeners.length] = listenerId;

		// set up Core._removeAllListeners to clean up all listeners on unload
		if (!targetWindow._unloadListenerAdded) {
			targetWindow._unloadListenerAdded = true;
			targetWindow.attachEvent("onunload", Core._removeAllListeners);
		}
	};

	Core.removeEventListener = function(target, type, listener) {
		// find out if the listener was actually added to target
		var listenerIndex = Core._findListener(target, type, listener);
		if (listenerIndex == -1) return;

		// get a reference to the window object containing target
		var targetDocument = target.document || target;
		var targetWindow = targetDocument.parentWindow;

		// obtain the record of the listener from the window object
		var listenerId = target._listeners[listenerIndex];
		var listenerRecord = targetWindow._allListeners[listenerId];

		// remove the listener, and remove its ID from target
		target.detachEvent("on" + type, listenerRecord.listener2);
		target._listeners.splice(listenerIndex, 1);

		// remove the record of the listener from the window object
		delete targetWindow._allListeners[listenerId];
	};

	Core.preventDefault = function(event) {
		event.returnValue = false;
	};

	Core.stopPropagation = function(event) {
		event.cancelBubble = true;
	};

	Core._findListener = function(target, type, listener) {
		// get the array of listener IDs added to target
		var listeners = target._listeners;
		if (!listeners) return -1;

		// get a reference to the window object containing target
		var targetDocument = target.document || target;
		var targetWindow = targetDocument.parentWindow;

		// searching backward (to speed up onunload processing), find the listener
		for (var i = listeners.length - 1; i >= 0; i--) {
			// get the listener's ID from target
			var listenerId = listeners[i];

			// get the record of the listener from the window object
			var listenerRecord = targetWindow._allListeners[listenerId];

			// compare type and listener with the retrieved record
			if (listenerRecord.type == type && listenerRecord.listener == listener) {
				return i;
			}
		}
		return -1;
	};

	Core._removeAllListeners = function() {
		var targetWindow = this;

		for (id in targetWindow._allListeners) {
			var listenerRecord = targetWindow._allListeners[id];
			listenerRecord.target.detachEvent(
          "on" + listenerRecord.type, listenerRecord.listener2);
			delete targetWindow._allListeners[id];
		}
	};

	Core._listenerCounter = 0;
}

Core.addClass = function(target, theClass) {
	if (!Core.hasClass(target, theClass)) {
		if (target.className == "") {
			target.className = theClass;
		}
		else {
			target.className += " " + theClass;
		}
	}
};

Core.getElementsByClass = function(theClass) {
	var elementArray = [];

	if (document.all) {
		elementArray = document.all;
	}
	else {
		elementArray = document.getElementsByTagName("*");
	}

	var matchedArray = [];
	var pattern = new RegExp("(^| )" + theClass + "( |$)");

	for (var i = 0; i < elementArray.length; i++) {
		if (pattern.test(elementArray[i].className)) {
			matchedArray[matchedArray.length] = elementArray[i];
		}
	}

	return matchedArray;
};

Core.hasClass = function(target, theClass) {
	var pattern = new RegExp("(^| )" + theClass + "( |$)");

	if (pattern.test(target.className)) {
		return true;
	}

	return false;
};

Core.removeClass = function(target, theClass) {
	var pattern = new RegExp("(^| )" + theClass + "( |$)");

	target.className = target.className.replace(pattern, "$1");
	target.className = target.className.replace(/ $/, "");
};

Core.getComputedStyle = function(element, styleProperty) {
	var computedStyle = null;

	if (typeof element.currentStyle != "undefined") {
		computedStyle = element.currentStyle;
	}
	else {
		computedStyle = document.defaultView.getComputedStyle(element, null);
	}

	return computedStyle[styleProperty];
};

Core.start = function(runnable) {
	Core.addEventListener(window, "load", runnable.init);
};

//Core.start(Accordion);
addLoadEvent(prepareInputsForHints);
addLoadEvent(prepareInternalnav);
//addLoadEvent(pageLoad);


// print page
function bindPrintEvent() {
	var printicon = document.getElementById("printicon");
	if (printicon != null) {
		printicon.className = "opt2";
		printicon.onclick = printDoc;
	}
}
function printDoc() { window.print(); }
addLoadEvent(bindPrintEvent);


// site navigation dropdown controle 
sfHover = function() {
	var sfEls = document.getElementById("nav").getElementsByTagName("LI");
	for (var i = 0; i < sfEls.length; i++) {
		sfEls[i].onmouseover = function() {
			this.className += " sfhover";
		}
		sfEls[i].onmouseout = function() {
			this.className = this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);
// THE FOLLOWING FUNCTIONS ARE USED FOR TEXT FIELDS WITH DEFAULT VALUES
function attachFormEventHandlers() {
	var forms = document.forms;
	for (var form = 0; form < forms.length; form++) {
		var elements = forms[form].elements;
		for (var element = 0; element < elements.length; ++element) {
			var field = elements[element];
			if (field.nodeName == "INPUT" && field.getAttribute("type") == "text") {
				if (document.getElementById(field.id + "_default")) {
					field.value = field.defaultValue;
					field.defaultValue = document.getElementById(field.id + "_default").value;
					restoreDefaultValue(field);
					if (isDefault(field)) {
						addClass(field, "default");
					}
					field.onfocus = function() {
						removeDefaultValue(this);
						removeClass(this, "default");
					}
					field.onblur = function() {
						restoreDefaultValue(this);
						if (isDefault(this)) {
							addClass(this, "default");
						}
					}
				}
			}
		}
	}
}
function isEmpty(field) {
	if (field.nodeType == 1) {
		if (field.value.search(/^\s*$/) > -1) return true;
	}
	return false;
}
function isDefault(field) {
	if (field.nodeType == 1) {
		if (field.value == field.defaultValue) return true;
	}
	return false;
}
function removeDefaultValue(field) {
	if (field.nodeType == 1) {
		if (isDefault(field)) field.value = "";
	}
}
function restoreDefaultValue(field) {
	if (field.nodeType == 1) {
		if (isEmpty(field)) field.value = field.defaultValue;
	}
}
// THE PRECEDING FUNCTIONS ARE USED FOR TEXT FIELDS WITH DEFAULT VALUES


/*variable maintains state of
*currently selected section
*/
var selectedSectionNumber;
function showSection(sectionNumber) {
	if (!document.getElementById) return false;
	if (!document.getElementsByTagName) return false;
	if (sectionNumber) {
		if (selectedSectionNumber) {
			hideSection("section" + selectedSectionNumber);
			document.getElementById("abstract" + selectedSectionNumber).className = "hide";
		}
		else {
			var sections = document.getElementById("sections");
			if (sections != null) {
				var sectionItems = sections.getElementsByTagName("li");
				for (var index = 0; index < sectionItems.length; index++) {

					if (sectionItems[index].className == "section") {
						hideSection(sectionItems[index].id);
					}
				}

				//Magic numbers corelate to number of sections 
				//in home-page.xml
				for (var i = 1; i < 6; i++) {
					document.getElementById("abstract" + i).className = "hide";
				}
			}
		}
		selectedSectionNumber = sectionNumber;
		var sectionElement = document.getElementById("section" + sectionNumber);
		if (sectionElement) {
			document.getElementById("abstract" + sectionNumber).className = "show";
			sectionElement.style.display = "block";
		}
		var sectionElement = document.getElementById("secondarySection" + sectionNumber);
		if (sectionElement) {
			document.getElementById("option1").style.display = "none";
			document.getElementById("option2").style.display = "block";
		} else {
			document.getElementById("option1").style.display = "block";
			document.getElementById("option2").style.display = "none";
		}
	}
}
function hideSection(sectionID) {
	if (!document.getElementById) return false;
	if (sectionID) {
		document.getElementById(sectionID).style.display = "none";
	}
}

addLoadEvent(function() {
	//Not used but left in as place holder to show logic of adding calls to onload event 
});

var waitingForCallback = false;
function findNearby(sMapElementId) {
	if (!document.getElementById) return;
	if (!isDefault(document.getElementById('query'))) {
		waitingForCallback = true;
		if (document.getElementById('query').value == null || isEmpty(document.getElementById('query'))) {
			document.getElementById("lat").value = 0;
			document.getElementById("long").value = 0;
			waitingForCallback = false;
			return;
		}
		var searchTerm;
		switch (document.getElementById('query').value.toLowerCase()) {
			case 'mount baker':
			case 'san juan islands':
			case 'methow valley':
			case 'chinook pass':
			case 'stevens pass':
			case 'blewitt pass':
			case 'potholes reservoir':
			case 'fort simcoe':
			case 'hanford reach':
			case 'yakama indian reservation':
				searchTerms = document.getElementById('query').value;
				break;
			case 'mount adams':
				searchTerms = 'mt adams';
				break;
			case 'columbia river gorge':
			case 'the gorge':
				searchTerms = 'grant, washington, united states';
				break;
			case 'palouse falls':
				searchTerms = 'pasco, washington, united states';
				break;
			default:
				searchTerms = document.getElementById('query').value + ', washington, united states';
				break;
		}
		$find(sMapElementId)._Map.Find(null, searchTerms, null, null, null, null, false, null, false, false, findNearbyCallback);
		return false;
	}
	return true;
}

var submitOnCallback = false;
function findNearbyCallback(shapeLayer, findResults, places, moreResults, errorMessage) {
	if (!document.getElementById) return;
	if (places != null && places.length > 0) {
		document.getElementById("lat").value = places[0].LatLong.Latitude;
		document.getElementById("long").value = places[0].LatLong.Longitude;
	}
	waitingForCallback = false;
	if (submitOnCallback) {
		document.forms[0].onsubmit();
		document.forms[0].submit();
	}
}

function stillWaitingForFindNearbyCallback() {
	if (waitingForCallback) {
		submitOnCallback = true;
		return true;
	}
	return false;
}


addLoadEvent(function() {
	attachFormEventHandlers();
	document.forms[0].onsubmit = function() {
		this.focus();
		if (stillWaitingForFindNearbyCallback()) {
			return false;
		} else {
			var fields = document.getElementsByTagName('input');
			for (var index = 0; index < fields.length; index++) {
				if (document.getElementById(fields[index].id + "_default")) {
					if (fields[index].getAttribute('type') == 'text') {
						removeDefaultValue(fields[index]);
					}
				}
			}
			return true;
		}
	}
});

function populateRadiusInput() {

    var oRadius = $get("slRadius")
    $get("tbRadius").value = oRadius.options[oRadius.selectedIndex].value;


}
//needed as invariant to make sure loop is escaped
var displayBoundingCircleRetries = 0;

//Used in conjunction with find control to 
//display a radius on the map
function displayRadiusCircleOnMap() { 
 

     try {
         var sUrl = window.location.href.toLowerCase();
         //if alows map radius to be turned off and on through bool or querry string
         if (sUrl.match("lat=") == null || sUrl.match("&long=") == null || sUrl.match("&radius=") == null) 
         {
             if (
                (typeof (bShowRadius) == 'undefined')
                ||
                (bShowRadius == false)
                ) { return; }
          }
       
        var oMapIDHiddenTestBox = $get("tbMapID");
        

        //these controls are always with a map or doom
        if (typeof (oMapIDHiddenTestBox) == 'undefined' || oMapIDHiddenTestBox == null) 
        {
            return;
        }
        else {
            AddRadiusShapeToMap(oMapIDHiddenTestBox.value);
        }

           }
    catch (e) {

        //NOTE:  Since the map takes time to load, we must ensure it exists
        //the issue is that the if block
        // if ($find(oMapIDHiddenTestBox.value)._Map == null || typeof ($find(oMapIDHiddenTestBox.value)._Map) == 'undefined') {}
        //does not always catch the map being not instantiated on load
        //To wait for the map to load
        //we want to retry N times then figure something catastrophic happened
        displayBoundingCircleRetries++;
        if (displayBoundingCircleRetries < 6) {
            setTimeout(displayRadiusCircleOnMap, 500);
        }
        else {
            displayBoundingCircleRetries = 0;
            return;
         }
    }

}

//Function draws a radius shape on the map
//at some specific radius in miles
//This is tightly coupled to the map and find control
//sMapContainerID is the id of the maps parent container 
function AddRadiusShapeToMap(sMapContainerID)
{
    
    var radius = parseInt($get('tbRadius').value); 
    var earthRadiusInMiles = 3949;
    var origin = $find(sMapContainerID)._Map.GetCenter()
    var lat = (origin.Latitude * Math.PI) / 180; //rad
    var lon = (origin.Longitude * Math.PI) / 180; //rad
    var angularDistance = parseFloat(radius) / earthRadiusInMiles;  // angular distance covered on earth's surface
    var locs = new Array();
    for (x = 0; x <= 360; x++) {
        var pointOnCircle = new VELatLong(0, 0)
        brng = x * Math.PI / 180; //rad
        pointOnCircle.Latitude = Math.asin(Math.sin(lat) * Math.cos(angularDistance) + Math.cos(lat) * Math.sin(angularDistance) * Math.cos(brng));
        pointOnCircle.Longitude = ((lon + Math.atan2(Math.sin(brng) * Math.sin(angularDistance) * Math.cos(lat), Math.cos(angularDistance) - Math.sin(lat) * Math.sin(pointOnCircle.Latitude))) * 180) / Math.PI;
        pointOnCircle.Latitude = (pointOnCircle.Latitude * 180) / Math.PI;
        locs.push(pointOnCircle);
    }

    circle = new VEShape(VEShapeType.Polygon, locs);
    circle.HideIcon();
    circle.SetFillColor(new VEColor(228, 196, 186, 0.25));
    circle.SetLineColor(new VEColor(33, 33, 33, 0.5));
    $find(sMapContainerID)._Map.AddShape(circle);
}

addLoadEvent(displayRadiusCircleOnMap);

// Accommodations filtering
function updateFilterGroup(filterGroupID) {
	if (!document.getElementById) return;
	if (!document.getElementsByTagName) return;

	var filterGroup = document.getElementById(filterGroupID);
	var filterGroupContainer = document.getElementById(filterGroupID + '_filters');
	if (filterGroup && filterGroupContainer) {
		if (!filterGroup.checked) {
			var isFiltered = false;
			var filters = filterGroupContainer.getElementsByTagName('input');
			for (var index = 0; index < filters.length; index++) {
				var filter = filters[index];
				if (filter.checked) {
					isFiltered = true;
				}
			}
			filterGroup.checked = isFiltered;
		}
	}
}
function updateFilters(filterGroupID) {
	if (!document.getElementById) return;
	if (!document.getElementsByTagName) return;

	var filterGroup = document.getElementById(filterGroupID);
	var filterGroupContainer = document.getElementById(filterGroupID + '_filters');
	if (filterGroup && filterGroupContainer) {
		if (!filterGroup.checked) {
			var filters = filterGroupContainer.getElementsByTagName('input');
			for (var index = 0; index < filters.length; index++) {
				var filter = filters[index];
				filter.checked = false;
			}
		}
	}
}

///////////////////////////////
//////////////////////////////
/// image slide
/////////////////////////////
////////////////////////////

PageSliderControl = new function() {
	var _sliders = [];
	var _positions = [];
	var _interval = 30;
	var _steps = 30;
	var _timer = 0;
	var _isSliding = false;
	var _containerHeight = 219;
	var _controllerHeight = 219;
	var _articleWidth = 309;
	var _numberArticles = null;

	/*main();
	function main(){
	onload=load;
	}*/
	this.load = load;
	function load() {
		//NOTE: Code bellow is used in conjuntion with a slider control.
		//At this time control has been removed and is not used.
		//Code has been left here commented out incase either the
		//control is used again or in case removal of code causes adverse effects

		var container = $('sliderContainer');
		var controller = $('sliderControlContainer');
		if (container == null || controller == null) {
			return;
		}

		var divs = controller.getElementsByTagName('div');

		controller.style.height = _controllerHeight + "px";


		var buttonRight = document.createElement('img');
		divs[0].insertBefore(buttonRight, container);
		buttonRight.setAttribute('src', '/assets/styles/decoration/arrowright.png');
		buttonRight.setAttribute('alt', 'Next Article');
		buttonRight.setAttribute('id', 'articleRight');
		buttonRight.onclick = function() {
			PageSliderControl.startNextSlider(true)
		}
		buttonRight.style.float = "right";
		buttonRight.style.marginTop = "90px";


		var buttonLeft = document.createElement('img');
		divs[0].insertBefore(buttonLeft, buttonRight);
		buttonLeft.setAttribute('src', '/assets/styles/decoration/arrowleft.png');
		buttonLeft.setAttribute('alt', 'Previous Article');
		buttonLeft.setAttribute('id', 'articleLeft');
		buttonLeft.onclick = function() {
			PageSliderControl.startNextSlider(false)
		}
		buttonLeft.style.float = "left";
		buttonLeft.style.marginTop = "90px";

		var divs = container.getElementsByTagName('div');
		_numberArticles = divs.length;
		_left = _numberArticles - 1;
		_right = _numberArticles - 2;
		_positions[_numberArticles - 1] = -_articleWidth;
		for (var i = 0; i < _numberArticles - 1; i++) {
			_positions[i] = i * _articleWidth;
		}

		for (var i = 0; i < divs.length; i++) {
			_sliders.push(new Slider(divs[i]));
		}

		for (var i = 0; i < _sliders.length; i++) {
			_sliders[i].get_element().style.position = 'absolute';
			_sliders[i].get_element().style.left = _positions[i] + 'px';
		}

		var container = document.getElementById('sliderContainer');
		container.style.overflow = 'hidden';
		container.style.display = 'block';
		container.style.height = _containerHeight + 'px';

	}

	this.startNextSlider = startNextSlider;
	function startNextSlider(forward) {

		if (_right >= _sliders.length) _right = 0;
		if (_left >= _sliders.length) _left = 0;
		if (_right < 0) _right = _numberArticles - 1;
		if (_left < 0) _left = _numberArticles - 1;

		if (_isSliding === false) {
			_isSliding = true;
			if (forward) {

				var slider = _sliders[_left];
				if (slider) {
					slider.get_element().style.left = _positions[_numberArticles - 2] + "px";
				}

				for (var i = 0; i < _sliders.length; i++) {
					if (i != _left) {
						var slider = _sliders[i];
						if (slider) {
							var elt = slider.get_element();
							slider.move([parseInt(getStyle(elt, 'left')) - _articleWidth, parseInt(getStyle(elt, 'top'))], _steps, _interval, slideComplete);
						}
					}
				}

				_left++;
				_right++;

			} else {

				var slider = _sliders[_right];
				if (slider) {
					slider.get_element().style.left = _positions[_numberArticles - 1] + "px";
				}

				for (var i = 0; i < _sliders.length; i++) {
					if (i != _right) {
						var slider = _sliders[i];
						if (slider) {
							var elt = slider.get_element();
							slider.move([parseInt(getStyle(elt, 'left')) + _articleWidth, parseInt(getStyle(elt, 'top'))], _steps, _interval, slideComplete);
						}
					}
				}

				_left--;
				_right--;
			}
		}
	}

	function slideComplete(slider, step) {
		if (step < _steps) return;
		if (_timer) clearTimeout(_timer);
		_isSliding = false;
	}

	function hideComplete(slider, step) {
		if (step < _steps) return;
	}

	function getStyle(elt, rule) {
		if (elt) {
			var styl = elt.currentStyle;
			if (!styl && document.defaultView && document.defaultView.getComputedStyle) styl = document.defaultView.getComputedStyle(elt, "");
			if (styl) return styl[rule];
		}
		return "";
	}

	function $(id) {
		return document.getElementById(id);
	}
}

function Slider(element, callback) {
	var _this = this;
	var _step = null;
	var _source = null;
	var _target = null;
	var _current = 0;
	var _steps = 20;
	var _interval = 50;
	var _sliding = 0;
	var _callback = typeof (callback) == 'function' ? callback : null;
	var _stepCallback;

	this.id = 'slider_' + new Date().getTime() * Math.random() * 1000000;
	this.move = move;
	this.get_element = function() { return element; }

	function move(target, steps, interval, stepCallback) {
		if (!target || target.length < 2) return;
		if (_sliding) clearTimeout(_sliding);
		_target = target;
		if (steps) _steps = steps;
		if (interval) _interval = interval;
		if (typeof (stepCallback) == 'function') _stepCallback = stepCallback;
		_source = [parseInt(getStyle(element, 'left')), parseInt(getStyle(element, 'top'))];
		for (var i = 0; i < _source.length; i++) if (isNaN(_source[i])) _source[i] = 0;
		_current = 0;
		element.sliderID = _this.id;
		slide();
	}

	function slide() {
		if (_sliding) clearTimeout(_sliding);
		if (element.sliderID != _this.id) return;
		if (_stepCallback && _stepCallback(_this, _current) == false) return;
		if (_current++ >= _steps) return _callback ? _callback(_this, element) : '';
		try {
			_step = getStep();
			var left = (_source[0] + (_step[0] * _current));
			element.style.left = left + 'px';
			var top = (_source[1] + (_step[1] * _current))
			element.style.top = top + 'px';
			_source = [left, top];
		} catch (e) { debug('slide error: ' + e.description) }
		_sliding = setTimeout(slide, _interval);
	}

	function getStep(source, target) {
		var step = [];
		for (var i = 0; i < _target.length; i++) {
			step[i] = ((_target[i] || 0) - (_source[i] || 0)) / _steps;
		}
		return step;
	}

	function getStyle(elt, rule) {
		if (elt) {
			var styl = elt.currentStyle;
			if (!styl && document.defaultView && document.defaultView.getComputedStyle) styl = document.defaultView.getComputedStyle(elt, "");
			if (styl) return styl[rule];
		}
		return "";
	}
}

function debug(msg) {
	// TODO: comment out for go-live;
	// alert(msg);
}

addLoadEvent(PageSliderControl.load);
