window.pux = window.pux || {};

pux.new_filter = false;
pux.go_to_cart = false;

//// helpers
pux.dt = function(date) {

    var date_from = date['from'] ? date['from'] : date[0];
    var date_to = date['to'] ? date['to'] : date[1];

    return pux.dtIntToCz(date_from)  + ' &ndash; ' + pux.dtIntToCz(date_to);
};

pux.dtIntToCz = function(datestring) {
    return dateformater.formatDate(dateformater.parseDate(datestring, 'Y-m-d'), 'd.m.Y');
};

pux.dtCzToInt = function(datestring) {
    return dateformater.formatDate(dateformater.parseDate(datestring, 'd.m.Y'), 'Y-m-d');
};

pux.dateDiff = function(datestring_from, datestring_to) {
    return Math.round((dateformater.parseDate(datestring_to, 'd.m.Y') - dateformater.parseDate(datestring_from, 'd.m.Y'))/(1000*60*60*24));
};

//// forms
// form - hiding value
pux.form_hiding_value = function() {

    var hiding_fields = $('form').find('.hiding_value');
    if($('form').find('.val_error').length != 0) {
        hiding_fields = $('form').find('.val_error .hiding_value');
//        hiding_fields = {};
    }

    $(hiding_fields).each(function() {
        var default_value = this.value;
        $(this).focus(function() {
            if(this.value == default_value) {
                this.value = '';
                $(this).addClass('focused');
                $(this).removeClass('empty');
            }
        });
        $(this).blur(function() {
            if(this.value == '') {
                this.value = default_value;
                $(this).removeClass('focused');
                $(this).addClass('empty');
            }
        });

        $(this).addClass('empty');
    });
};

// form - hiding captcha
pux.form_hide_captcha = function() {
    $('form').find('.captcha').val('2').hide();
};

// form - ajaxize forms
pux.form_ajaxize = function() {
    $('form.ajax').live('submit', function() {
        $(this).ajaxSubmit({
            target: $(this).closest('.module'),
            replaceTarget: true,
            success: function() {
                pux.form_hiding_value();
                pux.form_hide_captcha();
            }
        });

        return false;
    });

    // info o načítání stránky
    if($('form.with-loading-info').length) {
        $('form.with-loading-info').live('submit', function() {
            pux.showLoading();
        });
    
        // přednačtení obrázků v loading dialogu

        var r = pux.showLoading();
        r.hide();
    }
};


//// galleries
pux.conf = {};
pux.conf.prettyPhoto = {
    social_tools: ''
};

pux.lightbox = function() {
    // mediaboxes, articles
    //$("a[rel^='media']").prettyPhoto(pux.conf.prettyPhoto);
    $('a.media').prettyPhoto(pux.conf.prettyPhoto);

    // images in articles, infopages
    $(".article, .infopage")
//        .find('a:has(img)')
        .find('a')
        .filter("[href*='.jpeg'],[href*='.jpg'],[href*='.gif'],[href*='.png']")
        .attr('rel', 'prettyPhoto[gallery]');
    $(".article, .infopage").find("a[rel^='prettyPhoto']").prettyPhoto(pux.conf.prettyPhoto);

    // odkazy Galerie, Plan, Prohlidka v detailu rezidence
    $('.facility-detail .resort-icons a').each(function() {
      var id = $(this).attr('href').replace(/^.*?\#(.*)$/, '#$1');
      if (! $(id).length) {
        // galerie je prazdna -> zneaktivnit ikonku
        $(this).addClass('inactive');
        $(this).click(function() {
          return false;
        });
      }
    });

    // gallery in facility detail
    $('.facility-detail a.gallery').click(function() {
        $('#gallery').find('a:first').trigger('click');

        return false;
    });

    // plan gallery in facility detail
    $('.facility-detail a.plan').click(function() {
        $('#gallery-plan').find('a:first').trigger('click');

        return false;
    });

    // tour in facility detail
    $('.facility-detail a.tour').click(function() {
        // aktualizace cílové URL tak, aby se v PrettyPhoto zobrazila v iframe
        var link = $('#gallery-tour').find('a:first');
        link.attr('href', link.attr('href') + '?iframe=true&width=905&height=500');
        link.trigger('click');

        return false;
    });
};


//// infobubbles
pux.initInfoBubbles = function() {
    var timeout;
    var isBubbleVisible = false;

    var LEFT = 1, RIGHT = 2;

    // zobrazí vybranou bublinu na zadané pozici
    var showBubble = function(position, bubble, align) {
        // skryje všechny bubliny
        $('.info-bubble').hide();

        // titulek bubliny vezmeme z "title" atributu
        if (! bubble.find('.title').length && ! bubble.find('h4').length && bubble.attr('title')) {
            bubble.prepend('<span class="title">' + bubble.attr('title') + '</span>');
        }

        clearTimeout(timeout);

        if (align == LEFT) {
            bubble.css('right', 'auto');
            bubble.css('top', position.top + 40);
            bubble.css('left', position.left + 5);

        } else {
            bubble.css('left', 'auto');
            bubble.css('top', position.top + 40);
            bubble.css('left', position.left - 15 - bubble.width());
        }

        if (isBubbleVisible) {
            bubble.show();
        } else {
            bubble.fadeIn("fast");
        }

        isBubbleVisible = true;
    };

    // skryje vybranou bublinu (se zpožděním)
    var hideBubble = function(bubble) {
        clearTimeout(timeout);
        timeout = setTimeout(function() {
            isBubbleVisible = false;
            bubble.fadeOut("fast");
        }, 500);
    };

    var showLoadingInfo = function(bubble, newtable) {
		if(newtable === true){
			bubble.html('<b class="top newfiltertable"></b><p>Načítám...</p>');
		}else{
			bubble.html('<b class="top"></b><p>Načítám...</p>');
		}
    }

    var getPricelistBubble = function(newfiltertable) {
        var bubble = $('#system-bubble-payments');
		if(newfiltertable === true){
			bubble.addClass('newfiltertable');
		}else{
			bubble.removeClass('newfiltertable');
		}
		
        if (! bubble.length) {
            // vytvoříme bublinu
            bubble = $(document.createElement('div'));
            bubble.attr('id', 'system-bubble-payments');
            bubble.addClass('info-bubble');
			if(newfiltertable === true){
				bubble.addClass('newfiltertable');
			}else{
				bubble.removeClass('newfiltertable');
			}
            bubble.css('display', 'none');
            bubble.mouseover(function() {
                clearTimeout(timeout);
            });
            bubble.mouseout(function() {
                //hideBubble(bubble);
            });
            $('body').append(bubble);
        }

        return bubble;
    }

    $('.search .ico16-help').hover(function(e) {
        var bubble = getPricelistBubble();
        bubble.removeClass('left');

        bubble.html( $(this).attr('alt') );
        
        var position = $(this).offset();
        showBubble(position, bubble, LEFT);
    }, function(e) {
        hideBubble(getPricelistBubble());
    });

    $('.price .ico16-help').hover(function(e) {
        var bubble = getPricelistBubble();
        bubble.removeClass('left');

        if($(this).attr('alt') == undefined || $(this).attr('alt') == ""){
            showLoadingInfo(bubble);
            bubble.load($(this).attr('href'));
        } else {
            bubble.html( $(this).attr('alt') );
        }

        var position = $(this).offset();
        showBubble(position, bubble, RIGHT);
    }, function(e) {
        hideBubble(getPricelistBubble());
    }).click(function(){
        return false;
    });

    // tooltip u ikonek
    $('.icon-info li, .tooltips-li li').hover(function(e) {
        var tooltip = $(this).find('.info-bubble');
        if (! tooltip.length)
          return;

        var position = $(this).position();
        position.left += 10;
        position.top += 20;

        showBubble(position, tooltip, RIGHT);
        
        $(this).css('cursor', 'help');

    }, function(e) {
        var tooltip = $(this).find('.info-bubble');
        if (! tooltip.length)
          return;

        hideBubble(tooltip);
    });

	$('.newpricelist_row .newpricelist_term_info, .pricelist .unit_info').click(function(e){
		$('.cart-bubble').hide();
		$('.info-bubble').hide();
		
		var bubble = getPricelistBubble(true);
		bubble.removeClass('left');
		
		if ($(this).attr('alt') == undefined || $(this).attr('alt') == "") {
			showLoadingInfo(bubble, true);
			bubble.load($(this).attr('href'));
		}
		else {
			bubble.html($(this).attr('alt'));
		}
		
		var position = $(this).offset();
		position.left += $(this).width() + 20;
		position.top -= 15;
		
		showBubble(position, bubble, LEFT);
		return false;
    });
	
	$('.newpricelist_row .nepricelist_price_info, .pricelist .price_info').click(function(e){
		e.preventDefault();
		$('.cart-bubble').hide();
		$('.info-bubble').hide();
		
		var bubble = getPricelistBubble(true);
		bubble.removeClass('left');
		
		if ($(this).attr('alt') == undefined || $(this).attr('alt') == "") {
			showLoadingInfo(bubble, true);
			bubble.load($(this).attr('href'));
		}
		else {
			bubble.html($(this).attr('alt'));
		}
		
		var cell = $(this).closest('td');
		var position = cell.offset();
		//console.log(position);
		position.left += cell.width() - 5;
		position.top -= 7;
		
		showBubble(position, bubble, LEFT);
		return false;
    });
	
	$('.info-bubble .ico20-close').live('click', function(){
		$('.info-bubble').hide();
		return false;
	});

    // najetí na bublinu zruší timeout pro její skrytí
    $('.info-bubble').mouseover(function() {
        clearTimeout(timeout);
    });

    // schová bublinu po odjetí z ní
    $('.info-bubble').mouseout(function() {
        //hideBubble($(this));
    });

    // omezí max. délka textu v ikonkách na dva řádky (a zobrazí "..." při přetečení)
    var iif = $('.icon-info');
    for(var i = 0; i < iif.length; i++) {
        // skip empty <ul> lists
        if ($(iif[i]).find('li').length) {
            iif = $(iif[i]);
            break;
        }
    }

    if (iif.length) {
        // dočasný blok, který nám pomůže určit výšku dvouřádkového textu
        var tmp = $(document.createElement('span')).addClass('attr-desc').html('Gy<br />Qj');
        iif.find('li:first').append(tmp);
        var height = tmp.height();
        tmp.remove();

        $('.icon-info .attr-desc').each(function() {
            var i = 20; // max. počet pokusů
            var step = 5; // počet znaků, po kterých se bude délka kontrolovat

            var shouldBreak = false;
            var t = $.trim($(this).text().replace(/[ ]+/g, ' '));
            $(this).text('…'); // inicializace

            do {
                // do textu přidáváme $step znaků, a to tak dlouho, dokud nepřetečeme nad stanovenou výšku
                var current = $(this).text();
                $(this).text(current.substr(0, current.length - 1) + t.substring(0, step) + '…');
                t = t.substring(step);

                shouldBreak = false;
                if ($(this).height() > height) {
                    $(this).text(current);
                    shouldBreak = true;
                }

                if (shouldBreak || i < 0 || ! t) {
                    break;
                }

                i--; // jistota nezacyklení
            } while(1);

            if (! t) {
                // text se vejde celý, tři tečky ("…") odstraníme
                $(this).text($(this).text().substr(0, $(this).text().length - 1));
            }
        });
    };
}


//// pricelists
pux.initPricelists = function() {

	this.choosed_el = false;

    // objekt pux.cart obsahuje pri vkladani ubytovani do kosiku data ceniku (pl_dataset) a data vkladaneho radku (row_dataset)
    // inicializace objektu pux.cart
    pux.cart = pux.cart || {row_dataset: {}, pl_dataset: {}};

    var showBubble = function(el, position, value, cart_state) {
        el.css('top', position.top + 33);
        el.show();
        el.css('left', position.left - el.width() + 11);

        var data = pux.cart.row_dataset;

        if(data) {
            // kopiruji dataset z radku do bubliny
            $(el).dataset(data);

            // doplnim texty do bubliny
            for(var i in cart_state) {
                if(i == 'term') {
                    cart_state[i] = pux.dt(cart_state[i]);
                }

                $(el).find('.data-current.'+i).html(cart_state[i]);
            }

//            console.log(data);
//            for(var i in data) {
//                $(el).find('.data-new.'+i).html(data[i]);
//
//            }
            $(el).find('.data-new').html(value);
        }
    };

    var closeBubble = function(el, reset_cart) {
        $(el).closest('.cart-bubble').hide();
		if(pux.new_filter !== true){
			$('.info-bubble').hide();
		}
        if(reset_cart) {
            pux.cart = {};
        }
    };

    // cart button
    $('.add-to-cart').live('click', function() {

        // schovej ostatní bubliny
        $('.cart-bubble:visible .close').each(function() {
            closeBubble(this, false);
        });

        // nastav dataset - vyresetuj, pokud je aktivovano nove tlacitko (novy radek ceniku)
        var new_button = (jQuery.isEmptyObject(pux.cart.row_dataset) || $(this).attr('id') != "" || $(this).attr('id') == '#add-to-cart-' + pux.cart.row_dataset['price-id']);

        pux.cart.row_dataset = new_button ? $(this).closest('.data-holder').dataset() : pux.cart.row_dataset;
        pux.cart.pl_dataset = new_button ? $(this).closest('.pricelist.data-holder').dataset() : pux.cart.pl_dataset;

		var el = $(this);
		var add_to_cart_id = '#add-to-cart-' + pux.cart.row_dataset['price-id'];
		
		if (el.hasClass('finish-reservation')) {
			pux.go_to_cart = true;
		}
        
		if(pux.new_filter === true){
			var cell = $('#add-to-cart-cell-' + pux.cart.row_dataset['price-id']);
			var position = cell.position();
			//console.log(position);
			position.left += cell.width() + 348;
			position.top += 13;
		}else{
			var position = $(add_to_cart_id).position();
		}

        // rozliseni akce (normalni/force)
        // force zrusi kontrolu strediska, facility a terminu a pred vkladanim nove polozky smaze kosik
        var action = null;
        if($(this).hasClass('force')) {
            if($(this).hasClass('orobie')) {
                action = 'rezervace/pridat-orobie/1';
            } else {
                action = 'rezervace/pridat/1';
            }
        } else if($(this).hasClass('orobie')) {
            action = 'rezervace/pridat-orobie';
        } else {
            action = 'rezervace/pridat';
        }

        // FREE - zadani terminu u volneho ceniku
        if(pux.cart.row_dataset['pl-type'] == 'free') {

            // datum neni vybrano -> zobraz bublinu
            if(!pux.cart.row_dataset['date-chosen']) {
                pux.cart.row_dataset['date-chosen'] = true;
                showBubble($('#bubble-cart-choose-date'), position, pux.cart.pl_dataset['resort-name'], []);
                return false;

            // datum je vybrano -> zpracuj a predej dal
            } else {
                // ziskani dat z inputu
                var date_from = $('#bubble-cart-choose-date').find('.date-from').val();
                var date_to = $('#bubble-cart-choose-date').find('.date-to').val();

                // overeni zadaneho data - datum neni vyplneno nebo nesplnuje podminku min_days
                if(!date_from || !date_to
                    || ! date_from.match(/\d{1,2}\.\d{1,2}\.\d{4}/) || ! date_to.match(/\d{1,2}\.\d{1,2}\.\d{4}/)
                    || (pux.dateDiff(date_from, date_to) < pux.cart.row_dataset['min-nights'])) {
                    showBubble($('#bubble-cart-choose-date'), position, pux.cart.pl_dataset['resort-name'], {'invalid-term': 'Zadejete správné termíny.'});
                    return false;
                }

                // konverze data na serverovy format
                date_from = pux.dtCzToInt(date_from);
                date_to = pux.dtCzToInt(date_to);

                // vlozeni do datasetu
                pux.cart.row_dataset['term-from'] = date_from;
                pux.cart.row_dataset['term-to'] = date_to;
            }
        }

        // zpracovani pozadavku -> odeslani na server
        $.ajax({
            type: 'POST',
            url: pux.PATH + action,
            data: pux.cart.row_dataset,

            success: function(response) {
				if(pux.go_to_cart === true){
					window.location = pux.PATH + 'rezervace';
				}else{
					showBubble($('#bubble-cart-success'), position, pux.cart.pl_dataset['resort-name'], response['cart_state']);
				}             
                pux.cart = {};
            },

            error: function (xhr, ajaxOptions, thrownError){
                var response = $.parseJSON(xhr.responseText);

                // na zaklade druhu chyby se rozhoduji, kterou bublinu zobrazit
                if(response['error'] == 'RESORT_ERROR') {
                    //console.log('RESORT_ERROR');
                    showBubble(
                        $('#bubble-cart-resort-change'),
                        position,
                        pux.cart.pl_dataset['resort-name'],
                        response['cart_state']
                    );
                } else if(response['error'] == 'FACILITY_ERROR') {
                    //console.log('FACILITY_ERROR');
                    showBubble(
                        $('#bubble-cart-facility-change'),
                        position,
                        pux.cart.pl_dataset['facility-name'],
                        response['cart_state']
                    );
                } else if(response['error'] == 'TERM_ERROR') {
                    //console.log('TERM_ERROR');
                    showBubble(
                        $('#bubble-cart-term-change'),
                        position,
                        pux.dt([pux.cart.row_dataset['term-from'], pux.cart.row_dataset['term-to']]),
                        response['cart_state']
                    );
                }
            }
        });

        return false;
    });

    // zavírací tlačítko
    $('.cart-bubble .close, .cart-bubble .dismiss').live('click', function() {
        closeBubble(this, true);
		$('.info-bubble').hide();
        return false;
    });
};


//// layout
pux.modifyDesign = function() {
    // stejná výška sloupců
    var div = $('.same-height');
    if (div.length) {
        var cols = div.find('.height-col');
        var l = cols.length;
        var maxHeight = 0;
        for (var i = 0; i < l; i++) {
            var h = $(cols[i]).height();
            if (h > maxHeight)
                maxHeight = h;
        }

        for (var i = 0; i < l; i++) {
            $(cols[i]).height(maxHeight);
        }
    }
    // klikací elementy
    $('.clickable').css('cursor', 'pointer');
    $('.clickable').live('click', function() {
        var a = $(this).find('a:first');
        if (! a.length)
            return;

        var link = a.attr('href');
        
        if(a.not('[href*="'+pux.DOMAIN+'"]').not('[href^="#"]').not('[href^="/"]').length) {
            window.open(link);
        } else {
            window.location = link;
        }
    });
    $('.clickable').live('mouseover mouseout', function(event) {
        // při najetí na element přidej všem odkazům třídu "hover"
        if ( event.type == 'mouseover' ) {
            $(this).find('a').addClass('hover');
        } else {
            $(this).find('a').removeClass('hover');
        }
    });
};

pux.initDatepicker = function() {
    $.datepicker.regional['cs'] = {
		closeText: 'Zavřít',
		prevText: '&#x3c;Dříve',
		nextText: 'Později&#x3e;',
		currentText: 'Nyní',
		monthNames: ["Leden", "Únor", "Březen", "Duben", "Květen", "Červen", "Červenec", "Srpen", "Září", "Říjen", "Listopad", "Prosinec"],
		monthNamesShort: ["Led", "Úno", "Bře", "Dub", "Kvě", "Čvn", "Čvc", "Srp", "Zář", "Říj", "Lis", "Pro"],
		dayNames: ["Neděle", "Pondělí", "Úterý", "Středa", "Čtvrtek", "Pátek", "Sobota"],
		dayNamesShort: ["Ne", "Po", "Út", "St", "Čt", "Pá", "So"],
		dayNamesMin: ["Ne", "Po", "Út", "St", "Čt", "Pá", "So"],
		weekHeader: 'Týd',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['cs']);
    
    $('.datepicker .input, .datepicker b').live('mousedown', function() {
        var i = $(this).is('input') ? $(this) : $(this).parent().find('.input');
        if(! $(i).hasClass('hasDatepicker')){
            $(i).datepicker({
                 beforeShow: function(input, inst){
                     var minDate = null,
                        maxDate = null;
                    if($(input).hasClass('date-to')){
                        var dateFromInput = $('input.date-from', $(input).closest('.buttons'));
                        if(dateFromInput.length == 1 && dateFromInput.val() != ''){
                            minDate = $.datepicker.parseDate('dd.mm.yy', dateFromInput.val());
                            if(typeof minDate == 'object'){
                                minDate.setDate(minDate.getDate() + 1);
                            }
                        }
                    }
                    if($(input).hasClass('date-from')){
                        var dateToInput = $('input.date-to', $(input).closest('.buttons'));
                        if(dateToInput.length == 1 && dateToInput.val() != ''){
                            maxDate = $.datepicker.parseDate('dd.mm.yy', dateToInput.val());
                            if(typeof maxDate == 'object'){
                                maxDate.setDate(maxDate.getDate() - 1);
                            }
                        }
                    }
                    $(input).datepicker('option', 'minDate', minDate);
                    $(input).datepicker('option', 'maxDate', maxDate);
                    // osklivy hotfix pro nastaveni z-indexu
                    setTimeout(function(){
                       $('.ui-datepicker').css('z-index', 999);
                    }, 10);
                 }
            });
        }
    });
    
    $('.datepicker b').live('click', function() {
        $(this).parent().find('.input').datepicker( "show" );
    });
};

pux.initHP = function() {
    if($('#homepage-banners .banner').size() > 1) {
        $('#homepage-banners .banner-holder').cycle({
            fx:       'fade',
            speed:    800,
            timeout:  6000,
            pause:    1,
            pager:  '#banners-nav',
            startingSlide: Math.floor(Math.random()*3)
        });
    }
}

pux.showLoading = function() {
    if ($('#loading').length) {
        $('#loading').remove();
    }

    $('body').append('<div id="loading"><em>Čekejte prosím, operace se provádí</em></div>');

    return $('#loading');
}

pux.initSliders = function() {

    /**
     * Javascriptové slidery u středisek
     */

    /* fce pro posun obsahu na základě pozice slideru*/
    var updatePosition = function(slider, ui) {
        slider.data('ul').get(0).scrollTop = (slider.data('ulHeight') - slider.data('panelHeight')) - Math.round( ui.value / 100 * ( slider.data('ulHeight') - slider.data('panelHeight') ));
    }

    var initializeSliders = [];

    /* inicializace všech sliderů na stránce */
    $('.slider div').each(function() {
        // nalezneme <ul> seznam se setředisky
        var ul = $($(this).parent().parent().find('ul').get(0));
        if (!ul)
            return;
        $(this).data('ul', ul);

        // zjistíme jeho aktuální výšku
        var originalHeight = ul.height();
        var originalMaxHeight = ul.css('max-height');
        ul.css('height', 'auto');
        ul.css('max-height', '100000px');
        ul.addClass('with-scrollbar'); // nastavíme margin

        // nastavíme výšku na "auto" -> roztáhne se na skutečnou výšku, tu si uložíme
        $(this).data('ulHeight', ul.height());
        $(this).data('panelHeight', originalHeight);

        // krok posunu
        var coef = 7;

        // pokud je skutečná výška menší jak nastavená, není co scrollovat a scrollbar skryjeme
        if ($(this).data('ulHeight') <= $(this).data('panelHeight')) {
            $(this).parent().hide();
            // odebereme nastavený margin
            ul.removeClass('with-scrollbar');

        } else {
            if ($(this).data('ulHeight') - $(this).data('panelHeight') < 70) {
              coef = 50;
            }
        }

        // obnovíme původní výšku a schováme scrollbar vykreslený browserem
        ul.css('height', originalHeight);
        ul.css('overflow', 'hidden');

        // přidáme onmousewheel handler
        var slider = $(this);
        ul.bind('mousewheel', function(event, delta) {
            var newVal = slider.slider('value') + delta * coef;
            if (newVal > 100)
              newVal = 100;
            slider.slider('value', newVal);
            updatePosition(slider, {
                value: slider.slider('value')
                });

            return false;
        });
        
        var selected = ul.find('a.selected');
        if (selected.length) {
          if (selected.position().top > $(this).data('panelHeight')) {
            var position = 100 - Math.round((100 * selected.position().top / $(this).data('ulHeight')));
            initializeSliders.push(function() {slider.slider('value', position);updatePosition(slider, {value: position});});
          }
        }
    });

    // inicializace pomocí jQuery UI
    $(".slider div").slider({
        orientation: "vertical",
        min: 0,
        max: 100,
        value: 100,
        slide:function(e, ui){
            // posuneme se v závislosti na pozici scrollbaru
            updatePosition($(this), ui);
        }
    });

    // slidery byly vytvořeny, inicializujeme je
    var l = initializeSliders.length;
    for ( var i = 0; i < l; i++) {
      initializeSliders[i]();
    }
}

// js filter v ceniku - bez ajaxu
pux.initPricelist = function() {
    if ($('.pricelist').length < 1) {
        return;
    }
     var push = function(array, value){
        if($.inArray(value, array) < 0){
            array.push( value );
        }
     }
     // skryti a zobrazeni hodnoty selectu fungujici ve vsech prohlizecich
     $.fn.hideOption = function() {
        this.each(function() {
            if( ! $(this).parent().is('span') && ! $.browser.webkit){
                $(this).wrap('<span>').hide();
                $(this).closest('span').hide();
            }
            $(this).hide();
        });
    }
    $.fn.showOption = function() {
        this.each(function() {
            if($(this).parent().is('span')){
                $(this).show();
                $(this).parent().replaceWith( $(this) );
            }
            $(this).show();
        });
    }
    var dateSlug = function(from, to){
        return from+'-'+to;
    }
    // zjisteni maximalni obsazenosti pokoju
    var maxRoomPeople = {};
    $('.pricelist tbody tr').each(function(){
        var unit = $(this).attr('data-unit-id');
        var persons = parseInt( $(this).attr('data-term-persons') );
        if(typeof maxRoomPeople[ unit ] == 'undefined' || maxRoomPeople[ unit ] < persons){
             maxRoomPeople[ unit ] = persons;
        }
    });
    
    var selectedOrder = [];
    $('.pricelist select').val('');
    $('.pricelist select').change(function() {
        var order = $(this).closest('th').prevAll('th').length,
            form = $(this).closest('form'),
            table = $(this).closest('table'),
            // Load filter values
            date = $('select[name="rs_price_list_price_filters[pl_date_from]"] option:selected', form).attr('value'),
            nights = $('select[name="rs_price_list_price_filters[pl_nights]"] option:selected', form).attr('value'),
            unit = $('select[name="rs_price_list_price_filters[rs_unit_id]"] option:selected', form).attr('value'),
            persons = $('select[name="rs_price_list_price_filters[persons]"] option:selected', form).attr('value');

        if ($(this).val() != '' && $(this).val() != '0') {
            // When some filter is applied, save its index
            push(selectedOrder, order);
        } else if($.inArray(order, selectedOrder) >= 0) {
            // When some filter is removed, remove its index
            selectedOrder.splice($.inArray(order, selectedOrder), 1);
        }

        // Hide row which does not apply with the selected filters
        $('tbody tr', table).css('display', 'table-row').each(function(){
            var $this = $(this);

            var rowFrom = $this.attr('data-term-from'),
                rowTo = $this.attr('data-term-to'),
                rowNights = $this.attr('data-night'),
                rowUnit = $this.attr('data-unit-id'),
                rowPersons = $this.attr('data-term-persons');
            if (
                (date != '' && dateSlug(rowFrom, rowTo) != date)
                || (nights != '' && rowNights != nights )
                || (unit != '' && rowUnit != unit)
                || (persons != '' && persons != 'full' && rowPersons != persons)
                || (persons == 'full' && maxRoomPeople[rowUnit] != rowPersons)
            ){
                $this.hide();
            }
        });

        // In case the row result is empty, remove previously applied filter
        if ($('tbody tr:visible', table).length == 0 && selectedOrder.length >= 2) {
            // Since the last one is the currently selected, we need the second last
            var lastSelectIndex = selectedOrder.slice(-2)[0];
            var $lastSelect = $('select:eq(' + lastSelectIndex + ')', form);

            $lastSelect.val('');

            // If jQuery select box is loaded, refresh it
            if ($lastSelect.selectBox != undefined) {
                $lastSelect.selectBox('refresh');
            }

            $lastSelect.trigger('change');
            return;
        }

        // Restore visual difference between even & odd rows by refreshing the assignment of CSS class .odd
        $('tbody tr', table).removeClass('odd');
        $('tbody tr:visible:odd', table).addClass('odd');
    });

    // vybrani nejblizsiho terminu je-li polozek v ceniku moc
    if($('.pricelist tbody tr').length > 50){
        var select  = $('.pricelist select[name="rs_price_list_price_filters[pl_date_from]"]');
        var option = $('option:eq(1)', select);
        if(option.length == 1){
            select.val( option.attr('value') ).change();
        }
    }
    // maximalni obsazenost je defaultne vybrana
    $('.pricelist select[name="rs_price_list_price_filters[persons]"]').val('full').change();
    selectedOrder.pop();
    // hack pro IE aby fungovalo onchange
    if($.browser.msie){
        $('.pricelist select').live('click', function(){
            $(this).closest('select').change();
        });
    }
    
    // ceny skipasu
    $('.skipassesTable').hide();
    $('.skipassesShow').click(function(){
        if($('.skipassesTable').is(':visible')){
            $('.skipassesTable').hide();
        } else {
            $('.skipassesTable').show();
        }
        return false;
    });
};

// omezeni vkladanych znaku ve formularich
pux.initFormRestrict = function(){
    $('#requestForm_email, #subscribeForm_email_address, #contactForm_email').onlyChars('a-zA-Z0-9.@_\\-~');
    $('#requestForm_phone').onlyChars('0-9+ ');
    $('#requestForm_date_from, #requestForm_date_to').onlyChars('0-9.');
};

// otevirani externich odkazu do noveho okna
pux.externalLinkToNewWindow = function() {
    $('a:not([href*="'+pux.DOMAIN+'"])')
        .not(function(){ return $(this).parents("#homepage-banners .banner-holder").length })
        .not('[href^="#"]').not('[href^="/"]').attr({ target: "_blank" })
        .addClass("external");
};

// GA trackPageview
pux.gaTrackPageview = function(url) {
    if(typeof _gaq !== "undefined" && _gaq !== null && ! pux.gaFormTracked) {
        _gaq.push(['_trackPageview', url]);
        _gaq.push(['b._trackPageview', url]);
        //console.log('GA trackPageview: ' + url);
    }
};

$(document).ready(function() {
    pux.form_hiding_value();
    pux.form_ajaxize();
    pux.form_hide_captcha();
    pux.lightbox();
    pux.modifyDesign();
    pux.initInfoBubbles();
    pux.initHP();

    if ($('.pricelist').length) {
        pux.initPricelists();
    }

    pux.initDatepicker();
    pux.initSliders();
    pux.initPricelist();
    pux.initFormRestrict();
    pux.externalLinkToNewWindow();
});
