var photoExplorer = {};
/** przetrzymuje id aktualnie pokazywanego zdjecia */
photoExplorer.showedId;
/** predkosc przesuwania zdjec */
photoExplorer.speed = 0;
/** informacja, czy myszka znajduje sie ponad obszarem przegladarki zdjec */
photoExplorer.mouseOver = false;
/**
 * inicjalizacja, ukrycie niepotrzebnych zdjec, przypisanie zdarzen
 */
photoExplorer.init = function()
{
    if(!$('thumbs')){
        return; // nie ma zdjec przy ofercie, lub jest tylko jedno
    }
    var photos = $('photoBigContainer').childElements();
    photoExplorer.showedId = photos[0].id;
    photos[0].addClassName('chosen');
    for(var i=1; i<photos.length; i++){
        photos[i].hide();
    }
    
    var thumbs = $('thumbs').childElements();
    var id;
    for(var i=0; i<thumbs.length; i++){
        id = thumbs[i].id.split(':')[1];
        thumbs[i].observe('click', photoExplorer.showBig.bindAsEventListener(photoExplorer, id));
    }
    
    $('thumbs').style.left = '0px';
    if($('thumbLeft')){
        setInterval(photoExplorer.scroll, 50);
        $('thumbs').up().observe('mousemove', photoExplorer.setScrollSpeed);
        
        $('thumbLeft').observe('mousedown', function(){photoExplorer.speed*=3});
        $('thumbLeft').observe('mouseup', function(){photoExplorer.speed/=3});
        $('thumbRight').observe('mousedown', function(){photoExplorer.speed*=3});
        $('thumbRight').observe('mouseup', function(){photoExplorer.speed/=3});
    }
    
    setInterval(photoExplorer.changeImage, 5000);
    $$('.photos')[0].observe('mouseover', function(){photoExplorer.mouseOver = true});
    $$('.photos')[0].observe('mouseout', function(){photoExplorer.mouseOver = false});
}
/**
 * przelacanie zdjecia po kliknieciu
 * @param {Object} event
 * @param {int} id
 */
photoExplorer.showBig = function(event, id)
{
    if(photoExplorer.showedId != 'photoBig'+id){
        new Effect.Fade($(photoExplorer.showedId), {duration:0.5});
        $('photo:'+photoExplorer.showedId.substr(8)).removeClassName('chosen');
        photoExplorer.showedId = 'photoBig'+id;
        $('photo:'+id).addClassName('chosen');
        new Effect.Appear($(photoExplorer.showedId), {duration:0.5});
    }
}
/**
 * obsluga przewijania myszka (reaguje na pozycje wskaznika)
 */
photoExplorer.setScrollSpeed = function(event)
{
    var pos = event.pointerX() - this.cumulativeOffset().left;
    var margin = 50;
    var width = this.getWidth();
    if((width-pos)<margin){
        photoExplorer.speed = ((width-margin)-pos)/10;
    } else if(pos<margin){
        photoExplorer.speed = (margin/10)-pos/10;
    } else {
        photoExplorer.speed = 0;
    }
}
/**
 * funkcja wywolywana z intevrala, przesuwa zdjecia o wartosc okreslona w speed
 */
photoExplorer.scroll = function()
{
    if(parseInt($('thumbs').style.left) + photoExplorer.speed > 0){
        $('thumbs').style.left = '0px';
        return;
    }
    if(parseInt($('thumbs').style.left) + photoExplorer.speed < -($('thumbs').getWidth() - $('thumbs').up().getWidth())){
        $('thumbs').style.left = (-($('thumbs').getWidth() - $('thumbs').up().getWidth()))+'px';
        return;
    }
    $('thumbs').style.left = (parseInt($('thumbs').style.left) + photoExplorer.speed)+'px';
}
/**
 * funkcja wywolywana z intevrala, zmienia obrazek co 5 sekund (jesli wskaznik jest poza obszarem zdjec)
 */
photoExplorer.changeImage = function()
{
    if(!photoExplorer.mouseOver){
        if($(photoExplorer.showedId).next()){
            var showNow = $(photoExplorer.showedId).next();
        } else {
            var showNow = $(photoExplorer.showedId).up().down();
        }
        photoExplorer.showBig(null, showNow.id.substr(8))
    }
}
$(document).observe('dom:loaded', photoExplorer.init);




/**
 * dodawanie do obserwowanych offer
 */
$(document).observe('dom:loaded', function(){
	if( $('addObserved') ) {
	$('addObserved').observe('click', function(event){
				event.stop();
				if( currentUserLogged ){
					element = event.element();
					offerId = element.href.substr( element.href.lastIndexOf('/')+1 );
					$('observe').update('Zapisuję...');
					new Ajax.Request('/main/offer/addToObserved', {
							parameters : { 'offerId' : offerId },
							onSuccess : function(transport){
									if( transport.responseText == 1 ){
										$('observe').update('Dodane do obserwowanych.');
									} else {
										$('observe').update('Błąd...');
									}
								},
							onFailure : function(transport){
									$('observe').update('Błąd...');
								}
						});
				}
			} );
	}
});


/**
 * odmiana słów w zależności od liczby
 * wybiera odpowiednia forme z podanych i zwraca ja
 * @param {int} num
 * @param {array} words - tablica z liczbami, kolejne pola to formy dla 
 *                         ilości elementów: 1, 2 i 5; przykładowo:
 *                         'minuta', 'minuty', 'minut'
 * @return {string}
 */
function fleksja(num, words)
{
	if( num == 0 ) return words[2];
	if( num == 1 ) return words[0];
	if( num < 5 ) return words[1];
	if( num < 21 ) return words[2];
	if( num%10 > 1 && num%10 < 5 ) return words[1];
	return words[2];
};


var rentSystem = {};
/**
 * najwazniejsze dane, czesc jest pobieranych z serwera
 * z tych danych korzystaja rozne metody obiektu
 */
rentSystem.data = {
	'prices'			: {},
	'seasons'			: {},
	'priceModelId'		: {},
	'rents'				: {},
	'additionalOptions' : [],
	'maxRentTime'		: 0, // w miesiacach
	'minRentTime'		: 0, // w sekundach
	'today'				: new Date(), // obiekt typu date
	'currentSelection'	: {'from':new Date(), 'to':new Date()} // obiekty typu date
};
/**
 * inicjalizacja funkcji wynajmu - pokazanie kalendarzukow, przypisanie zdarzen..
 */
rentSystem.init = function()
{
	$('infoNoJS').down('p').update(offerPageLang.loadingData);
	
	rentSystem.loadData();
}
/**
 * laduje z serwera dane dotyczace bierzacej oferty (cenniki, czasy dostepnosci)
 */
rentSystem.loadData = function()
{
	new Ajax.Request('/main/offer/getCalendarData', {
		parameters : {'offerId':offerId},
		onSuccess : rentSystem.loadDataOnSuccess,
		onFailure : function(){
			$('infoNoJS').down('p').update(offerPageLang.loadingError);
		}
	} );
}
/**
 * funkcja wywolywana na zakonczenie zapytania o dane
 * @param {object} transport
 */
rentSystem.loadDataOnSuccess = function(transport)
{
	try {
		var json = transport.responseText.evalJSON();
		
		rentSystem.data = Object.extend(rentSystem.data, {
			'prices'			: json.prices,
			'seasons'			: json.seasons,
			'priceModelId'		: json.priceModelId,
			'rents'				: json.rents,
			'additionalOptions'	: json.additionalOptions,
			'maxRentTime'		: json.maxRentTime+1,
			'minRentTime'		: json.minRentTime
		});
		
		rentSystem.data.today.setYear(json.today.year);
		rentSystem.data.today.setMonth((json.today.month-1));
		rentSystem.data.today.setDate(json.today.day);
		rentSystem.data.today.setHours(json.today.hour);
		rentSystem.data.today.setMinutes(json.today.minute);
		
		rentSystem.prices.init();
		rentSystem.additionalOptions.init();
		rentSystem.rent.init();
		
		$('infoNoJS').hide();
		$('calendarsAndRentBox').show();
		var options = {
			'rents'			: rentSystem.data.rents,
			'maxRentTime'	: rentSystem.data.maxRentTime,
			'minRentTime'	: rentSystem.data.minRentTime,
			'today'			: rentSystem.data.today,
			'startDate'		: rentSystem.data.today,
			'onChange'		: rentSystem.updateView,
			'getDayColor'	: rentSystem.prices.getPriceLevel 
		};
		calendar.init(options);
	}
	catch(exc){
		if(console.error){
			console.error(exc);
		}
		$('infoNoJS').show();
		$('calendarsAndRentBox').hide();
		$('infoNoJS').down('p').update(offerPageLang.loadingError);
	}
}
/**
 * wywolywane po zmianie danych, uaktualnia okresy zaznaczenia i cene wynajmu
 */
rentSystem.updateView = function()
{
	rentSystem.data.currentSelection.from = calendar.getFromDate();
	rentSystem.data.currentSelection.to = calendar.getToDate();
	rentSystem.prices.update();
}


/**
 * modul odpowiedzialny za akcje wynajmu
 */
rentSystem.rent = {};
/**
 * przypisanie zdarzen
 */
rentSystem.rent.init = function()
{
	$('rentButton').observe('click',rentSystem.rent.rent);
}
/**
 * obsluga klikniecia na przycisk wynajmu
 * @param {object}
 */
rentSystem.rent.rent = function(event)
{
	event.stop();
	if(!currentUserLogged){
		new jsWindowManager.Window(offerPageLang.mustLoginTitle, offerPageLang.mustLogin, {'type':'info'});
	} else if(!currentUserFullAccount){
		new jsWindowManager.Window(offerPageLang.mustFullRegisterTitle, offerPageLang.mustFullRegister, {'type':'info'});
	} else if($('fAcceptStatute') && $('fAcceptStatute').checked==false){
		new jsWindowManager.Window(offerPageLang.mustAcceptStatueTitle, offerPageLang.mustAcceptStatue, {'type':'info'});
		$('fAcceptStatuteError').show();
	} else {
		if($('fAcceptStatuteError')){
			$('fAcceptStatuteError').hide();
		}
		var interval = (rentSystem.data.currentSelection.to.getTime()-rentSystem.data.currentSelection.from.getTime())/1000+1;
		if(interval >= rentSystem.data.minRentTime){
			var data = {};
			if(rentSystem.data.minRentTime<86400){
				data.rentFrom = rentSystem.data.currentSelection.from.getHours()+':00 ';
				data.rentTo = rentSystem.data.currentSelection.to.getHours()+':59 ';
			} else {
				data.rentFrom = '';
				data.rentTo = '';
			}
			data.rentFrom += rentSystem.data.currentSelection.from.getDate()+' '
							+ calendarLang.months[rentSystem.data.currentSelection.from.getMonth()]+' '
							+ rentSystem.data.currentSelection.from.getFullYear();
			data.rentTo += rentSystem.data.currentSelection.to.getDate()+' '
							+ calendarLang.months[rentSystem.data.currentSelection.to.getMonth()]+' '
							+ rentSystem.data.currentSelection.to.getFullYear();
			var hours = Math.round(interval/3600);
			var days = Math.floor(hours/24);
			hours = hours%24;
			data.totalTime = (days ? days+' '+fleksja(days, calendarLang.days) : '')+' '
							+ (hours ? hours+' '+fleksja(hours, calendarLang.hours) : '');
			data.price = rentSystem.prices.getPrice();
			data.additionalPrice = rentSystem.additionalOptions.getPrice();
			data.totalPrice = data.price+data.additionalPrice;
			var templ = new Template(offerPageLang.confirmRent);
			new jsWindowManager.Window(offerPageLang.confirmRentTitle, templ.evaluate(data), {'width':400, 'id':'confirmRentWindow'});
			$('confirmRentButton').observe('click', rentSystem.rent.makeReservation);
		}
	}
}
/**
 * obsluga klikniecia w potwierdzenie rejestracji - zapisanie danych na serwerze
 * @param {object}
 */
rentSystem.rent.makeReservation = function(event)
{
	event.stop();
	var data = {};
	data.offerId = offerId;
	data.timeFrom = Math.floor(rentSystem.data.currentSelection.from.getTime()/1000);
	data.timeTo = Math.ceil(rentSystem.data.currentSelection.to.getTime()/1000);
	data.additionalOptions = rentSystem.additionalOptions.getChosenOptionsIds().join(';');
	$('confirmRentText').hide();
	$('confirmRentInfo').show();	
	new Ajax.Request('/main/offer/makeReservation', {
		parameters: data,
		onFailure: function(){
			$('confirmRentText').show();
			$('confirmRentInfo').hide();
			new jsWindowManager.Window(offerPageLang.confirmRentErrorTitle, offerPageLang.confirmRentError, {'type':'error'});	
		},
		onSuccess: rentSystem.rent.makeReservationOnSuccess
	});
}
/**
 * obsluga klikniecia w potwierdzenie rejestracji - zapisanie danych na serwerze
 * @param {object}
 */
rentSystem.rent.makeReservationOnSuccess = function(transport)
{
	try {
		var response = transport.responseText.evalJSON();
		if(response.result){
			new jsWindowManager.Window(offerPageLang.confirmRentOkTitle, offerPageLang.confirmRentOk, {'type':'info'});
			if(win = jsWindowManager.getWindow('confirmRentWindow')){
				win.close();
			}
		} else {
			$('confirmRentText').show();
			$('confirmRentInfo').hide();
			new jsWindowManager.Window(offerPageLang.confirmRentErrorTitle, offerPageLang.confirmRentError, {'type':'error'});
		}
	}
	catch(exc){
		if(console.error){
			console.error(exc);
		}
		$('confirmRentText').show();
		$('confirmRentInfo').hide();
		new jsWindowManager.Window(offerPageLang.confirmRentErrorTitle, offerPageLang.confirmRentError, {'type':'error'});
	}
}

/**
 * modul odpowiedzialny za obliczanie ceny wynajmu, dostarczanie informacji o kolorach kalendarza itp.
 */
rentSystem.prices = {};
/**
 * inicjalizacja modulu cen (utworzenie obiektu priceModel)
 */
rentSystem.prices.init = function()
{
	var model = rentSystem.prices.model = priceModels.getPriceModel(rentSystem.data.priceModelId, rentSystem.data.prices, rentSystem.data.seasons);
	var priceLevels = rentSystem.prices.levels = model.getPriceLevels();
	
	var rows = $$('.prices table td.priceZl');
	for(var i=0; i<rows.length; i++){
		var price = parseInt(rows[i].innerHTML);
		var level = priceLevels.indexOf(price)+1;
		if(level){
			rows[i].previous('td.color').down().addClassName('priceLevel'+level);
		}
	} 
}
/**
 * uaktualnia informacje o koszcie wynajmu
 */
rentSystem.prices.update = function()
{
	var interval = (rentSystem.data.currentSelection.to.getTime()-rentSystem.data.currentSelection.from.getTime())/1000+1;
	if(interval<rentSystem.data.minRentTime){
		var intervalHours = rentSystem.data.minRentTime/3600;
		var intervalDays = intervalHours/24;
		if(Math.ceil(intervalDays) == intervalDays){
			var message = offerPageLang.minDays.sub('#{num}', intervalDays);
		} else {
			var message = offerPageLang.minHours.sub('#{num}', intervalHours);
		}
		$('totalPrice').update(message);
	} else {
		var price = rentSystem.prices.getPrice();
		price = price + rentSystem.additionalOptions.getPrice();
		$('totalPrice').update(price+' '+offerPageLang.currency);
	}
}
/**
 * zwraca cene za wynajem (bez ceny za opcje dodatkowe)
 */
rentSystem.prices.getPrice = function()
{
	var price = rentSystem.prices.model.getPrice(rentSystem.data.currentSelection.from, rentSystem.data.currentSelection.to);
	return Math.round(price*100)/100;
}
/**
 * zwraca poziom ceny dla podanego dnia (uzywane do kolorowania kalendarzykow)
 * @param {int} year
 * @param {int} month
 * @param {int} day
 * @return {int}
 */
rentSystem.prices.getPriceLevel = function(year, month, day)
{
	var price = Math.round(rentSystem.prices.model.getPriceForDay(year, month, day));
	var level = rentSystem.prices.levels.indexOf(price)+1;
	//console.log(year, month, day, price, level, rentSystem.prices.levels);
	level = ( (level==0 || level>8) ? 1 : level );
	return level;
}


/**
 * modul odpowiedzialny za zczytywanie zaznaczonych opcji dodatkowych i obliczanie ceny za nie 
 */
rentSystem.additionalOptions = {};
/**
 * przypisanie zdarzen do opcji
 */
rentSystem.additionalOptions.init = function()
{
	$$('.additionalOptions input').each(function(input){
		input.observe('click', rentSystem.additionalOptions.inputClick);
	});
}
/**
 * obsluga klikniecia (zaznaczenia/odznaczenia) opcji
 */
rentSystem.additionalOptions.inputClick = function(event)
{
	var id = event.element().id.substr(16);
	for(var i=0; i<rentSystem.data.additionalOptions.length; i++){
		if(rentSystem.data.additionalOptions[i].additionalOptionId == id){
			rentSystem.data.additionalOptions[i].checked = event.element().checked;
		}
	}
	rentSystem.updateView();
}
/**
 * zwraca calkowity koszt opcji dodatkowych
 * @return {float}
 */
rentSystem.additionalOptions.getPrice = function()
{
	var price = 0;
	for(var i=0; i<rentSystem.data.additionalOptions.length; i++){
		if(rentSystem.data.additionalOptions[i].checked && rentSystem.data.additionalOptions[i].checked==true){
			if(!rentSystem.data.additionalOptions[i].priceFixed.blank()){
				price += parseFloat(rentSystem.data.additionalOptions[i].priceFixed.sub(',','.'));
			} else {
				price += rentSystem.additionalOptions.getPriceForOption(rentSystem.data.additionalOptions[i].pricePerHour,
										rentSystem.data.additionalOptions[i].pricePerDay);
			}
		}
	}
	return Math.round(price*100)/100;
}
/**
 * zwraca koszt obliczony na podstawie czasu najmu
 * @param {string} pricePerHour
 * @param {string} pricePerDay
 * @return {float}
 */
rentSystem.additionalOptions.getPriceForOption = function(pricePerHour, pricePerDay)
{
	var interval = (rentSystem.data.currentSelection.to.getTime()-rentSystem.data.currentSelection.from.getTime())/1000+1;
	var hours = Math.round(interval/3600);
	if(hours<24){
		return hours*parseFloat(pricePerHour.sub(',','.'));
	} else {
		return hours*parseFloat(pricePerDay.sub(',','.'))/24;
	}
}
/**
 * zwraca id wybranych opcji w tablicy
 * @return {array}
 */
rentSystem.additionalOptions.getChosenOptionsIds = function()
{
	var result = [];
	for(var i=0; i<rentSystem.data.additionalOptions.length; i++){
		if(rentSystem.data.additionalOptions[i].checked && rentSystem.data.additionalOptions[i].checked==true){
			result.push(rentSystem.data.additionalOptions[i].additionalOptionId);
		}
	}
	return result;
}


$(document).observe('dom:loaded', rentSystem.init);

