//create an empty console.log function if firebug is not running to avoid errors.
if(typeof(window.console) == "undefined"){
	window.console = { log:function(){}};
};

LICOR43 = {};
LICOR43.admin = {};

//list of images to pre-load.
LICOR43.imagesToPreload = [

	/*'../images/prehome-agecheck-submit-over.png',

	'../images/basic-content-header.jpg',
	'../images/header-historia-hover.png',
	
	'../images/header-button-facebook.png',
	'../images/header-button-facebook-hover.png',
	'../images/header-button-twitter.png',
	'../images/header-button-twitter-hover.png',
	'../images/header-button-youtube.png',
	'../images/header-button-youtube-hover.png',
	
	'../images/homepage-box1-fondo.jpg',
	'../images/homepage-box2-fondo.jpg',
	'../images/homepage-box3-fondo.jpg',
	'../images/home-newsticker-fondo.jpg',
	'../images/homepage-main-box3-item-bg.png',
	'../images/footer-motif.jpg',
	// '../images/footer-motif-hover.jpg',
	
	'../images/news-ticker-arrow-right.png',
	'../images/news-ticker-arrow-right-over.png',
	'../images/news-ticker-arrow-left.png',
	'../images/news-ticker-arrow-left-over.png',
	
	'../images/basic-content-header.jpg',
	'../images/basic-content-bg.png',
	'../images/basic-content-top.png',
	'../images/basic-content-bottom.png',
	
	'../images/concursos-header.jpg',
	'../images/concursos-fondo.jpg',
	'../images/concursos-destacadas-fondo.jpg',
	'../images/concursos-item-fondo.png',

	'../images/fiestas-header.jpg',
	'../images/busca-fiestas-fondo.jpg',
	'../images/mejores-fiestas.jpg',
	'../images/homepage-main-box3-item-bg.png',
	'../images/fiesta-result-fondo.jpg',
	'../images/fiesta-ficha-fotos-fondo.png',

	'../images/noticias-fondo.jpg',
	'../images/noticias-destacadas-fondo.jpg',
	'../images/news-item-fondo.jpg',

	'../images/cocteles-banners-fondo.jpg',
	'../images/coctel-del-mes-banner.png',
	'../images/cocteles-mouseover.png',
	'../images/cocteles-carousel-arrow-right-hover.png',
	'../images/cocteles-carousel-arrow-right-active.png',
	'../images/cocteles-carousel-arrow-left-hover.png',
	'../images/cocteles-carousel-arrow-left-active.png',

	'../images/coctel-del-mes-header.jpg',
	'../images/coctel-del-mes-selector.jpg',
	'../images/coctel-del-mes-drinks.jpg',

	'../images/tv-header.jpg',
	'../images/tv-column-fondo.jpg',
	
	'../images/sitemap-section-fondo.png'*/
];

if( document.partyDays !== undefined) {
	LICOR43.partyNights = document.partyDays;
}

$( document).ready( function(){

	//console.log( $("#age-check-layer").size() );
	if( $("#age-check-layer").size() > 0) {
		//we got the age picker, hide the page content just in case:
		//console.log('hide wrapper');
		$("#wrapper").hide();
	}


	$("#prehome-homelink").remove();
	$("#ageCheckSubmitButton").attr('href', '#');
	$("#ageCheckSubmitButton").click( function() {
		
		if( LICOR43.isOldEnough() ) {
			LICOR43.dropAgeVerifiedCookie();
			//document.location.href = '/home?acbp=' + LICOR43.age_check_bypass_token;
			//document.location.href = document.location.href;
			window.location.reload();	//but this time with the cookie set, so we shouldn't see the age selector
			//$('#age-check-layer').slideUp();
			
		} else {
			LICOR43.openDialog( 'Verificador de Edad', 'Debes ser mayor de 18 años para acceder');
		}
		return false;
	});
	//$("#page.prehome").fadeIn();

	/*$("#busca-fiesta-button").click( function() {
		$("#fiesta-filter-form").submit();
		return false;
	});
	$("#fiesta-filter-form").ajaxForm( {
		beforeSubmit:function( formData, jqForm, options) {
			//need to grab the selected date from the datepicker:
			//console.log( $("#datepicker").datepicker( "getDate") );
			return true;
		},
		success:function( responseText, statusText, xhr, $form) {
			$("#fiesta-results").empty().hide().append( responseText).fadeIn();
		}
	});*/

	$("#datepicker").datepicker({
		dateFormat: 'dd-mm-yy',
		beforeShowDay: function(date){
			return LICOR43.isAPartyDay( date);
		},
		/*onSelect: function( selectedDate, datePicker) {
			//LICOR43.daySelected( selectedDate, datePicker);
		},*/
		beforeShow: function(input, datePicker) {},
		altField:'#fiestas-filter-date'
	});



	// Checks if there are parties to rotate.
	if ($("#mejores-fiestas .fiesta-banner-list-wrapper ul li").size() > 3) {				
		var fiestasDelay = function() {
			var homepageConcursosWidetSelector = '#mejores-fiestas';
			LICOR43.rotateConcursos(homepageConcursosWidetSelector , true);
		};
		var t = setTimeout( fiestasDelay, 10);
	}else {
		$("#mejores-fiestas .fiesta-banner-list-wrapper ul").css('top', 0);
	}
	
	
	// Checks if there are contest to rotate.
	if ($("#homepage-concursos-widget .rotate-square-div .box1-item-list li").size() > 3) {
			
		var homepageConcursosDelay = function() {
			var homepageConcursosWidetSelector = '#homepage-concursos-widget';
					
			LICOR43.rotateConcursos(homepageConcursosWidetSelector, false);		
		};
		var t = setTimeout( homepageConcursosDelay, 10);	
		
	}else {
		$("#homepage-concursos-widget .rotate-square-div .box1-item-list").css('top', 0);		
	}


//	if ( $.isFunction( $.lightBox) ) {
		$("#photo-gallery a").lightBox({fixedNavigation: true, maxWidth: 800, maxHeight: 400});
		$(".photo-gallery a").lightBox({fixedNavigation: true, maxWidth: 800, maxHeight: 400});
		
//	}
	
	$("#agency-fiesta-selector").change( function() {
		LICOR43.admin.fiestaSelected();
	});
//	LICOR43.admin.fiestaSelected();
//	var selectorTimer = setTimeout( 'LICOR43.admin.fiestaSelected()', 3000);

	
	$("#admin-party-manager-selection-form").ajaxForm( {
		beforeSubmit:function( formData, jqForm, options) {
			return true;
		},
		success:function( responseText, statusText, xhr, $form) {
			LICOR43.admin.loadFiestaDetails( responseText);
			LICOR43.admin.fiestaPhotos();
		}
	});	
	
	
	LICOR43.handleMouseOverClicks();
	
	LICOR43.coctelesCarousel();
	
	LICOR43.ageSpinners();
	
	LICOR43.tickerScrollButtons();
	LICOR43.fiestaScrollButtons();
	LICOR43.fiestaFotosScrollButtons();
	LICOR43.concursosDestacadosScrollButtons();
	LICOR43.noticiasDestacadosScrollButtons();
	
	LICOR43.checkTickerScrollButtons( '#news-ticker-mask', '#news-ticker-left-button', '#news-ticker-right-button');
	LICOR43.checkTickerScrollButtons( '#coctel-carousel-mask', '#coctels-spin-left-button', '#coctels-spin-right-button');
	LICOR43.checkTickerScrollButtons( '#photo-carousel-mask', '#fiesta-fotos-left-button', '#fiesta-fotos-right-button');

	LICOR43.checkScrollerButtons( "#concursos-destacadas-list-mask", "#concursos-destacados-scroll-up-button","#concursos-destacados-scroll-down-button");
	LICOR43.checkScrollerButtons( "#noticias-destacadas-list-mask", "#noticias-destacados-scroll-up-button","#noticias-destacados-scroll-down-button");
	LICOR43.checkScrollerButtons( "#box3-list-mask", "#fiestas-scroll-up-button", "#fiestas-scroll-down-button");
	
	LICOR43.urlMessagePopup();
	

	/*
	var fiestaId = $("#agency-fiesta-selector").val();
	var uploadPath = $("#uploadPath").val() + fiestaId;
	alert( uploadPath);
	//var t = setTimeout( LICOR43.admin.addParamsToUploader'uploadPath', uploadPath), 1000);	
	LICOR43.admin.addParamsToUploader( 'uploadPath', uploadPath);	
	*/
	
	LICOR43.imagePreloader();
});


LICOR43.urlMessagePopup = function() {
	
	if(window.location.hash) {
		//Fragment exists, check for specific page messages:
		var fragment = location.href.substr( location.href.indexOf("#") ).substr( 1);
		
		if( 'verificacion-edad' ===  fragment) {
			LICOR43.openDialog( 'Verificador de Edad', 'Debes ser mayor de 18 años para acceder');
		}
	}
	
};

LICOR43.admin.addParamsToUploader = function( attrName, attrValue) {

	if( undefined === document.jumpLoaderApplet) {
		return;
	}

	var uploader = document.jumpLoaderApplet.getUploader();
	var attrSet = uploader.getAttributeSet();
	var attr = attrSet.createStringAttribute( attrName, attrValue);
	attr.setSendToServer( true);
};

LICOR43.dropAgeVerifiedCookie = function() {
	var cookieName = 'licor43-age-verified';
	var value = 'verified';
	//var expiredays = 28;
	var expiredays = null;	//cookie removed when all browser windows are closed.
	var exdate = new Date();
	exdate.setDate( exdate.getDate() + expiredays );
	document.cookie = cookieName + "=" + escape(value) + ((expiredays==null) ? "" : ";expires=" + exdate.toUTCString() );
};

LICOR43.isOldEnough = function() {
	var year = parseInt( $("#year-spinner li.selected").attr('value'), 10);
	var month = parseInt( $("#month-spinner li.selected").attr('value'), 10) - 1;
	var day = parseInt( $("#day-spinner li.selected").attr('value'), 10);

	var ageCheckDate = new Date(year + 18, month, day, 0, 0, 0, 0);
	var dateNow = new Date();
	if( ageCheckDate.getTime() > dateNow.getTime() ) {
		return false;
	}
	return true;
};

LICOR43.admin.loadFiestaDetails = function( fiestaBlockHTML) {
	$("#fiesta-details").empty().append( fiestaBlockHTML);
};

LICOR43.admin.fiestaSelected = function() {
	
	if( $("#agency-fiesta-selector").size() < 1) {
		return false;
	}
	
	var fiestaId = $("#agency-fiesta-selector").val();
	if( '' === fiestaId) {
		alert( 'Selecciona una fiesta');
		return;
	}
	var uploadPath = $("#uploadPath").val() + fiestaId;
	//alert( uploadPath);

	//LICOR43.admin.addParamsToUploader( 'fiestaId', fiestaId);
	LICOR43.admin.addParamsToUploader( 'uploadPath', uploadPath);
	
	//$("#upload-container").show();
};

LICOR43.daySelected = function( selectedDate, datePicker){
	$("#fiestas-filter-date").val( selectedDate);
};

LICOR43.stringToDate = function( dateString) {
	var dateParts = dateString.split('-');
	var newDate = new Date( parseInt( dateParts[2], 10), parseInt( dateParts[1], 10) - 1, parseInt( dateParts[0], 10), 0, 0,0 );
	return newDate;
};

LICOR43.isAPartyDay = function( pickerDate) {
	
	var itsAPartyNight = false;
	
	$.each( LICOR43.partyNights, function( i, partyDateString) {
		
		var partyDate = LICOR43.stringToDate( partyDateString);
		if( LICOR43.daysAreEqual( partyDate, pickerDate) ) {
			itsAPartyNight = true;
			return false;	//return from $.each, not from function
		}
	});
	
	if( itsAPartyNight) {
		return [true,'enabled','Fiesta!'];
	}
	return [false];
};

LICOR43.daysAreEqual = function(date1, date2){
	if( date1.getDate() === date2.getDate() && date1.getMonth() === date2.getMonth() && date1.getFullYear() === date2.getFullYear() ) {
		return true;
	}
	return false;
};

LICOR43.rotateConcursos = function( parentSelector, rotateSquareBanner) {

	if( $( parentSelector + " .rotate-square-div").size() < 1 ) {
		//nothing to rotate:
		return false;
	}	

	// Local variables
	var itemNumber = $( parentSelector + " .rotate-banners-div ul li").length,
			currentItem = 0,
			squareSeparation = 232,
			thumbSeparation = 81,
			animationSpeed = 1000,
			animationEasing = 'swing';			
	
	// Recurrent function to scroll images
	function rotateImages(Selector, rotateBanner){
		
		// If there is a banner to rotate.
		if (rotateBanner) {
			// Gets first element.
			var firstItem = $(Selector + " .rotate-banners-div ul li:first");
			
			$(Selector + " .rotate-banners-div ul li").stop(true,true).animate({
				top: -squareSeparation
			}, animationSpeed, animationEasing, function(){
				$(this).css('top', 0);
				// Remove first and adds it at the end.
				firstItem.remove();
				firstItem.appendTo($(parentSelector + " .rotate-banners-div ul"));
				//firstItem.after($(Selector + " .rotate-banners-div ul li:last"));			
			});
		}
			
		// Gets last element.
		var lastItem = $(Selector + " .rotate-square-div ul li:last");
		
		$(parentSelector + " .rotate-square-div ul").stop(true,true).animate({
				top: 0
			}, animationSpeed, animationEasing, function() {
				$(this).css('top', -thumbSeparation);
				lastItem.remove();
				lastItem.prependTo( $(parentSelector + " .rotate-square-div ul") );
				//lastItem.before($(Selector + " .rotate-square-div ul li:first"));
		});
		
		//LICOR43.handleMouseOverClicks();		
	}
	
	var rotateDelay = function() {
		rotateImages(parentSelector, rotateSquareBanner);
	};	
	setInterval(rotateDelay,4500);

	/*if( $( parentSelector + " .rotate-square-div").size() < 1 ) {
		//nothing to rotate:
		return false;
	}

	var rotateDelay = function() {
		LICOR43.rotateConcursos(parentSelector , rotateSquareBanner);
	};
	var t = setTimeout( rotateDelay, 4500);


	//prepare new banner:
	if (rotateSquareBanner) {
		var newBannerItem = $(parentSelector + " .rotate-banners-div ul li:first").clone();
	} else {
		var newBannerItem = $(parentSelector + " .rotate-square-div ul li:last").clone();
	}
	if( 1 === newBannerItem.size() ) {

		if( rotateSquareBanner) {
			newBannerItem.find('.square-content').hide();
			newBannerItem.find('.banner-content').show();
			var imgSrc = newBannerItem.find( 'img').attr('src');
			//var newImgSrc = imgSrc.replace('.square.', '.thumb.'); 
			var newImgSrc = imgSrc.replace('presets', 'presets/thumbs');
			newBannerItem.find('img').attr('src', newImgSrc);
			newBannerItem.find('div').removeClass('big');
		}
		$(".rotate-square-div ul").css('top', -81);
		newBannerItem.prependTo( $(parentSelector + " .rotate-square-div ul") );
	}

	var newSquareItem = $(parentSelector + " .rotate-square-div ul li:last").clone();
	if( newSquareItem.size() === 1) {
		newSquareItem.find('.square-content').show();
		newSquareItem.find('.banner-content').hide();
		var imgSrc = newSquareItem.find('img').attr('src');
		//var newImgSrc = imgSrc.replace('.thumb.', '.square.');
		var newImgSrc = imgSrc.replace('presets/thumbs','presets');
		newSquareItem.find('img').attr('src', newImgSrc);
		newSquareItem.find('div').addClass('big');
		newSquareItem.appendTo( $(parentSelector + " .rotate-banners-div ul") );
	}

	LICOR43.handleMouseOverClicks();

	if (rotateSquareBanner) {
		$(parentSelector + " .rotate-banners-div ul").animate({
			top: '-=232'
		}, 1000, 'swing', function(){
			$(this).css('top', 0);
			$(this).find('li:first').remove();
		});
	}
	
	$(parentSelector + " .rotate-square-div ul").animate({
			top:'+=81'
		}, 1000, 'swing', function() {
			$( this).find('li:last').remove();
	});*/
	
};

LICOR43.setListWidth = function( list) {
	var itemWidth = list.children('li:first').outerWidth( true);
	var numberOfItems = list.children("li").size();
	var listWidth = itemWidth * numberOfItems;
	list.css('width', listWidth);
};

LICOR43.coctelesCarousel = function() {
	
	LICOR43.coctelesCarouselMoving = false;
	
	//dynamic set ul width:
	LICOR43.setListWidth( $("#coctel-carousel-mask > ul") );
	
	$("#coctels-spin-left-button").click( function() {
		if( LICOR43.coctelesCarouselMoving) {
			return false;
		}
		LICOR43.coctelesCarouselMoving = true;
		$("#coctel-carousel-mask > ul").animate({
				left:'+=180'
			}, 800, 'swing', function() {
				LICOR43.checkTickerScrollButtons( '#coctel-carousel-mask', '#coctels-spin-left-button', '#coctels-spin-right-button');
				LICOR43.coctelesCarouselMoving = false;
		});
	});

	$("#coctels-spin-right-button").click( function() {
		if( LICOR43.coctelesCarouselMoving) {
			return false;
		}
		LICOR43.coctelesCarouselMoving = true;
		$("#coctel-carousel-mask > ul").animate({
				left:'-=180'
			}, 800, 'swing', function() {
				LICOR43.checkTickerScrollButtons( '#coctel-carousel-mask', '#coctels-spin-left-button', '#coctels-spin-right-button');
				LICOR43.coctelesCarouselMoving = false;
		});
	});
	
};

LICOR43.ageSpinners = function() {

	var dayMinValue = 1; 
	var dayMaxValue = 31; 

	var monthMinValue = 1; 
	var monthMaxValue = 12; 

	var yearMinValue = 1900; 
	var yearMaxValue = 2012; 
	
	var spinSpeed = 170;

	var autoSpin = false;
	var isSpinning = false;

	$("#age-select-day-up").click( function() {
		autoSpin = false;
	});
	$("#age-select-day-up").mousedown( function() {
		autoSpin = true;
		ageSelectDayUpSpin();
	});
	$("#age-select-day-up").mouseleave( function() {
		autoSpin = false;
	});
	
	var ageSelectDayUpSpin = function() {
		
		if( isSpinning) { return false; } else { isSpinning = true; }
		
		$("#day-spinner li").removeClass('selected');

		//preprend a new list item:
		var topItemClone = $("#day-spinner li:first").clone();
		var nextValue = parseInt( topItemClone.attr('value'), 10) + 1;
		if( nextValue > dayMaxValue) {
			nextValue = dayMinValue;	//rotate
		}
		topItemClone.attr( 'value', nextValue); 
		topItemClone.html( LICOR43.pad( nextValue, 2) + '.' ); 
		
		$("#day-spinner").prepend( topItemClone);
		$("#day-spinner").css('top', -19);
		$("#day-spinner").animate({
				top:'+=19'
			}, spinSpeed, 'linear', function() {
				$("#day-spinner li:last").remove();
				$("#day-spinner li:eq(2)").addClass('selected');
				isSpinning = false;
				//keep firing if mouse is over arrow:
				if( autoSpin) {
					ageSelectDayUpSpin();
				};
		});
		return false;		
	};


	$("#age-select-day-down").click( function() {
		autoSpin = false;
	});
	$("#age-select-day-down").mousedown( function() {
		autoSpin = true;
		ageSelectDayDownSpin();
	});
	$("#age-select-day-down").mouseleave( function() {
		autoSpin = false;
	});
	var ageSelectDayDownSpin = function() {
		
		if( isSpinning) { return false; } else { isSpinning = true; }
		
		$("#day-spinner li").removeClass('selected');

		//append a new list item:
		var oldLastItem = $("#day-spinner li:last");
		oldLastItem.removeClass('last-child');
		var lastItemClone = oldLastItem.clone();
		lastItemClone.addClass('last-child');
		var nextValue = parseInt( lastItemClone.attr('value'), 10) - 1;
		if( nextValue < dayMinValue) {
			nextValue = dayMaxValue;	//rotate
		}
		lastItemClone.attr( 'value', nextValue); 
		lastItemClone.html( LICOR43.pad( nextValue, 2) + '.' ); 
		
		$("#day-spinner").append( lastItemClone);
		
		
		$("#day-spinner").animate({
				top:'-=19'
			}, spinSpeed, 'linear', function() {
				$("#day-spinner li:first").remove();
				$("#day-spinner").css('top', 0);
				$("#day-spinner li:eq(2)").addClass('selected');
				isSpinning = false;
				//keep firing if mouse is over arrow:
				if( autoSpin) {
					ageSelectDayDownSpin();
				};
		});
		return false;		
	};


	$("#age-select-month-up").click( function() {
		autoSpin = false;
	});
	$("#age-select-month-up").mousedown( function() {
		autoSpin = true;
		ageSelectMonthUpSpin();
	});
	$("#age-select-month-up").mouseleave( function() {
		autoSpin = false;
	});
	var ageSelectMonthUpSpin = function() {

		if( isSpinning) { return false; } else { isSpinning = true; }

		$("#month-spinner li").removeClass('selected');

		//preprend a new list item:
		var topItemClone = $("#month-spinner li:first").clone();
		var nextValue = parseInt( topItemClone.attr('value'), 10) + 1;
		if( nextValue > monthMaxValue) {
			nextValue = monthMinValue;	//rotate
		}
		topItemClone.attr( 'value', nextValue); 
		topItemClone.html( LICOR43.pad( nextValue, 2) + '.' ); 
		
		$("#month-spinner").prepend( topItemClone);
		$("#month-spinner").css('top', -19);
		$("#month-spinner").animate({
				top:'+=19'
			}, spinSpeed, 'linear', function() {
				$("#month-spinner li:last").remove();
				$("#month-spinner li:eq(2)").addClass('selected');
				isSpinning = false;
				//keep firing if mouse is over arrow:
				if( autoSpin) {
					ageSelectMonthUpSpin();
				};
		});
		return false;
	};

	$("#age-select-month-down").click( function() {
		autoSpin = false;
	});
	$("#age-select-month-down").mousedown( function() {
		autoSpin = true;
		ageSelectMonthDownSpin();
	});
	$("#age-select-month-down").mouseleave( function() {
		autoSpin = false;
	});
	var ageSelectMonthDownSpin = function() {

		if( isSpinning) { return false; } else { isSpinning = true; }
	
		$("#month-spinner li").removeClass('selected');

		//append a new list item:
		var oldLastItem = $("#month-spinner li:last");
		oldLastItem.removeClass('last-child');
		var lastItemClone = oldLastItem.clone();
		lastItemClone.addClass('last-child');
		var nextValue = parseInt( lastItemClone.attr('value'), 10) - 1;
		if( nextValue < monthMinValue) {
			nextValue = monthMaxValue;	//rotate
		}
		lastItemClone.attr( 'value', nextValue); 
		lastItemClone.html( LICOR43.pad( nextValue, 2) + '.' ); 
		
		$("#month-spinner").append( lastItemClone);
		
		$("#month-spinner").animate({
				top:'-=19'
			}, spinSpeed, 'linear', function() {
				$("#month-spinner li:first").remove();
				$("#month-spinner").css('top', 0);
				$("#month-spinner li:eq(2)").addClass('selected');
				isSpinning = false;
				//keep firing if mouse is over arrow:
				if( autoSpin) {
					ageSelectMonthDownSpin();
				};
		});
		return false;		
	};


	$("#age-select-year-up").click( function() {
		autoSpin = false;
	});
	$("#age-select-year-up").mousedown( function() {
		autoSpin = true;
		ageSelectYearUpSpin();
	});
	$("#age-select-year-up").mouseleave( function() {
		autoSpin = false;
	});
	var ageSelectYearUpSpin = function() {

		if( isSpinning) { return false; } else { isSpinning = true; }

		$("#year-spinner li").removeClass('selected');

		//preprend a new list item:
		var topItemClone = $("#year-spinner li:first").clone();
		var nextValue = parseInt( topItemClone.attr('value'), 10) + 1;
		if( nextValue > yearMaxValue) {
			nextValue = yearMinValue;	//rotate
		}
		topItemClone.attr( 'value', nextValue); 
		topItemClone.html( nextValue); 
		
		$("#year-spinner").prepend( topItemClone);
		$("#year-spinner").css('top', -19);
		$("#year-spinner").animate({
				top:'+=19'
			}, spinSpeed, 'linear', function() {
				$("#year-spinner li:last").remove();
				$("#year-spinner li:eq(2)").addClass('selected');
				isSpinning = false;
				//keep firing if mouse is over arrow:
				if( autoSpin) {
					ageSelectYearUpSpin();
				};
		});
		return false;		
	};


	$("#age-select-year-down").click( function() {
		autoSpin = false;
	});
	$("#age-select-year-down").mousedown( function() {
		autoSpin = true;
		ageSelectYearDownSpin();
	});
	$("#age-select-year-down").mouseleave( function() {
		autoSpin = false;
	});
	var ageSelectYearDownSpin = function() {

		if( isSpinning) { return false; } else { isSpinning = true; }

		$("#year-spinner li").removeClass('selected');

		//append a new list item:
		var oldLastItem = $("#year-spinner li:last");
		oldLastItem.removeClass('last-child');
		var lastItemClone = oldLastItem.clone();
		lastItemClone.addClass('last-child');
		var nextValue = parseInt( lastItemClone.attr('value'), 10) - 1;
		if( nextValue < yearMinValue) {
			nextValue = yearMaxValue;	//rotate
		}
		lastItemClone.attr( 'value', nextValue); 
		lastItemClone.html( nextValue); 
		
		$("#year-spinner").append( lastItemClone);
		
		$("#year-spinner").animate({
				top:'-=19'
			}, spinSpeed, 'linear', function() {
				$("#year-spinner li:first").remove();
				$("#year-spinner").css('top', 0);
				$("#year-spinner li:eq(2)").addClass('selected');
				isSpinning = false;
				//keep firing if mouse is over arrow:
				if( autoSpin) {
					ageSelectYearDownSpin();
				};	
		});
		return false;		
	};
};


LICOR43.checkTickerScrollButtons = function( listMaskName, leftButtonName, rightButtonName) {
	
	var leftShift = parseInt( $( listMaskName + " ul").css('left'), 10);
	
	if( leftShift >= 0) {
		//disabled the left button:
		$( leftButtonName).addClass('disabled');
	} else {
		$( leftButtonName).removeClass('disabled');
	}
	
	var totalWidth =  $( listMaskName + " ul").innerWidth();
	var displayWidth = $( listMaskName).outerWidth( true);
	
	var itemWidth = $("#news-ticker ul li:first").outerWidth( true);

	if( Math.abs( leftShift) >= (totalWidth - displayWidth) ) {
		$( rightButtonName).addClass('disabled');
	} else {
		$( rightButtonName).removeClass('disabled');
	}
	
};

LICOR43.fiestaFotosScrollButtons = function() {
	LICOR43.setListWidth( $("#photo-carousel-mask > ul") );
	var itemWidth = $("#photo-carousel-mask > ul > li:first").outerWidth( true);

	$("#fiesta-fotos-left-button").click( function() {
		if( $("#photo-carousel-mask ul").is(':animated') ) {
			return false;
		}
		$("#photo-carousel-mask ul").animate({
				left:'+=' + itemWidth
			}, 300, 'swing', function() {
				LICOR43.checkTickerScrollButtons( '#photo-carousel-mask', '#fiesta-fotos-left-button', '#fiesta-fotos-right-button');
		});
		
		return false;
	});

	$("#fiesta-fotos-right-button").click( function() {
		if( $("#photo-carousel-mask ul").is(':animated') ) {
			return false;
		}
		$("#photo-carousel-mask ul").animate({
				left:'-=' + itemWidth
			}, 300, 'swing', function() {
				LICOR43.checkTickerScrollButtons( '#photo-carousel-mask', '#fiesta-fotos-left-button', '#fiesta-fotos-right-button');
		});
		return false;

	});
};

LICOR43.tickerScrollButtons = function() {

	LICOR43.setListWidth( $("#news-ticker ul") );
	var itemWidth = $("#news-ticker ul li:first").outerWidth( true);

	$("#news-ticker-left-button").click( function() {
		if( $("#news-ticker ul").is(':animated') ) {
			return false;
		}
		$("#news-ticker ul").animate({
				left:'+=' + itemWidth
			}, 300, 'swing', function() {
				LICOR43.checkTickerScrollButtons( '#news-ticker-mask', '#news-ticker-left-button', '#news-ticker-right-button');
		});
		return false;
	});

	$("#news-ticker-right-button").click( function() {
		if( $("#news-ticker ul").is(':animated') ) {
			return false;
		}
		$("#news-ticker ul").animate({
				left:'-=' + itemWidth
			}, 300, 'swing', function() {
				LICOR43.checkTickerScrollButtons( '#news-ticker-mask', '#news-ticker-left-button', '#news-ticker-right-button');
		});
		return false;
	});

};

LICOR43.handleMouseOverClicks = function() {
	$(".item-mouseover-content").click( function() {
		var href = $( this).attr('href');
		//console.log( href);
		document.location = href;
		return false;
	});
};

LICOR43.fiestaScrollButtons = function(){
	
	var isFiestasScrolling = false;
	
	$("#fiestas-scroll-up-button").click( function( event) {
		event.preventDefault();
		
		if( isFiestasScrolling) {
			return false;
		} else {
			isFiestasScrolling = true;
		}
		
		$("#box3 ul").animate({
				top:'+=59'
			}, 300, 'swing', function() {
				LICOR43.checkScrollerButtons( "#box3-list-mask", "#fiestas-scroll-up-button", "#fiestas-scroll-down-button");
				isFiestasScrolling = false;
		});
		return false;
	});

	$("#fiestas-scroll-down-button").click( function( event) {
		event.preventDefault();
		
		if( isFiestasScrolling) {
			return false;
		} else {
			isFiestasScrolling = true;
		}
		
		$("#box3 ul").animate({
				top:'-=59'
			}, 300, 'swing', function() {
				LICOR43.checkScrollerButtons( "#box3-list-mask", "#fiestas-scroll-up-button", "#fiestas-scroll-down-button");
				isFiestasScrolling = false;
		});
		return false;
	});
};

LICOR43.concursosDestacadosScrollButtons = function(){
	$("#concursos-destacados-scroll-up-button").click( function() {
		$("#concursos-destacadas ul").animate({
				top:'+=79'
			}, 300, 'swing', function() {
				LICOR43.checkScrollerButtons( "#concursos-destacadas-list-mask", "#concursos-destacados-scroll-up-button","#concursos-destacados-scroll-down-button");
		});
		return false;
	});

	$("#concursos-destacados-scroll-down-button").click( function() {
		$("#concursos-destacadas ul").animate({
				top:'-=79'
			}, 300, 'swing', function() {
				LICOR43.checkScrollerButtons( "#concursos-destacadas-list-mask", "#concursos-destacados-scroll-up-button","#concursos-destacados-scroll-down-button");
		});
		return false;
	});
};

LICOR43.noticiasDestacadosScrollButtons = function(){
	$("#noticias-destacados-scroll-up-button").click( function() {
		$("#noticias-destacados ul").animate({
				top:'+=79'
			}, 300, 'swing', function() {
				LICOR43.checkScrollerButtons( "#noticias-destacadas-list-mask", "#noticias-destacados-scroll-up-button","#noticias-destacados-scroll-down-button");
		});
		return false;
	});

	$("#noticias-destacados-scroll-down-button").click( function() {
		$("#noticias-destacados ul").animate({
				top:'-=79'
			}, 300, 'swing', function() {
				LICOR43.checkScrollerButtons( "#noticias-destacadas-list-mask", "#noticias-destacados-scroll-up-button","#noticias-destacados-scroll-down-button");
		});
		return false;
	});
};


LICOR43.openDialog = function( title, contents) {
	var dialog = $("#layerDialog");
	
	if( 0 === dialog.size() ) {
		//create dialog:
		var dialog = $('<div id="layerDialog" style="display:none">' + contents + '</div>');
		dialog.appendTo( $("#page") );
	
		$( dialog).dialog({
			modal: true,
			buttons: {
				Vale: function() {
					$( this ).dialog( "close");
				}
			},
			resizable:false,
			draggable:false,
			autoOpen:false,
			title:title
		});
	} else {
		//set title and content:
		dialog.dialog('option', 'title', title);	
		dialog.html( contents);
	}

	dialog.dialog('open');	
	//set content and open it.
};

LICOR43.checkScrollerButtons = function( listMaskName, upButtonName, downButtonName) {

	if( 0 === $( listMaskName).size() ) {
		//no scroller found:
		return false;
	}

	var topShift = parseInt( $(listMaskName + " ul").css('top'), 10);
	
	if( topShift >= 0) {
		//disabled the left button:
		$( upButtonName).addClass('disabled');
	} else {
		$( upButtonName).removeClass('disabled');
	}
	
	var totalHeight =  $(listMaskName + " ul").height();
	var displayHeight = $( listMaskName).height();

	if( Math.abs( topShift) >= (totalHeight - displayHeight) ) {
		$( downButtonName).addClass('disabled');
	} else {
		$( downButtonName).removeClass('disabled');
	}

};



LICOR43.admin.confirmDialog = function( title, message, onConfirmCallback) {
	var dialog = $("#confirmDialog");
	
	if( 0 === dialog.size() ) {
		//create dialog:
		var dialog = $('<div id="confirmDialog" style="display:none">' + message + '</div>');
		dialog.appendTo( $("#page") );
	
		$( dialog).dialog({
			modal: true,
			buttons: {
				Sí: function() {
					if( $.isFunction( onConfirmCallback) ) {
						onConfirmCallback();
					}
					$( this ).dialog( "close");
				},
				No: function() {
					$( this ).dialog( "close");
				}
			},
			resizable:false,
			draggable:false,
			autoOpen:false,
			title:title
		});
	} else {
		//set title and content:
		dialog.dialog('option', 'title', title);	
		dialog.html( message);
	}

	dialog.dialog('open');	
	//set content and open it.
};


LICOR43.admin.fiestaPhotos = function() {
	
	$(".admin-delete-gallery-photo-button").click( function() {
		
		var photoRow = $( this).closest('tr');
		var photoName = photoRow.attr('id');
		
		var onConfirmDeleteCallback = function() {
			
			var fiestaId = $( "#fiesta-id").html();
			var data = {'photoName':photoName, 'fiestaId':fiestaId};
			
			$.ajax({
				type:'POST',
				url:'/admin-delete-fiesta-photo',
				data:data,
				success: function(response, textStatus, XMLHttpRequest) {
					if( response.AdminDeleteFiestaPhoto.delete_success) {
						//alert( 'delete was successful');
						//remove row from table:
						photoRow.slideUp( function() {
							photoRow.remove();
						});
					} else {
						//some error
						LICOR43.openDialog('Error deleting photo', 'Something went wrong, please try refreshing this page and trying again.');
					}
				},
				dataType:'json'
			});
		}
		LICOR43.admin.confirmDialog( 'Confirm delete', 'Are you sure you wish to delete photo "' + photoName + '"?', onConfirmDeleteCallback);
		
		return false;
	});
};
	
LICOR43.pad = function(number, length) {
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
    return str;
}


LICOR43.imagePreloader = function() {
	var container = $('<div style="display:none"></div>');
	 $('body').append( container);
	
	$.each( LICOR43.imagesToPreload, function( i, imageURL) {
		LICOR43.preloadImage( container, i, imageURL);
	});
};

LICOR43.preloadImage = function( container, i, imageURL) {
	container.append('<img id="img-preload-' + i + '" src="' + imageURL + '" />');
};
