/*
 * Global JS for Globalista
*/

$(document).ready(function() {
	/* Manually adding first and last class. */
	$("li:first-child").addClass('first');
	$("li:last-child").addClass('last');

	/* Clearing default input value on click and blur */
	var inputValue = $("input#form_globalSearch").val();
	$("input#form_globalSearch").click(function() {
		$("input#form_globalSearch").attr("value", "");
	});
	$("input#form_globalSearch").blur(function() {
		if ($("input#form_globalSearch").val() == ("")) {
			$("input#form_globalSearch").attr("value", inputValue);
		}
	});

    $('.keywords dd:last-child').css({background: 'none'}); // Fixes issue with trailing comma on keyword list

	$("input.btn").click(function() {
		if ($(".searchResults").is(":hidden")) {
			$(".searchResults").fadeIn("fast");
		}
		else {
			$(".searchResults").hide();
		}
	});
    $('.resultsPager').change(function(){
        runSearch($(this).val());
        return false;
    });
});

displayLogin = function(redirectUrl, itineraryLabel, itineraryId)
 {	
	if(redirectUrl != '')
	{
		$('input.redirectUrl').val(redirectUrl);
	}
    
	if(itineraryLabel)
	{
        $('.login .extra_info').hide();
        $('.login .top h3').remove();
        $('.login .top').prepend('<h3>In order to view this report you must be a member - or you can:</h3>');
        $('.login #login_report .highlight span').html(itineraryLabel);
        $('.login #login_report').show();
		//$('span#itineraryLabel').val(itineraryLabel);
	}
    else
    {
        $('.login .extra_info').hide();
        $('.login .top h3').remove();
        $('.login .top').prepend('<h3>Sign in to Globalista</h3>');
		$('.login #login_register').show();
    }	

    // replace href for join in modal so that if join occurs, it's preselected specified itinerary
	if(itineraryId)
	{
		$('.modalJoinLink').attr('href', '/join/p/itineraryId/'+itineraryId);
	}

    if(itineraryLabel)
	{
        tb_show(null,"#TB_inline?height=390&width=638&inlineId=itineraryModal&modal=true",null);
    }
    else
    {
        $('#password_form_main').hide();
        $('#login_form_main').show();
        $('#loginContainer h3').remove();
        $('#loginContainer .top').prepend('<h3>Sign in to Globalista</h3>');
        tb_show(null,"#TB_inline?height=390&width=638&inlineId=loginModal&modal=true",null);
    }

    replaceWithSIFR();

	return false;
 }
 
 setValue = function(ElementId, DefaultValue) {
 	if($('#'+ElementId) && '' == $('#'+ElementId).value) {
 		$('#'+ElementId).value = DefaultValue;
 	}
 };
 
 clearValue = function(ElementId, DefaultValue) {
 	if($('#'+ElementId) && DefaultValue == $('#'+ElementId).value) {
 		$('#'+ElementId).value = '';
 	}
 };
 
 resetPager = function() {
 	if($('#form_resultsPagerTop')) {
 		//$('#form_resultsPagerTop').val(1);
 	}
 };
 
 resetSearchType = function() {
 	if($('#search_type')) {
 		$('#search_type').val('site');
 	}
 };
 
 
 var SearchTimer;
 
startSearch = function() {
	if(SearchTimer) {
		clearTimeout(SearchTimer);
	}
	SearchTimer = setTimeout('runSearch(1)', 1000); 

};

doDateSearch = function(NewDate, obj) {
    $('#globalistaCalendar td a').css('font-weight', 'normal');
    $('#globalistaCalendar td a').css('color', '#FFFFFF');
	if($('#event-date')) {
		$('#event-date').val(NewDate);
	}
    $(obj).css('font-weight', 'bold');
    $(obj).css('color', '#3BABE5');
	return runSearch(1);
}

runSearch = function(Page) {
	//show loader
	if($('.preloader')) {
		$('.preloader').show();
	}
	$('#keyword').val($('#keyword').val().replace('/', ' ')); 
	var Data = $("#global_search_form").serialize();

	if(!Page) {
		Page = 1;
	}

	$.ajax({
	    url: '/search/p/ajax/1/lastajax/1/page/'+Page,
	    type: 'post',
	    data: Data,
	    timeout: 50000,
	    dataType: 'json',
	    error: function(){
	    	//todo - rethink
	    },
	    success: handleSearchResults
	});
	return false;

};
updateContent = function(Url) {
    //show loader
	if($('.preloader')) {
		$('.preloader').show();
	}
    $.ajax({
	    url: Url,
	    timeout: 50000,
	    dataType: 'json',
	    error: function(){
	    	//todo - rethink
	    },
	    success: handleSearchResults
	});
	return false;
};
handleSearchResults = function(data) {
	    	if(data.Status && 'ok' == data.Status) {
	    		if($('.preloader')) {
					$('.preloader').hide();
				}
				if(data.Results) {
					drawResults(data.Results);
				}
				if($('.search_pagination') && data.Pagination) {
					var Collection = $('.search_pagination');
                    Collection.each(function(i, elem) {
                        $(elem).html('');
                        $(elem).html(data.Pagination);
                        if (0 == i) {
                            var SelectElement = $(elem).find('select');
                            SelectElement.attr('name', 'page1');
                        }

                    });
					//$('.search_pagination').html(data.Pagination);
                    $('.resultsPager').change(function(){
                        runSearch($(this).val());
                        return false;
                    });
				}

				//only update filters if global
				var Container = '';
				if($('#search-result-container') && $('#search-result-container').val()) {
					Container = $('#search-result-container').val();
				}
				if('' == Container) {
					if($('#search_filters') && data.Filters) {
						$('#search_filters').html('');
						$('#search_filters').html(data.Filters);
					}
				}
	    	}
	    }

drawResults = function(ResultCollection) {
	//remove previous results.
	if($('#search_results')) {
		$('#search_results').html('');
		//check if any
		if(0 == ResultCollection.length) {
			var Item = document.createElement('li');
			Item.setAttribute('class','error');
			Item.innerHTML = '<p>Sorry, no results were found</p>';
			document.getElementById('search_results').appendChild(Item);
		} else {
			
			//figure out how 
			var Container = '';
			if($('#search-result-container') && $('#search-result-container').val()) {
				Container = $('#search-result-container').val();
			}
			for(var i = 0; i < ResultCollection.length; i++) {
				//create Li
				var Item = document.createElement('li');
				switch(Container) {
					case 'destination':
						var ItemHtml = '<h3>';
						ItemHtml += '<a href="'+ResultCollection[i].url+'" title="'+ResultCollection[i].title+'">'+ResultCollection[i].title+'</a></h3>';
						break;
					case 'event':
						var ItemHtml = '<a class="load-map" href="/search/p/action/map/maptype/global/maplayers/Events" onclick="return showMap(\'global\', \'Events\', \'\', \''+ResultCollection[i].content_id+'\');" title="Map this Event">Map This Event</a>'; 
						ItemHtml += '<h3><span class="date">'+ResultCollection[i].date_label+'</span> <strong>'+ResultCollection[i].title+'</strong> - '+ResultCollection[i].meta_keywords+'</h3>';
               			ItemHtml += '<dl class="keywords">';
						ItemHtml +=	'<dt>Keywords:</dt>';
						ItemHtml += ResultCollection[i].tags_split;
						ItemHtml += '</dl>';
                		ItemHtml += '<a href="http://'+ResultCollection[i].meta_description+'" target="_blank" rel="follow" class="link external">'+ResultCollection[i].meta_description+'</a>';
						break;
					default:
						var ItemHtml = '<h3>';
						ItemHtml += '<a href="'+ResultCollection[i].url+'" title="'+ResultCollection[i].title+'">'+ResultCollection[i].title+'</a></h3>';
						if('' != ResultCollection[i].content) {
							if(150 < ResultCollection[i].content.length) {
								ItemHtml +=	'<p>'+ResultCollection[i].content.substr(0, 150) +'...</p>';
							} else {
								ItemHtml +=	'<p>'+ResultCollection[i].content+'</p>';
							}
						}
						ItemHtml +=	'<dl class="keywords">';
						ItemHtml +=	'<dt>Keywords:</dt>';
						ItemHtml += ResultCollection[i].tags_split;
						ItemHtml += '</dl>';
						break;
				}
				Item.innerHTML = ItemHtml;
				document.getElementById('search_results').appendChild(Item);
				//add to list
			}
		}
	}
}

showMap = function(Type, SelectedLayers, LimitIds, ShowId) {
	//show container
	//$("#map-overlay").show();
    
	var MapParams = new Object();
	MapParams.type = Type;
	if(ShowId && '' != ShowId) {
		MapParams.showId = ShowId;
	}
    if(SelectedLayers && '' !== SelectedLayers) {
        MapParams.selectedLayers = SelectedLayers;
	}
    if(LimitIds && '' !== LimitIds) {
        MapParams.limitToIds = LimitIds;
    }

	loadMap('map', MapParams);
	
	// Remove scroll bar in browsers other than ie6 (which thickbox does!!!)
	// IE7 does not play game
	if(!$.browser.msie)
		$("body").css({"overflow":"hidden", "padding-right":"15px"});
	
  tb_show(null,"#TB_inline?height=530&width=860&inlineId=dynamicMapContainer&modal=true",null);
  $('#TB_window').css('margin-top', '-265px');

	return false;
}

hideMap = function() {
	
	tb_remove();
	
	// Show scroll bar again
	if(!$.browser.msie) {
		setTimeout(function(){
				$("body").css({"overflow":"","padding-right":""});
		},500);
	}
	
	//$('#map').html('');
	return false;
}

showForgottenPassword = function() {
	tb_remove();

	setTimeout(
				function () {
					tb_show(null,"#TB_inline?height=280&amp;width=570&amp;inlineId=hiddenModalContent_ForgottenPassword&amp;modal=true",null);
					replaceWithSIFR();
				},
				500);

	return false;
}

showEmailThisReport = function() {
	tb_show(null,"#TB_inline?height=370&amp;width=760&amp;inlineId=hiddenModalContent_EmailReport&amp;modal=true",null);
	replaceWithSIFR();
	return false;
}