 var map_groups = {};
var maps_more = new Array();
var map_markers = {};
var geocoder; 
var timer = null;
function textCounter(field, countfield, maxlimit) {
    if (field.value.length > maxlimit) {
        field.value = field.value.substring(0, maxlimit);
    } else { 
        countfield.value = maxlimit - field.value.length;
    }
}

function rewrite(text, target, validchars, separator) {
    var str = "";
    var i;
    var exp_reg = new RegExp("[" + validchars + separator + "]");
    var exp_reg_space = new RegExp("[ ]");
    text.toString();
    for (i=0; i < text.length; i++) {
        if (exp_reg.test(text.charAt(i))) {
            str = str+text.charAt(i);
        } else {
            if (exp_reg_space.test(text.charAt(i))) {
                if (str.charAt(str.length-1) != separator) {
                    str = str + separator;
                }
            }
        }
    }
    if (str.charAt(str.length-1) == separator) str = str.substr(0, str.length-1);
    document.getElementById(target).value = str.toLowerCase();
}

function newWindow(mypage,myname,w,h,features) {
    if(screen.width) {
          var winl = (screen.width-w)/2;
          var wint = (screen.height-h)/2;
      } else {
          winl = 0;wint =0;
      }

      if (winl < 0) winl = 0;
      if (wint < 0) wint = 0;

      var settings = 'height=' + h + ',';
      settings += 'width=' + w + ',';
      settings += 'top=' + wint + ',';
      settings += 'left=' + winl + ',';
      settings += features;
      settings += ' scrollbars=yes ';

      win = window.open(mypage,myname,settings);

      win.window.focus();
}

var timer_handles = [];    
function set_timer(id,code,time) {
    if(id in timer_handles) {
        clearTimeout(timer_handles[id]);
    }
    timer_handles[id] = setTimeout(code,time)
}

$(document).ready(function(){
    $.ajaxSetup({
        error: function(x,e){
            if(x.status==0) {
                // Do nothing, this results in bad popups if changing pages fast
            } else if(x.status==404) {
                alert('Requested URL not found.');
            } else if(x.status==302) {
                window.location = x.responseText;
            } else if(x.status==500) {
                if(x.responseText == 'Bad Token') {
                    alert('Page timeout.  Please reload the page.');
                } else {
                    alert('Internel Server Error.');
                }
            } else if(e=='parsererror') {
                alert('Error.\nParsing request failed.');
            } else if(e=='timeout') {
                alert('Request Time out.');
            } else {
                alert('Unknow Error.\n'+x.responseText);
            }
        }
    });

	if ($('#home_map').size()) {
	
		initialize_home();
	}

	if ($('#city_map').size()) {
		var city = $('#city_map').attr('city');
		initialize_city(city);
	}

	$('input.map_groups').click(function() {
		var group = $(this).val();
		toggleGroup(group);
	});

	$('#map_groups').find('table.group_item').hide();
	$('#map_group_message').click(function() {
		$(this).hide();
		$('#map_groups').find('table.group_item').show();
	});

	$('div.holder_next, div.holder_prev').hover(function() {
		$(this).css('background-color', '#efefef');
	},
	function () {
		$(this).css('background-color', '');
	});
	$('div.map_tabs ul li').click(function() {
		$(this).parent().find('li').removeClass('active');
		$(this).addClass('active');
		set_group_active($(this));
	});
	/*$('div.holder_next, div.holder_prev').click(function() {
			var photo_holder = $(this).parents('.popular_photo_holder');
			var scroll_photo_holder = $(this).parents('.popular_photo_holder').find('.popular_photos');;
			var parent_width = $(scroll_photo_holder).parent().width();
			var current_margin = parseInt($(scroll_photo_holder).attr('current_margin'));
			var current_width = $(scroll_photo_holder).width();

			if ($(this).hasClass('holder_next')) {
				next_margin = current_margin - parent_width;
				margin_limit = (current_width - parent_width) * -1
				if (next_margin < margin_limit) next_margin = margin_limit;
				$(scroll_photo_holder).attr('current_margin', next_margin);
			}
			else {
				prev_margin = current_margin + parent_width;
				margin_limit = 0
				if (prev_margin > margin_limit) prev_margin = margin_limit;
				$(scroll_photo_holder).attr('current_margin', prev_margin);
			}
			$(scroll_photo_holder).animate({marginLeft: $(scroll_photo_holder).attr('current_margin')+'px'}, 1000);

	});*/

	/*if ($('div.popular_photos').size())	{
		$('div.popular_photos a').lightBox({
			overlayBgColor: '#FFF',
			overlayOpacity: 0.6,
			imageLoading: global_site_url+'/images/lightbox-ico-loading.gif',
			imageBtnClose: global_site_url+'/images/lightbox-btn-close.gif',
			imageBtnPrev: global_site_url+'/images/lightbox-btn-prev.gif',
			imageBtnNext: global_site_url+'/images/lightbox-btn-next.gif',
			containerResizeSpeed: 350,
			txtImage: 'Imagem',
			txtOf: 'de'
		});
	}*/

	if ($('.popular_photos').size())	{
		$('.popular_photos').css('visibility', 'visible');
		$('.popular_photos').find('ul.actual_photos li').hide();
		$('.popular_photos').find('ul.actual_photos li:first').show();
		$('.popular_photos').find('ul.actual_photos li:first').show();
		$('.popular_photos').attr('current_photo', '0');

		$('.popular_photos').find('ul#thumbs_photos li:first').addClass('current_thumb');

		timer = setTimeout(function() { init_slideshow();}, 3000);
		$('.popular_photos').mouseenter(function() {
			$(this).find('div#controls').animate({marginTop:'265px'}, 100);
		});
		$('.popular_photos').mouseleave(function() {
			if ($(this).find('div#thumbs').is(':hidden')) {
				$(this).find('div#controls').animate({marginTop:'300px'}, 100);
			}
		});

		$('div#controls div.play').click(function() {
				if ($(this).attr('state') == 'pause') {
					$(this).css('font-size', '25px');
					$(this).html('&#9654;');
					$(this).attr('state', 'play');
					$(this).addClass('enabled');
					init_slideshow();
				}
				else {
					$(this).css('font-size', '16px');
					$(this).html(' &#9612;&#9612;');
					$(this).attr('state', 'pause');
					$(this).removeClass('enabled');
					clearTimeout(timer);

				}
		});

		$('div#controls div.next').click(function() {
				clearTimeout(timer);
				init_slideshow();

		});
		$('div#controls div.prev').click(function() {
			clearTimeout(timer);
			var max = $('.popular_photos').find('ul.actual_photos li').length - 2;
			var current = parseInt($('.popular_photos').attr('current_photo'));
			var next = current-2;
			next = (next < 0) ? max : next;
			$('.popular_photos').attr('current_photo', next);
			init_slideshow();
		});

		$('div#controls div.preview').click(function() {
				if ($(this).attr('state') == 'show') {
					$(this).attr('state', 'hide');
					$('.popular_photos').find('div#thumbs').hide();
					$(this).removeClass('enabled');
				}
				else {
					$(this).attr('state', 'show');
					$('.popular_photos').find('div#thumbs').show();
					$(this).addClass('enabled');
				}
		});

		$('div#thumbs div.move_left, div#thumbs div.move_right').mouseenter(function() {
				$(this).parents('.popular_photos').attr('in_scroll', 'yes');
				$(this).css('opacity', '1');

				var left = $('#thumbs_photos').width() - (470+55);
				var right = 0;
				var current = parseInt($('#thumbs_photos').css('margin-left'));
				var dir = $(this).hasClass('move_left') ? 'right' : 'left';
				var move_time = (dir == 'left') ? ((left - current) * 25) : Math.abs(0 - current) * 25;
				if (dir == 'left') {
					$('ul#thumbs_photos').stop(true, false).animate({marginLeft:left * -1}, move_time);
				}
				else {
					$('ul#thumbs_photos').stop(true, false).animate({marginLeft:0}, move_time);
				}
		});

		$('div#thumbs div.move_left, div#thumbs div.move_right').mouseleave(function() {
			$(this).parents('.popular_photos').attr('in_scroll', 'no');
			$(this).css('opacity', '0.8');
			$('ul#thumbs_photos').stop(true);
		});

		$('ul#thumbs_photos li').click(function() {
			clearTimeout(timer);
			var index = $('ul#thumbs_photos li').index($(this)) - 1;
			$('.popular_photos').attr('current_photo', index);
			$('ul#thumbs_photos').stop(true, false);
			init_slideshow();
		});
		

	}
	
	$('.map_locator').click(function() {
		var m_long = $(this).attr('long');
		var m_lat = $(this).attr('lat');
		var lid = $(this).attr('listing_id');
		var point =	new GLatLng(m_lat,m_long);
		var infowindow = $(this).attr('infowindow');
		var marker = map_markers[lid];
        map.setCenter(point, 20);
		if (marker)	marker.openInfoWindowHtml(infowindow);

	});


});
function set_group_active(tab) {
    var main_group = $(tab).attr('icon_group');
	var real_group = $(tab).attr('group_name');
	$(tab).parent().find('li').each(function() {
	    var group = $(this).attr('icon_group');
		toggleGroup1(group, (main_group == 'All') ? 1 : 0);
		//toggleGroup1(group, (main_group == 'Top') ? 1 : 0);

	});
	if (main_group != 'All' /*|| main_group != 'Top'*/) {
		toggleGroup1(main_group, 1);
		current_sub = real_group;
	}
	else {
		current_sub = '';
	}
	get_data(main_group);
	
}

function get_data(main_group) {
	$('.review_box').each(function() {
		var sub = $(this).attr('id').replace('box_', '');
		if ($(this).attr('id') != 'box_' + main_group && main_group != 'All') {
			$(this).hide();
		}
		else {
			if (main_group == 'All') { 
				$('#content_'+sub).html('<img src="'+global_site_url+'/images/lightbox-ico-loading.gif" />');
				$.get(global_site_url+'/?page=ajax&name='+current_city+'&action=getinfo&sub='+sub+'&default=1', function(response) {

					$('#content_'+sub).html(response);
				}, "html");
				$(this).show();
			} /*else if(main_group == 'Top'){
				
						$('#content_'+sub).html('<img src="'+global_site_url+'/images/lightbox-ico-loading.gif" />');
						$.get(global_site_url+'/?page=ajax&name='+current_city+'&action=getinfo&sub='+sub+'&default=1', function(response) {
		
							$('#content_'+sub).html(response);
						}, "html");
						$(this).show();
				
			}*/
			else {
				$('#content_'+sub).html('<img src="'+global_site_url+'/images/lightbox-ico-loading.gif" />');
				$.get(global_site_url+'/?page=ajax&name='+current_city+'&action=getinfo&sub='+sub, function(response) {
					$('#content_'+sub).html(response);
				}, "html");
				$(this).show();
			}
		}
	});

}

function get_reviews_text(review_counts) {
	var titles = new Array('Hot&eacute;is','Restaurantes','Praias');
	var counts = review_counts.split('-');
	var text = '';
	for (i=0;i<counts.length;i++) {
		if (counts[i] != 0) text += titles[i] + ': '+ counts[i] + '<br />'; 
	}
	if (text != '') {
		text = '<small><b>Coment&aacute;rios</b><br />'+text+'</small>' ;
	}
	return text;
}
// Call this function when the page has been loaded
function initialize_home() {
	map = new GMap2(document.getElementById("home_map"));
	//map.setUIToDefault();
	var zoomControl = new GLargeMapControl3D();
	map.addControl(zoomControl);
	showAddress('Brasil', 4);
	
	$('#main_locations').find('a').each(function() {
		var lat = $(this).attr('lat');
		var long =  $(this).attr('long');
		var name = $(this).text();
		var href = $(this).attr('href');
		var review_counts = $(this).attr('review_counts');
		showMarker_point(name, href, lat, long, null, null, 'main_locations', null, get_reviews_text(review_counts));
	});

	$('#more_locations').find('a').each(function() {
		var lat = $(this).attr('lat');
		var long =  $(this).attr('long');
		var name = $(this).text();
		var href = $(this).attr('href');
		var review_counts = $(this).attr('review_counts');
		showMarker_point(name, href, lat, long, null, null, 'more_locations', null, get_reviews_text(review_counts));
	});
	GEvent.addListener(map, 'zoomend', function() {
		if (map.getZoom() >= 5) {
			toggleGroup1('more_locations', 1);	
		}
		else {
			toggleGroup1('more_locations', 0);	
		}
	});

	toggleGroup('more_locations');
}

function initialize_city(city) {
	map = new GMap2(document.getElementById("city_map"));
	var zoomControl = new GLargeMapControl3D();
	map.addControl(zoomControl);
	var moveListener = GEvent.addListener(map, "moveend", function() {
		$('div#map_holder div#map_load').show();
		var bounds = map.getBounds();
		var southWest = bounds.getSouthWest();
		var northEast = bounds.getNorthEast();

		var bounds = map.getBounds();
	  var southWest = bounds.getSouthWest();
	  var northEast = bounds.getNorthEast();
	  var lat_left = southWest.lat();
	  var lat_right = northEast.lat();
	  var lng_top = northEast.lng();
	  var lng_bottom = southWest.lng();
 
		var url = global_site_url + '?page=ajax&action=get_listings&sub='+current_sub+'&lat='+lat_left+'|'+lat_right+'&lng='+lng_top+'|'+lng_bottom;
		//alert(url);
		$.post(url, {}, function(response) {
			maps = response;
			initialize_city_map_markers();
			$('div#map_holder div#map_load').hide();
		}, "json");


	});

	showAddress(city + ', Brasil', 13);
	
}

function initialize_city_map_markers() {
	for (key in maps) {
	  var data = maps[key];
	  showMarker_point((data.place + ' - ' + data.type), data.href, data.latitude, data.longitude, data.icon, null, data.group, data.listing_id, data.address);
	}
}


function showAddress(address,zoom) {
  geocoder = new GClientGeocoder();
  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        //alert(address + " not found");
      } else {
        map.setCenter(point, zoom);
      }
    }
  );
}

function showMarker(address) {
 geocoder = new GClientGeocoder();
  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
		  
      } else {
          var marker = new GMarker(point);
		  map.addOverlay(marker);
      }
    }
  );
}

function showMarker_point(name, href, lat, long, icon, new_window, group, listing_id,address) {
	//alert("showMarker_point");
	//infoBox = new BFInfoWindow();
	var point =	new GLatLng(lat,long);
	var marker;

	if (icon && icon != 'default'){
		var Icon = new GIcon();
		Icon.image = global_site_url +"/images/icons/"+icon+'.gif';
		Icon.iconSize = new GSize(24, 28);
		Icon.iconAnchor = new GPoint(6, 20);
		Icon.infoWindowAnchor = new GPoint(6, 1);
	    marker = new GMarker(point, Icon);
	}
	else {
	    marker = new GMarker(point);
	}
	if (!map_groups[group]) map_groups[group] = new Array();
	if (listing_id) map_markers[listing_id] = marker;
	

	map_groups[group].push(marker);
//================
//marker = new GMarker( new GLatLng(43, -120), redIcon1);
//          GEvent.addListener(marker, 'click', function(){ 
//            marker.openExtInfoWindow(
//              map,
//              "extInfoWindow_funkyBox",
//              "<p>I'm a funky ExtInfoWindow with HTML content.</p>",
//              {beakOffset: 2}
//            ); 
//          });


//	var baseIcon = new GIcon();
//	baseIcon.shadow = global_site_url +"/images/icons/C1"+icon+'.gif';
//	baseIcon.iconSize = new GSize(20, 34);
//	baseIcon.shadowSize = new GSize(37, 34);
//	baseIcon.iconAnchor = new GPoint(9, 34);
//	baseIcon.infoWindowAnchor = new GPoint(9, 2);
//	baseIcon.infoShadowAnchor = new GPoint(18, 25);

	GEvent.addListener(marker, "mouseover", function() {
																								                          
		  //marker.openInfoWindowHtml('<div class="popup_location_name">'+name + '</div>'+((address) ? address : ''));
			marker.openInfoWindowHtml('<div onclick="window.location='+href+'"><a href="'+href+'" ><div class="popup_location_name" onclick="window.location.href=\''+href+'\'" style="color: #03487d; cursor: pointer;"><a href="'+href+'">'+name + '</a></div><div style="font-family: arial,helvetica,serif; padding-left: 10px; background: #ffffff; color: #03487d"><a href="'+href+'">'+((address) ? address : ''+'</a></div</a></div>'));
		 
		/* infoBox.set_content('<a href="'+href+'"><div class="popup_location_name" onclick="window.location.href=\''+href+'\'" style="color: #03487d; cursor: pointer;"><a href="'+href+'">'+name + '</a></div><div style="font-family: arial,helvetica,serif; padding-left: 10px; border-left: 1px solid #C9CBCC; border-right: 1px solid #C9CBCC; background: #ffffff; color: #03487d"><a href="'+href+'">'+((address) ? address : ''+'</a></div</a>' );
    infoBox.open(map, marker);*/
		
		
		 
//           marker.openExtInfoWindow(
//              map,
//              "extInfoWindow_coolBlues",
//              '<a href="'+href+'"><div class="popup_location_name" onclick="window.location.href=\''+href+'\'" style="color: #03487d; cursor: pointer;"><a href="'+href+'">'+name + '</a></div><div style="font-family: arial,helvetica,serif; padding-left: 10px; border-left: 1px solid #C9CBCC; border-right: 1px solid #C9CBCC; background: #ffffff; color: #03487d"><a href="'+href+'">'+((address) ? address : ''+'</a></div</a>'),
//              {beakOffset: 2}
//            ); 

/*marker.openExtInfoWindow(
              map,
              "extInfoWindow_coolBlues",
              "<div>With some clever use of gradients, widths, and the "+
              "GIcon.infoWindowAnchor position, we can make a cool info window "+
              "with a beak pointing to the Lat / Lon on the map</div>",
              {beakOffset: 1}
            ); */



// last working....
/* marker.openExtInfoWindow(
              map,
              "extInfoWindow_coolBlues",
              '<a href="'+href+'"><div class="popup_location_name" onclick="window.location.href=\''+href+'\'" style="color: #03487d; cursor: pointer;"><a href="'+href+'">'+name + '</a></div><div style="font-family: arial,helvetica,serif; padding-left: 10px; border-right: 1px solid #C9CBCC; border-left: 1px solid #C9CBCC; background: #ffffff; color: #03487d"><a href="'+href+'">'+((address) ? address : ''+'</a></div</a>'),
              {beakOffset: 2}
            ); 
*/

   });
	
	 GEvent.addListener(marker, "mouseout", function() {
		  //marker.closeInfoWindow();
	 });
	 if (href != '')  {
		 GEvent.addListener(marker, "click", function() {
			 if (new_window) {
				window.open(href);
			 }
			 else {
				 
				 location.href = href;
			 }
		 });
	 }
	map.addOverlay(marker);

}

UTF8 = {
	encode: function(s){
		for(var c, i = -1, l = (s = s.split("")).length, o = String.fromCharCode; ++i < l;
			s[i] = (c = s[i].charCodeAt(0)) >= 127 ? o(0xc0 | (c >>> 6)) + o(0x80 | (c & 0x3f)) : s[i]
		);
		return s.join("");
	},
	decode: function(s){
		for(var a, b, i = -1, l = (s = s.split("")).length, o = String.fromCharCode, c = "charCodeAt"; ++i < l;
			((a = s[i][c](0)) & 0x80) &&
			(s[i] = (a & 0xfc) == 0xc0 && ((b = s[i + 1][c](0)) & 0xc0) == 0x80 ?
			o(((a & 0x03) << 6) + (b & 0x3f)) : o(128), s[++i] = "")
		);
		return s.join("");
	}
};


function toggleGroup(type) {
      for (var i = 0; i < map_groups[type].length; i++) {
        var marker = map_groups[type][i];
        if (marker.isHidden()) {
          marker.show();
        } else {
          marker.hide();
        }
      } 
 }




function toggleGroup1(type, show_or_hide) {
	if (typeof map_groups[type] == 'undefined') return;
      for (var i = 0; i < map_groups[type].length; i++) {
        var marker = map_groups[type][i];
        if (show_or_hide == 1) {
          marker.show();
        } else {
          marker.hide();
        }
      } 
 }

 function init_slideshow() {
	var max = $('.popular_photos').find('ul.actual_photos li').length - 1;
	var current = parseInt($('.popular_photos').attr('current_photo'));
	var next = ((current + 1) > max) ? 0 : current + 1;
	$('.popular_photos').find('ul.actual_photos li').each(function() {
		var index = $('ul#thumbs_photos li').index($(this));
		if (index != current && index != next) {
			$(this).hide();
		}
	});
	$('.popular_photos').find('ul.actual_photos li').eq(current).fadeOut(1000);
	$('.popular_photos').find('ul.actual_photos li').eq(next).fadeIn(1000);
	$('.popular_photos').attr('current_photo', next);
	$('#current_photo').text(next+1);
	$('.popular_photos').find('ul#thumbs_photos li').removeClass('current_thumb');
	$('.popular_photos').find('ul#thumbs_photos li').eq(next).addClass('current_thumb');
	if ($('.popular_photos').attr('in_scroll') != 'yes') {
		center_thumbs(next);
	}
	timer = setTimeout(function() {init_slideshow();}, 4000);
}

function center_thumbs(index) {
	var width = parseInt($('ul#thumbs_photos').css('width'));
	var center = (470/2)+(61/2)
	var current_point = index * 61;
	var des = (current_point*-1) + (center-55);
	var max_left = (width * -1)	+ 470;
	des = (des < max_left) ? max_left : des;
	des = (des > 0) ? 0 : des;
	$('ul#thumbs_photos').stop().animate({marginLeft:des}, 1000);
}





