/**
 * Справочник цен: 
 *   [номер][дата][количество человек] = [цена].
 */
pricesByDate = new Array();

/**
 * Обновляет количество человек в выпадающем списке при изменении номера.
 *
 * Параметры:
 *  peopleCountElem - Элемент списка количества человек.
 *  numberElem        - Элемент списка номеров.
 *  selectedValue   - Выбранное количество человек (@todo: понять зачем).
 *
 * Пользуется глобальным массивом peopleCount - количество человек от номера.
 */ 
function updatePeopleCount( peopleCountElem, numberElem, selectedValue )
{
    // Получаем выбранный номер.
    if ( numberElem == null )
    {
        numberElem = $( 'number_id' );
    }

    numberId = numberElem.value;

    currentPeopleCount = peopleCount[ numberId ];

    if ( peopleCountElem == null ) { peopleCountElem = $( 'people_count' ); }

    // Если значение которое нужно установит не передано - считываем старое значение в списке
    if ( !selectedValue ) { selectedValue = peopleCountElem.value; }

    // Если список был пуст и есть предустановленное значение количества человек - выбираем его.
    if ( selectedValue != '' ) selectedValue = Number( selectedValue );

    // Если всё равно ничего не выбрано - выбираем одного.
    if ( selectedValue == '' ) selectedValue = 1;

    // Удаляем все элементы списка.
    for ( i = peopleCountElem.length-1; i > -1; i-- )
    {
        Element.remove( peopleCountElem[ i ] );
    }

    // Добавляем назад.
    for ( i = 0; i < currentPeopleCount; i++ )
    {
        var option = Builder.node( 'option', { 'value': ( i+1 ) }, i+1 );
        peopleCountElem.appendChild( option );
    }

    // Восстанавливаем выбранное количество человек.
    if ( selectedValue > currentPeopleCount ) selectedValue = currentPeopleCount;
    peopleCountElem.value = Number( selectedValue );
}

/**
 * Заполняет справочник цен.
 */
function fillPricesByDate()
{
    for( numberId in prices )
    {
        periods = prices[ numberId ];
        for( periodId in periods )
        {
            period = periods[ periodId ];

            var startDate = new Date( period[ 'start_year' ], period[ 'start_month' ]-1, period[ 'start_day' ] );
            var endDate   = new Date( period[ 'end_year' ], period[ 'end_month' ]-1, period[ 'end_day' ] );

            if (pricesByDate[ numberId ] == undefined)
            {
                pricesByDate[ numberId ] = new Array();
            }

            if ( endDate > startDate )
            {
                var curDate = startDate;
                while ( curDate <= endDate )
                {
                    pricesByDate[ numberId ][ curDate ] = new Array();

                    pricesByDate[ numberId ][ curDate ][ 1 ] = period[ 'price1' ];
                    pricesByDate[ numberId ][ curDate ][ 2 ] = period[ 'price2' ];
                    pricesByDate[ numberId ][ curDate ][ 3 ] = period[ 'price3' ];
                    pricesByDate[ numberId ][ curDate ][ 4 ] = period[ 'price4' ];
                    pricesByDate[ numberId ][ curDate ][ 5 ] = period[ 'price5' ];
                    pricesByDate[ numberId ][ curDate ][ 6 ] = period[ 'price6' ];

                    nextUTC = Date.parse( curDate.toString() );
                    nextUTC += 1000*60*60*24;
                    curDate = new Date( nextUTC );

                    if ( curDate.getHours() == 23 )
                    {
                        nextUTC += 1000*60*60;
                        curDate = new Date( nextUTC );
                    }

                    if ( curDate.getHours() == 1 )
                    {
                        nextUTC -= 1000*60*60;
                        curDate = new Date( nextUTC );
                    }
                }
            }
        }
    }
}


/**
 * Возвращает цены номера по периодам.
 *
 * Параметры:
 *  
 * Если цена неизвестна, то она равна -1.
 */
function getPrice( start_yearElem, start_monthElem, start_dayElem, end_yearElem, end_monthElem, end_dayElem, numberElem, peopleCountElem )
{
    // Переменные, выбранные в форме.
    var peopleCount = Number( peopleCountElem.value );
    var numberId    = Number( numberElem.value );
    var startDate   = new Date( start_yearElem.value, start_monthElem.value-1, start_dayElem.value );
    var endDate     = new Date( end_yearElem.value, end_monthElem.value-1, end_dayElem.value );

    if ( endDate < startDate ) return new Array();

    var chunks = new Array();

    var chunkStartDate = startDate;
    var chunkLength    = 0;

    var curDate   = startDate;
    var prevDate  = null;
    var prevPrice = null;
    var curPrice  = -2;

    while( curDate < endDate )
    {
        try
        {
            curPrice = pricesByDate[ numberId ][ curDate ][ peopleCount ];
        }

        catch(e)
        {
            curPrice = -1;
        }

        if ( ( curPrice != prevPrice ) && ( curDate != startDate ) )
        {
            chunk = new Array();
            chunk[ 'startDate' ]  = chunkStartDate;
            chunk[ 'endDate' ]    = prevDate;
            chunk[ 'length' ]     = chunkLength;
            chunk[ 'price' ]      = prevPrice;
            chunk[ 'totalPrice' ] = prevPrice*chunkLength;

            chunkStartDate = curDate;
            chunkLength = 0;

            chunks.push( chunk );
        }

        chunkLength++;
        prevPrice = curPrice;
        prevDate  = curDate;

        nextUTC = Date.parse( curDate.toString() );
        nextUTC += 1000*60*60*24;
        curDate = new Date( nextUTC );        

        if ( curDate.getHours() == 23 )
        {
            nextUTC += 1000*60*60;
            curDate = new Date( nextUTC );
        }

        if ( curDate.getHours() == 1 )
        {
            nextUTC -= 1000*60*60;
            curDate = new Date( nextUTC );
        }
    }

    chunk = new Array();

    chunk[ 'startDate' ]  = chunkStartDate;
    chunk[ 'endDate' ]    = curDate;
    chunk[ 'length' ]     = chunkLength;
    chunk[ 'price' ]      = prevPrice;
    chunk[ 'totalPrice' ] = prevPrice*chunkLength;

    chunks.push( chunk );

    return chunks;
}

/**
 * Форматирует и возвращает полученную цену для формы бронирования.
 */
function formatPrice( price )
{
    var totalPrice = 0;
    var avgPrice = '';
    var multiPrice = 0;

    // Если цен нет (на всякий случай) - возвращаем пустой массив.
    if ( price.length == 0 )
    {
        return new Array( '', '' );
    } else if ( price.length != 1 )
    {
        for( i = 0; i < price.length; i++ )
        {
            if ( totalPrice > 0 ) totalPrice += price[ i ][ 'totalPrice' ];
            startDate   = price[ i ][ 'startDate' ];
            endDate     = price[ i ][ 'endDate' ];

            avgPrice += '<p class="br"><span style="font-size: 70%;">в&nbsp;период с&nbsp;';
            avgPrice += startDate.getDate()+'.'+(startDate.getMonth()+1)+'.'+(startDate.getYear()+1900)+'&nbsp;по&nbsp;';
            avgPrice += endDate.getDate()+'.'+(endDate.getMonth()+1)+'.'+(endDate.getYear()+1900);
            if ( price[ i ][ 'price' ] > 0 )
            {
                avgPrice += '</span>&nbsp;<span class="calsmall"><b>' + String(price[ i ][ 'price' ]) + '</b> руб. в&nbsp;сутки</span></p>';
            } else {
                avgPrice += '</span>&nbsp;<span class="calsmall"><b>цена неизвестна</b></span></p>';
                totalPrice = '';
            }
        }
    } else {
        totalPrice = price[ 0 ][ 'totalPrice' ];
        avgPrice = price[ 0 ][ 'price' ];

        if ( totalPrice < 0 ) totalPrice = 0;
        if ( avgPrice < 0 ) avgPrice = 0;

        if ( avgPrice ) 
        {
            avgPrice = '<b>'+String( avgPrice ) + "</b>&nbsp;руб. в сутки";
        }
    }

    if ( totalPrice )
    {
        totalPrice = String( totalPrice );
    }

    return new Array( avgPrice, totalPrice );
}
