function defArg(arg, defaultValue) {
	return (typeof arg == "undefined") ? defaultValue : arg;
}

function openWnd(url, name, width, height) {
	name = defArg(name, "newwnd");
	width = defArg(width, 640);
	height = defArg(height, 480);
	var attrs = 'menubar=no,scrollbars=no,resizable=yes,location=no,toolbar=no,width='+width+',height='+height;
	return window.open( url, name, attrs, true);
}

function switchContent(cid, arrCidOff) {
	if (typeof arrCidOff == 'object' && arrCidOff.constructor == Array) {
		for (i=0; i<arrCidOff.length; i++)
			$(arrCidOff[i]).style.display = "none";
	}
	$(cid).className = ($(cid).className == "visible") ? "hidden" : "visible";
}





var thumbsMoving = 0;
var thumbImageWidth = 100;
var thumbWidth = thumbImageWidth + 5 + 5 + 1 + 1;

var thumbsShowAtOnce = 3;


function thumbsSetButtons(num)
{
	var thumbsContainer = $('thumbs_container_'+num);
	if (!thumbsContainer)
		return;

	var hidden = 0;
	var visible = 0;


	var links = thumbsContainer.getElementsByTagName('a');
	for (var i = 0; i < links.length; i++)
		if (links[i].style.display == 'none')
			hidden++;
		else
			visible++;




	var buttonNext = $('button_next_'+num);
	var buttonPrev = $('button_prev_'+num);

	if (visible <= thumbsShowAtOnce)
	{
		buttonNext.src = '/images/photo_next_disabled.gif';
		buttonNext.parentNode.href = 'javascript:void(0);';
		buttonNext.style.cursor = 'default';
	}
	else
	{
		buttonNext.src = '/images/photo_next.gif';
		buttonNext.parentNode.href = 'javascript:thumbsNext('+ num +');';
		buttonNext.style.cursor = 'pointer';
	}



	if (hidden == 0)
	{
		buttonPrev.src = '/images/photo_prev_disabled.gif';
		buttonPrev.parentNode.href = 'javascript:void(0);';
		buttonNext.style.cursor = 'default';
	}
	else
	{
		buttonPrev.src = '/images/photo_prev.gif';
		buttonPrev.parentNode.href = 'javascript:thumbsPrev('+ num +');';
		buttonNext.style.cursor = 'pointer';
	}
}


function thumbsPrev(num)
{
	//show the last hidden
	var thumbsContainer = $('thumbs_container_'+num);
	var links = thumbsContainer.getElementsByTagName('a');
	for (var i = links.length-1; i >= 0; i--)
		if (links[i].style.display == 'none')
		{
			links[i].style.display = 'inline';
			break;
		}

	thumbsSetButtons(num)
}

function thumbsNext(num)
{
	//hide the first visible
	var thumbsContainer = $('thumbs_container_'+num);
	var links = thumbsContainer.getElementsByTagName('a');
	for (var i = 0; i < links.length; i++)
		if (links[i].style.display != 'none')
		{
			links[i].style.display = 'none';
			break;
		}

	thumbsSetButtons(num)
}


function thumbShowLarge(where, what)
{
	$(where).src = what;
}




/*
*         FUNCTIONS FOR EXPANDING LISTS
			why_big_island/adventures page
			why_big_island/places page


		To make this work, list must have structure as follows:
		(please note that title of each sublist MUST be between <strong> and </strong>)

		<ul id="main_ul_id">
		<li><strong>title 1</strong>
			<ul>
				<li>subitem1</li>
				<li>subitem2</li>
				<li>subitem2</li>
				.....
			</ul>
		</li>

		....


		<li><strong>title M</strong>
			<ul>
				<li>subitem1</li>
				<li>subitem2</li>
				<li>subitem2</li>
				......
			</ul>
		</li>
		</ul>

		<script type="text/javascript">
		advlist_init('main_ul_id');
		</script>



*/

function advlist_toggle(divId) {
	if (advlist_in_progress[divId])
		return;
/*
	if (!advlist_height[divId]) {
		advlist_height[divId] = new Array();
		
		var tr = $(divId).parentNode.parentNode.parentNode.parentNode.parentNode;
		var td = $(divId).parentNode.parentNode.parentNode.parentNode;

		advlist_height[divId]['tdHeight'] = td.clientHeight;
		advlist_height[divId]['trHeight'] = tr.clientHeight;
		advlist_height[divId]['tr'] = tr;
		advlist_height[divId]['td'] = td;
	}
*/
//console.log('height: '+advlist_height[divId]['height']);
//console.log('height: '+advlist_height[divId]['td']);

	advlist_in_progress[divId] = true;
//	var functionText = "advlist_in_progress['"+divId+"'] = false; advlist_height['"+divId+"']['td'].setStyle({height: advlist_height['"+divId+"']['tdHeight']}); advlist_height['"+divId+"']['tr'].setStyle({height: advlist_height['"+divId+"']['trHeight']})";
//	var functionText = "advlist_in_progress['"+divId+"'] = false; advlist_height['"+divId+"']['td'].height = advlist_height['"+divId+"']['tdHeight']; advlist_height['"+divId+"']['tr'].height = advlist_height['"+divId+"']['trHeight']";
//	var functionText = "advlist_in_progress['"+divId+"'] = false; advlist_height['"+divId+"']['td'].setStyle('height', advlist_height['"+divId+"']['tdHeight']); advlist_height['"+divId+"']['tr'].setStyle('height', advlist_height['"+divId+"']['trHeight'])";
//	var functionText = "advlist_in_progress['"+divId+"'] = false; advlist_height['"+divId+"']['td'].setStyle('display', ''); advlist_height['"+divId+"']['tr'].setStyle('display', '')";
//	var functionText = "advlist_in_progress['"+divId+"'] = false; alert(advlist_height['"+divId+"']['td']); alert(advlist_height['"+divId+"']['tr'])";

//eval(functionText);
//alert(functionText);
//console.log(functionText);
//	new Effect.toggle(divId, 'slide', {afterFinish: new Function('advlist_in_progress[\''+divId+'\'] = false; advlist_height[\''+divId+'\'][\'td\'].height = advlist_height[\''+divId+'\'][\'height\']')});
//	new Effect.toggle(divId, 'slide', {afterFinish: new Function(functionText)});
	new Effect.toggle(divId, 'slide', {afterFinish: new Function('advlist_in_progress[\''+divId+'\'] = false')});


}


var advlist_last_id = 1;
function advlist_set_id(element)
{
	if (!element.id)
	{
		element.id = 'adv_list_'+advlist_last_id;
		advlist_last_id++;
	}
}


function advlist_init(ulId)
{
	var ul = $(ulId);
	var lis = ul.childNodes;

	for (var i = 0; i < lis.length; i++)
	{
		var li = lis.item(i);
		if (!li.tagName || !li.tagName.toLowerCase() == 'li')
			continue;

		var b = li.getElementsByTagName('strong').item(0);
		if (!b)
			continue;

		var subUl = li.getElementsByTagName('ul').item(0);
		if (!ul)
			continue;

		//put ul into div
		var div = document.createElement('div');
		advlist_set_id(div);
		li.insertBefore(div, subUl);
		div.appendChild(subUl);

		//hide subUl
		div.style.display = 'none';
		subUl.style.marginBottom = '30px';

		//set paddin-bottom: 10px; for all <li>s of subUl
		$A(subUl.getElementsByTagName('li')).each (function (e)
		{
			e.style.marginBottom = '10px';
		});

		var a = document.createElement('a');
		a.href = 'javascript:advlist_toggle(\''+div.id+'\')';

		li.insertBefore(a, b);
		a.appendChild(b);
	}
}

var advlist_in_progress = new Array();
var advlist_height = new Array();


function softSwitchImage(id, newSrc)
{
	//make clone of image
	var img = $(id);
	//img.style.position = 'absolute';
	//img.style.left = '0px';
	//img.style.top = '0px';
	img.style.zIndex = 3;

	var clone = img.cloneNode(true);
	//clone.style.position = 'absolute';
	//clone.style.left = '0px';
	//clone.style.top = '0px';
	clone.style.zIndex = 4;

	//put clone over original
	img.parentNode.appendChild(clone);


	//change original image
	img.src = newSrc;


	//hide clone smoothly
	Effect.Fade(clone, {duration: 0.8, afterFinish: softSwitchImagesFinished});
}


function softSwitchImagesFinished(effect)
{
	var e = effect.element;
	Element.remove(e);
}

function switchContent(vtId, type)
{
	if (type == 'overview')
	{
		if (!villaComplexData[vtId][type]['content'] && !villaComplexData[vtId][type]['slideshow'].length)
			type = 'areainfo';
	}



	//0. highlight current item
	var linksContainer= $('links_'+vtId);
	var links = $A(linksContainer.getElementsByTagName('a'));

	var map = ['overview', 'areainfo'];


	for (var i = 0; i < map.length; i++)
	{
		if (!villaComplexData[vtId][map[i]]['content'] && !villaComplexData[vtId][map[i]]['slideshow'].length && map[i] != 'areainfo')
			links[i].style.display = 'none';



		if (type == map[i])
			links[i].className = 'selected';
		else
			links[i].className = '';

	}



	//1. switch text
	//$('content_'+vtId).innerHTML = '<p>'+villaComplexData[vtId][type]['title']+'</h4>';
	$('content_'+vtId).innerHTML = villaComplexData[vtId][type]['content'];


	//2. switch images


	var btnPrev = $('btn_prev_'+vtId);
	var btnNext = $('btn_next_'+vtId);

	if (villaComplexData[vtId][type]['slideshow'].length)
	{
		$('btn_container_'+vtId).style.display = 'block';
		btnPrev.onclick = new Function('villaComplexData[\''+vtId+'\'][\''+type+'\'][\'slideshow\'].prev(); return false;');
		btnNext.onclick = new Function('villaComplexData[\''+vtId+'\'][\''+type+'\'][\'slideshow\'].next(); return false;');
	}
	else
	{
		$('btn_container_'+vtId).style.display = 'none';
		villaComplexData[vtId][type]['slideshow'].addImage('/images/noimage.gif');
		villaComplexData[vtId][type]['slideshow'].refresh();
	}

	villaComplexData[vtId][type]['slideshow'].refresh('xxx');
}


function submitFirstForm(e)
{
	while (e.parentNode)
	{
		alert(e.nodeName);

		if (e.nodeName && e.nodeName.toLowerCase()=='form')
		{
			e.submit();
			return true;
		}

		e = e.parentNode;
	}

	return false;
}



















/*
*  SLIDESHOW CLASS
*/


function Slideshow(imgId, numId, totId)
{
	this.imgId = imgId;
	this.numId = numId;
	this.totId = totId;

	this.current = 0;
	this.filenames = [];
	this.preloads = [];

	this.length = 0;
}

Slideshow.prototype.addImage = function(src)
{
	this.filenames.push(src);
	this.length++;
}

Slideshow.prototype.setImage = function(i)
{
	var n = this.filenames.length;
	if (i >= n) i = 0;
	if (i < 0) i = n-1;

	this.current = i;

	this.showLoading();

	if (!this.preloads[i])
	{
		this.preloads[i] = new Image();
		this.preloads[i].src = this.filenames[i];
	}


	$(this.imgId).src = this.preloads[i].src;
	$(this.imgId).onload = this.onImgLoaded.bind(this, i);
	$(this.numId).innerHTML = i+1;
	$(this.totId).innerHTML = n;


}

Slideshow.prototype.next = function(i)
{
	this.setImage(this.current + 1);
}

Slideshow.prototype.prev = function(i)
{
	this.setImage(this.current - 1);
}

Slideshow.prototype.onImgLoaded = function(imgNum)
{
	this.hideLoading();
}

Slideshow.prototype.showLoading = function()
{
	if ($(this.imgId+'_l'))
		return;


	var img = $(this.imgId);
	var parent = img.parentNode;
	parent.style.position = 'relative';

	var loadingDiv = Builder.node('div');
	loadingDiv.id = this.imgId+'_l';
	loadingDiv.style.position = 'absolute';
	this.initLoadingDiv(loadingDiv);

	parent.appendChild(loadingDiv);
}

Slideshow.prototype.initLoadingDiv = function(div)
{
	div.innerHTML = 'Loading...';
}

Slideshow.prototype.hideLoading = function()
{
	if (!$(this.imgId+'_l'))
		return;
	Element.remove($(this.imgId+'_l'));
}

Slideshow.prototype.refresh = function()
{
	this.setImage(this.current);
}




/*
*   PROP_SLIDESHOW CLASS
*/

function PropSlideshow(propId)
{
	this.propId = propId;
	this.parentConstructor = Slideshow;
	this.parentConstructor(propId+'_img', propId+'_num', propId+'_tot');
}

PropSlideshow.prototype = Slideshow.prototype;



PropSlideshow.prototype.initLoadingDiv = function(div)
{
	div.className = 'transp';
	div.style.background = 'red';
	div.style.padding = '2px 10px';
	div.style.position = 'absolute';
	div.style.left = '10px';
	div.style.top = '11px';



	div.style.fontWeight = 'bold';
	div.style.fontFamily = 'Verdana';
	div.style.fontSize = '12px';
	div.innerHTML = 'Loading...';
}



var propSlideshows = [];




function toggleAreaDetails(resId)
{
	new Effect.toggle('ad_'+resId, 'slide');
}



var Dom = {
  get: function(el) {
    if (typeof el === 'string') {
      return document.getElementById(el);
    } else {
      return el;
    }
  },
  add: function(el, dest) {
    var el = this.get(el);
    var dest = this.get(dest);
    dest.appendChild(el);
  },
  remove: function(el) {
    var el = this.get(el);
    el.parentNode.removeChild(el);
  }
};

var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        //input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        //output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

function showSpecialDescription(obj, description) {

	if ($('specialDescriptionBox') == undefined) {
		var el = document.createElement('div');
		el.innerHTML = '';
		el.id = 'specialDescriptionBox';
		el.className = 'specialDescriptionBox';
		Dom.add(el, document.body);
	}

	description = Base64.decode(description);
	$('specialDescriptionBox').innerHTML = description +
		'<br /><br /><a href="javascript:void(0);" ' +
		'onclick="javascript:$(\'specialDescriptionBox\').style.display = \'none\';">' +
		'Close</a>';

	var pos = Position.cumulativeOffset($(obj));
	$('specialDescriptionBox').style.left = Math.round(pos[0] + 0) + 'px';
	$('specialDescriptionBox').style.top = Math.round(pos[1] + 15) + 'px';

	$('specialDescriptionBox').style.display = 'block';
}


function SetCookie(cookieName,cookieValue,nDays) {
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue)
                 + ";expires="+expire.toGMTString();
}

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}



function simpleAjax(link)
{
	new Ajax.Request(link.href);
}

function number_format( number, decimals, dec_point, thousands_sep ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // %        note 1: For 1000.55 result with precision 1 in FF/Opera is 1,000.5, but in IE is 1,000.6
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
 
    var n = number, prec = decimals;
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep == "undefined") ? ',' : thousands_sep;
    var dec = (typeof dec_point == "undefined") ? '.' : dec_point;
 
    var s = (prec > 0) ? n.toFixed(prec) : Math.round(n).toFixed(prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
 
    var abs = Math.abs(n).toFixed(prec);
    var _, i;
 
    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;
 
        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
 
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }
 
    return s;
}