showmap = false; //only for vienna template

var currentGirlId = 0;
var videoPlaceholder = '<a id="VideoPortalLink" href="' + videoPortalUrl + '"></a>';

$(document).ready(function() {
	//set default search words
	$('#newSearchWord').val(defaultSearchWord);
	$('.videoSearchWord').val(defaultVideoSearchWord);
	
	//load video placeholder and attach it to DOM
	$('#Player').append(videoPlaceholder);
	
	//initialize girls showroom
	//if page is called via girlId parameter then take that, else take first girl of in girls list below
	var girlId = (typeof $('#GirlId').val() != 'undefined') ? $('#GirlId').val() : $('.Girl').eq(0).attr('id').replace('girl-','');
	
	//load girl into showroom and set height of first image as callback
	updateGirlsShowroom(girlId, function() { 
		//set girls showroom height to height of first image
		setContainerHeight();
	});
	

	//initialize slider
	//attach SliderToolTip to DOM
	$('.SliderContainer').append('<div id="SliderToolTip"></div>');
	
	//calculate slider values
	var StartYear = 2008;
	var EndYear = (new Date()).getFullYear();
	var CurrentMonth = (new Date()).getMonth(); //(returns month from 0-11)
	var YearDifference = EndYear-StartYear;

	//calculate month since start date to last month
	var Months = (YearDifference*12) + CurrentMonth;
	
	Min = 0;
	Step = 30;
	Max = 30 * Months;
	Value = Max;
	
	//create month array
	MonthMapping = [];

	for (var i = 0; i <= Months; i++) {
		var DateBase = new Date(StartYear,0,1,0,0,0);
		//need last day of i-times month
		//begin of next month: November search goes from beginning of timeslider to 30.11.2009 23:59:59 (1259621999)
		var NewDate = new Date(DateBase.setMonth(i+1)); //next month
		NewDate = new Date(NewDate.setSeconds(-1)); //minus one minute
		
		MonthMapping.push({
			value:parseInt(i*Step), //i-times step length
			timestamp:NewDate.getTime()/1000, //UNIX timestamp
			description:monthNames[NewDate.getMonth()] + " " + NewDate.getFullYear()
		});
	}
	
	//initialize timespan slider with following parameters	
	$("#TimespanSlider").slider({
		min: Min,
		max: Max,
		step: Step,
		value: Value, //ein schieber
		slide: function(event, ui) {
			//update description and position (attach it to mouse cursor) of slider tooltip
			$("#SliderToolTip").html(MonthMapping[ui.value/Step].description).css("left",parseInt(ui.handle.offsetLeft-60)+"px");
			//update hidden field with unix timestamp
			$("#searchTimespan").val(MonthMapping[ui.value/Step].timestamp);
		},
		start: function(event, ui) { $("#SliderToolTip").fadeIn("slow"); },
		stop: function(event, ui) { $("#SliderToolTip").fadeOut("slow"); $("#SearchButton").click(); }
	});
	
	
	//append to timespan-slider parent for each year a label
	YearCount = 0;
	for (var j = new Date(StartYear,0,1,0,0,0).getFullYear(); j <= new Date().getFullYear(); j++) {
		PosLeft = (YearCount == 0) ? "0px" : (($('#TimespanSlider').width()/Months) * YearCount * 12) + "px";
		
		$('.SliderContainer').append("<span style='left:" + PosLeft + ";'>" + j + "</span>");
		YearCount++;
	}

	//render BestRated box
	var BestRated = new MostViewedBox("BestRated", 250);
	BestRated.Render();

	
	//HANDLERS
	//click on search button starts new search, fetches rendered content and loads the first girl in showroom
	$("#SearchButton").live("click", function() {
		//check if element exists (customfield location)
		if ($("#CategorySelect").val() != "" && typeof $("#CategorySelect").val() != "undefined") {
			if ($("#location").length == 0) {
				$("#params").append('<input name="cf[location]" id="location" type="hidden"/>');
			}
			$('#location').val($("#CategorySelect").val());
		}
		else {
			$('#location').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 (toTimestamp value)
		if ($("#searchTimespan").val() != "") {
			if ($("#toTimestamp").length == 0) {
				$("#params").append('<input name="toTimestamp" id="toTimestamp" type="hidden"/>');
			}
			$("#toTimestamp").val($("#searchTimespan").val());
		}
		else {
			$('#toTimestamp').remove();
		}
		
		//remove these fields to prevent wrong results
		$('#currentPage').remove();
		$('#maxPages').remove();
		$('#count').remove();
		$('#startIndex').val(0);
		
		searchGirls(function() { $.scrollTo('#GirlsOfCurrentMonthContainer', 800); });
		
		return false;
	});
	//click on paging starts new search, fetches rendered content and loads the first girl in showroom
	$(".Paging a").live("click", function() {
		$("#startIndex").val($(this).attr("rel"));	
		searchGirls(function() { $.scrollTo('#GirlsOfCurrentMonthContainer', 800); });
		return false;
	});
	
	//click on a girl opens it in showroom
	$("a.GirlLink").live("click", function() {
		//var girlId = $(this).parent().attr('id').replace('girl-','');
		
		var girlId = $(this).closest(".Girl, span[id^='girl-']").attr("id").replace('girl-','');
		
		//fallback (especially for MostViewedBox)
		if (typeof girlId == "undefined" || girlId == "") {
			var girlId = $(this).parent().next("span[id^='girl-']").attr("id").replace('girl-','');
		}
		
		
		blockColumn();
		
		updateGirlsShowroom(girlId, function() { unblockColumn(); $.scrollTo('.WrapInfo', 800); });
		$.scrollTo('.WrapInfo', 800);
		
		return false;
	});
	//click on a month fires a search
	$("a[id^='search-']").live("click", function() {
		var searchString = $(this).attr('id').replace('search-','');
		var girlId = $(this).closest(".Girl").attr("id").replace('girl-','')
		
		var searchTimespan = searchString.split("-");
		var fTimestamp = searchTimespan[0];
		var tTimestamp = searchTimespan[1];	

		if ($("#fromTimestamp").length == 0) {
			$("#params").append('<input name="fromTimestamp" id="fromTimestamp" type="hidden"/>');
		}
		$("#fromTimestamp").val(fTimestamp);
		
		if ($("#toTimestamp").length == 0) {
			$("#params").append('<input name="toTimestamp" id="toTimestamp" type="hidden"/>');
		}
		$("#toTimestamp").val(tTimestamp);	
		
		//remove these fields to prevent wrong results
		$('#currentPage').remove();
		$('#maxPages').remove();
		$('#count').remove();
		$('#location').remove();
		$("#searchWord").remove();
		$("#startIndex").val(0);
		
		
		//fire search and load preferred girl
		searchGirls(function () {
			$.scrollTo('#GirlsOfCurrentMonthContainer', 800);
		}, girlId);
	
		
		return false;
	});
	
	//video search
	$("#VideoSearchButton").bind("click", function() {
		if ($(".videoSearchWord").val() != defaultVideoSearchWord)
			$("#videoSearch").submit();
		else
			$(".videoSearchWord").val("").focus();
	});
	
	//search fields
	$("#newSearchWord, .videoSearchWord").bind("click", function() {
		if ($(this).val() == defaultSearchWord || $(this).val() == defaultVideoSearchWord) {
			$(this).val("");
		}
	});
	$("#newSearchWord").bind("blur", function() {
		if ($(this).val() == "") {
			$(this).val(defaultSearchWord);
		}
	});
	$(".videoSearchWord").bind("blur", function() {
		if ($(this).val() == "") {
			$(this).val(defaultVideoSearchWord);
		}
	});
	
	
	//submit on enter
	$("#newSearchWord, .videoSearchWord").keyup(function(event){
	  if(event.keyCode == 13){
		$(this).next().click(); //is always div where clickhandler is attached to
	  }
	});

	$("#CategorySelect").change(function(event){
		$("#SearchButton").click();
	});
	
	
	//rating
	$("a.RatingLink").live("click", function() {
		var rateGirlId = $('#itemId').val();
		var authToken = $('#authToken').val();
		var result = null;
		
		if (!$(this).hasClass("Rated")) {
			url = ratingUrl.replace("##girlId##", rateGirlId).replace("##rateInt##", 5).replace("##authToken##", authToken);	
			$.ajax({
				'async': false,
				'global': false,
				'url': url,
				'success': function (data) {
					result = data.split("\n");
				},
				'error': function() {
					$(this).removeClass("rated")
				}
			});

			if (result != null && result.length > 0) {
				var itemId = result[0];
				$('#itemId').val(itemId);
				//console.log("itemId: " + itemId);
				var rating = result[1];
				$('#rating').val(rating);
				//console.log("rating: " + rating);
				var votes = result[2];
				$('#votes').val(votes);
				//console.log("votes: " + votes);
				var userRating = result[3];
				$('#userRating').val(userRating);
				//console.log("userRating: " + userRating);
				var galleryAuthToken = result[4];
				$('#galleryAuthToken').val(galleryAuthToken);
				//console.log("galleryAuthToken: " + galleryAuthToken);
								
				updateRatingText();
			}
		}
		return false;
	});
});



//helper functions
function updateGirlsShowroom(girlId, f) {
	//check, if girl is already displayed, otherwise load it into showroom
	if (currentGirlId != girlId) {
		$.ajax({
			type: "GET",
			url: girlsShowroomUrl + "/" + girlId,
			success: function(rdata) {
				$("#GirlOfTheDay").empty().html(rdata);
				
				//create gallery
				$("#gallery-wrapper").gallery({
					numberOfThumbnails: defaultNumberOfThumbnails,
					imageWidth: defaultWidth,
					imageHeight: defaultHeight,
					imageResizerUrl: imageResizerUrl + "/?maxh=" + defaultHeight + "&maxw=" + defaultWidth + "&url="
				});
				
				//create rating control (stars rating)
				//$("form.Rating").rating();
				updateRatingText();
				
				//rounded corners
				$(".RatingContainer, .Fields").corner("5px");
				
				//attach function to onclick event to resize gallery container
				$("a.next, a.prev, span.next, span.prev, a[class^=t]").each(function() {
					if ($.browser.msie)
						this.attachEvent("onclick",function(event) { setContainerHeight(); },false);
					else
						this.addEventListener("click",function(event) { setContainerHeight(); },false);
				});
				
				
				//exectue callback function
				if (typeof f == "function") f();
				
				//initialize video player respectively load new video (but only if videoId is set or if a url to a video is fetched from alternative rss feed)
				if((videoId != '' && videoId != null && typeof videoId != "undefined") || (typeof rssVideo != "undefined" && rssVideo.videoUrl != '' && rssVideo.videoUrl != null)) {
					$('#Player').empty();
					
					urlvideo = (videoId != '') ? videoUrlPrefix + videoId + ".flv" : rssVideo.videoUrl;
					urlimage = (videoId != '') ? videoThumbnailUrlPrefix + videoId + ".jpg" : (rssVideo.imageUrl).replace("?version=","");
					
					flowplayer("Player", 
						{
							// our Flash component
							src: flowPlayerUrl,
							
							// we need at least this version
							version: [9, 115],

							// older versions will see a custom message
							onFail: function()  {
								document.getElementById("Player").innerHTML =
									"Updaten Sie bitte Ihren Flash Player auf die aktuellste Version (Ihre Version ist " + this.getVersion() + ")";
							}
						},
						{ // here is our third argument which is the Flowplayer configuration
							// here is our playlist with two clips 
							playlist: [ 
							 
								// this first clip works as a splash image 
								{ 
									url: urlimage,
									scaling: 'orig'
								}, 
								 
								// second clip is a video. when autoPlay is set to false the splash screen will be shown 
								{ 
									url: urlvideo,
									autoPlay: false,  
									
									autoBuffering: false  
								} 
							],
							key: flowPlayerKey
						}
					);
				}
				else { //remove video player to prevent displaying the wrong video
					$('#Player').empty().html(videoPlaceholder);
				}
				
				//let column appear	
				showColumn();
				
				//remember id of current girl to avoid loading the same girl second time
				currentGirlId = girlId;
			},
			error: function() {
				//display error message
				$("#GirlOfTheDay").empty().append('<div class="GalleryNotFound">' + galleryNotFoundErrorMessage + '</div>');
				//let column appear
				showColumn();
			}
		 });
	}
	else {
		//let column appear
		showColumn();
		unblockColumn();
	}
}

function searchGirls(f, loadGirlId) {
	blockColumn();		
	
	searchParams = $('#params input').serialize();
	$.post(searchUrl, searchParams,
		function(data) {			
			$("#GirlsOfCurrentMonthContainer").fadeTo("fast",0).remove();
			$(".inner").append(data);
			
			unblockColumn();
			
			var firstItem = $('#GirlsOfCurrentMonthContainer .Girl').eq(0);
			var firstId = (firstItem.length > 0) ? firstItem.attr('id').replace('girl-','') : 0;
			
			if (loadGirlId > 0)
				firstId = loadGirlId;
			
			if (firstId > 0) {
				updateGirlsShowroom(firstId);
			}
			else {
				showColumn();
				unblockColumn();
			}
			
		}
	);
	
	//exectue callback function
	if (typeof f == "function") f();
	
	$.scrollTo('#GirlsOfCurrentMonthContainer', 800)
}


function blockColumn() {
	$('.inner').block({
		message: null,
		overlayCSS:  {  
			opacity: '0.5',
			backgroundColor: '#ffffff'
		}
	});
}
function unblockColumn() {
	$('.inner').unblock();
}

function showColumn() {
    //let the two containers appear
	window.setTimeout(function() {
		$('#gallery-wrapper, #GirlsOfCurrentMonthContainer').css("visibility","visible");
	}, 25 );
}

function setContainerHeight() {
	window.setTimeout(function() {
		toHeight = images[parseInt($('.current-pos').text())-1].imageHeight;
		//alert("current pos: " + parseInt($('.current-pos').text()-1) + "\ncurrent height: " + images[parseInt($('.current-pos').text()-1)].imageHeight);
		
		if (toHeight > 0) {
			toHeight += "px";
			$("#large-image").animate({ 
				height: toHeight
			  }, 500 );
		}
	}, 20 );
}

function updateRatingText() {
	numVotes = $("#votes").val();
	
	oldVotes = $(".Rating > span.Count").text();
	newVotes = (numVotes.indexOf(" ") > -1) ? numVotes.substring(0, numVotes.indexOf(" ")) : numVotes; //"2 Stimmen" => "2"
	
	if (oldVotes != newVotes && oldVotes != '') {
		//switch button
		$("a.RatingLink").addClass("Rated");
	}
	
	//adapt rating text (singular/plural)
	personstext = (newVotes == 1) ? ratingText["singular"] : personstext = ratingText["plural"];
	
	//increase count
	$(".Rating > span.Count").text(newVotes);
	$(".Rating > span.Text").html(" " + personstext + " " + ratingText["additionalText"]);
}

function setPageValues(map) {
	videoId = map.videoId;
	document.title = document.title.replace(/(.*)(.*)?- (.*) - (.*)/,  map.title + " - $3 - $4");
	$("#TabsNavigation li.Active span").text(map.title);
}