/**
 * UI aplikace Dobrebydleni
 *
 * @copyright   Copyright (c) 2010 Roman Pistek
 * @package     Dobrebydleni
 */

/* -- GOOGLE MAPA ------------------------------------------------------ */
jQuery.fn.extend({
    googleMap: function(lat, lon) {
        var marker;
        var map;
        var position = new google.maps.LatLng(lat, lon);

        var mapOptions = {
            zoom: 13,
	    maxZoom: 15,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            center: position,
            scrollwheel: false
        };

        map = new google.maps.Map($(this).get(0), mapOptions);

        marker = new google.maps.Marker({
            map: map,
            animation: google.maps.Animation.DROP,
            position: position
        });
    }
});



$(document).ready(function() {
    
    /* -- INTERAKCE -------------------------------------------------------- */
    (function() {
        
        $.ajaxSpinner.init();

        $('#realty-map .map a').live('click', function() {
            $('#search-form select[name=lokalita]').val($('strong', $(this).parent('li')).text()).change();
            return false;
        });
        
        $('.realty .photo')
            .live('mouseenter', function() {
                var title = $('.title', this);
                title.animate({ top: '-=' + title.outerHeight() + 'px' }, 100, 'swing');
            })
            .live('mouseleave', function() {
                var title = $('.title', this);
                title.animate({ top: '+=' + title.outerHeight() + 'px' }, 50, 'swing');
            })
            
        $('#realty-map .map a')
            .live('mouseenter', function() {
                $(this).css({ 'z-index': '5000' });
                $(this).before(
                    $('<span class="map-sign-label">' + $('strong', $(this).parent('li')).text() + '</span>')
                        .hide()
                        .css({ 'z-index': '4999', top: $(this).position().top + 'px', left: $(this).position().left + 'px' })
                        .show()
                );
            })
            .live('mouseleave', function() {
                $(this).css({ 'z-index': '0' });
                $('#realty-map .map-sign-label').remove();
            });
            
        $('.realties-list .paginator.bottom a,' + 
          '.realties-list .realty a').live('click', function() {
            $.scrollTo('#search-form', 300);
        });
        
        // Pas s nahledy fotografii nemovitosti
        $('#realty-card .photo .photo-nav a').live('click', function() {
            var strip = $('#realty-card .photo .strip');
            if ($(this).parent('p').hasClass('move-right')) {
                if ((strip.children('a').size() - 3) * -150 < strip.position().left) {
                    strip.animate({ left: '-=450px' }, 150);
                }
            } else if (strip.position().left < 0) {
                strip.animate({ left: '+=450px' }, 150);
            }
            return false;
        });
        $('#realty-card .photo .strip a').live('click', function() {
            $('#realty-card .photo .strip a.active').removeClass('active');
            $('#realty-card .photo .big img').attr('src', $(this).addClass('active').attr('href'));
            return false;
        });
        
        $("a.iframe").fancybox({
            centerOnScroll: true,
            width: 900,
            height: 700
        });
        
        $("a.fancy").fancybox({
            centerOnScroll: true,
        });

    }());                                                         
    


    /* -- FORMULARE -------------------------------------------------------- */
    (function() {
        
        var searchBarSelector = '#search-form',
            formSelector      = searchBarSelector + ' form',
        
        priceSlider = function(priceFrom, priceTo, limitPriceFrom, limitPriceTo) {
            var priceRange = function(left, right) {
                return 'od <strong>' + number_format(left, 0, ',', ' ') + '</strong> do <strong>' + (isInt(right) ? number_format(right, 0, ',', ' ') : '&infin;') + '</strong> Kč';
            };
            
            $('#std-price-range').hide();
            if (priceFrom > 0 && priceTo > 0) {
                var min = toInt(limitPriceFrom),
                    max = toInt(limitPriceTo),
                    from = toInt(priceFrom),
                    to = toInt(priceTo);
                var delta = max - min;
                var step = (delta / 1000000) > 1 ? 20000 : ((delta / 100000) > 1 ? 5000 : ((delta / 10000) > 1) ? 1000 : 500);
                $('#price-range-slider').slider({
                    range: true,
                    min: min,
                    max: max,
                    step: step,
                    values: [from, to],
                    slide: function(event, ui) {
                        $('#price-range').html(priceRange(ui.values[0], ui.values[1]));
                    },
                    stop: function(event, ui) {
                        $('input[name=cenaOd]').val(ui.values[0]);
                        $('input[name=cenaDo]').val(ui.values[1]).change();
                    }
                });
            }
            $('#price-range').html(priceRange($('#price-range-slider').slider('values', 0), $('#price-range-slider').slider('values', 1)));
        };

        redraw = function(form, first) {
            if (!form) {
                form = formSelector;
            }
            $('input:radio:not(:checked), input:checkbox:not(:checked)', form).each(function() {
                $(this).next('label').removeClass('checked');
            });
            $('input:radio:checked, input:checkbox:checked', form).each(function() {
                $(this).next('label').addClass('checked');
            });
            priceSlider(
                $('input[name=cenaOd]', form).val(),
                $('input[name=cenaDo]', form).val(),
                $('input[name=limitCenaOd]', form).val(),
                $('input[name=limitCenaDo]', form).val()
            );
            // Nahrazeni submitu odkazy ve stylu tlacitka
            $('input[type=submit]', form).replaceWith(function() {
                return '<a href="#" class="submit btn right">' + $(this).val() + '</a>';
            });
            if (first) {
                toggleFlatParams($('input[name=typNemovitosti]:checked', form));
            }
        };
        
        toggleFlatParams = function(radios) {
            if ($(radios).val() == 'byt') {
                $('#search-form .params-wrapper.flat').css('visibility', 'visible');
            } else {
                $('#search-form .params-wrapper.flat').css('visibility', 'hidden');
            }
        };

        // init
        redraw(false, true);
        
        // Pri akci nad vyhledavacim formularem...
        $(formSelector).live('change', function() {
            redraw(this);
            if ($(this).parents(searchBarSelector).size()) {
                $.ajaxSpinner.over('#realty-map');
                $(this).ajaxSubmit(this);
            }
            $.scrollTo(260, 500);
            return false;
        });
        
        // Stylovani prvku vyhledavaciho formulare
        $(formSelector + ' input:radio, form input:checkbox').hide();
        $(formSelector + ' input:radio + label').addClass('radio');
        $(formSelector + ' input:checkbox + label').addClass('checkbox');
        $(formSelector + ' label')
            .live('click', function(e) {
                e.preventDefault();
                $(this).prev('input:radio, input:checkbox').trigger('click').trigger('change');
            })
            .live('mouseenter', function() { $(this).addClass('active'); })
            .live('mouseleave', function() { $(this).removeClass('active'); })
            
        $(formSelector + ' a.submit').live('click', function() {
            var form = $(this).parents('form');
            $.ajaxSpinner.over($(form));
            form.ajaxSubmit(form);
            return false;
        });

        // Parametry nemovitosti ve vyhledavacim formulari
        $(formSelector + ' input[name=typNemovitosti]').live('change', function() {
            toggleFlatParams(this);
        });
        $('#search-form .params-wrapper .switch')
            .live('mouseenter', function() { $(this).parents('.params-wrapper').addClass('hover'); })
            .live('mouseleave', function() { $(this).parents('.params-wrapper').removeClass('hover'); })
            .live('click', function() {
                $(this).parents('.params-wrapper').addClass('opened');
                $(this).next('.params').show();
                return false;
            });
        var hideParamsTimeout = false;
        $('#search-form .params-wrapper')
            .live('mouseleave', function() {
                var _this = this;
                hideParamsTimeout = setTimeout(function() {
                    $(_this).fadeOut(200, function() {
                        $('.params', _this).hide();
                        $(_this).removeClass('opened');
                        $(_this).show();
                    });
                    
                }, 1500);
            });
        $('#search-form .params')
            .live('mouseenter', function() {
                if (!hideParamsTimeout) { return; }
                clearTimeout(hideParamsTimeout);
                hideParamsTimeout = false;
                $(this).parents('.params-wrapper').addClass('opened');
                $(this).show();
            });

    }());

});
        
    
/* -- rutiny ----------------------------------------------------------- */
    
    
    
function isInt(x) {
    var y = parseInt(x);
    if (isNaN(y)) return false;
    return x == y && x.toString() == y.toString();
}



function toInt(x) {
    return parseInt(x) + 0;
}



function number_format(number, decimals, dec_point, thousands_sep) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // +      input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +   improved by: davook
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Jay Klehr
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Theriault
    // +      input by: Amirouche
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'
    // *    example 10: number_format('1.20', 2);
    // *    returns 10: '1.20'
    // *    example 11: number_format('1.20', 4);
    // *    returns 11: '1.2000'
    // *    example 12: number_format('1.2000', 3);
    // *    returns 12: '1.200'
    // *    example 13: number_format('1 000,50', 2, '.', ' ');
    // *    returns 13: '100 050.00'
    number = (number+'').replace(',', '').replace(' ', '');
    var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}


