/**
 * 
 */

/* Czech initialisation for the jQuery UI date picker plugin. */
/* Written by Tomas Muller (tomas@tomas-muller.net). */
jQuery(function($) {
    $.datepicker.regional['sk'] = {
        closeText: 'Close',
        prevText: '&#x3c;Prev',
        nextText: 'Next&#x3e;',
        monthNames: ['Január','Február','Marec','Apríl','Máj','Jún',
                     'Júl','August','September','Októbe','November','December'],
        monthNamesShort: ['jan','feb','mar','apr','máj','jún',
                          'júl','aug','sep','okt','nov','dec'],
        dayNames: ['nedeľa', 'pondelok', 'utorok', 'streda', 'štvrtok', 'piatok', 'sobota'],
        dayNamesShort: ['ne', 'po', 'ut', 'st', 'št', 'pi', 'so'],
        dayNamesMin: ['ne','po','ut','st','št','pi','so'],
        weekHeader: 'Wk',
        dateFormat: 'dd.mm.yy', //'yy-mm-dd',
        firstDay: 1,
        numberOfMonths: [1, 2],
        showOtherMonths: false,
        minDate: +0,
        maxDate: '+2y',
        hideIfNoPrevNext: true,
        currentText: 'Dnes',
        defaultDate: null,
        constrainInput: true,
        changeYear: false,
        changeMonth: false,
        yearRange: 'c-0:c+1',
        disabled: true,
        isRTL: false,
        showMonthAfterYear: false,
        yearSuffix: ''
    };
    $.datepicker.setDefaults($.datepicker.regional['sk']);
});

function IsNumeric(input)
{
   return (input - 0) == input && input.length > 0;
}

function scollWin(speed, scrollTo)
{
    if (scrollTo == '' || scrollTo == null){
        scrollTo = 0;
    }
	$('html, body').animate({
		scrollTop: (IsNumeric(scrollTo)) ? scrollTo : $(scrollTo).offset().top - 30
	}, speed);
}

/**
 * This function is for left menu, accordion 
 */
function initMenu() {
	$('#menuLeft ul').hide();
	$('#menuLeft li a').removeClass('menuLeftSelected');
	//$('#menuLeft ul:first').show();
	$('#menuLeft > li > a').click(function() {
		$('#menuLeft li a').removeClass('menuLeftSelected');
		$(this).addClass('menuLeftSelected');
		var checkElement = $(this).next();
		if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
			return false;
		}
		if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
			$('#menuLeft ul:visible').slideUp('normal');
			checkElement.slideDown('normal');
			return false;
		}
	});
    $('#menuLeft > li > ul > li > a').click(function() {
        var componentName = 'justoFilter';
        var countryId = this.id.replace('leftCountryFilter_', '');
        $('#frm' + componentName + '-country_1').val(countryId);
        $('#frm' + componentName + '-country_2').val('');
        $('#frm' + componentName + '-country_3').val('');

        $('#frm-' + componentName).submit();
    });
    $('.countries a').click(function() {
        var componentName = 'justoFilter';
        var countryId = this.id.replace('bottomCountryFilter_', '');
        $('#frm' + componentName + '-country_1').val(countryId);
        $('#frm' + componentName + '-country_2').val('');
        $('#frm' + componentName + '-country_3').val('');

        $('#frm-' + componentName).submit();
    });
}

/**
 * This function add/remove additional fields in search (filter) form.
 * Currently now it uses for 'country' and 'location' fields.
 *  
 * @param type
 * @param id
 */
function setAddField(type, id)
{
    var plus = minus = '';
    if (type == 'country'){
        plus = 'Pridať ďalšiu krajinu';
        minus = 'Odobrať kajinu';
    } else if (type == 'location') {
        plus = 'Pridať ďalšiu oblasť';
        minus = 'Odobrať oblasť';
    }
    
    if (id == 1){
        var id2 = id + 1;
        id2 = '#' + type + '_' + id2;
        var id3 = id + 2;
        id3 = '#' + type + '_' + id3;
        var this1 = $('#' + type + '_' + id + ' :button');

        var displayState2 = $(id2).css('display');
        var displayState3 = $(id3).css('display');
        
        if (displayState2 === 'none'){
            $(id2).show();
            this1.toggleClass('selectButtonMin');
            this1.attr('title', minus);
        } else if (displayState2 === 'block'){
            if (displayState3 === 'block'){
                return;
            } else if (displayState3 === 'none'){
                $(id2).hide();
                $(id2 + " option:selected").attr('selected', '');
                $(id2 + " option[value='']").attr('selected', 'selected');
                this1.toggleClass('selectButtonMin');
                this1.attr('title', plus);
                return;
            }
        }
    } else if(id == 2) {
        var id3 = id + 1;
        id3 = '#' + type + '_' + id3;
        var this2 = $('#' + type + '_' + id + ' :button');
        
        var displayState3 = $(id3).css('display');
        
        if (displayState3 === 'none'){
            $(id3).show();
            this2.toggleClass('selectButtonMin');
            this2.attr('title', minus);
            return;
        } else if (displayState3 === 'block'){
            $(id3).hide();
            $(id3 + " option[value='']").attr('selected', 'selected');
            this2.toggleClass('selectButtonMin');
            this2.attr('title', plus);
            return;
        }
    }
}

/**
 * AJAX connections
 **/

//country selectors
$("select.ajaxSelect").live("change", function () {
    $(this).parents("form").find("input:submit[name=filter]").ajaxSubmit();
	return false;
});

$('a.ajax').live('click', function(event) {
    //event.preventDefault();
    //if ($.active) return;
    $.post(this.href, $.nette.success);

    return false;
});

$('a.ajaxRemove').live('click', function(event) {
    //event.preventDefault();
    //if ($.active) return;
    $.post(this.href, $(this).remove());

    return false;
});

function removeElement(e)
{
    $(e).remove();
}

function openArrangeMeetingForm()
{
    if ($('#orderMeetForm').length > 0){
        var form = $('#orderMeetForm');
        var displayState = form.css('display');
        
        if (displayState === 'none'){
            form.show();
            return;
        } else if (displayState === 'block'){
            form.hide();
            return;
        }
    }
    
}

function openMailFriend()
{
    if ($('#mailFriend').length > 0){
        var form = $('#mailFriend');
        var displayState = form.css('display');
        
        if (displayState === 'none'){
            form.show();
            return;
        } else if (displayState === 'block'){
            form.hide();
            return;
        }
    }
    
}

function printSection() {
    if ($('#doOrderContent5').length > 0){
        var sectionCode = $('#doOrderContent51').html();
        var host = location.hostname;
//        var path = 'http://' + host + basePath + '/print/printproduct/' + scheduleId;
        var styles = '.clearfix:after{content: ".";display: block;height: 0px;clear: both;visibility: hidden;font-size: 0;}' +
                        '.clearfix{display: inline-block;}' +
                        '* html .clearfix { height: 1%; } .clearfix { display: block; }' +
                        '.doOrderDetailBlock{margin: 0 0 20px 0;}' +
                        '.doOrderDesc{margin: 0 0 20px 0;}' +
                        '.doOrderContentTitleInline{width: 250px;font-size: 14px;font-weight: bold;float: left;display: inline;overflow: hidden;}' +
                        '.doOrderDetailContInline{float: left;display: inline;overflow: hidden;}' +
                        '.doOrderContentTitle{font-size: 14px;font-weight: bold;}' +
                        '.doOrderDetailCont{}' +
                        '.doOrderDetailPrice{width: 100px;display: inline;float: left;overflow: hidden;}' +
                        '.doOrderDetailCont label{width: 250px;font-weight: bold;float: left;display: inline;overflow: hidden;}';
        var style = "<style type=\"text/css\">" + styles + "</style>";
        
        myWindow=window.open('Print Order Details','_blank');
        myWindow.document.write(style + sectionCode);
        myWindow.document.close();
        
    } else {
        return false;
    }
}

function printProductDetail() {
    if ($('#hotelDetailsForm').length > 0){
        var termin = $('#hotelDate option:selected').text();
        
        var html1 = '<div class="hotelDetailsField clearfix">' +
                        '<label for="hotelDate">Termín:</label>' +
                        '<div class="hotelDetailsFormContent">' + termin + '</div>'+
                    '</div>';
        var html2 = $('#hotelDetailsForm').html();
//        var html2 = $('#hotelTripPrice').html();
        var html3 = $('#contMain').html();
        var host = location.hostname;
//        var path = 'http://' + host + basePath + '/print/printproduct/' + scheduleId;
        var styles = '.clearfix:after{content: ".";display: block;height: 0px;clear: both;visibility: hidden;font-size: 0;}' +
                        '.clearfix{display: inline-block;}' +
                        '* html .clearfix { height: 1%; } .clearfix { display: block; }' +
                        '.hotelDetailsField{margin: 0 0 8px 0;}' +
                        '.hotelDetailsFormContent{float: left;display: inline;overflow: hidden;}' +
                        '.hotelDetailsField label{width: 98px;margin: 0 5px 0 0;font-weight: bold;float: left;display: inline;overflow: hidden;}' +
                        '.hotelTripPrices{width: 208px;float: left;display: inline;overflow: hidden;}' +
                        '.hotelTripSale{width: 39px;float: left;display: inline;overflow: hidden;}' +
                        '.contMainTitleGreyL{margin: 20px 0 5px 0;font-size:18px;font-weight: bold;}' +
                        '.contMainContent{}' +
                        '.infoTitle{font-weight: bold;}' +
                        '.infoDescription{margin: 0 0 15px 0;}';
        var style = "<style type=\"text/css\">" + styles + "</style>";
        
        myWindow=window.open('Print Order Details','_blank');
        myWindow.document.write(style + html1 + html2 + html3);
        myWindow.document.close();
        
    } else {
        return false;
    }
}

function printCompare()
{
    if ($('.compTable').length > 0){
        var html1 = $('.compTable').html();
        var host = location.hostname;
        
        myWindow=window.open('Print Compare Page','_blank');
        myWindow.document.write(html1);
        myWindow.document.close();
        
    } else {
        return false;
    }
}

function getCookie(c_name)
{
    var i,x,y,ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x = x.replace(/^\s+|\s+$/g,"");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

function setCookie(c_name,value,exdays)
{
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

function removeSpaces(string)
{
    newstring = string.replace(/ /g, '');
    return newstring;
}

function str_split(string, number)
{
    var string_array = [];
    
    if (string.length > 3){
        var substr = '';
        for (var i = 0; i < string.length; i++){
            if ((i % number != 0) || (i == 0)){
                substr += string[i];
            } else if (i % number == 0){
                string_array.push(substr);
                var substr = '';
                substr += string[i];
            }
        }

        if (substr != ''){
            string_array.push(substr);
        }
        return string_array;
    } else {
        return string_array.push(string);
    }
}

/*
 * This function change view of price
 */
function formatPrice(price, symbol)
{
    if (jQuery.trim(price) != '') {
        var patt1 = RegExp(/,/g);
        var patt2 = RegExp(/./g);
        var priceObj = new String(price);
        var decArr = [];
        
        if (price.match(patt1) != null) {
            var priceExplode = priceObj.split(',');
            var decNew = '';
            var priceNew = '';
            
            if (priceExplode[0].length > 3) {
                var splitext = priceExplode[0].split("");
                var revertext = splitext.reverse();
                var decRev = revertext.join("");
                
                decArr = str_split(decRev, 3);
                decNew = decArr.join(' ');
                
                splitext = decNew.split("");
                revertext = splitext.reverse();
                decNew = revertext.join("");
            } else {
                decNew = priceExplode[0];
            }
            priceNew = decNew + ',' + priceExplode[1];
            
        } else if (price.match(patt2) != null) {
            var priceExplode = priceObj.split('.');
            var decNew = '';
            var priceNew = '';

            if (priceExplode[0].length > 3) {
                var splitext = priceExplode[0].split("");
                var revertext = splitext.reverse();
                var decRev = revertext.join("");
                
                decArr = str_split(decRev, 3);
                decNew = decArr.join(' ');
                
                splitext = decNew.split("");
                revertext = splitext.reverse();
                decNew = revertext.join("");
            } else {
                decNew = priceExplode[0];
            }
            priceNew = decNew + '.' + priceExplode[1];
        } else {
            var decNew = '';
            var priceNew = '';

            if (price.length > 3) {
                var splitext = price.split("");
                var revertext = splitext.reverse();
                var decRev = revertext.join("");
                
                decArr = str_split(decRev, 3);
                decNew = decArr.join(' ');
                
                splitext = decNew.split("");
                revertext = splitext.reverse();
                decNew = revertext.join("");
            } else {
                decNew = price;
            }
            priceNew = decNew;
        }
    } else {
        priceNew = price;
    }
    
    return priceNew;
}

function setDefaultFilterValues(){
    $('#frmjustoFilter-action_type-0').attr('checked', 'checked');
    $('#frmjustoFilter-country_1, #frmjustoFilter-type').val('');
}

$(document).ready(function() {
    
    /**
     * Hide Arrange meeting form on dom ready
     */
    if ($('#orderMeetForm').length > 0){
        $('#orderMeetForm').css('display', 'none');
    }
    if ($('#mailFriend').length > 0){
        $('#mailFriend').css('display', 'none');
    }
    /**
     * Set close Arrange meeting form on Close button click 
     */
    if ($('.orderMeetFormClose').length > 0){
        $('.orderMeetFormClose').click(function(){
            openArrangeMeetingForm();
        })
    }
    if ($('.mailFriendClose').length > 0){
        $('.mailFriendClose').click(function(){
            openMailFriend();
        })
    }
    
    /**
     * Scroll for Order form steps
     */
    if ($('#scrollToOrder').length > 0){
        scollWin(0, '#doOrderWrap');
    } else if ($('#oneTripBrief').length > 0){
        scollWin(0, '#oneTripBrief');
    } else if ($('#tripsTable').length > 0){
        scollWin(0, '#tripsTable');
    } else {
        $(window).scroll(function(){
            var scrollTop = $(window).scrollTop();
            setCookie('scrollJusto', scrollTop, 1);
        })
        
        var scrollCookie = getCookie('scrollJusto');
        if (scrollCookie != '' && scrollCookie != null){
            scollWin(0, scrollCookie);
        }
    }
	
    /**
     *  Hide all additional fields in search form
     */
    $('.selectWrap').hide();
    /**
     *  Show all additional fields in search form if they are not empty after refresh
     */
    $('.isSet').show().each(function(){
        var prevId = $(this).prev().attr('id');
        $('#' + prevId + ' :button').toggleClass('selectButtonMin');
    });
    
	/**
	 * Change, forward the page of product
	 */
	$('#hotelDate').change(function(){
		var url = $(this).val();
		window.location.replace(url)
	})
	
	/**
	 * This is initializes Slimbox
	 */
	if (!/android|iphone|ipod|series60|symbian|windows ce|blackberry/i.test(navigator.userAgent))
	{
		$(function($) {
			$("a[rel^='lightbox']").slimbox({
				/* Put custom options here */
				},
				null,
				function(el) {
					return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
				}
			);
		});
	}
	
	if (jQuery.trim($("#scroller").html()) != ''){
    	$("#scroller").simplyScroll({
    		speed: 11
    	});
        var totalWidth = 0;
        $("#scroller > li").each(function() {
            totalWidth += $(this).outerWidth(true);
        });
    	$("#scroller").css('width', totalWidth + 400);
	}
	
	/**
	 * Initialize left menu accordion
	 */
	initMenu();
	
	/**
	 * This is script for main menu
	 */
	$('.menuMainTop > ul > li').each(function(){
		$('.menuMainTop .menuMainBottom').hide();
		$(this).mouseover(function(){
			$(this).find('.menuMainBottom').show();
		});
		$(this).mouseout(function(){
			$(this).find('.menuMainBottom').hide();
		});
	})
	
	/**
	 * This script is for open and close advanced search field
	 */
	$('#searchPrice, #searchTransport, #searchTourType, #searchFood, #searchAdvText, #searchHotelLevel').each(function(){
		$('.advSearchWrap').hide();
		$(this).click(function(){
			var openedItem = $('#' + this.id + 'Wrap');
			openedItem.show();
			$('#' + this.id + 'Wrap > .advSearchClose').click(function(){
				openedItem.hide();
			});
		});
	});

	if ($('#frmjustoFilter-transport_type option:selected').val() != ''){
	    $('#searchTransport').addClass('redButton');
    } else {
        $('#searchTransport').removeClass('redButton');
    }
	
	$('#frmjustoFilter-transport_type').change(function(){
        var transportValue = $('#frmjustoFilter-transport_type option:selected').val();
        
        if (transportValue != ''){
            $('#searchTransport').addClass('redButton');
        } else {
            $('#searchTransport').removeClass('redButton');
        }
    });
	
    if ($('#frmjustoFilter-type option:selected').val() != ''){
        $('#searchTourType').addClass('redButton');
    } else {
        $('#searchTourType').removeClass('redButton');
    }
    
    $('#frmjustoFilter-type').change(function(){
        var typeValue = $('#frmjustoFilter-type option:selected').val();
        
        if (typeValue != ''){
            $('#searchTourType').addClass('redButton');
        } else {
            $('#searchTourType').removeClass('redButton');
        }
    });
    
    if ($('#frmjustoFilter-food_type option:selected').val() != ''){
        $('#searchFood').addClass('redButton');
    } else {
        $('#searchFood').removeClass('redButton');
    }
    
    $('#frmjustoFilter-food_type').change(function(){
        var foodValue = $('#frmjustoFilter-food_type option:selected').val();
        
        if (foodValue != ''){
            $('#searchFood').addClass('redButton');
        } else {
            $('#searchFood').removeClass('redButton');
        }
    });
    
    if ($('#frmjustoFilter-text').val() != ''){
        $('#searchAdvText').addClass('redButton');
    } else {
        $('#searchAdvText').removeClass('redButton');
    }
    
    $('#frmjustoFilter-text').change(function(){
        var textValue = $('#frmjustoFilter-text').val();
        
        if (textValue != ''){
            $('#searchAdvText').addClass('redButton');
        } else {
            $('#searchAdvText').removeClass('redButton');
        }
    });
    
    if ($('.advSearchCheckbox input:checked').length != ''){
        $('#searchHotelLevel').addClass('redButton');
    } else {
        $('#searchHotelLevel').removeClass('redButton');
    }
    
    $('#frmjustoFilter-all_levels, #frmjustoFilter-two_stars, #frmjustoFilter-three_stars, #frmjustoFilter-four_stars, #frmjustoFilter-five_stars, #frmjustoFilter-six_and_more_stars').each(function(){
        $(this).change(function(){
            var starValue = $('.advSearchCheckbox input:checked').length;
            
            if (starValue != ''){
                $('#searchHotelLevel').addClass('redButton');
            } else {
                $('#searchHotelLevel').removeClass('redButton');
            }
        });
    });
    
	/**
	 * This is datepicker for dates from search form
	 */
	var datesSearchForm = $( "#searchDateFrom, #searchDateTo" ).datepicker({
		defaultDate: null,
		numberOfMonths: 2,
		onSelect: function( selectedDate ) {
			var option = this.id == "searchDateFrom" ? "minDate" : "maxDate",
			instance = $( this ).data( "datepicker" );
			date = $.datepicker.parseDate(
			instance.settings.dateFormat ||
			$.datepicker._defaults.dateFormat,
			selectedDate, instance.settings );
			datesSearchForm.not( this ).datepicker( "option", option, date );
			$('#frmjustoFilter-sort_date_from').attr('checked', 'checked');
		},
		showOn: "both", //"button"
	    buttonImage: basePath + "/images/date.jpg",
	    buttonImageOnly: true
	});

    //$('#' + datesSearchForm[0].id).next('img').attr({ // This was causing error in IE
	$('#searchDateFrom').next('img').attr({
        alt: 'Od',
        title: 'Od'
    });
    //$('#' + datesSearchForm[1].id).next('img').attr({ // This was causing error in IE
	$('#searchDateTo').next('img').attr({
        alt: 'Do',
        title: 'Do'
    });
	
	$( "#searchDateFrom, #searchDateTo" ).each(function(){
        $(this).change(function(){
            var fromDate = $('#searchDateFrom').val();
            var toDate = $('#searchDateTo').val();
            if (fromDate != '' || toDate != ''){
                $('#frmjustoFilter-sort_date_from').attr('checked', 'checked');
            } else {
                $('#frmjustoFilter-sort_date_from').attr('checked', '');
            }
	    });
	})
//	$( "#searchDateFrom, #searchDateTo" ).each(function(){
//        var fromDate = $('#searchDateFrom').val();
//        var toDate = $('#searchDateTo').val();
//        if (fromDate != '' || toDate != ''){
//            $('#frmjustoFilter-sort_date_from').attr('checked', 'checked');
//        } else {
//            $('#frmjustoFilter-sort_date_from').attr('checked', '');
//        }
//    })
	
	/**
	 * This function set restricion on input type
	 * 
	 */
	if ($('#frm-orderStep3').length != 0) {
	    $('[id^=frmorderStep3-passengers]').each(function(){
	        var text = RegExp(/[^A-Za-zľĽšŠčČťŤžŽýÝáÁíÍéÉĺĹřŘŕŔňŇďĎúÚäÄěĚôÔóÓůŮ]/gi);
            $(this).keyup(function(){
                if (!isNaN(this.value) && this.value.match(text) == null) {
                    this.value = this.value;
                } else {
                    this.value = this.value.replace(/[^A-Za-zľĽšŠčČťŤžŽýÝáÁíÍéÉĺĹřŘŕŔňŇďĎúÚäÄěĚôÔóÓůŮ]/gi, '');
                }
            });
	    });
	}
	if ($('#frm-orderStep4').length != 0) {
        var text = RegExp(/[^A-Za-zľĽšŠčČťŤžŽýÝáÁíÍéÉĺĹřŘŕŔňŇďĎúÚäÄěĚôÔóÓůŮ]/gi);
        var rodNumber = RegExp(/[^0-9\/]/gi);
        var phone = RegExp(/[^0-9()+ ]/gi);
        $('#frmorderStep4-orderCName, #frmorderStep4-orderCSurname').each(function(){
            $(this).keyup(function(){
                if (!isNaN(this.value) && this.value.match(text) == null) {
                    this.value = this.value;
                } else {
                    this.value = this.value.replace(/[^A-Za-zľĽšŠčČťŤžŽýÝáÁíÍéÉĺĹřŘŕŔňŇďĎúÚäÄěĚôÔóÓůŮ]/gi, '');
                }
            });
        });
        $('#frmorderStep4-orderCId').each(function(){
            $(this).keyup(function(){
                if (!isNaN(this.value) && this.value.match(rodNumber) == null) {
                    this.value = this.value;
                } else {
                    this.value = this.value.replace(/[^0-9\/]/gi, '');
                }
            });
        });
        $('#frmorderStep4-orderCPhone').each(function(){
            $(this).keyup(function(){
                if (!isNaN(this.value) && this.value.match(phone) == null) {
                    this.value = this.value;
                } else {
                    this.value = this.value.replace(/[^0-9()+ ]/gi, '');
                }
            });
        });
    }
	if ($('#frm-orderStep6').length != 0) {
        var text = RegExp(/[^A-Za-zľĽšŠčČťŤžŽýÝáÁíÍéÉĺĹřŘŕŔňŇďĎúÚäÄěĚôÔóÓůŮ]/gi);
        var rodNumber = RegExp(/[^0-9\/]/gi);
        var phone = RegExp(/[^0-9()+ ]/gi);
        $('[id^=frmorderStep6-passengersAdult-orderAdultName], [id^=frmorderStep6-passengersAdult-orderAdultSurname], [id^=frmorderStep6-passengersNonAdult-orderNonAdultName], [id^=frmorderStep6-passengersNonAdult-orderNonAdultSurname], #frmorderStep6-buyerContactName, #frmorderStep6-buyerContactSurname').each(function(){
            $(this).keyup(function(){
                if (!isNaN(this.value) && this.value.match(text) == null) {
                    this.value = this.value;
                } else {
                    this.value = this.value.replace(/[^A-Za-zľĽšŠčČťŤžŽýÝáÁíÍéÉĺĹřŘŕŔňŇďĎúÚäÄěĚôÔóÓůŮ]/gi, '');
                }
            });
        });
        $('[id^=frmorderStep6-passengersAdult-orderAdultId], [id^=frmorderStep6-passengersNonAdult-orderNonAdultId], #frmorderStep6-buyerContactId').each(function(){
            $(this).keyup(function(){
                if (!isNaN(this.value) && this.value.match(rodNumber) == null) {
                    this.value = this.value;
                } else {
                    this.value = this.value.replace(/[^0-9\/]/gi, '');
                }
            });
        });
        $('[id^=frmorderStep6-passengersAdult-orderAdultPhone], [id^=frmorderStep6-passengersNonAdult-orderNonAdultPhone], #frmorderStep6-buyerContactPhone').each(function(){
            $(this).keyup(function(){
                if (!isNaN(this.value) && this.value.match(phone) == null) {
                    this.value = this.value;
                } else {
                    this.value = this.value.replace(/[^0-9()+ ]/gi, '');
                }
            });
        });
    }
	
	
	/**
     * This function calculate prices according to quantity in Step2 of Order form
     *
     */
	if ($('#frm-orderStep2').length != 0){
	    
        $('[id^=frmorderStep2-price]').each(function(){
            $(this).keyup(function(){
                if (!isNaN(parseInt(this.value,10))) {
                    this.value = parseInt(this.value);
                } else {
                    this.value = 0;
                }
                this.value = this.value.replace(/[^0-9]/g, '');
                if (parseInt(this.value,10) > 100) {
                    this.value = 100;
                    return;
                }
                
                
                var qty = $(this).val();
                if (qty == ''){
                    qty = 0;
                }
                currentPriceE = $(this).parents('tr').find('[id^=currentPriceE]').text();
                currentPriceE = currentPriceE.split(' ').join('');
                currentPriceS = $(this).parents('tr').find('[id^=currentPriceS]').text();
                currentPriceS = currentPriceS.split(' ').join('');
                calcPriceE = formatPrice((Math.round(qty*currentPriceE*1000)/1000).toFixed(2), ' ');
                calcPriceS = formatPrice((Math.round(qty*currentPriceS*1000)/1000).toFixed(2), ' ');
                $(this).parents('tr').find('[id^=priceE]').text(calcPriceE);
                $(this).parents('tr').find('[id^=priceS]').text(calcPriceS);
    
                var totalPriceEC = totalPriceSC = 0.0;
                $(this).parents('table').find('[id^=priceE]').each(function(){
                    if ($(this).text() != 0){
                        totalPriceEC += parseFloat($(this).text().split(' ').join(''));
                    }
                })
                $('#totalPriceE').text(formatPrice(totalPriceEC.toFixed(2), ' '));
                
                $(this).parents('table').find('[id^=priceS]').each(function(){
                    if ($(this).text() != 0){
                        totalPriceSC += parseFloat($(this).text().split(' ').join(''));
                    }
                })
                totalPriceSC = formatPrice((Math.round(totalPriceSC*1000)/1000).toFixed(2), ' ');
                $('#totalPriceS').text(totalPriceSC);
            })
        })        
        
    	var totalPriceE = totalPriceS = 0.0;
    	$('[id^=frmorderStep2-price]').each(function(){
    	    var qty = $(this).val();
    	    if (qty == ''){
                qty = 0;
            }
	        currentPriceE = $(this).parents('tr').find('[id^=currentPriceE]').text();
            currentPriceE = currentPriceE.split(' ').join('');
            currentPriceS = $(this).parents('tr').find('[id^=currentPriceS]').text();
            currentPriceS = currentPriceS.split(' ').join('');
	        calcPriceE = Math.round(qty*currentPriceE*1000)/1000;
	        calcPriceS = Math.round(qty*currentPriceS*1000)/1000;
	        $(this).parents('tr').find('[id^=priceE]').text(formatPrice((calcPriceE).toFixed(2), ' '));
            $(this).parents('tr').find('[id^=priceS]').text(formatPrice((calcPriceS).toFixed(2), ' '));

            totalPriceE += calcPriceE;
            totalPriceS += calcPriceS;
    	})
    	
        totalPriceE = formatPrice((Math.round(totalPriceE*1000)/1000).toFixed(2), ' ');
        totalPriceS = formatPrice((Math.round(totalPriceS*1000)/1000).toFixed(2), ' ');
        $('#totalPriceE').text(totalPriceE);
        $('#totalPriceS').text(totalPriceS);
	}
	
	/**
	 * This function add/remove passengers quantity in Step3 of Order form
	 * Adults
	 */
	$('#orderAdultTable tr, #orderNonAdultTable tr').hide();
	
	var adultNum = $('#frmorderStep3-orderAdultNum option:selected').val();
	if (adultNum == ''){
        $('#orderAdultTable tr').each(function(){
            $(this).find('input').val('');
        })
        $('#orderAdultTable tr').hide();
    } else {
        var adultInfo = $('#orderAdultTable tr');
        adultInfo.each(function(index){
            if(index <= adultNum){
              $(this).show();
            } else {
                $(this).find('input').val('');
                $(this).hide();
            }
        })
    }
	$('#frmorderStep3-orderAdultNum').change(function(){
	    var adultNum = $('#frmorderStep3-orderAdultNum option:selected').val();
	    if (adultNum == ''){
	        $('#orderAdultTable tr').each(function(){
	            $(this).find('input').val('');
	        })
	        $('#orderAdultTable tr').hide();
	    } else {
	        var adultInfo = $('#orderAdultTable tr');
            adultInfo.each(function(index){
                if(index <= adultNum){
                  $(this).show();
                } else {
                    $(this).find('input').val('');
                    $(this).hide();
                }
            })
	    }
	})
	
	/**
	 * This function add/remove passengers quantity in Step3 of Order form
     * NonAdults
	 */
	var adultNum = $('#frmorderStep3-orderNonAdultsNum option:selected').val();
    if (adultNum == ''){
        $('#orderNonAdultTable tr').each(function(){
            $(this).find('input').val('');
        })
        $('#orderNonAdultTable tr').hide();
    } else {
        var adultInfo = $('#orderNonAdultTable tr');
        adultInfo.each(function(index){
            if(index <= adultNum){
              $(this).show();
            } else {
                $(this).find('input').val('');
                $(this).hide();
            }
        })
    }
    $('#frmorderStep3-orderNonAdultsNum').change(function(){
        var adultNum = $('#frmorderStep3-orderNonAdultsNum option:selected').val();
        if (adultNum == ''){
            $('#orderNonAdultTable tr').each(function(){
                $(this).find('input').val('');
            })
            $('#orderNonAdultTable tr').hide();
        } else {
            var adultInfo = $('#orderNonAdultTable tr');
            adultInfo.each(function(index){
                if(index <= adultNum){
                  $(this).show();
                } else {
                    $(this).find('input').val('');
                    $(this).hide();
                }
            })
        }
    })
	
	/**
	 * This even set on hotels rows.
	 * On click it toggle background and show hotel brief details.
	 * On load the position of hotel brief details changed according their qty.
	 */
    var rowsQty = $('.tripView').length;
    if (rowsQty > 5){
        $('.tripView').each(function(i){
            if (i >= rowsQty / 2 ){
                $(this).css({
                    bottom: '46px',
                    right: '21px'
                });
            }
        });
    }
	$('.tripsTableTd').each(function(){
		$('.tripView').hide();
		$('.favcompbuttons').hide();
		$('.tdItemWrap').click(function(){
		    
		    if ($('#tripsTable').length > 0){
		        scollWin(0, '#tripsTable');
		    } else if ($('.topTrips').length > 0){
		        scollWin(0, '.topTrips');
		    }
			$('.tripView').hide();
			$('.favcompbuttons').hide();
			$('.tdItemWrap').removeClass('selected');
			$(this).toggleClass('selected');
			$(this).find('.favcompbuttons').show();
			$(this).next('.tripView').show();
		});
		
		$(this).children('.tripView').children('.tripClose').click(function(){
			$(this).parents('.tripView').hide();
			$(this).parents('.tripView').prev('.tdItemWrap').removeClass('selected');
			$('.favcompbuttons').hide();
		});
	});

	/**
	 * This script set srcs for hotel mini details
	 * and change pic on hover
	 */
    $('.tripPics').each(function(){
            $(this).children('.mainPic').children('img').attr('src', $(this).children('.restPics').children('.tripPic').children('img').attr('src'));//.replace('_small.', '_medium.'));
            $('.tripPic').hover(function(){
                    $(this).parents('.restPics').prev('.mainPic').children('img').attr('src', $(this).children('img').attr('src'));//.replace('_small.', '_medium.'));
            }, function(){
                var a = 1;
            });
    });
    
    /**
     * This is datepicker for dates from Arrange Meeting form
     */
    var dateArrangeMeetingForm = $( "#arrangeMeetingDate" ).datepicker({
        defaultDate: null,
        numberOfMonths: 1,
        onSelect: function( selectedDate ) {
            var option = this.id == "arrangeMeetingDate",
            instance = $( this ).data( "datepicker" );
            date = $.datepicker.parseDate(
            instance.settings.dateFormat ||
            $.datepicker._defaults.dateFormat,
            selectedDate, instance.settings );
            datesSearchForm.not( this ).datepicker( "option", option, date );
        },
        showOn: "both", //"button"
        buttonImage: basePath + "/images/date.jpg",
        buttonImageOnly: true
    });
    $('#arrangeMeetingDate').next('img').attr({
        alt: 'Dátum stretnutia',
        title: 'Dátum stretnutia'
    });

    //$('li.red > a, li.blue > a, li.green > a, li.brown > a').attr('href', 'Javascript:void(0);');
    //$('li.greyDark > a:eq(0)').attr('href', 'Javascript:void(0);');
    //$('li.greyDark > a:eq(1)').attr('href', 'Javascript:void(0);');
    
    /*$('li.red > a').click(function() {
        setDefaultFilterValues();
        var componentName = 'justoFilter';
        $('#frm' + componentName + '-action_type-1').attr('checked', 'checked');

        $('#frm-' + componentName).submit();
    });
    $('li.blue > a').click(function() {
        setDefaultFilterValues();
        var componentName = 'justoFilter';   
        $('#frm-' + componentName).submit();
    });
    $('li.green > a').click(function() {
        setDefaultFilterValues();
        var componentName = 'justoFilter';
        $('#frm' + componentName + '-type').val('3');
    
        $('#frm-' + componentName).submit();
    });    
    $('li.brown > a').click(function() {
        setDefaultFilterValues();
        var componentName = 'justoFilter';
        $('#frm' + componentName + '-type').val('5');

        $('#frm-' + componentName).submit();
    });
    $('li.greyDark > a:eq(0)').click(function() {
        setDefaultFilterValues();
        var componentName = 'justoFilter';
        var countryId = '';
        var countryExists = false;
        $('#frmjustoFilter-country_1 > option').each(function(){
            if ($(this).text() == 'Slovensko') {
                countryId = $(this).val();
                countryExists = true;
            }
        });
        if (countryExists) {
            $('#frm' + componentName + '-country_1').val(countryId);
            $('#frm' + componentName + '-country_2').val('');
            $('#frm' + componentName + '-country_3').val('');
    
            $('#frm-' + componentName).submit();
        }
    });
    */
    /*$('li.greyDark > a:eq(1)').click(function() {
        setDefaultFilterValues();
        var componentName = 'justoFilter';
        $('#frm' + componentName + '-type').val('4');

        $('#frm-' + componentName).submit();
    });*/
});

