var showCatchAlert = false;
var panTimeoutIder = 0;
var iframemap = false;

function setPageTitle(title) {
	title = 'Trayle > ' + title;
	document.title = title;	
}

function doLogin() {
	document.loginform.submit();
}

function showBadLogin() {
	showBox('login_box', 620, 70);
	var d = document.getElementById('sendnewmsg');
	if (d) {
		show('sendnewmsg');
		d.innerHTML = 'Bad username and/or password';
	}
}

var popupCount = 0;
function openPopup(fileID, width, height, scroll) {
	width += 6;
	height += 5;
 	popupCount ++;
	return window.open(fileID , 'fly'+popupCount, "menubar=0,scrollbars=" + scroll + ",toolbar=0,location=0,directories=0,status=0,resizable=0,width=" + width + ",height=" + height + "left=10, top=10");
}

function submitFrontDestinationSearch(key) {
	if (key != '') {
		//window.location='/destinations/search/'+document.getElementById('qSearchKey').value;
		document.fdestinationsearch.action = '/destinations.php?go=search&searchKey='+key;
		document.fdestinationsearch.submit();
		return false;
	} else {
		 document.getElementById('fdestinationsearch').value = 'Please enter a search';
	}
}

function submitFrontTraylerSearch(key) {

}

function submitFrontOnlyDestinationSearch() {
	document.getElementById('qSearchKey').value = document.getElementById('qfSearchKey').value;
	submitFrontDestinationSearch();
}

/*
function historyInitialize() {
	dhtmlHistory.initialize();
	dhtmlHistory.addListener(handleHistoryChange);
	
	var currentLocation = dhtmlHistory.getCurrentLocation();

	handleHistoryChange(currentLocation, null);
}


function handleHistoryChange(newLocation, historyData) {
	if(newLocation == "") {
		newLocation = _defaultLocation;
	}
	var args = getArgumentsFromLocation(newLocation);
	var go;
	var type;
	if(args.length > 1) {
		type = args.shift(); //go:destination:3  =  type : go : arguments*
		go = args.shift();
	}
	displayLocation(go, args, historyData);
}
*/

function show(elementId) {
	if (document.getElementById) { 
		var theElement = document.getElementById(elementId); 
	} else {
		if (document.all) { 
			var theElement = document.all[elementId]; 
		} else { 
			var theElement = new Object(); 
		} 
	}
	if (!theElement) { return; }
	if (theElement.style) { theElement = theElement.style; }
	if (typeof(theElement.display) == 'undefined' && !( window.ScriptEngine && ScriptEngine().indexOf( 'InScript' ) + 1 ) ) { return; }

	theElement.display = 'block';
}

function hide(elementId) {
	if (document.getElementById) { 
		var theElement = document.getElementById(elementId); 
	} else {
		if (document.all) { 
			var theElement = document.all[elementId]; 
		} else { 
			var theElement = new Object(); 
		} 
	}
	if (!theElement) { return; }
	if (theElement.style) { theElement = theElement.style; }
	if (typeof(theElement.display) == 'undefined' && !( window.ScriptEngine && ScriptEngine().indexOf( 'InScript' ) + 1 ) ) { return; }
	
	theElement.display = 'none';
}

function toggle(e) {
	var theElement = document.getElementById(e); 
	if (theElement.style.display == "none")   {
		show(e);
	} else {
		hide(e);
	}
}

function toggleBlock(block, o, showtxt, hidetxt) {
	toggle(block);
	if(o.text == showtxt) {
		o.innerHTML = hidetxt;
		o.className = "hide";
	}else{
		o.innerHTML = showtxt;
		o.className = "show";
	}
}

function setMsg(id, msg) {
	document.getElementById(id).innerHTML = msg;	
}
function setHTML(id, msg) {
	document.getElementById(id).innerHTML = msg;
}

function getTrayleTagObject(o) {
	var result = new Object();
	var params = o.getElementsByTagName("abbr");
	

	//address
	result.countryCode		= '';
	result.locality			= '';
	result.streetAddress 	= '';
	result.postalCode 		= '';
	result.tagCategory 		= '';
	
	//geo
	result.latitude 		= 0;
	result.longitude 		= 0;
	
	//rating	
	result.overall 			= 0;
	result.qualityofservice = 0;
	result.atmosphere 		= 0;
	result.looks 			= 0;
	result.valueformoney 	= 0;
	result.pricelevel 		= 0;

	//rest
	result.category			= 0;
	resultsubcategory		= 0;
	result.fnorg			= '';
	result.tel				= '';
	result.email			= '';
	result.date				= '';
	


	for(var i = 0; i < params.length; i++) {
		var s = params[i].className;
		switch(s) {
			case "recommendable":		result.recommendable		= parseInt(params[i].title);	break;
			case "qualityofservice": 	result.qualityofservice 	= parseInt(params[i].title);	break;
			case "atmosphere":			result.atmosphere			= parseInt(params[i].title);	break;
			case "looks":				result.looks				= parseInt(params[i].title);	break;
			case "valueformoney":		result.valueformoney		= parseInt(params[i].title);	break;
			case "latitude":			result.latitude				= params[i].title;	break;
			case "longitude":			result.longitude			= params[i].title;	break;
			case "country-code":		result.countryCode			= params[i].title;	break;
			case "locality":			result.locality				= params[i].title;	break;
			case "street-address":		result.streetAddress		= params[i].title;	break;
			case "postal-code":			result.postalCode			= params[i].title;	break;
			case "category":			result.category				= params[i].title;	break;
			case "subcategory":			result.subcategory			= params[i].title;	break;
			case "fn org":				result.fnorg				= params[i].title;	break;
			case "tel":					result.tel					= params[i].title;	break;
			case "email":				result.email				= params[i].title;	break;
			case "date":				result.date					= params[i].title;	break;
		}
	}
	return result;
}

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
Array.prototype.inArray = function (value) {
// Returns true if the passed value is found in the
// array.  Returns false if it is not.
    var i;
    for (i=0; i < this.length; i++) {
        // Matches identical (===), not just similar (==).
        if (this[i] === value) {
            return true;
        }
    }
    return false;
};

if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(prefix) {
//    return (this.substr(0, prefix.length) == prefix);
    return (this.indexOf(prefix) === 0);
  };
}


function showBox(id, x, y) {
	var o = document.getElementById(id);
	o.style.display = "block";
	var t = document.getElementById("wrapper");
	o.style.left = x + t.offsetLeft + "px";
	o.style.top = y +"px";
}




function getNodeValue(obj,tag) {
	try {
		var o = obj.getElementsByTagName(tag)[0];
		if (o.hasChildNodes()) {
			return obj.getElementsByTagName(tag)[0].firstChild.nodeValue;
		} 
		return obj.getElementsByTagName(tag)[0].nodeValue;
	} catch (e) {
		alert(e.message);
	}
}


function pageScroll(x,y) {
		scrollTo(x,y);
//    	window.scrollBy(x,y); // horizontal and vertical scroll increments
//    	scrolldelay = setTimeout('pageScroll('+x+','+y+')',10); // scrolls every 10 milliseconds
}


function KillPoisOnMap() {
	var d=document.getElementById("poidiv");
	if (d) d.style.display = "none";
	poiPins = new Array(new Array(), new Array(), new Array(), new Array(), new Array(), new Array()); // empty the poipins array
}

function buildStars(x) {
	document.write(buildStarsReturn(x));
}

function buildStarsReturn(x) {
	var ret = '';
	for(var i = 2; i <= 10; i = i + 2) {
		if(i <= x) {
			ret += '<img src="/img/star.gif" width="13" height="12" border="0" alt="x" />';
		}else if(i == x + 1) {
			ret += '<img src="/img/star_half.gif" width="13" height="12" border="0" alt="x" />';	
		}else{
			ret += '<img src="/img/star_empty.gif" width="13" height="12" border="0" alt="x" />';
		}
	}
	return ret;
}

function buildStarsReturnNoImage(x) {
	if(x == 0) {
		return '<img src="/img/norating.gif" width="65" height="12" border="0" alt="no rating" title="no rating" />';
	}else{
		return buildStarsReturn(x);
	}
}

function waitProgress(state) {
	if(state == true) {
		document.body.style.cursor = "progress";
	}else{
		document.body.style.cursor = "auto";
	}
}

function wait(state) {
	if(state == true) {
		document.body.style.cursor = "wait";
	}else{
		document.body.style.cursor = "auto";
	}
}

var confirmMsg  = 'Delete?';

function confirmDelete(customMessage) {
	if (!customMessage || customMessage.length < 1) customMessage = confirmMsg;
    if (confirmMsg == '') {
        return true;
    }
    var is_confirmed = confirm(confirmMsg);
    return is_confirmed;
}

var g_playing = false;
var pauseNrOfLoops = 0;
function playOrPause() {
	//alert('pop');
	//return false;
	map.DetachEvent("onchangeview", navigateMap);
	var o = document.getElementById('frontplaypauseimg');
	if(g_playing == false) {
		//playing
		o.src = '/img/map/toolbar/pause.gif';
		g_playing = true;
		
		if (nrOfLoops == maxNrOfLoops) {
			nrOfLoops = 0;
			stopPan = false;
			panFront();
		}
	}else{
		//paused
		g_playing = false;
		o.src = '/img/map/toolbar/play.gif';
		pauseNrOfLoops = nrOfLoops;
		nrOfLoops = maxNrOfLoops;			
		clearTimeout(panTimeoutIder);	
	}	
}


var stopPan = false;
function selectMapItem(mapwebname, obj) {
	var as = document.getElementById("mapitemlist").getElementsByTagName("a");
	for(var i = 0; i < as.length; i++) {
		as[i].className = "inactive";
	}
	var selected = document.getElementById(''+mapwebname);
	selected.className = "active";	
	if (obj != null && obj != 'undefined') {
		//alert('detach');
		map.DetachEvent("onchangeview", navigateMap);
		var split = obj.id.split('_');
		nrOfLoops = 0;
		featuredCounter = split[1];
		stopPan = true;
		clearTimeout(panFrontTimeoutIder);
		panFront();
		g_playing = true;
		setTimeout("playOrPause()", 500);
	}
}
var g_lastDropDown = null;
var g_dropdownCount = 0;

function showDropdown(id, o, dx, dy) {
	var pos = getElementPosition(o);
	var dropdown = document.getElementById(id);
	dropdown.style.display = "block";
	dropdown.style.top = (pos.top + dy) + "px";
	dropdown.style.left = (pos.left + dx) + "px";
	g_lastDropDown = dropdown;

	var as = dropdown.getElementsByTagName('a');
	for(var i = 0; i < as.length; i++) {
		as[i].onmouseout = startDropDownMouseOut;
		as[i].onmouseover = stopDropDownMouseOver;
	}
}

function startDropDownMouseOut() {
	//alert("test out");
	g_dropdownCount = setInterval(hideLastDropDown, 1000);
}

function stopDropDownMouseOver() {
	//alert("test over");
	clearInterval(g_dropdownCount);
}

function hideLastDropDown() {
	stopDropDownMouseOver()
	if(g_lastDropDown != null) {
		g_lastDropDown.style.display = "none";
	}
}
function getClientDimensions() {
	var x,y;
	if (self.innerHeight) // all except Explorer
	{
		x = self.innerWidth;
		y = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
		// Explorer 6 Strict Mode
	{
		x = document.documentElement.clientWidth;
		y = document.documentElement.clientHeight;
	}
	else if (document.body) // other Explorers
	{
		x = document.body.clientWidth;
		y = document.body.clientHeight;
	}
	return {width:x, height:y}
}

function getElementPosition(o) {
    var offsetTrail = o;
    var offsetLeft = 0;
    var offsetTop = 0;
    while (offsetTrail) {
        offsetLeft += offsetTrail.offsetLeft;
        offsetTop += offsetTrail.offsetTop;
        offsetTrail = offsetTrail.offsetParent;
    }
    if (navigator.userAgent.indexOf("Mac") != -1 && 
        typeof document.body.leftMargin != "undefined") {
        offsetLeft += document.body.leftMargin;
        offsetTop += document.body.topMargin;
    }
    return {left:offsetLeft, top:offsetTop};
}

function getMousePosition(e) {
	if(!e) {
		e = window.event;
	}
	
	if (e.pageX || e.pageY) {
		g_cursor.x = e.pageX;
		g_cursor.y = e.pageY;
	} else {
		g_cursor.x = e.clientX + 
			(document.documentElement.scrollLeft || 
			document.body.scrollLeft) - 
			(document.documentElement.clientLeft || 
			document.body.clientLeft);
		g_cursor.y = e.clientY + 
			(document.documentElement.scrollTop || 
			document.body.scrollTop) - 
			(document.documentElement.clientTop || 
			document.body.clientTop);
	}
}

/**
* functions to show the loading screen and set a timeout in case something goes wrong.
* the checkPrevContent checks if the content is still 'loading' after 8 seconds and if so sets it back to the previous value
* this is done to make sure nobody gets stuck on a loading screen because of some double ajax calling which is done
* on the destinations tab
*/

var prevContent = '';
var prevContentId = '';
var checkPrevContentId = 0;

function showLoadingContent(contentEl) {	
	clearTimeout(checkPrevContentId);
	var d = document.getElementById(contentEl + 'content');
	if (d) {		
		prevContent = d.innerHTML;
		prevContentId = contentEl;
		d.innerHTML = '<div class="loading" style="height:'+Math.min(Math.max(200, d.offsetHeight), 500)+'px;">&nbsp;</div>';
	}
	checkPrevContentId = setTimeout(checkPrevContent, 8000);
	return true;
}

function checkPrevContent() {
	var d = document.getElementById(prevContentId + 'content');
	if (d) {
		if (d.innerHTML.startsWith('<div class="loading"')) {
			d.innerHTML = prevContent;
		}
	}
}

function setOptionList(xml, sel, all) {
	var op = sel.options; 
	op.length = 1;
	if(all != '') {
		op[0].value = "0";
		op[0].text = all;
		op.length = 2;
	}
	
	var x = xml.getElementsByTagName("o");
	for(var i = 0; i < x.length; i++) {
		op[i+1].value = x[i].attributes[0].value;
		op[i+1].text = x[i].firstChild.nodeValue;
		op.length++;
	}

}

/*
 * SCROLLING ACCORDING TO MOUSE
 */
var g_width = 0;
var g_height = 0;
var g_left = 0;
var g_top = 0;
var g_right = 0;
var g_bottom = 0;
var g_targetId = '';
var g_cursor = {x:0, y:0};

function startScrolling() {
	var o = document.getElementById("scrolllist")
	g_width = o.offsetWidth;
	g_height = o.offsetHeight;
	 
	var x = getElementPosition(o);
	g_left = x.left;
	g_top = x.top;
	g_right = x.left + g_width;
	g_bottom = x.top + g_height;
	g_targetId = 'mapitems';

	
	
	document.onmousemove = getMousePosition;
	setTimeout(scrollText, 100);

}

function scrollText() {
	var c = g_cursor;
	//alert(c.x + " < " + g_right + " && " + c.x + " > " + g_left + " && " + c.y + " < " + g_top + " && " + c.y + " > " + g_bottom);
	if(c.x < g_right && c.x > g_left && c.y < g_bottom && c.y > g_top) {
		var o = document.getElementById(g_targetId);
		var ow = o.offsetWidth;
		var x = Math.round(  ((c.x - g_left) / g_width) * (ow - g_width) );
		if(x < 10) x = 0;
		//setMSG("x = " + x);
		o.style.left = (-1 * x) + "px";
		
		setTimeout(scrollText, 100);
	}else{
		//setMSG("off");
		document.onmousemove = null;
	}
}


function toggleRadio(id) {
	var img = document.getElementById(id);
	var spl = img.src.split('.gif');
	if(img.src.indexOf('_on') > 1) {
		img.src = spl[0].substr(0, spl[0].length - 3) + ".gif";
	}else{
		img.src = spl[0] + "_on.gif";	
	}
}

function setActive(id, o) {
	var tg = document.getElementById(id);
	var as = tg.getElementsByTagName('a');
	for(var i = 0; i < as.length; i++) {
		as[i].className = 'inactive';
	}
	o.className = 'active';
}

function responseNewPass(o, success) {
	if (success) {
		var d = document.getElementById('sendnewmsg');
		if (d) {
			if (o.responseText == "failure") {
				d.innerHTML = "new password mail failed";
			} else {
				d.innerHTML = "new password sent";
			}
//			d.innerHTML = o.responseText;
		}
		show('sendnewmsg');	
		show('logininput');		
		hide('sendnew');
		return true;
	}
	var d = document.getElementById("sendnewmsg");
	if (d) d.innerHTML = "Something went wrong, please try again.";
}

function doNewPass() {
	Connect.setForm('loginform');	
	var cObj = Connect.asyncRequest('POST', '/call/user.php?go=newpass', responseNewPass);
}

function moreOrLess(short, long, a) {
	var so = document.getElementById(short);
	var lo = document.getElementById(long);
	if(so.style.display == 'block') {
		so.style.display = 'none';
		lo.style.display = 'block';
		a.innerHTML = "less";
	}else{
		so.style.display = 'block';
		lo.style.display = 'none';
		a.innerHTML = "more";
	}
}
var g_loccallback;
function locationSet(id, lat1, long1, lat2, long2) {
	g_loccallback(id, lat1, long1, lat2, long2);
}

function checkEmail(email) {
	var x = email;
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(x)) return true;
	return false;
}

function hideMapPopupFunction() {
//	alert('hide');
	if (hideMapPopup) {		
		clearTimeout(hideMapTimeoutId);
		document.getElementById('mappopupdiv').style.display = 'none';
	} else {
		clearTimeout(hideMapTimeoutId);
		if (document.getElementById('mappopupdiv').style.display = 'inline') {
			hideMapTimeoutId = setTimeout("hideMapPopupFunction()" , 3000);
		}		
	}
}

function showBrowseBox() {
	var o = document.getElementById('browseanchor');
	if(o) {
		var x = getElementPosition(o);
		var xo = document.getElementById('browsedestinations');
		xo.style.left = x.left + 70 + "px";
		xo.style.top = (x.top - 5) + "px";
		xo.style.display = "block";
		hide('flashcontent1');
	}
}

function hideBrowseBox() {
	show('flashcontent1');
	hide('browsedestinations');
}

function checkURL(url) {
	var regexp = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	return (regexp.test(url));
}

function buildRater(id) {
	var x = document.getElementById(id).value;

	var src = '<a href="#" onfocus="blur()" onclick="setStars(0, \''+id+'\'); return false;" onmouseover="showStars(0, \''+id+'\');" onmouseout="resetStars(\''+id+'\');"><img id="starimg_0_'+id+'" src="/img/empty.gif" width="13" height="12" alt="*" border="0" /></a>';
	document.write(src);
	for(var i = 2; i <= 10; i = i + 2) {
		var img = "star.gif";
		if(i == x + 1) {
			img = "star_half.gif";
		}else if(i > x) {
			img = "star_empty.gif";
		}
		
		src = '<a href="#" onfocus="blur()" onclick="setStars('+i+', \''+id+'\'); return false;" onmouseover="showStars('+i+', \''+id+'\');" onmouseout="resetStars(\''+id+'\');"><img id="starimg_'+i+'_'+id+'" src="http://trayle.oberon.nl/img/'+img+'" width="13" height="12" alt="*" border="0" /></a>';
		document.write(src);
	}
}

function setStars(x, id) {
	showStars(x, id);
	document.getElementById(id).value = x;
}

function resetStars(id) {
	showStars(document.getElementById(id).value, id);
}

function showStars(x, id) {
	for(var i = 0; i <= 10; i = i + 2) {
		var img = "star.gif";
		if(i == 0) {
			img = "empty.gif";
		}else if(i == x + 1) {
			img = "star_half.gif";
		}else if(i > x) {
			img = "star_empty.gif";
		}
		document.getElementById('starimg_'+i+'_'+id).src = 'http://trayle.oberon.nl/img/'+img;
	}	
}

function buildRaterMoney(id) {
	var x = document.getElementById(id).value;

	var src = '<a href="#" onfocus="blur()" onclick="setMoney(0, \''+id+'\'); return false;" onmouseover="showMoney(0, \''+id+'\');" onmouseout="resetMoney(\''+id+'\');"><img id="moneyimg_0_'+id+'" src="http://trayle.oberon.nl/img/empty.gif" width="13" height="12" alt="*" border="0" /></a>';
	document.write(src);
	for(var i = 2; i <= 10; i = i + 2) {
		var img = "dollar.gif";
		if(i == x + 1) {
			img = "dollar_half.gif";
		}else if(i > x) {
			img = "dollar_empty.gif";
		}
		
		src = '<a href="#" onfocus="blur()" onclick="setMoney('+i+', \''+id+'\'); return false;" onmouseover="showMoney('+i+', \''+id+'\');" onmouseout="resetMoney(\''+id+'\');"><img id="moneyimg_'+i+'_'+id+'" src="http://trayle.oberon.nl/img/'+img+'" width="13" height="12" alt="*" border="0" /></a>';
		document.write(src);
	}
}

function setMoney(x, id) {
	showMoney(x, id);
	document.getElementById(id).value = x;
}

function resetMoney(id) {
	showMoney(document.getElementById(id).value, id);
}

function showMoney(x, id) {
	for(var i = 0; i <= 10; i = i + 2) {
		var img = "dollar.gif";
		if(i == 0) {
			img = "empty.gif";
		}else if(i == x + 1) {
			img = "dollar_half.gif";
		}else if(i > x) {
			img = "dollar_empty.gif";
		}
		document.getElementById('moneyimg_'+i+'_'+id).src = 'http://trayle.oberon.nl/img/'+img;
	}	
}

function Get_Cookie(name)
{
  var cookies = ' ' + document.cookie + ';';
  var start = cookies.indexOf(' ' + name + '=');

  if (start == -1)
    return null;

  var offset = start + name.length + 2;
  var end = cookies.indexOf(';', offset);
  return unescape(cookies.substring(offset, end));
}

function Set_Cookie(name,value,expires,path,domain,secure)
{
  document.cookie = 
    name + '=' + escape(value) +
    ( (expires) ? ';expires=' + expires.toGMTString() : '') +
    ( (path) ? ';path=' + path : ';path=/') + 
    ( (domain) ? ';domain=' + domain : '') +
    ( (secure) ? ';secure' : '');
}
