var currentGirlId = 0;

$("document").ready(function() {
jQuery.ajaxSettings.traditional = true;
  $('#arhivalinks').change(function(){

         dates = $(this).val().split('/');
         window.open( "http://apps."+jsSite+".ro/fata-zilei/previous.asp?Month="+dates[0]+"&Year="+dates[1] );                       
  });

	//set default search words
	$('#newSearchWord').val(defaultSearchWord);
	$('.videoSearchWord').val(defaultVideoSearchWord);
	
	//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() != "") {
			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();
	});
});



//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="
				});
				
				 if (parseInt(videoId) == 1) videoId = 40260;
              
				//create rating control
				$("form.Rating").rating();
				$(".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 (only if videoId is set)
				if(videoId != '' && videoId != null && typeof videoId != "undefined") {
				flowplayer("Player", 
					{
						// our Flash component
						//src: flowPlayerUrl,
						src: videoLink,
						// 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: videoThumbnailUrlPrefix + videoId + ".jpg",
								scaling: 'orig' 
							}, 
							 
							// second clip is a video. when autoPlay is set to false the splash screen will be shown 
							{ 
								url: videoUrlPrefix + videoId + ".flv",
								autoPlay: false,  
								 
								// video will be buffered when splash screen is visible 
								autoBuffering: false  
							} 
						],
						key: flowPlayerKey
					}
				);
	}
	
				//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;				
		if (toHeight > 0) {
			toHeight += "px";
			$("#large-image").animate({ 
				height: toHeight
			  }, 500 );
		}
	}, 20 );
}
