
var bNotepadDontload = true;


/**
 * fetches all Hotels from DOM
 * used to initialize the filter functionality
 **/

var aHotels = null;
var aLocations = null;
function getAllHotelsFromDom() {
    var aHotels = [];
    aLocations = [];
    // step throug reagions
    $('#ibe_search_result > ul > li').each(function() {
        var oRegionLi = $(this);
        var sRegion = oRegionLi.find('h2').text();
        oRegionLi.find('li.ibe_result_item').each(function(){
            var oHotelLi    = $(this);
            var fPrice        = parseFloat(oHotelLi.find('.data-price').text());
            var iCategory    = parseInt(oHotelLi.find('.data-category').text());
            var sLocation    = oHotelLi.find('.data-location').text().replace (/^\s+/, '').replace (/\s+$/, '');
            var sProperties     = oHotelLi.find('.data-properties').val();
            eval('var oProperties = '+sProperties+';');
            if($.inArray(sLocation, aLocations) == -1) {
                aLocations.push(sLocation);
            }
            aHotels.push({
                sRegion:    sRegion
                ,sName:     oHotelLi.find('.data-name').text()
                ,sUrl:      oHotelLi.find('.data-link').text()
                ,sLocation:    sLocation
                //,sRoom:     oHotelLi.find('.data-room').text()
                //,sBoard:    oHotelLi.find('.data-board').text()
                ,fPrice:    isNaN(fPrice)?99999:fPrice
                ,iCategory:    isNaN(iCategory)?-1:iCategory
                ,oProperties:  oProperties
                ,sHtml:        oHotelLi.html()
            });
        })
    });
    return aHotels;
}




    
function fillLocations() {
    aLocations.sort();
    for(i in aLocations) {
        $('#filter-location').append('<option>'+aLocations[i]+'</option>');
    }
}

/**
 * orders hotels by given property
 * @param string property
 **/

function sortHotels(sKey) {
    var sSortProperty = null
    function fStringSort(a,b) {
        var a = a[sSortProperty];
        var b = b[sSortProperty];
        a = a==''?'zzzz':a.toLowerCase().replace(/ä/, 'ae').replace(/ö/, 'oe').replace(/ü/, 'ue').replace(/ß/, 'ss');
        b = b==''?'zzzz':b.toLowerCase().replace(/ä/, 'ae').replace(/ö/, 'oe').replace(/ü/, 'ue').replace(/ß/, 'ss');
        if(a > b) return 1;
        if(a < b) return -1;
        return 0;
    }
    function fFloatSort(a,b) {
        var a = a[sSortProperty];
        var b = b[sSortProperty];
        if(a > b) return 1;
        if(a < b) return -1;
        return 0;
    }
    var fSortFunction = null;
    switch(sKey) {
        case 'name':        fSortFunction = fStringSort;    sSortProperty = 'sName';        break;
        case 'location':    fSortFunction = fStringSort;    sSortProperty = 'sLocation';    break;
        //case 'room':        fSortFunction = fStringSort;    sSortProperty = 'sRoom';        break;
        //case 'board':        fSortFunction = fStringSort;    sSortProperty = 'sBoard';        break;
        case 'category':    fSortFunction = fFloatSort;        sSortProperty = 'iCategory';    break;
        default:
        case 'price':        fSortFunction = fFloatSort;        sSortProperty = 'fPrice';    break;
    }
    aHotels.sort(fSortFunction);
}




/**
 * defines global filter options
 */

var oFilterProperies = {
    fPriceFrom:        null
    ,fPriceUntil:      null
    ,iCategoryFrom:    null
    ,sLocation:        null
    ,sLocationType:    null
    ,sSortKey:         null
}
function getFilterPropertysFromDOM() {

    // price
    var sPriceInterval = $('#filter-price').val();
    if(sPriceInterval == -1 || sPriceInterval == undefined) {
        oFilterProperies.fPriceFrom     = null;
        oFilterProperies.fPriceUntil     = null;
    }
    else {
        aPriceInterval = sPriceInterval.split('-');
        oFilterProperies.fPriceFrom     = parseFloat(aPriceInterval[0]);
        oFilterProperies.fPriceUntil     = parseFloat(aPriceInterval[1]);
    }

    // category
    var sCategory = $('#filter-category').val();
    if(sCategory == -1 || sCategory == undefined) {
        oFilterProperies.iCategoryFrom     = null;
    }
    else {
        oFilterProperies.iCategoryFrom     = parseFloat(sCategory);
    }

    // location
    var sLocation = $('#filter-location').val();
    if(sLocation == -1 || sLocation == undefined) {
        oFilterProperies.sLocation         = null;
    }
    else {
        oFilterProperies.sLocation         = sLocation;
    }

    // location type
    var sLocationType = $('#filter-locationtype').val();
    if(sLocationType == -1 || sLocationType == undefined) {
        oFilterProperies.sLocationType     = null;
    }
    else {
        oFilterProperies.sLocationType     = sLocationType;
    }

    // sort key
    var sOrder = $('#filter-order').val();
    if(sOrder == -1 || sOrder == undefined) {
        oFilterProperies.sSortKey         = null;
    }
    else {
        oFilterProperies.sSortKey         = sOrder;
    }

    // properties
//    oFilterProperies.bBeach             = (typeof $('#filter-beach:checked').val()                != 'undefined');
//    oFilterProperies.bCity                 = (typeof $('#filter-city:checked').val()                != 'undefined');
//    oFilterProperies.bNature             = (typeof $('#filter-nature:checked').val()                != 'undefined');
    oFilterProperies.bAction             = (typeof $('#filter-action:checked').val()                != 'undefined');
    oFilterProperies.bGolf                 = (typeof $('#filter-golf:checked').val()                != 'undefined');
    oFilterProperies.bDiving             = (typeof $('#filter-diving:checked').val()                != 'undefined');
    oFilterProperies.bFishing             = (typeof $('#filter-fishing:checked').val()            != 'undefined');
    oFilterProperies.bWellness             = (typeof $('#filter-wellness:checked').val()            != 'undefined');
    oFilterProperies.bFamily             = (typeof $('#filter-family:checked').val()                != 'undefined');
    oFilterProperies.bSingleWithChild     = (typeof $('#filter-single_with_child:checked').val()    != 'undefined');
    oFilterProperies.bHoneymoon         = (typeof $('#filter-honeymoon:checked').val()            != 'undefined');
    oFilterProperies.bBusiness             = (typeof $('#filter-business:checked').val()            != 'undefined');
    oFilterProperies.bConnoisseur         = (typeof $('#filter-connoisseur:checked').val()        != 'undefined');
    oFilterProperies.bCharmed             = (typeof $('#filter-charmed:checked').val()            != 'undefined');
}




/**
 * renders sorted hotels into dom
 * filters by given filter propertys
 */

function renderSortedHotels() {
    var sHtml = '<ul class="ibe_result_region">';
    $.each(aHotels, function(iNr, oHotel) {

        //apply filters
        if(oFilterProperies.fPriceFrom != null       && oHotel.fPrice        <    oFilterProperies.fPriceFrom)       return;
        if(oFilterProperies.fPriceUntil != null      && oHotel.fPrice        >    oFilterProperies.fPriceUntil)      return;
        if(oFilterProperies.iCategoryFrom != null    && oHotel.iCategory     <    oFilterProperies.iCategoryFrom)    return;
        if(oFilterProperies.sLocation != null        && oHotel.sLocation     !=   oFilterProperies.sLocation)        return;
        if(
            oFilterProperies.sLocationType != null    
            && (
                (oFilterProperies.sLocationType == 'beach' && !oHotel.oProperties.bBeach)
                || (oFilterProperies.sLocationType == 'city' && !oHotel.oProperties.bCity)
                || (oFilterProperies.sLocationType == 'nature' && !oHotel.oProperties.bNature)
            )
        ) {
            return;
        }
        
//        if(oFilterProperies.bBeach                    && !oHotel.oProperties.bBeach)                return;
//        if(oFilterProperies.bCity                    && !oHotel.oProperties.bCity)                return;
//        if(oFilterProperies.bNature                    && !oHotel.oProperties.bNature)                return;
        if(oFilterProperies.bAction                    && !oHotel.oProperties.bAction)                return;
        if(oFilterProperies.bGolf                    && !oHotel.oProperties.bGolf)                return;
        if(oFilterProperies.bDiving                    && !oHotel.oProperties.bDiving)                return;
        if(oFilterProperies.bFishing                && !oHotel.oProperties.bFishing)            return;
        if(oFilterProperies.bWellness                && !oHotel.oProperties.bWellness)           return;
        if(oFilterProperies.bFamily                    && !oHotel.oProperties.bFamily)                return;
        if(oFilterProperies.bSingleWithChild        && !oHotel.oProperties.bSingleWithChild)    return;
        if(oFilterProperies.bHoneymoon                && !oHotel.oProperties.bHoneymoon)          return;
        if(oFilterProperies.bBusiness                && !oHotel.oProperties.bBusiness)           return;
        if(oFilterProperies.bConnoisseur            && !oHotel.oProperties.bConnoisseur)        return;
        if(oFilterProperies.bCharmed                && !oHotel.oProperties.bCharmed)            return;
        
        sHtml += '<li class="ibe_result_item">'+oHotel.sHtml+'</li>';
        
    });
    sHtml += '</ul>';
    $('#ibe_search_result').html(sHtml);
    resetIbeClick();
    $('#m3-sub a').unbind().click(function() {
        oWaitingScreen.open();
        document.location.href='?iRand='+Math.random()+$(this).attr('href');
    });
}




/**
 * sets click event
 */
function resetIbeClick() {
    $('.ibe_result_item').each(function(me) {
        var sUrl = $(this).find('.data-link').attr('href');
        $(this)
            .unbind()
            .bind('click', {sUrl:sUrl} ,function(o){window.location.href=o.data.sUrl;});
    });
}




/**
 * show individual meal filter
 */
function changeMealFilterOptions() {
    var sInputType = $('#input_to_type').val();
    // if hotels only...
    if (sInputType == 'hotel') {
        // hide meal filter option 'Verpflegung laut Programm'
        if ($('#searchfield_board_input').val() == 'program') {
            // set option 'all'
            $('#searchfield_board_input').val('');
        }
        $('.option-lp').hide();
        $('.searchfield_board').show();
    }
        
    // if circulartrips only
    else if (sInputType == 'circulartrip') {
        // hide the meal filter
        $('.searchfield_board').hide();
        // set option 'all'
        $('#searchfield_board_input').val('');
    }
        
    // if hotels and circulartrips
    else {
        // show meal filter with all options
        $('.option-lp').show();
        $('.searchfield_board').show();
    }
}




/**
 * init on page load
 */
$(document).ready(function() {
    $.lazyLoad(
        ['jqueryDatePicker', 'badjie-ibe-dev', 'cTemplate']
        , function() {
            oIbeSearchParameters.init();
            oIbeFlightMask.init('ibebox_content_2');
            
            $('#input_to_type').change(changeMealFilterOptions).change();
        }
    );
    aHotels = getAllHotelsFromDom();
    fillLocations();
    $('.ibe-filter').bind('change', function() {
        getFilterPropertysFromDOM();
        sortHotels(oFilterProperies.sSortKey);
        renderSortedHotels();
    });
    oNotepad.init();
});
