var localPostPath = localPostPath || false;

FC.vars = {
	selectors : {
		ACTION_PANEL : '.action-panel',
		ANCHOR_HTML : '<a href="#"></a>',
		POSTS : '.posts',
		POSTS_LI : '.posts li',
		MAP_CONTENT : '.map-content',
                MISSION_MAP_CONTENT: '.mission-map-content',
		CONTROLS_LI : '.controls li',
		PAUSE_LABEL : '.pause-label',
		PLAY_LABEL : '.play-label',
		PAUSE : '.pause',
		REWIND : '.rewind',
		LI_FIRST_CHILD_DIV : 'li:first-child > div',
		LI_FIRST_CHILD : 'li:first-child',
		VOICE : 'voice',
		TEXTAREA : '#addVoice textarea',
		COUNTER : '#counter',
                MAP_COUNTRY : '#country_map_canvas'
	},
        missionMap : {
                MARKERS : [],
                MARKERS_VISITED : [],
		ROUTE : [],
		ROUTE_VISITED : []
	},
	times :{
		PLAY_LENGTH : 60000,
		VOICE_LENGTH : 4000
	},
	strings : {
		LIMIT_REACHED : 'limit',
		CLOSED : 'closed',
		H2 : 'h2'
	},
	paths : {
		CLEAR_GIF : 'images/clear.gif',
		POSTS_PATH : localPostPath || 'xml/feed.xml'
	},
	state : {
		IE_ACTION_PANEL_MAX_Z_INDEX : 1
	}
};

var interval, timeout;

FC.voice_action_panels = function(){
	var __panels = $(FC.vars.selectors.ACTION_PANEL);
	
	__panels.each(function(){
		var __$ths = $(this), __heading, __show;
		__$ths.addClass(FC.vars.strings.CLOSED);
		__heading = __$ths.find(FC.vars.strings.H2);
		__show = $(FC.vars.selectors.ANCHOR_HTML);
		__show.append(__heading.text());
		__show.toggle(
			function(){
				__$ths.removeClass(FC.vars.strings.CLOSED);
				__$ths.parent().css('z-index', (FC.vars.state.IE_ACTION_PANEL_MAX_Z_INDEX + 1).toString());
				FC.vars.state.IE_ACTION_PANEL_MAX_Z_INDEX++;
			},
			function(){/* IE-specific fix */
				__$ths.addClass(FC.vars.strings.CLOSED);
				__$ths.parent().css('z-index', '0');
				FC.vars.state.IE_ACTION_PANEL_MAX_Z_INDEX--;
			}
		);
		
		__heading.empty();
		__heading.append(__show);
	});
}

FC.initPostAnimation = function () {
	var __$postsLi = $(FC.vars.selectors.POSTS_LI), _inc = Number(0), _isRunning = true, _isEnd = false, _isClicked = false;
	var __id = __$postsLi[0].id || (function(){__$postsLi[0].id='fc';return false})();
	
	var __paddingTop = "padding-top";
	var __paddingBottom = "padding-bottom";
	
	if(FC.hasIE){
		__paddingTop = "paddingTop";
		__paddingBottom = "paddingBottom";	
	}
	
	var	__cssObjOut = {
			paddingTop : FC.getStyle(__$postsLi[0].id, __paddingTop),
			paddingBottom : FC.getStyle(__$postsLi[0].id, __paddingBottom),
			marginTop : 0
		},
		__cssObjCollapse = {
			paddingTop : 0,
			paddingBottom : 0,
			marginTop : -1
		},
		__opacOn = {opacity:1},
		__opacOff = {opacity:0};
	
	__$postsLi[0].id = __id || null;	

	var _animateNewPost = function () {
		if (_inc == FC.vars.masterArray.length - 1) {
			_isEnd = true;
			clearInterval(interval);
		} else {
			_isEnd = false;
		}

		if (!FC.hasIE) {
			$(FC.vars.selectors.POSTS)
				.prepend(FC.vars.masterArray[_inc])
				.find(FC.vars.selectors.LI_FIRST_CHILD)
					.slideDown(0)
					.animate(__opacOn, 0)
					.animate(__cssObjCollapse, 0)
					.animate(__cssObjCollapse, 400)
					.animate(__cssObjOut, 400)
				.end()
				.find(FC.vars.selectors.LI_FIRST_CHILD_DIV)
					.slideUp(0)
					.animate(__opacOff, 0)
					.animate(__opacOff, 400)
					.slideDown(400)
					.animate(__opacOn, 400);
		} else {
			$(FC.vars.selectors.POSTS)
				.prepend(FC.vars.masterArray[_inc])
				.find(FC.vars.selectors.LI_FIRST_CHILD)
					.slideDown(0)
					.animate(__cssObjCollapse, 0, function () {								
						$(this).animate(__cssObjCollapse, 400, function () {
							$(this).animate(__cssObjOut, 400)
						})									  				  
					})

				.end()
				.find(FC.vars.selectors.LI_FIRST_CHILD_DIV)
					.slideUp(0,function(){
							
							

							//if(this.className=="text"){
								var _height = $(this).height()	
								_height=_height+20;
								$(this).animate({'height':0},0)
								.slideDown(400)
								.animate({'height':_height}, 400)			
							//}									  

										
					})
					
		}
		_inc++;
	};
	
	var _stopAnimation = function () {
		clearInterval(interval);
	};
	
	var _startAnimation = function () {
		clearInterval(interval);
		_animateNewPost();
		if (!_isEnd) {
			interval = setInterval(_animateNewPost, FC.vars.times.VOICE_LENGTH);
		}
	};
	
	var _animateExistingVoices = function () {
		var _saveInitialPosts = function () {
			var __i = __$postsLi.length, __arr = [];
			while (__i--) {
				__arr[__i] = __$postsLi[__i].cloneNode(true);
			}
			$(FC.vars.selectors.POSTS).empty();
			__arr.reverse();
			FC.vars.masterArray = (!FC.vars.masterArray) ? __arr : FC.vars.masterArray.concat(__arr);
			
		};
	
		var _setControlHandlers = function () {
			$(FC.vars.selectors.REWIND).bind('click', function(e){
				if (_inc > 1) {
					$(FC.vars.selectors.POSTS).find(FC.vars.selectors.LI_FIRST_CHILD)
						.slideUp(0)
						.animate(__opacOff, 0)
						.animate(__cssObjCollapse, 0, function () {
							$(this).remove();
							_inc = _inc-1;
							if (_isRunning) {
								clearTimeout(timeout);
								clearInterval(interval); //TH : added the clearinterval as it's reintiated in _startAnimation.
								timeout = setTimeout (_startAnimation, FC.vars.times.VOICE_LENGTH);
							}	
						});
				}
				return false;
			});
			
			$(FC.vars.selectors.PAUSE).bind('click', function(e){
				if (_isRunning) {
					_isRunning = false;
					if (!_isEnd) {
						_stopAnimation();
					}
					_isClicked = true;
					this.style.backgroundPosition = '0 -539px';
					$(FC.vars.selectors.PAUSE_LABEL, this)[0].style.display = 'none';
					$(FC.vars.selectors.PLAY_LABEL, this)[0].style.display = 'inline';
				} else {
					_isRunning = true;
					if (!_isEnd){
						_startAnimation();
					}
					_isClicked = false;
					this.style.backgroundPosition = '0 -215px';
					$(FC.vars.selectors.PLAY_LABEL, this)[0].style.display = 'none';
					$(FC.vars.selectors.PAUSE_LABEL, this)[0].style.display = 'inline';
				}
				return false;
			});
		};
		
		_saveInitialPosts();
		_setControlHandlers();
		_startAnimation();
	};
	
	var _callAjaxAndConstructHTML = function () {
		var _constructHTML = function (arr) {
			var __i = arr.length, __loopArr, __masterArr = [], __tmp, __tagArr, __tags, __tagLength, __tmpArr;
			
			while (__i--) {
				__loopArr = [], __o = {vo:'', vc:'', no:'',nc:'',fo:'',fc:'',to:'',tc:'',s:'s'};
				__loopArr.push('<li class="' + arr[__i].c + ' clear">\n');
					if (arr[__i].i) {
						__loopArr.push('\t<div class="image"><a href="/'+ arr[__i].vl+'"><img src="'+ arr[__i].i +'" alt="'+ arr[__i].ia +'" width="'+ arr[__i].iw +'" height="'+ arr[__i].ih +'" /></a></div>\n')
					}
					__loopArr.push('\t<div class="text">\n');
						__loopArr.push('\t\t<blockquote>\n');
							if (arr[__i].vl) {
								__o.vo = '<a href="'+ arr[__i].vl +'">';
								__o.vc = '</a>';
							}
							__loopArr.push('\t\t\t<p>'+__o.vo + arr[__i].v + __o.vc +'</p>\n');
						__loopArr.push('\t\t</blockquote>\n');
						if (arr[__i].nl) {
							__o.no = '<a href="'+ arr[__i].nl +'">';
							__o.nc = '</a>';
						}
						if (arr[__i].fl) {
							__o.fo = '<a href="'+ arr[__i].fl +'">';
							__o.fc = '</a>';
						}
						__loopArr.push('\t\t<p><cite>'+ __o.no + arr[__i].n + __o.nc +', '+ __o.fo + arr[__i].f + __o.fc +'</cite> via '+ arr[__i].o +', Tag: '+ __o.to + arr[__i].t + __o.tc +'</p>\n');
						if (arr[__i].r == '1') {
							__o.s = '';
						}
						__loopArr.push('\t\t<a href="'+ arr[__i].nl +'#comments">('+ arr[__i].r +' comment' + __o.s + ')</a> | ' + arr[__i].st + ' | '+ arr[__i].al + '\n');
					__loopArr.push('\t</div>\n');
				__loopArr.push('</li>\n');
				
				__masterArr.push(__loopArr.join(''));
			}
			
			__masterArr.reverse();
			FC.vars.masterArray = (!FC.vars.masterArray) ? __masterArr : FC.vars.masterArray.concat(__masterArr);
		};
		
		var _parseXML = function ($xml) {
			var __arr = [], __tmp, __attrs, __attr, __attrLength, __xmlLength, 
				__loopArr, __masterArr = [];
			
			_arrLength = __xmlLength = $xml.length;
			while (__xmlLength--) {
				__tmp = __arr[__xmlLength] = {};
				__attrs = $xml[__xmlLength].attributes;
				
				__attrLength = __attrs.length;
				while (__attrLength--) {
					__attr = __attrs[__attrLength];
					__tmp[__attr.nodeName] = __attr.nodeValue;
				}
			}
			
			return __arr;
		}
		
		$.ajax({ 
			url: FC.vars.paths.POSTS_PATH,
			cache: false,
			dataType : 'xml',
			error : function (XMLHttpRequest, textStatus, errorThrown) {
				  // typically only one of textStatus or errorThrown 
				  // will have info
				  // alert('ajax '+textStatus); // the options for this ajax request
			},
			success: function(xml){
				var __arr, __html;
				__arr = _parseXML($(FC.vars.selectors.VOICE, xml));
				_constructHTML(__arr);
				if (_isEnd && _isRunning) {
					_isEnd = false;
					if(!_isClicked){
						_startAnimation();
					}
				}
			}
		});
	}
	
	_animateExistingVoices();
	setInterval(_callAjaxAndConstructHTML, FC.vars.times.PLAY_LENGTH);
}

FC.countCharacters = function () {
	var _$textarea = $(FC.vars.selectors.TEXTAREA);
	_$textarea.before('<div id="counter" class=""></div>');
	var _$counter = $(FC.vars.selectors.COUNTER), _max = Number(250), _loadLength;
	var _textarea = _$textarea[0];
	
	_loadLength = (_textarea.value.length) ? _max - _textarea.value.length : _max;
	if (_loadLength == 0) {
		_$counter.addClass(FC.vars.strings.LIMIT_REACHED);
	}
	_$counter.text(_loadLength);
	
	var _textCalc = function (e) {		
		var __length = _textarea.value.length;
		
		if (e.keyCode != 46 && e.keyCode != 8) {
			if (__length >= _max) { // if too long...trim it!
				_$counter.addClass(FC.vars.strings.LIMIT_REACHED);
				_textarea.value = _textarea.value.substring(0, _max);
				_$counter.text(_max - __length);
				return false
			}else {
				_$counter.removeClass(FC.vars.strings.LIMIT_REACHED);
				_$counter.text(_max - __length);
			}
		} else {
			_$counter.removeClass(FC.vars.strings.LIMIT_REACHED);
			_$counter.text(_max - __length);
		}
	};
	
	_$textarea
		.bind('keydown', _textCalc)
		.bind('keyup', _textCalc)
		.bind('change', _textCalc);
};

FC.map_country = function() {
    //Setup and run map
    function setupMap(){
        if (GBrowserIsCompatible()) {
            //Setup map 
            map = new GMap2(document.getElementById("country_map_canvas"));
            map.setCenter(new GLatLng(25, 0), 2);
            map.setMapType(G_SATELLITE_MAP);
            map.addControl(new GLargeMapControl());
            mgr = new MarkerManager(map, {trackMarkers:true});			
        }	
    }
    setupMap();
}

//Google Map
FC.map = function(){
	
	
	function CreateIcon(length){
		
		var icon = new GIcon();
		icon.image = 'images/marker.gif';
		
		icon.iconSize = new GSize(20, 18);
		
		icon.iconAnchor = new GPoint(16, 16);
		icon.infoWindowAnchor = new GPoint(25, 0);
		return icon
	}

	//Markers array
	var countryMarkers = [
	  {
		"zoom": [0, 3],
		"places": []
	  },
	  
	   {
		"zoom": [4, 12],
		"places": []
	  }
	  
	];


	var __voices = new Array();
	var allmarkers = [];
	var __data = $(".data");
	var __countries = $(".data .country");
		
	var __remove = false;
	var __tags = $("#tags a");
	var __theme ="";
	var mgr;
	var map;
		
		
	//Setup and run map
	function setupMap(){
		if (GBrowserIsCompatible()) {
			//Setup map 
			map = new GMap2(document.getElementById("map_canvas"));
			map.setCenter(new GLatLng(25, 0), 2);
			map.setMapType(G_SATELLITE_MAP);
			map.addControl(new GLargeMapControl());
        	mgr = new MarkerManager(map, {trackMarkers:true});			
		}	
	}
	setupMap();
	
	
	//Build an array of objects of all the voices
	function buildVoices(__theme){
		
		
		//Build an array of objects for all the countries

		for(i=0;i<__countries.length;i++){
			
			
			//Get co-ordinates
			var __latlong = $(__countries[i]).find("h2").attr("rel").split(",");
			var __lat = __latlong[0];
			var __long = __latlong[1];
			var __content = $(__countries[i]).find(".top-voice").clone();
			var __icon = $(__countries[i]).find("h2").text();
			__icon = __icon.toLowerCase();
			
		
			__voices[i] = new Object();
			__voices[i].zoom = $(__countries[i]).attr("rel");
			__voices[i].name = $(__countries[i]).find("h2").text();
			__voices[i].icon = __icon;
			__voices[i].countryLength = $(__countries[i]).find("h2").attr("class");
			__voices[i].amount = $(__countries[i]).find(".total").attr("rel");
			__voices[i].posn = [__lat,__long];
			__voices[i].content = __content[0];
			__voices[i].tag = $(__countries[i]).find(".tag").attr("rel");
			
			
			
			if(__theme!=""){
			
				if(__theme==__voices[i].tag){
				
					//Push this object into the array of places for deep zoom levels
					countryMarkers[1].places.push(__voices[i]);
					
					//If this is an object to be viewed at the high zoom level, then push into the high level array as well
					if(__voices[i].zoom==0){
						countryMarkers[0].places.push(__voices[i]);
					}
					
					setupMarkers();
				
				}
			
			}
			else{
				
				//Push this object into the array of places for deep zoom levels
				countryMarkers[1].places.push(__voices[i]);
				
				//If this is an object to be viewed at the high zoom level, then push into the high level array as well
				if(__voices[i].zoom==0){
					countryMarkers[0].places.push(__voices[i]);
				}
				
				
			}
			
			
			
	
		}

		
		
	}
	buildVoices(__theme);
	
	
	
	//Set the theme	
	__tags.bind("click",function(){
		
		//Remove existing markers
		clearMarkers();
		

		//Find selected theme
		__theme = $(this).attr("rel");
		
		//Select link
		__tags.parents("h3").removeClass("highlighted");
		$(this).parents("h3").addClass("highlighted");
		
		//Add selected themed markers
		buildVoices(__theme);
		
		return false;
		
	});
	
	
	
	
	//Custom markers
	/*function Icon(country, length){
		var customIcon = new GIcon();
		customIcon.image = "images/marker.gif";
		customIcon.shadow = "images/marker-shadow.png";
		//If it's a long name - then put in the longer width otherwise put in the standard
		if(length=="long"){customIcon.iconSize = new GSize(75, 18);}
		else{customIcon.iconSize = new GSize(50, 18);}
		
		if(length=="long"){customIcon.shadowSize = new GSize(78, 21);}
		else{customIcon.shadowSize = new GSize(53, 21);}
		
		customIcon.iconAnchor = new GPoint(5, 34);
		customIcon.infoWindowAnchor = new GPoint(25, 2);
		customIcon.infoShadowAnchor = new GPoint(14, 25);
		customIcon.transparent = "images/marker-"+country+".gif";
		customIcon.printImage = "images/marker-"+country+".gif";
		customIcon.mozPrintImage = "images/marker-"+country+".gif";	
		
		return customIcon;
	}*/


	
	function setupMarkers() {

		allmarkers.length = 0;
		
		for (var i in countryMarkers) {
			var layer = countryMarkers[i];
			var markers = [];
			for (var j in layer["places"]) {
				var place = layer["places"][j];
				//var icon = Icon(place["icon"],place["countryLength"]);
				var title = place["name"];
				var posn = new GLatLng(place["posn"][0], place["posn"][1]);
				var cont = place["content"];
				var length = place["countryLength"];
				var amount = place["amount"];
				var marker = createMarker(posn,title,cont,length,amount);
				
				markers.push(marker);
				allmarkers.push(marker);
			}
		mgr.addMarkers(markers, layer["zoom"][0], layer["zoom"][1]);
		}
		mgr.refresh();
	}
	setupMarkers();
	
	
	
	function createMarker(posn, title, cont, length, amount) {
		
		var __icon = new CreateIcon(length);
		
		var __class ="";
		//Pick right class for amount of voices
		if(amount>100){__class="markerLabel100";}
		if(amount>250){__class="markerLabel250";}
		if(amount>500){__class="markerLabel500";}
		if(amount>750){__class="markerLabel750";}
		
		
		var __opts = {
			"icon": __icon,
			"clickable": true,
			"labelText": title,
			"labelClass": __class,
			"labelOffset": new GSize(-16, -16)
		};
		
		var marker = new LabeledMarker(posn, __opts);
		GEvent.addListener(marker, 'click', function() { marker.openInfoWindowHtml(cont)}); 
		return marker;
    }
	
    function deleteMarker() {
		var markerNum = parseInt(document.getElementById("markerNum").value);
		mgr.removeMarker(allmarkers[markerNum]);
    }
   
    function clearMarkers() {
		mgr.clearMarkers();
		countryMarkers[0].places = new Array();
		countryMarkers[1].places = new Array();
    }
   
    function reloadMarkers() {
		setupOfficeMarkers();
    }	
}




//Google Mission Map
FC.mission_map = function() {
	
	$.fn.reverse = [].reverse;

    function CreateIcon(visited) {

        var icon = new GIcon();
		
	visited ? icon.image = '/images/map-marker-visited.png' : icon.image = '/images/map-marker.png';

        icon.iconSize = new GSize(13, 13);

        icon.iconAnchor = new GPoint(7, 7);
        icon.infoWindowAnchor = new GPoint(7, 7);
        return icon
    }

    //Markers array
    var countryMarkers = [
		{
		  "zoom": [0, 4],
		  "places": []
		},

		{
		   "zoom": [5, 12],
		   "places": []
		}

	];


    var __voices = new Array();
    var allmarkers = [];
    var __data = $(".data");
    var __countries = $(".data .mission"); //.reverse();

    var __remove = false;
    var __tags = $("#tags a");
    var __theme = "";
    var mgr;
    var map;


    //Setup and run map
    function setupMap() {
        if (GBrowserIsCompatible()) {
            //Setup map 
            map = new GMap2(document.getElementById("map_canvas"));
            map.setCenter(new GLatLng(25, 0), 2);
            map.setMapType(G_HYBRID_MAP);
            map.addControl(new GLargeMapControl());
            mgr = new MarkerManager(map, { trackMarkers: true });
        }
    }
    setupMap();


    //Build an array of objects of all the voices
    function buildVoices(__theme) {


        //Build an array of objects for all the countries

        for (i = 0; i < __countries.length; i++) {


            //Get co-ordinates
            var __latlong = $(__countries[i]).find(".location").attr("rel").split(",");
            var __lat = __latlong[0];
            var __long = __latlong[1];
            var __content = $(__countries[i]).find(".mission-content").clone();
            var __icon = $(__countries[i]).find(".location").text();
            __icon = __icon.toLowerCase();


            __voices[i] = new Object();
            __voices[i].zoom = $(__countries[i]).attr("rel");
            __voices[i].name = $(__countries[i]).find(".day").text() + ' <strong>' +  $(__countries[i]).find(".location").text() + '</strong>';
            __voices[i].icon = __icon;
            __voices[i].countryLength = $(__countries[i]).find(".location").attr("class");
            __voices[i].amount = $(__countries[i]).find(".total").attr("rel");
            __voices[i].posn = [__lat, __long];
            __voices[i].content = __content[0];
            __voices[i].tag = $(__countries[i]).find(".tag").attr("rel");
			__voices[i].visited = $(__countries[i]).find(".mission-content").attr('rel') == 'visited' ? true : false;


            if (__theme != "") {

                if (__theme == __voices[i].tag) {
					
                    //Push this object into the array of places for deep zoom levels
                    countryMarkers[1].places.push(__voices[i]);

                    //If this is an object to be viewed at the high zoom level, then push into the high level array as well
                    if (__voices[i].zoom == 0) {
                        countryMarkers[0].places.push(__voices[i]);
                    }

                    setupMarkers();

                }

            }
            else {

                //Push this object into the array of places for deep zoom levels
                countryMarkers[1].places.push(__voices[i]);

                //If this is an object to be viewed at the high zoom level, then push into the high level array as well
                if (__voices[i].zoom == 0) {
                    countryMarkers[0].places.push(__voices[i]);
                }


            }




        }



    }
   
    buildVoices(__theme);



    //Set the theme	
    __tags.bind("click", function() {

        //Remove existing markers
        clearMarkers();


        //Find selected theme
        __theme = $(this).attr("rel");

        //Select link
        __tags.parents("h3").removeClass("highlighted");
        $(this).parents("h3").addClass("highlighted");

        //Add selected themed markers
        buildVoices(__theme);

        return false;

    });




    //Custom markers
    /*function Icon(country, length){
    var customIcon = new GIcon();
    customIcon.image = "images/marker.gif";
    customIcon.shadow = "images/marker-shadow.png";
    //If it's a long name - then put in the longer width otherwise put in the standard
    if(length=="long"){customIcon.iconSize = new GSize(75, 18);}
    else{customIcon.iconSize = new GSize(50, 18);}
		
		if(length=="long"){customIcon.shadowSize = new GSize(78, 21);}
    else{customIcon.shadowSize = new GSize(53, 21);}
		
		customIcon.iconAnchor = new GPoint(5, 34);
    customIcon.infoWindowAnchor = new GPoint(25, 2);
    customIcon.infoShadowAnchor = new GPoint(14, 25);
    customIcon.transparent = "images/marker-"+country+".gif";
    customIcon.printImage = "images/marker-"+country+".gif";
    customIcon.mozPrintImage = "images/marker-"+country+".gif";	
		
		return customIcon;
    }*/



    function setupMarkers() {
		
		var bounds = new GLatLngBounds();
		
        allmarkers.length = 0;
		
        for (var i in countryMarkers) {
            var layer = countryMarkers[i];
            for (var j in layer["places"]) {
				var place = layer["places"][j];
				//var icon = Icon(place["icon"],place["countryLength"]);
				var title = place["name"];
				var posn = new GLatLng(place["posn"][0], place["posn"][1]);
				var cont = place["content"];
				var length = place["countryLength"];
				var visited = place["visited"];
				var amount = place["amount"];
				var marker = createMarker(posn, title, cont, visited, amount);
				
				bounds.extend(marker.getLatLng());
				FC.vars.missionMap.ROUTE.push(posn);
				if (visited) FC.vars.missionMap.ROUTE_VISITED.push(posn);
				visited ? FC.vars.missionMap.MARKERS_VISITED.push(marker) : FC.vars.missionMap.MARKERS.push(marker);
				
			}
			var polyline = new GPolyline(FC.vars.missionMap.ROUTE, "#FFFF00", 4, 0.6);
			var polylineVisited = new GPolyline(FC.vars.missionMap.ROUTE_VISITED, "#FFFF00", 4, 1);
			map.addOverlay(polyline);
			map.addOverlay(polylineVisited);
			mgr.addMarkers(FC.vars.missionMap.MARKERS_VISITED, layer["zoom"][0], layer["zoom"][1]);
			mgr.addMarkers(FC.vars.missionMap.MARKERS, layer["zoom"][0], layer["zoom"][1]);
        }
        mgr.refresh();
		map.setCenter(bounds.getCenter());
		map.setZoom(map.getBoundsZoomLevel(bounds));
    }
    setupMarkers();

    function createMarker(posn, title, cont, visited, amount) {

        var __icon = new CreateIcon(visited);
        var __class = "markerLabelDark";

        var __opts = {
            "icon": __icon,
            "clickable": false
        };
		
		var __optsVisited = {
            "icon": __icon,
            "clickable": true,
            "labelText": title,
            "labelClass": __class,
            "labelOffset": new GSize(-40, -32)
        };
		
		if(visited){
			var marker = new LabeledMarker(posn, __optsVisited);
        	GEvent.addListener(marker, 'click', function() {
				offsetMap = function(){
					var latLng = marker.getLatLng();
					var south = map.getBounds().getSouthWest().lat();
					var north = map.getBounds().getNorthEast().lat();
					var offset = (north - south)/3;
					//console.log(offset);
					var newLatLng = new GLatLng(latLng.lat() + offset, latLng.lng());
					map.panTo(newLatLng);
				}
				prevClick = function(){
					$('.prevClick').bind('click', function(){
                                                map.closeInfoWindow();
						var index = $(this).attr('rel');
                                                GEvent.trigger(FC.vars.missionMap.MARKERS_VISITED[index], "click");
						$(this).unbind('click');
						return false;
					})
				}
                                nextClick = function(){
					$('.nextClick').bind('click', function(){
                                                map.closeInfoWindow();
						var index = $(this).attr('rel');
                                                GEvent.trigger(FC.vars.missionMap.MARKERS_VISITED[index], "click");
						$(this).unbind('click');
						return false;
					})
				}
				map.openInfoWindowHtml(posn, cont, {onOpenFn:function(){offsetMap();prevClick();nextClick();}});
			});
		} else {
			var marker = new GMarker(posn, __opts);
		}
        
        return marker;
    }
	
	

    function deleteMarker() {
        var markerNum = parseInt(document.getElementById("markerNum").value);
        mgr.removeMarker(allmarkers[markerNum]);
    }

    function clearMarkers() {
        mgr.clearMarkers();
        countryMarkers[0].places = new Array();
        countryMarkers[1].places = new Array();
    }

    function reloadMarkers() {
        setupOfficeMarkers();
    }
}


$(function(){
	FC.setJS();
	FC.pngFix(FC.vars.paths.CLEAR_GIF);
	FC.flickerFix();
	if($(FC.vars.selectors.ACTION_PANEL).length)FC.voice_action_panels();
	if($(FC.vars.selectors.POSTS).length)FC.initPostAnimation();
	if($(FC.vars.selectors.MAP_CONTENT).length)FC.map();
	if($(FC.vars.selectors.MISSION_MAP_CONTENT).length) FC.mission_map();
        if($(FC.vars.selectors.TEXTAREA).length)FC.countCharacters();
        if($(FC.vars.selectors.MAP_COUNTRY).length)FC.map_country();
});
