var current_hotspot 	= 0;
var hotspot_timer		= null;
var hotspot_delay 		= 7000;

function goto_from_object( object_id ) {
	window.location = document.getElementById( object_id ).value;	
	return false;
}

function goto( url ) {
	window.location = url;	
	return false;
}

function place_search_url( url ) {
	url += "/";
	if ( document.getElementById( 'region_id' ).value != '' ) 			url += "_r"+document.getElementById( 'region_id' ).value + "/";
	if ( url == "/" )													url += "_/";
	url += "1";
	return goto( url );
}

function barresto_search_url( url ) {
	url += "/";
	if ( document.getElementById( 'district' ).value != '' ) 			url += "_d"+document.getElementById( 'district' ).value + "/";
	if ( document.getElementById( 'phrase' ).value != '' ) 				url += "_k"+escape(document.getElementById( 'phrase' ).value ) + "/";
	//if ( document.getElementById( 'type' ).value != '' ) 				url += "_t"+document.getElementById( 'type' ).value + "/";
	if ( document.getElementById( 'price' ).value != '' ) 				url += "_pr"+document.getElementById( 'price' ).value + "/";
	if ( document.getElementById( 'cooking_ambiance' ).value != '' ) 	url += "_ca"+document.getElementById( 'cooking_ambiance' ).value + "/";
	if ( url == "/" )													url += "_/";
	url += "1";
	return goto( url );
}

function addressbook_search_url( url ) {
	url += "/";
	if ( document.getElementById( 'category_id' ).value != '' ) 		url += "_c"+document.getElementById( 'category_id' ).value + "/";
	if ( document.getElementById( 'where' ).value != '' ) 				url += "_w"+document.getElementById( 'where' ).value + "/";
	if ( document.getElementById( 'phrase' ).value != '' ) 				url += "_k"+escape(document.getElementById( 'phrase' ).value ) + "/";
	if ( url == "/" )													url += "_/";
	url += "1";
	return goto( url );
}

function addressbook1_search_url( url ) {
	url += "/";
	if ( document.getElementById( 'category_id' ).value != '' ) 		url += "_c"+document.getElementById( 'category_id' ).value + "/";
	if ( document.getElementById( 'where' ).value != '' ) 				url += "_w"+document.getElementById( 'where' ).value + "/";
	if ( url == "/" )													url += "_/";
	url += "1";
	return goto( url );
}
function addressbook2_search_url( url ) {
	url += "/";
	if ( document.getElementById( 'phrase' ).value != '' ) 				url += "_k"+escape(document.getElementById( 'phrase' ).value ) + "/";
	if ( url == "/" )													url += "_/";
	url += "1";
	return goto( url );
}

function global_search_url( url ) {
	url += "/";
	if ( document.getElementById( 'keyphrase' ).value != '' ) 			url += "_key"+escape(document.getElementById( 'keyphrase' ).value ) + "/";
	if ( url == "/" )													url += "_/";
	url += "1";
	return goto( url );
}


function display_comment_form( comment_id ) {
	document.getElementById('comment_id').value = comment_id;
	document.getElementById('addComment').style.display = "block";
	return false;
}

/* HOTSPOTS */
function display_previous_hotspot() {
	var length 	= document.getElementById('hotspots_sections').getElementsByTagName('ul').length;
	
	var index = current_hotspot - 1;
	if ( index < 0 ) {
		index = length-1;
	} 
	
	display_hotspot( index );
	
	clearInterval( hotspot_timer );
	hotspot_timer = setInterval( display_next_hotspot, hotspot_delay); 
	
}

function display_next_hotspot() {
	var length 	= document.getElementById('hotspots_sections').getElementsByTagName('ul').length;
	
	var index = current_hotspot + 1;
	if ( index > length-1 ) {
		index = 0;
	} 
	
	display_hotspot( index );
	
	clearInterval( hotspot_timer );
	hotspot_timer = setInterval( display_next_hotspot, hotspot_delay); 
	
}

function display_hotspot( index ) {
	var hotspots_sections 	= document.getElementById('hotspots_sections').getElementsByTagName('ul');
	var hotspots_nav		= document.getElementById('hotspots_nav').getElementsByTagName('li');
	
	hotspots_sections[current_hotspot].style.display 	= "none";	
	hotspots_sections[index].style.display 				= "block";
	
	hotspots_nav[current_hotspot].className = hotspots_nav[current_hotspot].className.replace(' selected', '');
	hotspots_nav[index].className 			= hotspots_nav[index].className + " selected";
	
	current_hotspot = index;	
	
	clearInterval( hotspot_timer );
	hotspot_timer = setInterval( display_next_hotspot, hotspot_delay); 
}


/* PICTURES */
function change_picture( image, highres, title, height ) {
	var picture = document.getElementById('picture');
	var style = ( height < 320 && height > 0 ) ? (Math.floor((320-height)/2))+'px' : '0px';
	
	picture.getElementsByTagName('img')[0].src = image;	
	picture.getElementsByTagName('img')[0].style.marginTop = style;	
	picture.getElementsByTagName('p')[0].getElementsByTagName('a')[0].href = highres;	
	picture.getElementsByTagName('p')[0].getElementsByTagName('a')[0].title = title;	
	picture.getElementsByTagName('p')[1].innerHTML = title;	
}


/* SOCIAL MEDIA */
function twitter_click( language ) {
    var width  = 575,
        height = 400,
        left   = (document.viewport.getWidth()  - width)  / 2,
        top    = (document.viewport.getHeight() - height) / 2,
        url    = "http://twitter.com/share/?url="+document.location.href,
        opts   = 'status=1' +
                 ',width='  + width  +
                 ',height=' + height +
                 ',top='    + top    +
                 ',left='   + left;
    
    window.open(url, 'twitter', opts);
 
    return false;
}

function facebook_click() {
    var width  = 626,
        height = 436,
        left   = (document.viewport.getWidth()  - width)  / 2,
        top    = (document.viewport.getHeight() - height) / 2,
        url    = "http://www.facebook.com/sharer.php?u="+document.location.href,
        opts   = 'status=1' +
                 ',width='  + width  +
                 ',height=' + height +
                 ',top='    + top    +
                 ',left='   + left;
    
    window.open(url, 'facebook', opts);
 
    return false;
}

function facebook_login() {
	var form = document.getElementById('subscribeUser');
	if ( form != null ) {
		form.submit();
	} else {
		var form = document.getElementById('addComment');
		if ( form != null )
			form.submit();
	}
}

window.fbAsyncInit = function() {
	FB.init({
	  appId      : fb_app_id, // App ID
	  status     : true, // check login status
	  cookie     : true, // enable cookies to allow the server to access the session
	  oauth      : true, // enable OAuth 2.0
	  xfbml      : true  // parse XFBML
	});
};

(function(d){
 var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
 js = d.createElement('script'); js.id = id; js.async = true;
 js.src = "//connect.facebook.net/"+fb_locale+"/all.js#appId="+fb_app_id+"&xfbml=1";
 d.getElementsByTagName('head')[0].appendChild(js);
}(document));

function printPage() {
	window.print();
	return false;
}

function showSendMail() {
	document.getElementById( 'sendToFriendForm' ).submit();	
	return false;
}

function showParticipateForm() {
	document.getElementById( 'participateForm' ).submit();	
	return false;
}

function setVote( language_id, object_type, object_id, user_id, vote ) {
	Request.send( '/'+language_id+'/ajax', { 'ajax' : 'vote', 'data_type' : object_type, 'data_id' : object_id, 'user_id' : user_id, 'vote' : vote },  updateVoteArea, false );
}

function updateVoteArea() {
	var new_rating = parseInt(this.responseXML.getElementsByTagName('rating')[0].firstChild.nodeValue);
	var rating_width = (new_rating * 20) + 1;
	var object = document.getElementById( 'rating' );
	object.getElementsByTagName('ul')[0].getElementsByTagName('li')[0].style.width = rating_width+"%";
	
	var parts = object.getElementsByTagName('p')[1].innerHTML.split(" ");
	var votes = parseInt(parts[0]);
	votes = votes + 1;
	object.getElementsByTagName('p')[1].innerHTML = votes+" "+parts[1];
	object.getElementsByTagName('p')[2].style.display = "block";
}



/* SLIDER */
var Slider = {
	
	sliders : {},
	
	slide: function ( object_id, direction, width, length ) {
		if ( !this.sliders[object_id] )
			this.sliders[object_id] = new CustomSlider();
		this.sliders[object_id].slide( object_id, direction, width, length );
	},

	autostart: function ( object_id, width, length ) {
		if ( !this.sliders[object_id] )
			this.sliders[object_id] = new CustomSlider();
		this.sliders[object_id].autostart( object_id, width, length );
	},
	
	loadmore: function ( language_id, object_id, direction, length, start, total, data_id, theme_id, prefer_section_color ) {
		if ( !this.sliders[object_id] )
			this.sliders[object_id] = new CustomSlider();
		this.sliders[object_id].loadmore( language_id, object_id, direction, length, 'more', start, total, data_id, theme_id, prefer_section_color );
	},
	
	load_and_slide: function ( language_id, object_id, length, ajax_function, total, data_type, data_id, theme_id, section_id, use_theme ) {
		if ( !this.sliders[object_id] )
			this.sliders[object_id] = new CustomSlider();
		this.sliders[object_id].load_and_slide( language_id, object_id, length, ajax_function, total, data_type, data_id, theme_id, section_id, use_theme );
	},
	
	slide_back: function( object_id ) {
		if ( !this.sliders[object_id] )
			this.sliders[object_id] = new CustomSlider();
		this.sliders[object_id].slide_back( object_id );
	}
	
}

CustomSlider = function () {
    
	var instance 	= this;
	
	this.object		= null;
	this.direction	= null;
	this.timer		= null;
	this.autotimer  = null;
	this.auto  		= false;
	this.load  		= false;
	this.width		= 0;
	this.length		= 0;
	this.step		= 0;
	this.start		= 0;
	this.end		= 0;
	this.position	= 0;
	this.startat	= 0;
	this.endat		= 0;
	this.loadedfrom = 1;
	this.loadedto	= 3;
	
	this.autostart	= function( object_id, width, length ) {
		this.auto 		= true;
		this.object 	= document.getElementById( object_id );
		this.width 		= width;
		this.length 	= length;
		
		this.delayedNext(); 
	};
	
	this.slide 		= function ( object_id, direction, width, length ) {
		
		if ( this.auto )
			clearInterval( this.autotimer );
		
		this.object 	= document.getElementById( object_id );
		this.direction 	= direction;
		this.width 		= width;
		this.length 	= length;
		
		this.start = this.object.style.left;
		if ( this.start == '' ) this.start = 0;
		else this.start = parseFloat( this.start );
		
		/*this.length		= (6*(196+7))+5 - this.object.parentNode.clientWidth;
		if ( object_id == 'pictures_slide' )
			this.length 	= 108;
		*/
		
		var offset = ( this.object.id == 'latest_slide' ) ? 6 : 0;
		
		var final_length	= ( this.load ) ? (length * 3)+offset : this.length;
		this.position = this.start - final_length;
		if ( this.direction == 'left' ) {
			this.position = this.start + final_length;
			this.end	= Math.min(0, this.position);
			this.step	= 40;
			if ( this.auto )
				this.delayedPrevious();
		} else if ( this.direction == 'right' ) {
			this.end	= Math.max(-(this.width - this.object.parentNode.clientWidth), this.position);
			
			this.step	= -40;
			if ( this.auto )
				this.delayedNext();
		}
		
		var lists = this.object.parentNode.parentNode.getElementsByTagName('ul');
		for ( var i=0; i < lists.length; i+= 1 ) {
			if (lists[i].className == 'slidenav') {
				var navlist = lists[i];
				navlist.getElementsByTagName('li')[0].style.display = ( this.position >= 0 ) ? "none" : "block";
				navlist.getElementsByTagName('li')[1].style.display = ( this.position < 0 && this.position <= -(this.width - this.object.parentNode.clientWidth) ) ? "none" : "block";
			}
		}
		//var navlist = this.object.parentNode.getElementsByTagName('ul')[0];
		//navlist.getElementsByTagName('li')[0].style.display = ( this.position >= 0 ) ? "none" : "block";
		//navlist.getElementsByTagName('li')[1].style.display = ( this.position < 0 && this.position <= -(this.width - this.object.parentNode.clientWidth) ) ? "none" : "block";
		
		this.delayedMove();
	};
	
	this.next = function() {
		this.slide( this.object.id, 'right', this.width, this.length );
		if ( this.position < 0 && this.position <= -(this.width - this.object.parentNode.clientWidth) ) {
			clearInterval( this.autotimer );
			this.delayedPrevious(); 
		}
	};

	this.previous = function() {
		this.slide( this.object.id, 'left', this.width, this.length );
		if ( this.position >= 0 ) {
			clearInterval( this.autotimer );
			this.delayedNext(); 
		}
	};
	
	this.delayedNext = function( func, time ) {
       this.autotimer = setInterval(function() { instance.next(); }, 6000);
    };

	this.delayedPrevious = function( func, time ) {
        this.autotimer = setInterval(function() { instance.previous(); }, 6000);
    };

	this.delayedMove = function( func, time ) {
        this.timer = setInterval(function() { instance.move(); }, 50);
    };
	
	this.move = function() {
		var newPosition = this.start + this.step;
		if ( ( this.direction == 'left' && newPosition > this.end ) 
				|| ( this.direction == 'right' && newPosition < this.end ) ) {
			newPosition = this.end;
		}
		
		this.start 				= newPosition;
		this.object.style.left 	= newPosition.toString()+'px';
		
		if ( newPosition == this.end ) {
			clearInterval( this.timer );
			this.timer = null;
		}
		
	};

	this.loadmore = function ( language_id, object_id, direction, length, ajax_function, start, total, data_id, theme_id, prefer_section_color ) {
		if ( !this.load ) {
			this.startat	= start;
			this.loadedfrom	= start;
			this.loadedto	= start+2;
		}
		this.load = true;
		if ( this.timer == null ) {
			//
			this.direction 	= direction;
			if ( ( this.direction == 'right' && this.startat < ( total-3) ) || ( this.direction == 'left' && this.startat >= 1 ) ) { 
				this.object		= document.getElementById( object_id );
				this.length		= length;
				this.startat 	+= ( this.direction == 'right' ) ? 3 : -3;
				this.startat	= Math.max( this.startat, 0 );
				this.endat 		= this.startat + 3;
				if ( this.direction == 'right' && this.endat > total )
					this.endat	= total;
				//if ( this.direction == 'left' && this.endat > this.loadedfrom )
				//	this.endat	= this.loadedfrom;
				//Math.min( Math.min( this.startat+3, total ), this.loadedfrom );
				this.width 		= total * length;
				if ( this.startat > (this.loadedto) || this.startat < (this.loadedfrom) || this.endat > this.loadedto ) {
					//alert( 'show:' + this.startat +'/' + this.endat + ', loaded:' + this.loadedfrom + '/' + this.loadedto );
					var start = Math.max( this.loadedto+1, this.startat );
					var limit = 3 - (start-this.startat);
					if ( this.direction == 'left' ) start = this.startat;
					if ( this.direction == 'left' ) limit = this.loadedfrom-this.startat;
					Request.send( 
						'/'+language_id+'/ajax', 
						{ 'ajax' : ajax_function, 'start' : start, 'limit' : limit, 'data_type' : 'article', 'data_id' : data_id, 'theme_id' : theme_id, 'prefer_section_color' : prefer_section_color },  
						this.loadmore_callback, 
						false );	
				} else {
					this.slide( object_id, this.direction, this.width, this.length );
				}
			}
		}
	};
	
	this.loadmore_callback = function () {
		var html = instance.object.innerHTML;
		
		if ( html.indexOf( "<LI>" ) > -1 ) {
			html = html.replace( new RegExp("<LI>","g"), '<li>' );
			html = html.replace( new RegExp("</LI>","g"), '</li>' );
		}
		var to_replace = '';
		var replace_by = this.responseText.replace( '<xml>', '').replace( '</xml>', '' );
		
		var start = -1;
		var end = 0;
		for ( var i=instance.startat; i < instance.endat; i+= 1 ) {
			var string = '<li>'+i+'</li>';
			var found = html.indexOf( string );
			if ( found > -1 ) {
				if ( start == -1 )
					start = found;
				end = found + string.length;
				to_replace += string;
			}
		}
		if ( html.indexOf( to_replace ) > -1 )
			html = html.replace( to_replace, replace_by );
		else
			html = html.substring( 0, start ) + replace_by + html.substring( end, html.length-end );
		instance.object.innerHTML = html;
		
		if ( instance.direction == 'right' ) {
			instance.loadedto = instance.endat-1;
		} else {
			instance.loadedfrom = instance.startat;
		}
		instance.slide( instance.object.id, instance.direction, instance.width, instance.length );
	}

	
	this.load_and_slide = function ( language_id, object_id, length, ajax_function, total, data_type, data_id, theme_id, section_id, use_theme ) {
		this.load = true;
		if ( this.timer == null ) {
			if ( this.startat < ( total-3) ) {
				this.object		= document.getElementById( object_id );
				this.length		= length;
				var loaded 		= this.object.getElementsByTagName('li');
				this.startat 	+= 3;
				this.endat 		= Math.min( this.startat+3, total );
				this.width 		= ( (this.endat+1) * length ) + 15;
				
				this.object.style.width = this.width+'px';
				if ( loaded.length < (this.startat+2) ) {
					Request.send( 
						'/'+language_id+'/ajax', 
						{ 'ajax' : ajax_function, 'start' : loaded.length+1, 'data_type' : data_type, 'data_id' : data_id, 'theme_id' : theme_id, 'section_id' : section_id, 'use_theme' : use_theme },  
						this.load_and_slide_callback, 
						false );	
				} else {
					this.slide( object_id, 'right', this.width, this.length );
				}
			}
		}
	}

	this.slide_back = function ( object_id ) {
		if ( this.timer == null ) {
			this.slide( object_id, 'left', this.width, this.length);
			if ( this.startat > 3 ) {
				this.startat -= 3;
			} else {
				this.startat = 1;	
			}
		}
	}

	this.load_and_slide_callback = function () {
		var html = this.responseText;
		html = html.replace('<xml>', '');
		html = html.replace('</xml>', '');
		instance.object.innerHTML = instance.object.innerHTML + html;
		instance.slide( instance.object.id, 'right', instance.width, instance.length );
	}
}

/* ZOOM */
function hideZoom() {
	hide('image');
	hide('overlay');
	
	var canvas 		= document.getElementById( 'image_canvas' );
	canvas.innerHTML = '';
	
	var image 		= document.getElementById( 'image' );
	image.style.width 		= 500+'px';
	image.style.height 		= 500+'px';
	image.style.marginLeft 	= -500/2+'px';
	
	return false;
}

function zoom( objLink, alt ) {
	var scrollOffsets 	= document.viewport.getScrollOffsets();
	
	var image 		= document.getElementById( 'image' );
	var lightboxTop = scrollOffsets[1] + (document.viewport.getHeight() / 10);
	image.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
	
	var canvas 		= document.getElementById( 'image_canvas' );
	var objImage 	= document.createElement("img");
	canvas.appendChild(objImage);
	show('image');
	
	var overlay = document.getElementById( 'overlay' );
	var pageSize = getPageSize();
	overlay.style.opacity   = 0.8;
	overlay.style.width 	= pageSize[0]+'px';
	overlay.style.height 	= pageSize[1]+'px';
	show('overlay');

	// preload image
	imgPreload = new Image();
	imgPreload.onload=function(){
		var width 	= imgPreload.width;
		var height 	= imgPreload.height;
		var ratio	= 1;
		
		if ( width > document.viewport.getWidth()-100 ) {
			ratio = (document.viewport.getWidth()-100) / width;
		}
		
		if ( height > document.viewport.getHeight()-50 ) {
			var ratio2 = (document.viewport.getHeight()-50) / width;
			if (ratio2 < ratio)
				ratio = ratio2;
		}
		
		width 	= width * ratio;
		height 	= height * ratio;
		
		var lightboxTop 		= scrollOffsets[1] + (document.viewport.getHeight() / 10);
		image.style.width 		= width+'px';
		image.style.height 		= height+'px';
		image.style.marginLeft 	= -width/2+'px';
		image.style.top 		= (lightboxTop < 0) ? "0px" : lightboxTop + "px";

		canvas.style.width 	= width+'px';
		canvas.style.height = height+'px';

		objImage.src 		= objLink.href;
		objImage.width 		= width;
		objImage.height 	= height;
		show('image_canvas');
		
		var pageSize = getPageSize();
		overlay.style.opacity   = 0.8;
		overlay.style.width 	= pageSize[0]+'px';
		overlay.style.height 	= pageSize[1]+'px';
		
		return false;
	}
	imgPreload.src = objLink.href;
	return false;
}

/* GOOGLEMAPS */
var map;
var infowindow;

function showGoogleMapMarkers() {
	var markersXML 	= this.responseXML.getElementsByTagName("marker");
	var markers = [];
	for (var i = 0; i < markersXML.length; i+=1) {
		var xml 	= markersXML[i];
		var id 	 	= parseFloat(xml.getAttribute("id"));
		var name 	= xml.getAttribute("name");
		var url 	= xml.getAttribute("url");
		var lines	= xml.getElementsByTagName("line");
		var html 	= '<p>';
		html 		+= '<strong>'+name+'</strong>';
		for (var n=0; n < lines.length; n+=1)
			html += '<br />'+lines[n].firstChild.nodeValue;
		if (url != '')	html += '<br /><a href="http://'+url+'" title"'+name+'">'+url+'</a>';
		html 		+= '</p>';
		
		var point 	= new google.maps.LatLng( parseFloat(xml.getAttribute("lat")), parseFloat(xml.getAttribute("lng")) );
        var marker 	= createMarker( i+1, html, point);
		markers.push(marker);
	}
	centerMap( map, markers, true );
}

function createMarker(i, html, latlng) {
    var image = 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld='+i+'|4b4b4b|ffffff';
	var marker = new google.maps.Marker({position: latlng, map: map, icon: image});
    google.maps.event.addListener(marker, "click", function() {
      if (infowindow) infowindow.close();
      infowindow = new google.maps.InfoWindow({content: html});
      infowindow.open(map, marker);
    });
    return marker;
  }

function showInsertGoogleMap( language_id, ids ) {
	var canvas = document.getElementById('picture_map');
	canvas.style.width = "320px";
	canvas.style.height = "320px";
	
	// API 3.0
	var myLatlng = new google.maps.LatLng(48.8566667, 2.3509871);
	var myOptions = {
	  zoom: 13,
	  center: myLatlng,
	  mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map( canvas, myOptions );
	
	Request.send( '/'+language_id+'/ajax', { 'ajax' : 'markers', 'ids' : ids },  showGoogleMapMarkers, false );	
}

function showDetailedGoogleMap( language_id, ids, currentid ) {
	var canvas = hide('map_canvas');
	canvas.style.width = "500px";
	canvas.style.height = "500px";
	
	// API 3.0
	var myLatlng = new google.maps.LatLng(48.8566667, 2.3509871);
	var myOptions = {
	  zoom: 20,
	  center: myLatlng,
	  mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map( canvas, myOptions );
	
	Request.send( '/'+language_id+'/ajax', { 'ajax' : 'markers', 'ids' : ids },  showGoogleMapMarkers, false );	

	show('map_canvas');
	google.maps.event.trigger(map, 'resize');
}

function showGoogleMap( language_id, currentid, ids ) {
	var overlay = document.getElementById( 'overlay' );
	var pageSize = getPageSize();
	overlay.style.opacity   = 0.8;
	overlay.style.width 	= pageSize[0]+'px';
	overlay.style.height 	= pageSize[1]+'px';
	show('overlay');
	
	var map_div = show('map');
	var scrollOffsets 	= document.viewport.getScrollOffsets();
	var topValue 		= scrollOffsets[1] + (document.viewport.getHeight() / 10);
	map_div.style.top		= topValue+'px';
	
	show('map');
	showDetailedGoogleMap( language_id, ids, currentid );
	
	return false;
}

function hideGoogleMap() {
	hide('map');
	hide('overlay');
	return false;
}

function centerMap( map, markers, hasInfo ) {
	for (var i in markers) {
		var this_lat = markers[i].getPosition().lat() || null;
		var this_lng = markers[i].getPosition().lng() || null;
		if ( (this_lat && !isNaN(this_lat)) && (this_lng && !isNaN(this_lng)) ) {
			var minLat = minLat || this_lat;
			var maxLat = maxLat || this_lat;
			var minLng = minLng || this_lng;
			var maxLng = maxLng || this_lng;
			
			//get min and max markers and save in variables
			minLat = Math.min(minLat, this_lat);
			maxLat = Math.max(maxLat, this_lat);
			minLng = Math.min(minLng, this_lng);
			maxLng = Math.max(maxLng, this_lng);						
		}
	}
	
	//avg of the coordinates
	var centerLat = minLat + ((maxLat - minLat) / 2);
	var centerLng = minLng + ((maxLng - minLng) / 2);

	//what's the distance of our coordinates? (in kilometers)	
	var dist = (6371 * 
					Math.acos(
						Math.sin(minLat / 57.2958) *						 						
						Math.sin(maxLat / 57.2958) + (
							Math.cos(minLat / 57.2958) * 
							Math.cos(maxLat / 57.2958) * 
							Math.cos(maxLng / 57.2958 - minLng / 57.2958)	
						)
					)					
				);
	
	//default zoom level
	var zoomLvl = map.getZoom();
	//determine the zoom level out of the calculated distance
	if(dist < 0.3)
		zoomLvl = 17;
	else if(dist < 0.8)
		zoomLvl = 16;		
	else if(dist < 1.6)    
		zoomLvl = 15;		
	else if(dist < 3.2)    
		zoomLvl = 14;		
	else if(dist < 4.8)    
		zoomLvl = 13;
	else if(dist < 11)    
		zoomLvl = 12;
	else if(dist < 24)    
		zoomLvl = 11;
	else if(dist < 48)
		zoomLvl = 10;	
	else if(dist < 96)
		zoomLvl = 9;		
	else if(dist < 192)
		zoomLvl = 8;
	else if(dist < 384)
		zoomLvl = 7;
	else if(dist < 768)
		zoomLvl = 6;		
	else if(dist < 1536)
		zoomLvl = 5; 
	else if(dist < 3072)
		zoomLvl = 4;			
	else if(dist < 6144)
		zoomLvl = 3; 			
	else if(dist < 12288)
		zoomLvl = 2; 			
	else if(dist < 24576)
		zoomLvl = 1; 			
	
    if( hasInfo )
		zoomLvl = zoomLvl-1;
				
	//center map and set zoomLvl
	var point = new google.maps.LatLng(centerLat, centerLng);
	map.setCenter(point);
	map.setZoom(zoomLvl);
};	


/* AJAX */
var Request = {
    
	XMLHttpRequest: null,
   
    init: function ( ) {
		if (window.XMLHttpRequest) // Firefox et autres
			this.XMLHttpRequest = new XMLHttpRequest(); 
		else if(window.ActiveXObject){ // Internet Explorer 
			try {
				this.XMLHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				this.XMLHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}
		} else {
			this.XMLHttpRequest = null; 
		} 
	},
	
	send: function( url, params,  callbackSuccess, callbackError ) {
		if ( this.XMLHttpRequest == null )
			this.init();
		
		if ( this.XMLHttpRequest == null ) 
			return false;
		
		var xhr = this.XMLHttpRequest;
		// using this.XMLHttpRequest fails in IE6-
		
		xhr.onreadystatechange = function() {
			if ( xhr.readyState == 4 ) {
				if ( xhr.status == 200 && callbackSuccess ) {
					callbackSuccess.apply(xhr);
				} else if ( callbackError ) {
					callbackError.apply(xhr);
				}
			}
		}
		xhr.open("POST",url,true);
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		
		var stringParameters = '';
		for ( var id in params ) {
			if ( stringParameters != '' )
				stringParameters += '&';
			stringParameters += id+'='+params[id];
		}
		xhr.send(stringParameters);		
	}
	
}


/* GENERAL */
function hide( id ) {
	var div	= document.getElementById( id );
	div.style.display 	= 'none';
	return div;
}
function show( id ) {
	var div	= document.getElementById( id );
	div.style.display 	= 'block';
	return div;
}

document.viewport = {
	getDimensions: function() {
		var windowWidth, windowHeight;
	
		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth 	= document.documentElement.clientWidth;
			windowHeight 	= document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth 	= document.body.clientWidth;
			windowHeight 	= document.body.clientHeight;
		}	
		return { width: windowWidth, height:windowHeight };
	},

	getWidth: function() {
		return this.getDimensions().width;
	},
	
	getHeight: function() {
		return this.getDimensions().height;
	},

	getScrollOffsets: function() {
		return 	[ 
				 window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft, 
				 window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop 
				];
	}
};

function getPosition(oElement) {
if( typeof( oElement.offsetParent ) != 'undefined' ) {
for( var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent ) {
posX += oElement.offsetLeft;
posY += oElement.offsetTop;
}
return [ posX, posY ];
} else {
return [ oElement.x, oElement.y ];
}
}
function getPageSize() {
	        
	var scrollValues 	= getScrollSize();
	var windowValues 	= getWindowSize();
	var scrollPositions = getScrollXY();
	
	var xScroll 	= scrollValues[0], 	yScroll 		= scrollValues[1];
	var windowWidth = windowValues[0], 	windowHeight 	= windowValues[1];
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}

	return [ pageWidth, pageHeight, windowWidth, windowHeight, xScroll, yScroll, scrollPositions[0], scrollPositions[1] ];
}

function getWindowSize() {
	var windowWidth, windowHeight;

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth 	= document.documentElement.clientWidth;
		windowHeight 	= document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth 	= document.body.clientWidth;
		windowHeight 	= document.body.clientHeight;
	}	
	
	return [windowWidth,windowHeight];
}

function getScrollSize() {
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	return [ xScroll, yScroll ];
}

function getScrollXY() {
	var xScroll, yScroll;
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		yScroll = window.pageYOffset;
		xScroll = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	}
	return [ xScroll, yScroll ];
}


Placeholder = {
	
	// The normal and placeholder colors
	defaultSettings : {
		normal		: '#595959',
		placeholder : '#999999'
	},

 	html5_ready: function() {
	  var i = document.createElement('input');
	  return 'placeholder' in i;
	},
	
	init: function(settings)
	{
		
		
		if ( this.html5_ready() ) {
			return;
		}
		
		// Merge default settings with the ones provided
		if(settings)
		{
			// Merge the desired settings
			for(var property in settings)
			{
				Placeholder.defaultSettings[property] = settings[property];
			}
		}
		
		// Let's make the funky part...
		// First for input texts
		var inputs = document.getElementsByTagName("input");
		for (var i=0; i < inputs.length; i++) {
			var placeholder = inputs[i].getAttribute("placeholder");
			
			if(placeholder && inputs[i].type == "text")
			{
				inputs[i].onfocus = function(){
					Placeholder.onSelected(this);
				};
				
				inputs[i].onblur = function(){
					Placeholder.unSelected(this);
				};
				
				inputs[i].style.color = Placeholder.defaultSettings.placeholder;
				inputs[i].value = placeholder;
			}
		};
		
		// Then for textareas
		var texts = document.getElementsByTagName("textarea");
		for (var i=0; i < texts.length; i++) {
			var placeholder = texts[i].getAttribute("placeholder");
			
			if(placeholder)
			{
				texts[i].onfocus = function(){
					Placeholder.onSelected(this);
				};
				
				texts[i].onblur = function(){
					Placeholder.unSelected(this);
				};
				
				texts[i].style.color = Placeholder.defaultSettings.placeholder;
				texts[i].value = placeholder;
			}
		};
		
		
	},
	
	
	onSelected: function(input)
	{	
		if(input.value == input.getAttribute('placeholder'))
		{
			input.value = '';
		}
		
		input.style.color = Placeholder.defaultSettings.normal;
	},
	
	unSelected: function(input)
	{
		// Reset a placeholder if the user didn't type text
		if(input.value.length <= 0)
		{
			input.style.color = Placeholder.defaultSettings.placeholder;
			input.value = input.getAttribute("placeholder");
		}
	}
};
  
  
LayerAd = {

	current : null,
	
	init: function() {
		if ( document.getElementsByClassName('ad_layer').length > 0 ) {
			LayerAd.current = document.getElementsByClassName('ad_layer')[0];
			LayerAd.current.style.left = (document.viewport.getWidth()/2) + 'px';
			LayerAd.current.style.top = 200 + 'px';
			LayerAd.open();
		}
	},
	
	close: function() {
		if ( LayerAd.current != null )
			LayerAd.current.style.display = "none";
		return true;
	},
	
	open: function() {
		if ( LayerAd.current != null )
			LayerAd.current.style.display = "block";
	}
};

LayoutAd = {

	current : null,
	
	init: function() {
		if ( document.getElementsByClassName('ad_layout').length > 0 ) {
			LayoutAd.current = document.getElementsByClassName('ad_layout')[0];
			LayoutAd.open();
		}
	},
	
	close: function() {
		if ( LayoutAd.current != null )
			LayoutAd.current.style.display = "none";
		return true;
	},
	
	open: function() {
		if ( LayoutAd.current != null ) {
			LayoutAd.current.style.display = "block";		
			//document.write('<style type="text/css">#container {margin-top:150px;}</style>');
		}
	}
};

