showmap = false; //only for vienna template

$("document").ready(function() {
	//set default search words
	$('#newSearchWord').val(defaultSearchWord);
	defaultTabName = $('#TabsNavigation li.Active span').text(); //configurable in config.php, store it in config for now
	
	var livecamId = (typeof $('#LivecamId').val() != 'undefined') ? $('#LivecamId').val() : 0;
	
	//PRELOADER
	//load predefined livecam on page load if one is set
	if (livecamId != 0) 
		displayLivecam(livecamId);
	
	//LIVECAM MAP
	//initialize livecam map
	livecamMap.init();
	//load markers (iterate through grid and fetch lat/lon)
	livecamMap.update();
	//call function to prevent memory leaks
	window.onunload = unloadMap;
	
	//BOXES
	//render BestRated box
	var BestRated = new MostViewedBox("BestRated", 250);
	BestRated.Render();
	//round corners of NewCameraBox
	$("#NewCameraBox").corner("5px");
	
	//DISPLAY GRID
	refreshSearchResultHeadline();
	showColumn();
	
	//SLIDER
	//attach SliderToolTip to DOM
	$('.SliderContainer').append('<div id="SliderToolTip"></div>');
	
	$("#AltitudeSlider").slider({
		min: altitudeSliderMin,
		max: altitudeSliderMax,
		step: 50,
		values: [altitudeSliderMin,altitudeSliderMax], //ein schieber
		range:true,
		slide: function(event, ui) {
			//update description and position (attach it to mouse cursor) of slider tooltip
			$("#SliderToolTip").html(ui.value + "m").css("left",parseInt(ui.handle.offsetLeft-20)+"px");
			//update hidden field with altitude range
			//$("#searchAltitudeFrom").val(ui.values[0]);
			//$("#searchAltitudeTo").val(ui.values[1]);
			$("#searchAltitude").val(ui.values[0] + ";" + ui.values[1]);
		},
		start: function(event, ui) { $("#SliderToolTip").fadeIn("slow"); },
		stop: function(event, ui) { $("#SliderToolTip").fadeOut("slow"); $("#SearchButton").click(); }
	});
	//append to altitude-slider parent some labels
	for (var i = altitudeSliderMin; i <= altitudeSliderMax; i++) {
		if (i%1000==0 || i==0) {
			PosLeft = (($('#AltitudeSlider').width()/altitudeSliderMax) * i);
			$('.SliderContainer').append("<span style='left:" + PosLeft + "px;'>" + i + "</span>");
		}
	}
	
	//HANDLERS
	//click on search button starts new search and fetches rendered content
	$("#SearchButton").live("click", function() {
		//check if element exists (customfield location)
		if ($("#TownSelect").val() != "" && typeof $("#TownSelect").val() != "undefined" && $("#TownSelect").val() != "-1") {
			if ($("#location").length == 0) {
				$("#params").append('<input name="cf[location]" id="location" type="hidden"/>');
			}
			$('#location').val($("#TownSelect").val());
		}
		else {
			$('#location').remove();
		}
		
		//check if element exists (customfield livecamcategory)
		if ($("#CategorySelect").val() != "" && typeof $("#CategorySelect").val() != "undefined" && $("#CategorySelect").val() != "-1") {
			if ($("#livecamCategory").length == 0) {
				$("#params").append('<input name="cf[livecamCategory]" id="livecamCategory" type="hidden"/>');
			}
			$('#livecamCategory').val($("#CategorySelect").val());
		}
		else {
			$('#livecamCategory').remove();
		}
		
		//check if element exists (searchword)
		if ($("#newSearchWord").val() != defaultSearchWord && $("#newSearchWord").val() != "") {
			if ($("#searchWord").length == 0) {
				$("#params").append('<input name="searchWord" id="searchWord" type="hidden"/>');
			}
			$("#searchWord").val($("#newSearchWord").val());
		}
		else {
			$("#searchWord").remove();
		}
		
		//check if element exists (altitude value)
		if ($("#searchAltitude").val() != "") {
			if ($("#altitude").length == 0) {
				$("#params").append('<input name="cf[altitude]" id="altitude" type="hidden"/>');
			}
			$("#altitude").val($("#searchAltitude").val());
		}
		else {
			$('#altitude').remove();
		}
		
		
		//rename tab if location is set
		if ($('#location').val() != "" && typeof $('#location').val() != "undefined") {
			$('#TabsNavigation li.Active span').text(defaultTabName + defaultTabNamePrefix + $('#location').val())
		}
		else {
			$('#TabsNavigation li.Active span').text(defaultTabName)
		}
		
		//remove these fields to prevent wrong results
		$('#currentPage').remove();
		$('#maxPages').remove();
		$('#count').remove();
		$('#startIndex').val(0);
		
		searchLivecams(function() { $.scrollTo('#LivecamsContainer', 800); });
		
		return false;
	});
	//click on paging starts new search and fetches rendered content
	$(".Paging a").live("click", function() {
		$("#startIndex").val($(this).attr("rel"));	
		searchLivecams(function() { 
			$.scrollTo('#LivecamsContainer', 800); 
		});
		return false;
	});
	//click on a livecam opens it in GalleryLightbox
	$("a.LivecamLink").live("click", function() {
		livecamId = getLivecamId($(this));
		
		displayLivecam(livecamId);
		
		this.onclick=function() {return false}; 
		return false;
	});

	
	//search fields
	$("#newSearchWord").bind("click", function() {
		if ($(this).val() == defaultSearchWord) {
			$(this).val("");
		}
	});
	$("#newSearchWord").bind("blur", function() {
		if ($(this).val() == "") {
			$(this).val(defaultSearchWord);
		}
	});
	
	//submit on enter
	$("#newSearchWord").keyup(function(event){
	  if(event.keyCode == 13){
		$(this).next().click(); //is always div where clickhandler is attached to
	  }
	});

	$("#TownSelect").change(function(event){
		$("#SearchButton").click();
	});
	$("#CategorySelect").change(function(event){
		$("#SearchButton").click();
	});
	
	
	//rating
	$("a.RatingLink").live("click", function() {
		var livecamId = getLivecamId($(this));
		var result = null;
		
		url = ratingUrl.replace("##livecamId##", livecamId).replace("##rateInt##", 5).replace("##authToken##", authToken);	
		$.ajax({
			'async': false,
			'global': false,
			'url': url,
			'success': function (data) {
				result = data.split("\n");
			}
		});

		if (result != null && result.length > 0) {
			var itemId = result[0];
			//console.log("itemId: " + itemId);
			var rating = result[1];
			//console.log("rating: " + rating);
			var votes = result[2];
			//console.log("votes: " + votes);
			var userRating = result[3];
			//console.log("userRating: " + userRating);
			var galleryAuthToken = result[4];
			//console.log("galleryAuthToken: " + galleryAuthToken);
			
			oldVotesText = $(this).parent().find("span.RatingCount").text();
			oldVotes = oldVotesText.substring(oldVotesText.indexOf("(")+1, oldVotesText.indexOf(")")-1);
			newVotes = votes.substring(0, votes.indexOf(" ")); //"2 Stimmen" => "2"
			
			message = (oldVotes == newVotes) ? ratingAlreadyDone : ratingSuccess;
			
			//increase count
			$(this).parent().find("span.RatingCount").text("(" + newVotes + ")")
			
			$(this).parent().block({
				message: message,
				overlayCSS:  {  
					opacity: '0.0',
					backgroundColor: '#FFFFFF',
					cursor: 'default'
				},
				CenterX:0,
				css: { 
					border: 'none', 
					padding: '14px', 
					//backgroundColor: '#AECADC', 
					'-webkit-border-radius': '5px', 
					'-moz-border-radius': '5px', 
					opacity: '0.4',
					color: '#ffffff',
					cursor: 'default',
					left: '-12px',
					width: '177px',
					'z-index': '100'
				}
			});
		}
	
		return false;
	});
});


//helper functions
function displayLivecam(livecamId) {
	showGalleryLightbox(livecamUrl + "/" + livecamId, gallerySlideshowSettings);
	
	valueMap={title:''};
	
	//attach function to onclick event when closing GalleryLightbox
	$("#galleryLightboxOverlay, a.close").each(function() {
		if ($.browser.msie)
			this.attachEvent("onclick",function(event) { setPageValues(valueMap) },false);
		else
			this.addEventListener("click",function(event) { setPageValues(valueMap) },false);
	});
}


function searchLivecams(f) {
	blockColumn();		
	
	searchParams = $('#params input').serialize();
	$.post(searchUrl, searchParams,
		function(data) {			
			$("#LivecamsContainer").fadeTo("fast",0).remove();
			$(".inner").append(data);
			
			unblockColumn();
			showColumn();
			
			window.setTimeout(function() {
				livecamMap.update();
		
				refreshSearchResultHeadline();
			}, 100 );		
		}
	);
	
	//exectue callback function
	if (typeof f == "function") f();
	
	$.scrollTo('#LivecamsContainer', 800)
}


function blockColumn() {
	$('.inner').block({
		message: null,
		overlayCSS:  {  
			opacity: '0.5',
			backgroundColor: '#ffffff'
		}
	});
}
function unblockColumn() {
	$('.inner').unblock();
}

function showColumn() {
    //let the container appear
	window.setTimeout(function() {
		$('#LivecamsContainer').css("visibility","visible");
	}, 25 );
}

function getLivecamId(jqueryObject) {
	//check if livecam is a special livecam
	var path = jqueryObject.attr("href");
	var pathComponent = path.substring(path.lastIndexOf("/")+1,path.length);
	
	if(!isNaN(pathComponent) || path == "#") {
		livecamId = jqueryObject.closest(".Livecam, span[id^='livecam-']").attr("id").replace('livecam-','');
	}
	else {
		return pathComponent;
	}

	
	//fallback (especially for MostViewedBox)
	if (typeof livecamId == "undefined" || livecamId == "") {
		var livecamId = jqueryObject.parent().next("span[id^='livecam-']").attr("id").replace('livecam-','');
	}
	
	return livecamId;
}

function refreshSearchResultHeadline() {
	searchHeadlineReplaced = searchHeadline;
	
	if ($("#CategorySelect").val() != '' && $("#CategorySelect").val() != '-1') {
		searchHeadlineReplaced = searchHeadlineReplaced.replace("##livecams##",$("#CategorySelect").val());
	}
	else {
		searchHeadlineReplaced = searchHeadlineReplaced.replace("##livecams##",searchResultDefaultValues[document.domain]["livecams"]);
	}
	
	if ($("#TownSelect").val() != '' && $("#TownSelect").val() != '-1') {
		searchHeadlineReplaced = searchHeadlineReplaced.replace("##preposition##",searchResultDefaultValues[document.domain]["preposition1"]).replace("##location##",$("#TownSelect").val());
	}
	else {
		searchHeadlineReplaced = searchHeadlineReplaced.replace("##preposition##",searchResultDefaultValues[document.domain]["preposition2"]).replace("##location##",searchResultDefaultValues[document.domain]["location"]);
	}
	
	altminmax = $("#searchAltitude").val();
	altminmax = altminmax.split(";");
	if ($("#searchAltitude").val() != '' && (altminmax[0] != altitudeSliderMin || altminmax[1] != altitudeSliderMax)) {
		searchHeadlineReplaced = searchHeadlineReplaced.replace("##between##",searchResultDefaultValues[document.domain]["between"]).replace("##altitudemin##",altminmax[0]).replace("##and##",searchResultDefaultValues[document.domain]["and"]).replace("##altitudemax##",altminmax[1]);
	}
	else {
		searchHeadlineReplaced = searchHeadlineReplaced.substring(0, searchHeadlineReplaced.indexOf("##between##"));
	}
	
	$('#LivecamsContainer h4').text(searchHeadlineReplaced);
}

function setPageValues(map) {
	mapValues = map;
	document.title = document.title.replace(/(.*)(.*)?- (.*) - (.*)/, "$3 - $4");
}

Array.prototype.contains = function (element) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == element) {
			return true;
		}
	}
	return false;
}
Array.prototype.indexInArray = function (element) {
	for(var index in this) {
	  if (index == element) {
		return true;
	  }
	}
	return false;
}
