Cufon.replace('.m_item');
Cufon.replace('.main_col h2');
Cufon.replace('h2');
Cufon.replace('.titlu_col_mic');
Cufon.replace('.titlu_col');
//Cufon.replace('.map_nav_tab');
//Cufon.replace('.map_nav_tab_u');

//conexiuni
$(document).ready(function() {
	//Moving selected item(s) to right select box provided
	$('#moveright').click(function() { 
		//If none of the items are selected, inform the user using an alert
		if(!isSelected("#fromSelectBox")){return false;} 
		//If atleast one of the item is selected, initially the selected option would be 'removed' and then it is appended to 'toSelectBox' (select box)
		$('#fromSelectBox option:selected').remove().appendTo('#toSelectBox'); 
		return false;
	});
	
	//Moving selected item(s) to left select box provided
	$('#moveleft').click(function() {
		//If no items are present in 'toSelectBox' (or) if none of the items are selected inform the user using an alert
		if(!noOptions("#toSelectBox") || !isSelected("#toSelectBox")){return false;} 
		//If atleast one of the item is selected, initially the selected option would be 'removed' and then it is appended to 'fromSelectBox' (select box)
		$('#toSelectBox option:selected').remove().appendTo('#fromSelectBox');
		return false;
	});
	
	//Moving selected item(s) to upwards
	$('#moveup').click(function(){
		//If no items are present in 'toSelectBox' (or) if none of the items are selected inform the user using an alert
		if(!noOptions("#toSelectBox") || !isSelected("#toSelectBox")){return false;}
		//If atleast one of the item is selected, through loop - the selected option would be moved upwards
		$('#toSelectBox option:selected').each(function(){$(this).insertBefore($(this).prev());});
		return false;
	});
	
	//Moving selected item(s) to upwards
	$('#movedown').click(function(){
		//If no items are present in 'toSelectBox' (or) if none of the items are selected inform the user using an alert
		if(!noOptions("#toSelectBox") || !isSelected("#toSelectBox")){return false;}
		//If atleast one of the item is selected, through loop - the selected option would be moved downwards
		var eleValue = $('#toSelectBox option:selected:last').next();
		$("#toSelectBox option:selected").each(function(){
			$(this).insertAfter(eleValue);
			eleValue = $(eleValue).next();
		});
		return false;
	});
	
	//Moving selected item(s) to topmost
	$('#topmost').click(function(){
		//If no items are present in 'toSelectBox' (or) if none of the items are selected inform the user using an alert
		if(!noOptions("#toSelectBox") || !isSelected("#toSelectBox")){return false;}
		//If the selected item(s) index is greater than first item (option) index then move that item to the first position
		if($('#toSelectBox option:selected').attr('index') > $('#toSelectBox option:first').attr('index')){
			$('#toSelectBox option:selected').insertBefore($('#toSelectBox option:first'));
		}
		return false;
	});
	
	$('#bottommost').click(function(){
		//If no items are present in 'toSelectBox' (or) if none of the items are selected inform the user using an alert	
		if(!noOptions("#toSelectBox") || !isSelected("#toSelectBox")){return false;}
		//If the selected item(s) index is less than last item (option) index then move that item to the last position
		if($('#toSelectBox option:selected').attr('index') < $('#toSelectBox option:last').attr('index')){
			$('#toSelectBox option:selected').insertAfter($('#toSelectBox option:last'));
		}
		return false;
	});
});

//Below function is to validate the select box, if none of the item(s) is selected then it alerts saying 'Please select atleast one option' if user selects an item then it returns true
function isSelected(thisObj){
	if (!$(thisObj+" option:selected").length){
		alert("Please select atleast one option");
		return 0;
	}
	return 1;
}

//Below function is to validate the select box, if none of the item(s) where present in the select box provided then it alerts saying 'There are no options to select/move' if select box has more than one item it returns true
function noOptions(thisObj){
	if(!$(thisObj+" option").length){
		//alert("There are no options to select/move");
		return 0;
	}
	return 1;
}

//Below function is to de-select all items if any of the item(s) are selected
function clearAll(thisObj){
	$('#'+thisObj).each(function(){$(this).find('option:selected').removeAttr("selected");});
}//function close

//Below function is to select all items
function selectAll(thisObj){
	if(!noOptions("#"+thisObj)){return false;}
	$('#'+thisObj+' option').each(function(){$(this).attr("selected","selected");});
}//function close

//sfarsit conexiuni

$(document).ready(function() {
						   
	//$('.main_col h2').css('visibility', 'hidden');
	//$('h2').css('visibility', 'hidden');
	//$('.m_item').css('visibility', 'hidden');
	
	$('.anunt_banner').draggable({ containment: 'parent' });
	
	$('.x_anunt').click(function(){
		$(this).parent().hide();
		return false;
	});
	
	$(".gotob").click(function(){
		$(".gotob").removeClass("gotob_selected");
		$(this).addClass("gotob_selected");
		$("#panels").scrollTo($(this).attr("href"), 500);	
		return false;
	});
						  
	$(".eveniment").hover(function() {
		if ($(".hover", this).css("display") == "block") { return false; }
		os = $(this).offset();
		height = $("div.hover", this).height()+10;
		width = $("div.hover", this).width();
		$("div.hover", this).css({top: os.top-height+50+"px", left: os.left-width/2+30+"px"}).animate({top: os.top-height+20+"px", opacity: "show"}, 250);
	},
	function() {
		os = $(this).offset();
		$(".hover", this).animate({top: os.top-height-50+"px", opacity: "hide"}, 250);
	});
	
	$(".tooltip").hover(function() {
		if ($(".hover_mic", this).css("display") == "block") { return false; }
		os = $(this).offset();
		height = $("div.hover_mic", this).height()+15;
		width = $("div.hover_mic", this).width();
		half = $(this).width()/2;
		$("div.hover_mic", this).css({top: os.top-height+25+"px", left: os.left-width/2+half+"px"}).animate({top: os.top-height+10+"px", opacity: "show"}, 125);
	},
	function() {
		os = $(this).offset();
		$(".hover_mic", this).animate({top: os.top-height-25+"px", opacity: "hide"}, 125);
	});
	
	$('.ul_gal').jqGalScroll({
		width: 320,
		height: 240,
		speed: 500,
		direction : 'horizontal' // vertical horizontal diagonal);
	});

	$('.media').media({ width: 320, height: 240 });
	$('.media_banner_1').media({ width: 460, height: 60 });
	$('.media_banner_2').media({ width: 160, height: 600 });
	$('.media_banner_3').media({ width: 200, height: 200 });
	
	$(".lightbox").lightbox();
	
	$('.rollover').hover(function() {
		$(this).attr('src', '/imagini/logo_over.jpg');
	}, function() {
		$(this).attr('src', '/imagini/logo.jpg');
	});
	
	$(".tab").click(function(){
		$(".tab").removeClass("tab_selected");
		$(this).addClass("tab_selected");
		//$("#panels").scrollTo($(this).attr("href"), 500);
		$(".tab_content").hide();
		$("#tab" + $(this).attr("rel")).show();
		$("input[name='select_all']").attr("checked", false);
		$(".selectable").attr("checked", false);
		return false;
	});
	
	$(".search_a").click(function(){
		$(".search_dropdown").show();
		return false;
	});
	
	$(document).click(function(){
		$(".search_dropdown").hide();
		//$(".transparent_black").hide();
	});
		
	$(".lanseaza_harta, .lanseaza_harta_v").click(function(){
		$(".transparent_black").fadeIn(400);
		initialize();
		return false;
	});
	
	$("#map_btn_setloc").click(function(){
		$(".transparent_black").fadeIn(400);
		initialize(2);
		var mypos = $("#mypos").val();
		if (mypos != undefined) {
			var mypos_arr = mypos.split(", ");
			var latlng = new google.maps.LatLng(mypos_arr[0], mypos_arr[1]);
			select_loc(latlng);
		}
		
		return false;
	});
	
	$("#map_btn_saveloc").click(function(){
		if (!marker_pos) {
			alert ('Please click on the map to select your location.');
			return false;
		}
		
		var mypos = marker_pos.getPosition();
		$('#mypos').val(mypos.lat() + ', ' + mypos.lng());
		$("#close_map").click();
		//window.location = "/comunitate/save_location.php?lat=" + mypos.lat() + "&lng=" + mypos.lng();
		
		return false;
	});
	
	$("#close_map").click(function(){
		$(".transparent_black").fadeOut(200);
		return false;
	});
	
	$(".map_nav_tab").click(function(){
		if (infoBox) infoBox.setMap(null);
		$(".map_nav_tab").removeClass("map_nav_tab_selected");
		$(this).addClass("map_nav_tab_selected");		
		loadFeed($(this).attr("rel"));
		return false;
	});
	
	$("input[name='select_all']").click(function(){
		$(".selectable").attr("checked", $(this).attr("checked"));
	});
	
	$('#adaugaimg').click(function() {
		var v_html = $('#TEMPLATE').html();
		var nr = $('#nr').val();
		v_html = v_html.replace(/elementid/g, "elem" + nr);
		nr++;
		$('#nr').val(nr);
		//alert(v_html);
		$('#loc_imagini').append(v_html);
		return false;
	});
	
	$('#adaugalang').click(function() {
		//$('textarea.art_body').tinymce().remove();
		
		var v_html = $('#TEMPLATE').html();
		var nr = Math.round(Math.random()*10000);
		//alert(nr);
		v_html = v_html.replace(/elementid/g, nr);
		$('#loc_lang').append(v_html);
		
		initTinymce('#text_' + nr);
		
		return false;
	});
	
	$(".limba").click(function(){
		$(".limba").removeClass("limba_s");
		$(this).addClass("limba_s");
		
		var id = $('#art_id').val();
		$('#art_title').text('loading...');
		$('#art_title').load('/comunitate/get_art.php?get=titlu&id=' + id + '&tip=' + $(this).attr('rel') + '&lang=' + $(this).text());
		$('#art_body').load('/comunitate/get_art.php?get=body&id=' + id + '&tip=' + $(this).attr('rel') + '&lang=' + $(this).text(), function() {
			Cufon.replace('h2');
		});
		
		return false;
	});
	
	$("select[name='publish_cat']").change(function(){
		//alert('url: ' + $(this).val());
		window.location = $(this).val();
		return false;
	});
	
	$(".link_admin").click(function(){							
		if ($(this).hasClass('rename_topic')) {
			var title = prompt('New title:');
			if (title == null) return false;
			var id = $(this).attr('rel');
			
			var url = '/comunitate/process_admin.php?action=rename_topic&id=' + id + '&title=' + title;
			
			if (confirm('Are you sure sure SURE you want to proceed?'))
				window.location = url;
			
			return false;	
		}
		
		return confirm('Are you sure sure SURE you want to proceed?');
	});
	
	//$('.article a').attr('target', '_blank');
	
});

function confirma2() {
	return confirm("Are you sure?");	
}

function search_select(tip) {
	$("#search_type").text(tip);
	$("input[name='tip']").val(tip);
}

function confirma () {
	var ok = true;
	$("form input[type='text']").each(function(){ 
		if ($(this).val() == "") {
			ok = false;
		}
	});
	$('form textarea').each(function(){ 
		if ($(this).val() == "") {
			ok = false;
		}
	});
	if ($("form select").val() == "---") {
		ok = false;
	}
	if (ok) {
		return true;
	} else {
		if(confirm("You didn't fill in all the text boxes. Continue anyway?")) {
			return true;
		} else {
			return false;
		}
	}
}

/* An InfoBox is like an info window, but it displays
 * under the marker, opens quicker, and has flexible styling.
 * @param {GLatLng} latlng Point to place bar at
 * @param {Map} map The map on which to display this InfoBox.
 * @param {Object} opts Passes configuration options - content,
 *   offsetVertical, offsetHorizontal, className, height, width
 */
function InfoBox(opts) {
  google.maps.OverlayView.call(this);
  this.latlng_ = opts.latlng;
  this.map_ = opts.map;
  this.content_ = opts.content;
  
  $("#dummy").html(this.content_);

  this.offsetHorizontal_ = -125;
  this.width_ = 250;
  this.offsetVertical_ = -65-$("#dummy").height();
  this.height_ = $("#dummy").height();
 
  var me = this;
  this.boundsChangedListener_ =
    google.maps.event.addListener(this.map_, "bounds_changed", function() {
      return me.panMap.apply(me);
    });
 
  // Once the properties of this OverlayView are initialized, set its map so
  // that we can display it.  This will trigger calls to panes_changed and
  // draw.
  this.setMap(this.map_);
}
 
/* InfoBox extends GOverlay class from the Google Maps API
 */
InfoBox.prototype = new google.maps.OverlayView();
 
/* Creates the DIV representing this InfoBox
 */
InfoBox.prototype.remove = function() {
  if (this.div_) {
    this.div_.parentNode.removeChild(this.div_);
    this.div_ = null;
  }
};
 
/* Redraw the Bar based on the current projection and zoom level
 */
InfoBox.prototype.draw = function() {
  // Creates the element if it doesn't exist already.
  this.createElement();
  if (!this.div_) return;
 
  // Calculate the DIV coordinates of two opposite corners of our bounds to
  // get the size and position of our Bar
  var pixPosition = this.getProjection().fromLatLngToDivPixel(this.latlng_);
  if (!pixPosition) return;
 
  // Now position our DIV based on the DIV coordinates of our bounds
  
  this.div_.style.left = (pixPosition.x + this.offsetHorizontal_) + "px";
  this.div_.style.top = (pixPosition.y + this.offsetVertical_) + "px";
  $("#map_balloon").fadeIn("fast");
};
 
/* Creates the DIV representing this InfoBox in the floatPane.  If the panes
 * object, retrieved by calling getPanes, is null, remove the element from the
 * DOM.  If the div exists, but its parent is not the floatPane, move the div
 * to the new pane.
 * Called from within draw.  Alternatively, this can be called specifically on
 * a panes_changed event.
 */
InfoBox.prototype.createElement = function() {
  var panes = this.getPanes();
  var div = this.div_;
  if (!div) {
    // This does not handle changing panes.  You can set the map to be null and
    // then reset the map to move the div.
    div = this.div_ = document.createElement("div");
	div.innerHTML = '<div class="baloon_top"></div><div id="map_balloon_content" class="baloon_middle" style="text-decoration: none; color: #FFFFFF;">' + this.content_ +  '</div><div class="baloon_bottom"></div>';
	div.className = "hover";
	div.id = "map_balloon";
	
	var topDiv = document.createElement("div");
    topDiv.style.position = "absolute";
	topDiv.style.right = "0";
	topDiv.style.top = "0";
    var closeImg = document.createElement("img");
    closeImg.style.width = "32px";
    closeImg.style.height = "32px";
    closeImg.style.cursor = "pointer";
    closeImg.src = "/imagini/map_close_infowindow.png";
    topDiv.appendChild(closeImg);
	
	function removeInfoBox(ib) {
      return function() {
        ib.setMap(null);
      };
    }
 
    google.maps.event.addDomListener(closeImg, 'click', removeInfoBox(this));
	
	div.appendChild(topDiv);
    panes.floatPane.appendChild(div);
    this.panMap();
  } else if (div.parentNode != panes.floatPane) {
    // The panes have changed.  Move the div.
    div.parentNode.removeChild(div);
    panes.floatPane.appendChild(div);
  } else {

    // The panes have not changed, so no need to create or move the div.
  }
}
 
/* Pan the map to fit the InfoBox.
 */
InfoBox.prototype.panMap = function() {
  // if we go beyond map, pan map
  var map = this.map_;
  var bounds = map.getBounds();
  if (!bounds) return;
 
  // The position of the infowindow
  var position = this.latlng_;
 
  // The dimension of the infowindow
  var iwWidth = this.width_;
  var iwHeight = this.height_;
 
  // The offset position of the infowindow
  var iwOffsetX = this.offsetHorizontal_;
  var iwOffsetY = this.offsetVertical_;
 
  // Padding on the infowindow
  var padX = 20;
  var padY = 20;
 
  // The degrees per pixel
  var mapDiv = map.getDiv();
  var mapWidth = mapDiv.offsetWidth;
  var mapHeight = mapDiv.offsetHeight;
  var boundsSpan = bounds.toSpan();
  var longSpan = boundsSpan.lng();
  var latSpan = boundsSpan.lat();
  var degPixelX = longSpan / mapWidth;
  var degPixelY = latSpan / mapHeight;
 
  // The bounds of the map
  var mapWestLng = bounds.getSouthWest().lng();
  var mapEastLng = bounds.getNorthEast().lng();
  var mapNorthLat = bounds.getNorthEast().lat();
  var mapSouthLat = bounds.getSouthWest().lat();
 
  // The bounds of the infowindow
  var iwWestLng = position.lng() + (iwOffsetX - padX) * degPixelX;
  var iwEastLng = position.lng() + (iwOffsetX + iwWidth + padX) * degPixelX;
  var iwNorthLat = position.lat() - (iwOffsetY - padY) * degPixelY;
  var iwSouthLat = position.lat() - (iwOffsetY + iwHeight + padY) * degPixelY;
 
  // calculate center shift
  var shiftLng =
      (iwWestLng < mapWestLng ? mapWestLng - iwWestLng : 0) +
      (iwEastLng > mapEastLng ? mapEastLng - iwEastLng : 0);
  var shiftLat =
      (iwNorthLat > mapNorthLat ? mapNorthLat - iwNorthLat : 0) +
      (iwSouthLat < mapSouthLat ? mapSouthLat - iwSouthLat : 0);
 
  // The center of the map
  var center = map.getCenter();
 
  // The new map center
  var centerX = center.lng() - shiftLng;
  var centerY = center.lat() - shiftLat;
 
  // center the map to the new shifted center
  map.setCenter(new google.maps.LatLng(centerY, centerX));
 
  // Remove the listener after panning is complete.
  google.maps.event.removeListener(this.boundsChangedListener_);
  this.boundsChangedListener_ = null;
};


var infoBox;
var marker_pos;
var total_markers = 0;
var markers = [];

function initialize(mode) {
	mode = (typeof mode == 'undefined') ? 1 : mode;
	
	total_markers = 0;
	
	geocoder = new google.maps.Geocoder();
	var latlng = new google.maps.LatLng(45.4332, 25.0913);
	var myOptions = {
		zoom: 6,
		center: latlng,
		//controls------
		mapTypeControl: false,
		//sau true
		//mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
		navigationControl: true,
		navigationControlOptions: {
			style: google.maps.NavigationControlStyle.SMALL,
			position: google.maps.ControlPosition.TOP_RIGHT
		},
		//--------------
		mapTypeId: google.maps.MapTypeId.TERRAIN
	};
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	
	if (mode == 1) {
		
		$("#map_sections").show();
		$("#map_options_bar").hide();
		
		loadFeed('guides');
	
	} else if (mode == 2) {
		
		$("#map_sections").hide();
		$("#map_options_bar").show();
		
		google.maps.event.addListener(map, 'click', function (event) {
			select_loc(event.latLng);
		});
		
	}
	
}

function select_loc(pozitie) {
	var image = new google.maps.MarkerImage('/imagini/blue_flag.png', new google.maps.Size(32, 32), new google.maps.Point(0, 0), new google.maps.Point(9, 30));
	if (marker_pos) {
		marker_pos.setPosition(pozitie);
		marker_pos.setMap(map);
	} else {
		marker_pos = new google.maps.Marker({
			map: map,
			draggable: true,
			icon: image,
			position: pozitie,
			zIndex: 10000
		});
	}
}

function placeMarker(location, nume, continut, tip) {
	var image;
	switch (tip) {
		case "guides":
			image = new google.maps.MarkerImage('/imagini/map_icon_guides.png', new google.maps.Size(24, 24), new google.maps.Point(0, 0), new google.maps.Point(12, 12));
			break;
		case "photos":
			image = new google.maps.MarkerImage('/imagini/map_icon_photos.png', new google.maps.Size(24, 24), new google.maps.Point(0, 0), new google.maps.Point(12, 12));
			break;
		default:
			image = new google.maps.MarkerImage('/imagini/map_icon_articles.png', new google.maps.Size(24, 24), new google.maps.Point(0, 0), new google.maps.Point(12, 12));
			break;
	}

	var marker = new google.maps.Marker({
		position: location,
		icon: image,
		title: nume,
		map: map,
		zIndex: 1000
	});

	markers[total_markers] = marker;
	total_markers++;

	google.maps.event.addListener(marker, "click", function () {
			if (infoBox) infoBox.setMap(null);
			infoBox = new InfoBox({latlng: marker.getPosition(), map: map, content: continut});
	});
}

function loadFeed(feed) {
	for (i=0; i<total_markers; i++) {
		markers[i].setMap(null);
	}
	total_markers = 0;
	
	$.get("/comunitate/get_feed.php?feed="+feed, function (data) {
		var data = eval( "(" + data + ")" );
		for (var i in data) {
			//alert(data[i].nume);
			var location = new google.maps.LatLng(data[i].lat, data[i].lng);
			placeMarker(location, data[i].nume, data[i].content, feed);
		}
	});
}
