// scripts/common.js

// TODO: test for document.documentElement
// if not available - no AJAX overlays
// if (document.documentElement) {...}
// set up variable for onclick return
// or find all internal links and set return false

// for map loads
// The stated purpose of XMLHttpRequest is indicated by its name. It loads an XML file from a server using HTTP. 
// However, it can be used to load any kind of file, including a .js file containing JavaScript code. 
// Pass the loaded code to eval(), and it's ready to be called.


/*---------------------------------------------------------------------------------------*/
// frame busters
if (self.location != top.location) { top.location = self.location; }

/*---------------------------------------------------------------------------------------*/
// functions to handle everything required on page load or resize
var map;

function init_main() {
	self.name='mainwindow';
	self.focus();
	
	modify_styles(location.href);
	
	modify_current_link(location.href);
	
	init_extramenu();
	init_searchbox();
	
	preload_common_images();
	random_banner();
	
	//map = new google.maps.Map2(document.getElementById('mapcontainer'));
	//map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);
	
	//show_map();
	
	MM_CheckFlashVersion('8,0,0,0','Some content on this website requires a newer version of Adobe Flash Player. Do you want to download it now?');
	
	//window.onunload=google.maps.Unload;
	
	//var sortable = new TableSort('sortable');
	
}

function resize_main() {
	init_extramenu();
	init_searchbox();
}

/*---------------------------------------------------------------------------------------*/
// function set_path()
// set absolute path to site root
// var filesRoot = set_path();
function set_path() {
	//alert(location.hostname);
	var filesRoot = '';
	if (location.hostname == 'www.kararu.com') {
		filesRoot = 'http://www.kararu.com';
	}
	else {
		filesRoot = 'http://localhost/Kararu/site';
	}
	return filesRoot;
}

/*---------------------------------------------------------------------------------------*/
// function show_map()
// Array('destination', 2.45, 1.57, 14, 'Fak Fak');
function show_map() {//mapDetails
	
	//alert('OK');
	
	// look for a dummy tag with attributes
	// mapDetails = 
	
	// if found search data table for details
	// or set up some variable
	
	//display_block('mapcontainer');
	
	//alert(mapDetails[0]);
	
	// load_script('array_changer.js.php?code={$territoryID}&parent=country&table=admins');
	
	// map.setCenter(new GLatLng(45.828799,-105.292969), 2);
	// map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);
	
	/*
	map.setCenter(new GLatLng(mapDetails[1], mapDetails[2]), mapDetails[3]);
	
	var uiOptions = map.getDefaultUI();
	uiOptions.zoom.scrollwheel = false;
	uiOptions.maptypes.physical = false;
	map.setUI(uiOptions);*/
	
	// add marker with title mapDetails[4]
	
}

/*---------------------------------------------------------------------------------------*/

function TableSort(id) {
    this.tbl = document.getElementById(id);
    this.lastSortedTh = null;
    if (this.tbl && this.tbl.nodeName == "TABLE") {
        var headings = this.tbl.tHead.rows[0].cells;
        for (var i=0; headings[i]; i++) {
            if (headings[i].className.match(/asc|dsc/)) {
                this.lastSortedTh = headings[i];
            }
        }
        this.makeSortable();
    }
}

TableSort.prototype.makeSortable = function () {
    var headings = this.tbl.tHead.rows[0].cells;
    for (var i=0; headings[i]; i++) {
	    headings[i].cIdx = i;
        var a = document.createElement("a");
            a.href = "#";
            a.innerHTML = headings[i].innerHTML;
            a.onclick = function (that) {
                return function () {
                    that.sortCol(this);
                    return false;
                }
            }(this);
        headings[i].innerHTML = "";
        headings[i].appendChild(a);
    }
}

TableSort.prototype.sortCol = function (el) {
    /*
     * Get cell data for column that is to be sorted from HTML table
     */
    var rows = this.tbl.rows;
    var alpha = [], numeric = [];
    var aIdx = 0, nIdx = 0;
    var th = el.parentNode;
    var cellIndex = th.cIdx;
    for (var i=1; rows[i]; i++) {
        var cell = rows[i].cells[cellIndex];
        var content = cell.textContent ? cell.textContent : cell.innerText;
        /*
         * Split data into two separate arrays, one for numeric content and 
         * one for everything else (alphabetic). Store both the actual data
         * that will be used for comparison by the sort algorithm (thus the need
         * to parseFloat() the numeric data) as well as a reference to the 
         * element's parent row. The row reference will be used after the new
         * order of content is determined in order to actually reorder the HTML
         * table's rows.
         */
        var num = content.replace(/(\$|\,|\s)/g, "");
          if (parseFloat(num) == num) { 
            numeric[nIdx++] = {
                value: Number(num),
                row: rows[i]
            }
        } else {
            alpha[aIdx++] = {
                value: content,
                row: rows[i]
            }
        }
    }
    
    /*
     * Sort according to direction (ascending or descending)
     */
    var col = [], top, bottom;
    if (th.className.match("asc")) {
        top = bubbleSort(alpha, -1);
        bottom = bubbleSort(numeric, -1);
        th.className = th.className.replace(/asc/, "dsc");
    } else {
        top = bubbleSort(numeric, 1);
        bottom = bubbleSort(alpha, 1);
        if (th.className.match("dsc")) {
            th.className = th.className.replace(/dsc/, "asc");
        } else {
            th.className += "asc";
        }
    }
    
    /*
     * Clear asc/dsc class names from the last sorted column's th if it isnt the
     * same as the one that was just clicked
     */
    if (this.lastSortedTh && th != this.lastSortedTh) {
        this.lastSortedTh.className = this.lastSortedTh.className.replace(/dsc|asc/g, "");
    }
    this.lastSortedTh = th;
    
    /*
     *  Reorder HTML table based on new order of data found in the col array
     */
    col = top.concat(bottom);
    var tBody = this.tbl.tBodies[0];
    for (var i=0; col[i]; i++) {
        tBody.appendChild(col[i].row);
    }
}

function bubbleSort(arr, dir) {
    // Pre-calculate directional information
    var start, end;
    if (dir === 1) {
        start = 0;
        end = arr.length;
    } else if (dir === -1) {
        start = arr.length-1;
        end = -1;
    }
    
    // Bubble sort: http://en.wikipedia.org/wiki/Bubble_sort
    var unsorted = true;
    while (unsorted) {
        unsorted = false;
        for (var i=start; i!=end; i=i+dir) {
            if (arr[i+dir] && arr[i].value > arr[i+dir].value) {
                var a = arr[i];
                var b = arr[i+dir];
                var c = a;
                arr[i] = b;
                arr[i+dir] = c;
                unsorted = true;
            }
        }
    }
    return arr;
}

/*---------------------------------------------------------------------------------------*/
// set up banner images array
var bannerImages = new Array('kapal-island', 'snappers', 'starfish', 'coral_leaves', 'turtle', 'sea_snake', 'diver_rock', 'shrimp_coral', 'plate_coral', 'snake_ledge', 'clown_coral', 'clown_coral_2', 'nudibrach', 'diver_cuttle', 'fish_eye', 'coral_fish', 'snorkeler');
var ajaxLoaders = new Array('main', 'pleasewait');

// function preload_common_images()
// receives arrays of image names and preloads same
function preload_common_images() {
	
	var preloadBanners = new Array();
	var preloadLoaders = new Array();
	
	for (var i = 0; i < bannerImages.length; i++) {
		var bannerImageName = bannerImages[i];
		var bannerImagePath = set_path() + '/images/common/banners/' + bannerImageName + '.jpg';
		preloadBanners[i] = new Image;
		preloadBanners[i].src = bannerImagePath;
	}
	
	for (var j = 0; j < ajaxLoaders.length; j++) {
		var loaderImageName = ajaxLoaders[j];
		var loaderImagePath = set_path() + '/images/common/loaders/' + loaderImageName + '.gif';
		preloadLoaders[j] = new Image;
		preloadLoaders[j].src = loaderImagePath;
	}
	
}

/*---------------------------------------------------------------------------------------*/
// function get_selected_radio()
// receives radio group as an object
// get_selected_radio(document.contactform.messageSubject);
// check that at least one is selected, returns value of selected if so
// returns false if none selected
function get_selected_radio(groupObject) { 
	
	for (var i = 0; i < groupObject.length; i++) {
		
		if (groupObject[i].checked) {
			return groupObject[i].value;
		}
		
	}
	
	return false;
	
}

/*---------------------------------------------------------------------------------------*/
// function url_encode()
// same as the php function
function url_encode(thestring) {
	return thestring.replace(' ', '+')
}

/*---------------------------------------------------------------------------------------*/
/* main overlay */
/*---------------------------------------------------------------------------------------*/
var overlayLoadingContent = document.getElementById('overlaycontent').innerHTML;

// function init_overlaycontent()
// sets overlay content container position, width and height
// receives topMargin, reqWidth, reqHeight
// tested in IE7, FF3, Chrome
function init_overlaycontent(topMargin, reqWidth, reqHeight) {
	
	var curScrollPos = document.documentElement.scrollTop;
	
	var overlaycontentwrapper = document.getElementById('overlaycontentwrapper');
	
	var reqScrollPos = (curScrollPos + topMargin);
	
	overlaycontentwrapper.style.marginTop = reqScrollPos + 'px';
	
	overlaycontentwrapper.style.width = reqWidth + 'px';
	
	overlaycontentwrapper.style.height = reqHeight + 'px';
		
}

// function set_overlay_height()
// sets overlay height to content height
// tested in IE7, FF3
// not working in chrome
function set_overlay_height() {
	
	// find scrollHeight
	var docHeight = document.documentElement.scrollHeight;
	
	// set overlay height to scrollHeight
	document.getElementById('overlay').style.height = docHeight + 'px';
	
}

// function hide_overlay()
// also resets overlay content to default
function hide_overlay() {
	
	display_none('overlay');
	
	document.getElementById('overlaycontent').innerHTML = overlayLoadingContent;
	
}

/*---------------------------------------------------------------------------------------*/
// function show_gallery_pic()
// receives photo URI
// show_gallery_pic(this.href)
// loads gallery photo into 'overlaycontent' via AJAX call
function show_gallery_pic(photoHref) {
	
	display_block('overlay');
	
	set_overlay_height();
	
	init_overlaycontent(90, 500, 500);
	
	processajax_simple(photoHref, 'overlaycontent');
	
}

/*---------------------------------------------------------------------------------------*/
// function show_agent_details()
// loads agent details into 'overlaycontent' via AJAX call
function show_agent_details(detailsHref) {
	
	display_block('overlay');
	
	set_overlay_height();
	
	init_overlaycontent(90, 450, 350);
	
	processajax_simple(detailsHref, 'overlaycontent');
	
}

/*---------------------------------------------------------------------------------------*/
// function show_route_map()
// loads flash video route map into 'overlaycontent' via AJAX call
function show_route_map(mapHref) {
	
	display_block('overlay');
	
	set_overlay_height();
	
	init_overlaycontent(90, 740, 400);
	
	processajax_simple(mapHref, 'overlaycontent');
	
}

/*---------------------------------------------------------------------------------------*/
// function init_searchbox()
function init_searchbox() {
	
	var searchbox = document.getElementById('searchbox');
	
	searchbox.style.position = 'absolute';
	searchbox.style.zIndex = '5';
	
	// anchor to <a id="searchboxtrigger">
	var searchboxtrigger = document.getElementById('searchboxtrigger');
	var anchorPosition = find_position(searchboxtrigger);
	// returns Array(elemX, elemY);
	var elemX = anchorPosition[0];
	
	var posnX = elemX - 78;
	var posnY = 1;
	
	searchbox.style.left = posnX + 'px';
	searchbox.style.top = posnY + 'px';
	
	//topsearchinput_focus();
	
}

function topsearchinput_focus() {
	
	var topsearchinput = document.getElementById('topsearchinput');
	
	topsearchinput.className = 'inputon';
	
	//topsearchinput.focus();
	
}

function topsearchinput_blur() {
	
	var topsearchinput = document.getElementById('topsearchinput');
	
	topsearchinput.className = 'inputoff';
		
}

function topsearchinput_suggest() {
	// ajax search suggest
}


/*---------------------------------------------------------------------------------------*/
// function init_extramenu()
function init_extramenu() {
	
	var extramenu = document.getElementById('extramenu');
	
	extramenu.style.display = 'none';
	extramenu.style.position = 'absolute';
	extramenu.style.zIndex = '4';
	extramenu.style.width = '180px';
	
	// anchor to <a id="morelink">
	var morelink = document.getElementById('morelink');
	var anchorPosition = find_position(morelink);
	// returns Array(elemX, elemY);
	var elemX = anchorPosition[0];
	
	var posnX = elemX - 123;
	var posnY = 0;
	
	extramenu.style.left = posnX + 'px';
	extramenu.style.top = posnY + 'px';
	
	extramenuListItems = extramenu.getElementsByTagName('li');
	extramenuLinks = extramenu.getElementsByTagName('a');
	
	for (var i = 0; i < extramenuListItems.length; i++) { // for (var i in extramenuListItems)
		
		extramenuListItems[i].style.display = 'block';
		
		extramenuLinks[i].style.width = '100%';
		
	}
}

/*---------------------------------------------------------------------------------------*/
// function load_script()

function load_script(scriptUrl) {
	
	var reqScript = document.createElement('script');
	reqScript.type = 'text/javascript';
	// script.setAttribute('type','text/javascript');
	reqScript.src = scriptUrl;
	
	document.body.appendChild(reqScript);
	
}

/*---------------------------------------------------------------------------------------*/
//function str_replace()
function str_replace(haystack, needle, replacement) {
    var temp = haystack.split(needle);
    return temp.join(replacement);
}

/*---------------------------------------------------------------------------------------*/
// function random_banner()
// receives array of image names
// sets a random image as header background
function random_banner() {
	
	var randomImage = Math.floor(Math.random() * bannerImages.length)
	
	var currentImageName = bannerImages[randomImage];
	
	var currentImagePath = set_path() + '/images/common/banners/' + currentImageName + '.jpg';
	//alert(currentImagePath);
	
	document.getElementById('topcontenttable').style.backgroundImage = 'url(' + currentImagePath + ')';
	
}

/*---------------------------------------------------------------------------------------*/
// function find_position()
// function to find out where an element is on the page
// find_position(this)
function find_position(obj) {
	
	var elemX = elemY = 0;
	
	if (obj.offsetParent) {
		
		do {
			elemX += obj.offsetLeft;
			elemY += obj.offsetTop;
		}
		while (obj = obj.offsetParent);
		
		return Array(elemX, elemY);
	}
	
	else {
		return false;
	}
}

// function set_position()
// receives entire object(s)
// set_position(this, this, int, int)
// returns X & Y co-ords as an array
function set_position(subjectObj, anchorObj, reqOffsetX, reqOffsetY) {
	
	var anchorPosition = find_position(anchorObj);
	
	if (anchorPosition != false) {
		
		var reqPosnX = anchorPosition[0] + reqOffsetX;
		var reqPosnY = anchorPosition[1] + reqOffsetY;
		
		subjectObj.style.left = reqPosnX + 'px';
		subjectObj.style.top = reqPosnY + 'px';
		
	}
	
}

/*---------------------------------------------------------------------------------------*/
// function display_block()
function display_block(divId) {
	var divToShow = document.getElementById(divId);
	divToShow.style.display = 'block';
}

// function display_none()
function display_none(divId) {
	var divToHide = document.getElementById(divId);
	divToHide.style.display = 'none';
}

/*---------------------------------------------------------------------------------------*/
// function modify_current_link()
// function to find and modify class of link to current page
// use php/css id to highlight the sections
// need to remove anchors and search string from currentPage

function modify_current_link(currentPage) {
	
	var docLinks = document.links;
	
	for (var i = 0; i < docLinks.length; i++) {
		
		if (docLinks[i].href == currentPage && docLinks[i].id != 'top') {
			
			docLinks[i].style.color = '#009900';
			docLinks[i].style.backgroundColor = '#FFFFFF';
			
			// if this is a sublink
			if (docLinks[i].className == 'sublink') {
				
				// find link to index of this section				
				// eg. http://localhost/Kararu/new/the-liveaboard/facilities-services.php
				
				// parse url - create url of index of this section
				
				// TODO: remove search string ??
				
				var urlArray = currentPage.split('/');
				var arrayLength = urlArray.length;
				var lastItem = urlArray[arrayLength - 1];
				var sectionIndex = currentPage.replace(lastItem, 'index.php');
				// eg. http://localhost/Kararu/new/the-liveaboard/index.php
				//alert(sectionIndex);
							   
				for (var j = 0; j < docLinks.length; j++) {
					if (docLinks[j].href == sectionIndex) {
						docLinks[j].style.color = '#009900';
						docLinks[j].style.backgroundColor = '#FFFFFF';
					}
				}
				
				return;
								
			} //end if (docLinks[i].className == 'sublink')
						
			/*docLinks[i].onclick = function(){
				alert('You are already viewing the page\n' + currentPage);
				return false;
			}*/
			
		} //end if (docLinks[i].href == currentPage)
		else {
			//docLinks[i].className = '';
			docLinks[i].style.color = '';
			docLinks[i].style.backgroundColor = '';
		}
	}
}

/*---------------------------------------------------------------------------------------*/
// function modify_styles()

function modify_styles(currentPage) {
	
	var contentContainer = document.getElementById('contentcontainer');
	
	var skypeStatus = document.getElementById('skypestatus');
	
	var toTop = document.getElementById('totop');
	
	if (currentPage == 'http://www.kararu.com/index.php' || currentPage == 'http://www.kararu.com/') {
	//if (currentPage == 'http://localhost/Kararu/site/index.php' || currentPage == 'http://localhost/Kararu/site/') {
		
		contentContainer.style.paddingTop = '0px';
		contentContainer.style.paddingRight = '0px';
		contentContainer.style.paddingBottom = '0px';
		contentContainer.style.paddingLeft = '0px';
		
		skypeStatus.style.display = 'none';
		toTop.style.display = 'none';
		
	}
	
	else {
		
		//padding: 15px 27px 15px 36px;
		contentContainer.style.paddingTop = '15px';
		contentContainer.style.paddingRight = '27px';
		contentContainer.style.paddingBottom = '15px';
		contentContainer.style.paddingLeft = '36px';
		
		skypeStatus.style.display = 'block';
		toTop.style.display = 'block';
		
	}	
}

/*---------------------------------------------------------------------------------------*/
// function show_bubbletip()
// receives entire link object
// show_bubbletip(this)
function show_bubbletip(linkObject) {
	
	var bubbletip = document.getElementById('bubbletip');
	
	display_block('bubbletip');
	// TODO: change display_block() to use object ??
	
	set_position(bubbletip, linkObject, 0, 10);
	
	var linkObjectTitle = linkObject.title;
	
	document.getElementById('tipcontent').innerHTML = linkObjectTitle;
	
	// origLinkObjectTitle = linkObjectTitle;
	//linkObject.title = '';
	
}

var tipLoadingContent = document.getElementById('tipcontent').innerHTML;
//var origLinkObjectTitle = '';
function hide_bubbletip(linkObject) {
	
	display_none('bubbletip');
	
	document.getElementById('tipcontent').innerHTML = tipLoadingContent;
	
	//linkObject.title = origLinkObjectTitle;
	
}

/*---------------------------------------------------------------------------------------*/
////// AJAX functions /////////

// function create_ajax_object()
// function to create an XMLHttp Object.
function create_ajax_object() {	
	var ajaxObject = false;	
	if (window.XMLHttpRequest) {
		ajaxObject = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		ajaxObject = new ActiveXObject('Microsoft.XMLHTTP');
	}
	return ajaxObject;
}

// function to load content from specified file into the main content cell
// TODO: set back button - history object to calling location.href
function load_main_content(filepath) {
	
	// hide extramenu
	display_none('extramenu');
	
	// scroll window back to top
	window.scrollTo(0,0);
	
	// set path to server page
	var filesRoot = set_path();
	
	// escape ajax call
	var escapedFilepath = escape(filepath);
	//alert(escapedFilepath);
	
	// create absolute URL to server page with search string
	var serverPage = filesRoot + '/ajax/content.php?source=' + escapedFilepath;
	
	var targetElement = document.getElementById('maincontentcell');
	
	ajaxObject = create_ajax_object();
	ajaxObject.open('GET', serverPage);
	
	ajaxObject.onreadystatechange = function() {
		
		if (ajaxObject.readyState == 1 || ajaxObject.readyState == 2 || ajaxObject.readyState == 3) {
			
			targetElement.innerHTML = '<div id="ajaxloader">&nbsp;</div>';
			//targetElement.innerHTML = '<h1>Retreiving Content....</h1><p>' + serverPage + '</p>';
			
			// set timeout of 45 seconds
			// if timeout display link to filepath with ajax=no appended to search string
			
		}
		
		if (ajaxObject.readyState == 4) {
			
			if (ajaxObject.status == 200) {
								
				// split ajaxObject.responseText
				var ajaxResponse = ajaxObject.responseText;
				// Document title changed<#>
				var responseArray = ajaxResponse.split('<#>');
				
				// change value of title
				// string replace '&amp;' with '&' or 'and'
				var newTitle = responseArray[0];
				newTitle = str_replace(newTitle, '&amp;', '&');
				document.title = newTitle;
								
				// replace main content
				targetElement.innerHTML = responseArray[1];
				
				pageTracker._trackPageview(filepath);
				
				modify_styles(filepath);
				
				// change banner image
				random_banner();
				
				//var sortable = new TableSort('sortable');
				
			}
			
			// if 404 or 500 call respective page
			
		} //end if (ajaxObject.status == 200)
		
		modify_current_link(filepath);
		
	} //end if (ajaxObject.readyState == 4)
	
	ajaxObject.send(null);
		
} //end function load_main_content

/*---------------------------------------------------------------------------------------*/
// function load_article_content()
// receives article HREF
// loads article content into 'overlaycontent' via AJAX call
function load_article_content(articleHref) {
	
	display_block('overlay');
	
	set_overlay_height();
	
	init_overlaycontent(50, 740, 600); // TEMP: height depends on content !!
	
	// set path to server page
	var filesRoot = set_path();
	
	// escape ajax call
	var escapedFilepath = escape(articleHref);
	//alert(escapedFilepath);
	
	// create absolute URL to server page with search string
	var serverPage = filesRoot + '/ajax/content.php?source=' + escapedFilepath;
	
	ajaxObject = create_ajax_object();
	ajaxObject.open('GET', serverPage);
	
	var targetElement = document.getElementById('overlaycontent');
	
	ajaxObject.onreadystatechange = function() {
				
		if (ajaxObject.readyState == 4) {
			
			if (ajaxObject.status == 200) {
								
				// split ajaxObject.responseText
				var ajaxResponse = ajaxObject.responseText;
				// Document title changed<#>
				var responseArray = ajaxResponse.split('<#>');
								
				// replace main content
				targetElement.innerHTML = responseArray[1];
				
				set_overlay_height();
				
			}
			
			// if 404 or 500 call respective page
			
		} //end if (ajaxObject.status == 200)
		
	} //end if (ajaxObject.readyState == 4)
	
	ajaxObject.send(null);
	
}

/*---------------------------------------------------------------------------------------*/
// function load_hotel_detail()
// receives hotel Id
// loads hotel details into 'overlaycontent' via AJAX call
function load_hotel_detail(detailHref) {
	
	display_block('overlay');
	
	set_overlay_height();
	
	init_overlaycontent(50, 700, 600); // TEMP: height depends on content !!
	
	// set path to server page
	var filesRoot = set_path();
	
	// escape ajax call
	var escapedFilepath = escape(detailHref);
	//alert(escapedFilepath);
	
	// create absolute URL to server page with search string
	var serverPage = filesRoot + '/ajax/content.php?source=' + escapedFilepath;
	
	ajaxObject = create_ajax_object();
	ajaxObject.open('GET', serverPage);
	
	var targetElement = document.getElementById('overlaycontent');
	
	ajaxObject.onreadystatechange = function() {
				
		if (ajaxObject.readyState == 4) {
			
			if (ajaxObject.status == 200) {
								
				// split ajaxObject.responseText
				var ajaxResponse = ajaxObject.responseText;
				// Document title changed<#>
				var responseArray = ajaxResponse.split('<#>');
								
				// replace main content
				targetElement.innerHTML = responseArray[1];
				
				set_overlay_height();
				
			}
			
			// if 404 or 500 call respective page
			
		} //end if (ajaxObject.status == 200)
		
	} //end if (ajaxObject.readyState == 4)
	
	ajaxObject.send(null);
	
}

/*---------------------------------------------------------------------------------------*/
// function to process a simple XMLHttpRequest (one target element)
// recieves server side page, target element, get or post method, post string if post method
function processajax_simple(serverPage, targetElement, getOrPost, postStr) {
	
	if (typeof(getOrPost) == 'undefined') getOrPost = 'get';
	if (typeof(postStr) == 'undefined') postStr = null;
	
	ajaxObject = create_ajax_object();
	var targetElement = document.getElementById(targetElement);
	
	if (ajaxObject) {
		// if get method
		if (getOrPost == 'get'){
			ajaxObject.open('GET', serverPage);
			ajaxObject.onreadystatechange = function() {
				if (ajaxObject.readyState == 1 || ajaxObject.readyState == 2 || ajaxObject.readyState == 3) {
					targetElement.innerHTML = '<div id="ajaxloader">&nbsp;</div>';
				}
				if (ajaxObject.readyState == 4 && ajaxObject.status == 200) { // split this depending on status
					targetElement.innerHTML = ajaxObject.responseText;
				}
			}
			ajaxObject.send(null);
		} // end if get method
		// if post method
		else {
			ajaxObject.open('POST', serverPage, true);
			ajaxObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
			ajaxObject.onreadystatechange = function() {
				if (ajaxObject.readyState == 4 && ajaxObject.status == 200) {
					targetElement.innerHTML = ajaxObject.responseText;
				}
			}
			ajaxObject.send(postStr);
		} // end if post method	
	} // end if (ajaxObject)
	
	else {
		// targetElement.innerHTML = 'Cannot Create AJAX Object';
	}
	
} //end function processajax_simple

/*---------------------------------------------------------------------------------------*/
////////  Popup Windows ////////

function pop_win(url, type) {	
	
	if (typeof(newWindow) != 'undefined') {
		newWindow.close();
	}
		
	var tools = '';
	
	if (type == 'deckplans'){
		strWidth = 970;
		strHeight = 330;
		tools = 'resizable,toolbar=no,location=no,scrollbars=no,menubar=no,width='+strWidth+',height='+strHeight+',top=30,left=10';
	}
	else if (type == 'currconvert'){
		strWidth = 650;
		strHeight = 200;
		tools = 'resizable,toolbar=no,location=no,scrollbars=no,menubar=no,width='+strWidth+',height='+strHeight+',top=150,left=150';
	}
	else if (type == 'newsletter') {
		strWidth = 780;
		strHeight = 650;
		// TODO: centre on page and set height to available height
		tools = 'resizable,toolbar=no,location=no,scrollbars=yes,menubar=no,width='+strWidth+',height='+strHeight+',top=60,left=60';
	}
	else if (type == 'promovid' || type == 'galleryvid') {
		strWidth = 450;
		strHeight = 450;
		// TODO: centre on page
		tools = 'resizable,toolbar=no,location=no,scrollbars=yes,menubar=no,width='+strWidth+',height='+strHeight+',top=90,left=90';
	}
	else if (type == 'vdive') {
		strWidth = 680;
		strHeight = 450;
		tools = 'resizable,toolbar=no,location=no,scrollbars=no,menubar=no,width='+strWidth+',height='+strHeight+',top=90,left=90';
	}
	else if (type == 'routemap') {
		strWidth = 720;
		strHeight = 310;
		tools = 'resizable,toolbar=no,location=no,scrollbars=no,menubar=no,width='+strWidth+',height='+strHeight+',top=30,left=10';
	}
	else if (type == 'sendPage') {
		strWidth = 500;
		strHeight = 520;
		tools = 'resizable,toolbar=no,location=no,scrollbars=no,menubar=no,width='+strWidth+',height='+strHeight+',top=60,left=60';
	}
	else if (type == 'vTour') {
		strWidth = 700;
		strHeight = 590;
		tools = 'resizable,toolbar=no,location=no,scrollbars=no,menubar=no,width='+strWidth+',height='+strHeight+',top=60,left=60';
	}
	else if (type == 'fullScreen'){
		strWidth = screen.availWidth - 10;
		strHeight = screen.availHeight - 160;
		tools = 'resizable,toolbar=yes,location=yes,scrollbars=yes,menubar=yes,width='+strWidth+',height='+strHeight+',top=0,left=0';
	}	
	else {
		// will just pop a new default window/tab
	}
	
	var newWindow = window.open(url, 'newWindow', tools);
	newWindow.focus();
	
} //end function pop_win()

/*---------------------------------------------------------------------------------------*/
/////// Macromedia functions ////////////
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images) { if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_CheckFlashVersion(reqVerStr,msg){
  with(navigator){
    var isIE  = (appVersion.indexOf("MSIE") != -1 && userAgent.indexOf("Opera") == -1);
    var isWin = (appVersion.toLowerCase().indexOf("win") != -1);
    if (!isIE || !isWin){  
      var flashVer = -1;
      if (plugins && plugins.length > 0){
        var desc = plugins["Shockwave Flash"] ? plugins["Shockwave Flash"].description : "";
        desc = plugins["Shockwave Flash 2.0"] ? plugins["Shockwave Flash 2.0"].description : desc;
        if (desc == "") flashVer = -1;
        else{
          var descArr = desc.split(" ");
          var tempArrMajor = descArr[2].split(".");
          var verMajor = tempArrMajor[0];
          var tempArrMinor = (descArr[3] != "") ? descArr[3].split("r") : descArr[4].split("r");
          var verMinor = (tempArrMinor[1] > 0) ? tempArrMinor[1] : 0;
          flashVer =  parseFloat(verMajor + "." + verMinor);
        }
      }
      // WebTV has Flash Player 4 or lower -- too low for video
      else if (userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 4.0;

      var verArr = reqVerStr.split(",");
      var reqVer = parseFloat(verArr[0] + "." + verArr[2]);
  
      if (flashVer < reqVer){
        if (confirm(msg))
          window.location = "http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash";
      }
    }
  } 
}

/*---------------------------------------------------------------------------------------*/
////////  Form Validation ////////
// DW extension function
function YY_checkform() { //v4.66
//copyright (c)1998,2002 Yaromat.com
  var args = YY_checkform.arguments; var myDot=true; var myV=''; var myErr='';var addErr=false;var myReq;
  for (var i=1; i<args.length;i=i+4){
    if (args[i+1].charAt(0)=='#'){myReq=true; args[i+1]=args[i+1].substring(1);}else{myReq=false}
    var myObj = MM_findObj(args[i].replace(/\[\d+\]/ig,''));
    myV=myObj.value;
    if (myObj.type=='text'||myObj.type=='password'||myObj.type=='hidden'){
      if (myReq&&myObj.value.length==0){addErr=true}
      if ((myV.length>0)&&(args[i+2]==1)){ //fromto
        var myMa=args[i+1].split('_');if(isNaN(myV)||myV<myMa[0]/1||myV > myMa[1]/1){addErr=true}
      } else if ((myV.length>0)&&(args[i+2]==2)){
          var rx=new RegExp("^[\\w\.=-]+@[\\w\\.-]+\\.[a-z]{2,4}$");if(!rx.test(myV))addErr=true;
      } else if ((myV.length>0)&&(args[i+2]==3)){ // date
        var myMa=args[i+1].split("#"); var myAt=myV.match(myMa[0]);
        if(myAt){
          var myD=(myAt[myMa[1]])?myAt[myMa[1]]:1; var myM=myAt[myMa[2]]-1; var myY=myAt[myMa[3]];
          var myDate=new Date(myY,myM,myD);
          if(myDate.getFullYear()!=myY||myDate.getDate()!=myD||myDate.getMonth()!=myM){addErr=true};
        }else{addErr=true}
      } else if ((myV.length>0)&&(args[i+2]==4)){ // time
        var myMa=args[i+1].split("#"); var myAt=myV.match(myMa[0]);if(!myAt){addErr=true}
      } else if (myV.length>0&&args[i+2]==5){ // check this 2
            var myObj1 = MM_findObj(args[i+1].replace(/\[\d+\]/ig,""));
            if(myObj1.length)myObj1=myObj1[args[i+1].replace(/(.*\[)|(\].*)/ig,"")];
            if(!myObj1.checked){addErr=true}
      } else if (myV.length>0&&args[i+2]==6){ // the same
            var myObj1 = MM_findObj(args[i+1]);
            if(myV!=myObj1.value){addErr=true}
      }
    } else
    if (!myObj.type&&myObj.length>0&&myObj[0].type=='radio'){
          var myTest = args[i].match(/(.*)\[(\d+)\].*/i);
          var myObj1=(myObj.length>1)?myObj[myTest[2]]:myObj;
      if (args[i+2]==1&&myObj1&&myObj1.checked&&MM_findObj(args[i+1]).value.length/1==0){addErr=true}
      if (args[i+2]==2){
        var myDot=false;
        for(var j=0;j<myObj.length;j++){myDot=myDot||myObj[j].checked}
        if(!myDot){myErr+='* ' +args[i+3]+'\n'}
      }
    } else if (myObj.type=='checkbox'){
      if(args[i+2]==1&&myObj.checked==false){addErr=true}
      if(args[i+2]==2&&myObj.checked&&MM_findObj(args[i+1]).value.length/1==0){addErr=true}
    } else if (myObj.type=='select-one'||myObj.type=='select-multiple'){
      if(args[i+2]==1&&myObj.selectedIndex/1==0){addErr=true}
    }else if (myObj.type=='textarea'){
      if(myV.length<args[i+1]){addErr=true}
    }
    if (addErr){myErr+='* '+args[i+3]+'\n'; addErr=false}
  }
  if (myErr!=''){alert('The following required information is incomplete or contains errors:\n\n' + myErr)}
  document.MM_returnValue = (myErr=='');
}

/*---------------------------------------------------------------------------------------*/

