﻿/// <reference path="jquery-1.5.2.min.js"/>

var _scrollTo = { offset: -40 };

/* fast fixes */
$(function() {

    // text-toggle
    $('.text-togglable').each(function() {
        if (!$('.text-collapsed .text-toggle', this).length) {
            $('.text-collapsed', this).append('<p><a href="#" class="text-toggle">Свернуть</a></p>');
        }

        $('a.text-toggle', this).each(function() {
            var $toggle = $(this);

            if (!$(this).parents('.text-collapsed').length)
                $(this).addClass('text-toggle-preview');
        });
    });

    // righttext
    $('.righttext').each(function() {
        if ($(this).text().replace(/([^\da-zа-я])/gi, '') == '')
            $(this).remove();
    });
    $('.righttext').last().addClass('righttext-last');

    // breadcrumbs
    $('.breadcrumbs ul li.active').each(function() {
        $(this).prependTo($(this).parent());
    });

    // manager-cards-bottom
    $('.manager-cards-bottom .manager-card').filter(function(index) {
        return !(index % 5);
    }).css({ clear: 'left' });

    //empty gal
    $('.gal').each(function() {
        if ($('img', this).length == 0)
            $(this).remove();
    });
});


/* */
$(function() {

    $('a[rel*=blank]').click(function() {
        window.open($(this).attr('href'));
        return false;
    });

    $('a.print').click(function() {
        window.print();
        return false;
    });


    $('.fancy a').attr('rel', 'fancy').fancybox();

    $('input.hint, textarea.hint').attr({
        autocomplete: 'off'
    }).focus(function() {
        if ($(this).val() == $(this).attr('title'))
            $(this).removeClass('hint').val('');
    }).blur(function() {
        if ($(this).val().replace(/\s/g, '') == '')
            $(this).addClass('hint').val($(this).attr('title'));
    });

    $('.validators-check-onfocus').bind('focus keyup change blur', function() {
        var $input = $(this).parents('.input');
        setTimeout(function() {
            if ($input.find('.validator:visible').length)
                $input.addClass('input-error');
            else
                $input.removeClass('input-error');
        }, 50);
    });

    $('.tooltip').each(function() {
        $(this).append('<span class="tip">' + $(this).attr('title') + ' <i></i></span>');
        $(this).removeAttr('title');
    }).hover(function() {
        var $tip = $('.tip', this);
        $tip.css({
            left: 0 - Math.round(($tip.outerWidth() - $(this).width()) / 2)
        });
    }, function() {
        $('.tip', this).css({ left: -9999 });
    });

    $('.popup').appendTo('body');
    $('a.popup-toggle, .popup-toggle a').click(function() {
        var $popup = $($(this).attr('href'));
        $('body').append('<div id="fader" />');
        $('#fader').css({
            cursor: 'pointer'
        }).click(function() {
            $('.popup').css({
                left: -10000,
                top: -10000
            });
            $('#fader').remove();
        });
        $popup.css({
            left: '50%',
            top: $(window).scrollTop() + Math.ceil(($(window).height() - $popup.outerHeight()) / 2)
        });

        if ($(this).attr('rel') && $(this).attr('rel').length)
            eval($(this).attr('rel'), window);

        return false;
    });
    $('.popup .close').click(function() {
        $(this).parents('.popup').css({
            left: -10000,
            top: -10000
        });
        $('#fader').remove();
        return false;
    });

    $('.map-block').css({ cursor: 'pointer' }).click(function() {
        $('.popup-toggle a', this).click();
        return false;
    });

    // index
    $('.variants h2 a').click(function() {
        var $div = $(this).parent().next('div');
        if ($div.is(':animated'))
            return false;

        var height = $div.find('a:eq(0)').outerHeight();
        if ($div.hasClass('collapsed'))
            height *= Math.ceil($('.variants .tour-type').length / 8);

        $div.animate({
            height: height
        }, 500, function() {
            $div.toggleClass('collapsed').toggleClass('expanded');
        });
        return false;
    });

    $('.chooseonmap h2 a, .chooseonmap button').click(function() {
        $('.chooseonmap .list').toggle();
        var $button = $('.chooseonmap button'),
		        swap = $button.text();

        $button.text($button.attr('rel'));
        $button.attr('rel', swap);

        var enable = true;
        if ($('.chooseonmap .list').is(':visible')) {
            enable = false;
        }
        getMovie('map').enableMap(enable);

        return false;
    });


    $('#menu .submenu').each(function() {
        popup_shadow($(this));
    });
    $('.agentline .hassub ul').each(function() {
        popup_shadow($(this), 8, 'popup-shadow-light');
    });

    $('.agentline .nonauth a.login').click(function() {
        $(this).toggleClass('active');
        $('.agentline .nonauth .form').toggle();
        return false;
    });

    $('.text-toggle').click(function() {
        if ($(this).parents('.text-togglable')
			     .find('.text-collapsed, .text-expanded')
			     .toggleClass('text-collapsed')
			     .toggleClass('text-expanded').attr('class') == 'text-expanded'
			     && $(this).is('.text-toggle-preview')) {
            $(this).parents('.text-togglable').find('.text-toggle-preview').hide();
        } else {
            $(this).parents('.text-togglable').find('.text-toggle-preview').show();
            $.scrollTo($(this).parents('.maintext'), 500, _scrollTo);
        }

        return false;
    });

    $('.breadcrumbs .hassub').mouseenter(function() {
        $('.breadcrumbs .hasshown').removeClass('hasshown');
        $(this).parents('li').addClass('hasshown');
        return false;
    });
    $('.breadcrumbs .pos').mouseleave(function() {
        $(this).parents('.hasshown').removeClass('hasshown');
    });
    $('.breadcrumbs .close').click(function() {
        $(this).parents('.hasshown').removeClass('hasshown');
        return false;
    });

    $('.spos h2 a').click(function() {
        $(this).parents('.spos').toggleClass('spos-collapsed').toggleClass('spos-expanded');
        return false;
    });


    $('.prices table').each(function() {
        var $table = $(this);
        var $trs = $('tr:has(th.days), tr:has(td)', $table);
        var i;


        $('th.days, td:not(.title)', $table).hover(function() {
            var $tds = $(this).parents('tr').children();
            i = $tds.index(this);
            $trs.each(function() {
                $(this).children().eq(i).addClass('hover');
            });
        }, function() {
            $trs.each(function() {
                $(this).children().eq(i).removeClass('hover');
            });
        });
    });


    $('.hotel-review-form input').attr({ autocomplete: 'off' });

    $('.hotel-review-form .rates i').mouseover(function() {
        var $p = $(this).parent();
        var cl = $p.attr('class');
        cl = cl.replace(/[^\s]+\d+/g, '').replace(/\s/g, '');
        cl = cl + ' rate' + ($(this).prevAll().length * 10);
        $p.attr('class', cl);
    }).mouseout(function() {
        var $p = $(this).parent();
        var cl = $p.attr('class');
        cl = cl.replace(/[^\s]+\d+/g, '').replace(/\s/g, '');
        cl = cl + ' rate' + ($p.find('input').val() * 10);
        $p.attr('class', cl);
    }).click(function() {
        $(this).parent().find('input').val($(this).prevAll().length);
    });

    $('ul.hotels, .hotel_results_wrap').delegate('.img', 'mouseenter', function(e) {
        if ($('img', this).attr('src').match(/nohotel.gif$/)) {
            return;
        }
        $('body').append('<div class="topmost hotels" />');
        $('.topmost.hotels').html($('span', this).html()).css({
            left: e.pageX + 10,
            top: e.pageY + 10,
            zoom: 1
        });
    }).delegate('.img', 'mousemove', function(e) {
        if ($('img', this).attr('src').match(/nohotel.gif$/)) {
            return;
        }
        $('.topmost.hotels').css({
            left: e.pageX + 10,
            top: e.pageY + 10
        });
    }).delegate('.img', 'mouseleave', function() {
        if ($('img', this).attr('src').match(/nohotel.gif$/)) {
            return;
        }
        $('.topmost.hotels').remove();
    });


    $('.white-submenu .tospos').click(function() {
        $('#spos h2 a').click();
        return false;
    });
    $('.white-submenu .scrollto').click(function() {
        var $to = $($(this).attr('href'));
        if ($to.length) {
            $.scrollTo($to, 'slow', _scrollTo);
        }
        return false;
    });
    $('.section-menu a.spo').click(function() {
        if ($('#spos').length) {
            $('#spos h2 a').click();
            $.scrollTo($('#spos'), 'slow', _scrollTo);
        }
    });

    if (document.location.hash == '#spos')
        $('#spos h2 a').click();

    if (/^#[a-z0-9_-]+$/.test(document.location.hash)) {
        var $anchor = $(document.location.hash);
        if ($anchor.length)
            $.scrollTo($anchor, 'slow', _scrollTo);
    }
});


/*** gallery ***/
$(function() {
    var li_width = 106,
        car_anim = 150,
        big_anim = 500;

    $('.gal').each(function() {
        var $gal = $(this),
            $car = $('.carousel', this),
            $lis = $('li', $car),
            $big = $('.active-big', $gal),
            lis_width = $lis.length * li_width,
            gal_width = $gal.width();

        $car.width(lis_width);

        if (lis_width <= gal_width) {
            $('.prev, .next', $gal).remove();
        }
        
        function gal_scroll(nextpos, time) {
            if (nextpos > 0)
                nextpos = 0;
            if (nextpos < 0 - lis_width + gal_width)
                nextpos = 0 - lis_width + gal_width;

            if (nextpos == 0) {
                $('.prev', $gal).hide();
            } else {
                $('.prev', $gal).show();
            }

            if (nextpos == 0 - lis_width + gal_width) {
                $('.next', $gal).hide();
            } else {
                $('.next', $gal).show();
            }

            if (nextpos <= 0 && nextpos >= 0 - lis_width + gal_width) {
                $car.animate({
                    left: nextpos
                }, time);
            }
        }

        $('.prev, .next', $gal).click(function() {
            if ($car.is(':animated'))
                return false;

            var pos = $car.position().left,
                nextpos = pos;

            if ($(this).hasClass('prev')) {
                nextpos += li_width * 4;
            } else {
                nextpos -= li_width * 4;
            }

            gal_scroll(nextpos, car_anim * 4);

            return false;
        });

        var $img = $('img', $big);
        $img.load(function() {
            var height = $img.height(),
                width = $img.width();
            $img.css({
                position: 'absolute',
                left: '50%',
                top: 0,
                marginLeft: 0 - Math.round(width / 2)
            });
            $big.css({
                paddingTop: height
            });
        });
        setTimeout(function() {
            $img.trigger('load');
        }, 500);


        $('a', $car).click(function() {
            if ($big.is(':animated'))
                return false;

            var alt = $(this).next('span').text(),
                title = $(this).next('span').html(),
                $img = $('<img src="' + $(this).attr('href') + '" alt="' + alt + '" />'),
                $active = $('img', $big),
                $span = $('span', $big);

            $('li.active', $car).removeClass('active');
            $(this).parents('li').addClass('active');

            $img.css({
                position: 'absolute',
                left: '50%',
                top: 0,
                opacity: 0
            }).prependTo($big).load(function() {
                var width = $img.width(),
                    height = $img.height();
                $img.css({
                    marginLeft: 0 - Math.round(width / 2)
                }).animate({
                    opacity: 1
                }, big_anim);

                $active.animate({
                    opacity: 0
                }, big_anim, function() {
                    $active.remove();
                });

                $big.animate({
                    paddingTop: height
                }, big_anim);

                $span.animate({
                    opacity: 0
                }, big_anim / 2, function() {
                    $span.html(title).animate({
                        opacity: 1
                    }, big_anim / 2, function() {
                        $span.clearTypeFix();
                    });
                });

            });

            return false;
        });

        if ($lis.length == 1) {
            $('img', $big).css({ cursor: 'default' });
        } else {

            $big.delegate('img', 'click', function() {
                if ($big.is(':animated'))
                    return false;

                if ($car.is(':animated'))
                    return false;

                var $li = $car.find('li.active').next('li').eq(0);
                if (!$li.length)
                    $li = $lis.eq(0);

                $('a', $li).click();

                var car_pos = $car.position().left,
                    li_pos = $li.position().left;

                if (car_pos + li_pos >= gal_width || car_pos + li_pos <= 0) {
                    var nextpos = 0 - li_pos;
                    gal_scroll(nextpos, Math.min(
                        Math.abs(nextpos - car_pos) / li_width * car_anim,
                        2000
                    ));
                }

                return false;
            });
        
        }

    });
});



/*** popup shadow ***/
function popup_shadow($popup, padding, cssclass) {
    if (typeof $popup == 'undefined' || !$popup.length)
        return;
    if (typeof padding == 'undefined')
    	padding = 9;
    if (typeof cssclass == 'undefined')
    	cssclass = 'popup-shadow';
    else
        cssclass = 'popup-shadow ' + cssclass;	
        
    $popup.append('<table class="' + cssclass + '">' +
        '<tr><td class="lt" width="20" height="20" /><td class="t" /><td class="rt" width="20" height="20" /></tr>' +
        '<tr><td class="l" /><td /><td class="r" /></tr>' +
        '<tr><td class="lb" /><td class="b" /><td class="rb" /></tr>' +
        '</table>'
    );
    var width = $popup.outerWidth() + padding * 2;
    var height = $popup.outerHeight() + padding * 2;
    $shadow = $popup.find('.popup-shadow')
        .css({
            display: 'none',
            marginLeft: parseInt($popup.css('margin-left')) - padding,
            marginTop: parseInt($popup.css('margin-top')) - padding
        })
        .find('.lt, .rb').css({padding: 0}).html('<div style="width:20px;" />').end()
        .find('.t').css({ padding: 0 }).html('<div style="width:' + (width - 40) + 'px;" />').end()
        .find('.l').height(height - 40).end()
        .show();
}

function popup_unshadow($popup) {
    $popup.find('.popup-shadow').remove();
}

var $botline;
function botline_attach() {
    var bot = $('#footer').offset().top;
    var scroll = (document.documentElement.scrollTop || self.pageYOffset || 0);
    if (bot <= scroll + $(window).height()) {
        $botline.addClass('botline-attached').css({ bottom: $('#footer').outerHeight() });
    } else {
        $botline.removeClass('botline-attached').css({ bottom: 0 });
    }
}

$(function() {
    $botline = $('.botline');
    if ($botline.length) {
        $(window).bind('scroll', botline_attach);
        botline_attach();
    }
});



/* search_results */
$(function() {
    $('.section-menu').find('a[href$=search]').click(function() {
        if (typeof formCookie != 'undefined')
            $.cookie('formCookie', formCookie, { path: '/' });
        return true;
    });



    $('.search_results .scrollpane').jScrollPane({
        autoReinitialise: true
    });

    $('input, select,textarea', '.searchform, .pickform').attr({ autocomplete: 'off' });
    
});


/* hotel reviews */
$(function() {
    $('.hotelReviewsPaginated').delegate('.paginator a', 'click', function() {
        current_page = $(this).attr('href').replace('?p=', '');
        $.ajax({
            url: '/ws/hotel.asmx/getHotelReviews',
            type: 'GET',
            contentType: 'application/json',
            dataType: 'json',
            data: {
                hotel_id: '"' + hotel_id + '"',
                page: '"' + current_page + '"',
                hotel_url: '"' + hotel_url + '"'
            },
            error: function() {
                alert('Произошла ошибка');
            },
            success: function(json) {
                $('.hotelReviewsPaginated .white').
                    find('dl, .paginator').remove().end()
                    .append(json.d);

                $.scrollTo('.hotelReviewsPaginated', 350, _scrollTo);
            }
        });

        return false;
    });


    $('.review-form button').click(function() {
        if ($('.review-form .user_name').val().replace(/\s/g, '') == '') {
            alert('Введите имя');
            $('.review-form .user_name').focus();
            return false;
        }
        if ($('.review-form .user_mail').val().replace(/\s/g, '') == '') {
            alert('Введите e-mail');
            $('.review-form .user_mail').focus();
            return false;
        }
        var re = /^([0-9a-zA-Z\.\-_]+)@([0-9a-zA-Z\.\-_]+)\.(.)+$/;
        if ($('.review-form .user_mail').val().match(re) == null) {
            alert('Введите корректный e-mail');
            $('.review-form .user_mail').focus();
            return false;
        }

        if ($('.review-form').hasClass('hotel-review-form')) {
            if ($('.hotel-review-form .rate1').val() == '-1'
                || $('.hotel-review-form .rate2').val() == '-1'
                || $('.hotel-review-form .rate3').val() == '-1') {
                alert('Оцените номера, питание и сервис');
                return false;
            }
        }
        if ($('.review-form .comment_plus').val().replace(/\s/g, '') == ''
           || $('.review-form .comment_plus').val() == $('.review-form .comment_plus').attr('title')) {
            alert('Опишите плюсы');
            $('.review-form .comment_plus').focus();
            return false;
        }
        if ($('.review-form .comment_minus').val().replace(/\s/g, '') == ''
           || $('.review-form .comment_minus').val() == $('.review-form .comment_minus').attr('title')) {
            alert('Опишите минусы');
            $('.review-form .comment_minus').focus();
            return false;
        }

        var data = "{" +
            'user_name: "' + $('.review-form .user_name').val().replace(/"/g, '&quot;') + '"' +
           ',user_mail: "' + $('.review-form .user_mail').val().replace(/"/g, '&quot;') + '"' +
           ',comment_plus: "' + $('.review-form .comment_plus').val().replace(/"/g, '&quot;') + '"' +
           ',comment_minus: "' + $('.review-form .comment_minus').val().replace(/"/g, '&quot;') + '"';
        var url;

        if ($('.review-form').hasClass('hotel-review-form')) {
            data += ",hotel_id:" + hotel_id +
                    ',rate1: ' + $('.hotel-review-form .rate1').val().replace(/"/g, '&quot;') +
                    ',rate2: ' + $('.hotel-review-form .rate2').val().replace(/"/g, '&quot;') +
                    ',rate3: ' + $('.hotel-review-form .rate3').val().replace(/"/g, '&quot;');
            url = '/ws/hotel.asmx/addHotelReview';
        } else if ($('.review-form').hasClass('city-review-form')) {
            data += ",city_id:" + city_id;
            url = '/ws/reviews.asmx/addCityReview';
        } else if ($('.review-form').hasClass('country-review-form')) {
            data += ",country_id:" + country_id;
            url = '/ws/reviews.asmx/addCountryReview';
        }

        data += '}';

        if (!url) {
            alert('Произошла ошибка');
            return false;
        }

        $.ajax({
            type: 'POST',
            url: url,
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: data,
            error: function() {
                alert('Произошла ошибка');
            },
            success: function(json) {
                if (json.d) {
                    $('.review-form').hide();
                    $('.review-form-ok').show();
                } else {
                    alert('Произошла ошибка');
                }
            }
        });

        return false;
    });
});


/* Tour types by Vova */
$(function() {
    if (typeof tourTypeKey == 'undefined')
        tourTypeKey = 0;

    var tourTypeCountry = 0,
        tourTypeRegion = 0;


    $('.tour_types_tbl').delegate('.paginator a', 'click', function() {
        var match = $(this).attr('href').match(/=([\d]+)$/);
        if (match == null) {
            current_page = 1;
        }
        else if (match.length == 2) {
            current_page = match[1];
        }
        $.ajax({
            url: '/ws/tourtype.asmx/getSpos',
            type: 'GET',
            contentType: 'application/json',
            dataType: 'json',
            data: {
                tourTypeKey: tourTypeKey,
                country_id: tourTypeCountry,
                region_id: tourTypeRegion,
                page: current_page,
                sort: current_sort
            },
            error: function() {
                alert('Произошла ошибка');
            },
            success: function(json) {
                $('.tour_types_tbl').empty().append(json.d).find('.popup').remove();
                $.scrollTo('.tour_types_tbl', 350, _scrollTo);
            }
        });

        return false;
    });

    $('.tour_types_tbl').delegate('th > a', 'click', function() {
        sposrel = $(this).attr('rel');
        $.ajax({
            url: '/ws/tourtype.asmx/getSpos',
            type: 'GET',
            contentType: 'application/json',
            dataType: 'json',
            data: {
                tourTypeKey: tourTypeKey,
                country_id: tourTypeCountry,
                region_id: tourTypeRegion,
                page: 1,
                sort: sposrel
            },
            error: function() {
                alert('Произошла ошибка');
            },
            success: function(json) {
                current_sort = sposrel;
                $('.tour_types_tbl').empty().append(json.d).find('.popup').remove();
            }
        });

        return false
    });

    $('.tour_types_list a').click(function() {
        var rel = parseInt($(this).attr('rel').replace('r', ''));
        if (rel == NaN)
            return false;

        if ($(this).is('.tour_types_list div a')) {
            tourTypeRegion = rel;
            tourTypeCountry = 0;
            $('.tour_types_list .active').removeClass('active');
            $(this).closest('li').addClass('active');
        } else {
            tourTypeRegion = 0;
            tourTypeCountry = rel;
            $('.tour_types_list td').removeClass('active');
            $(this).closest('td').addClass('active');
        }


        current_page = 1;
        current_sort = 0;

        $.ajax({
            url: '/ws/tourtype.asmx/getSpos',
            type: 'GET',
            contentType: 'application/json',
            dataType: 'json',
            data: {
                tourTypeKey: tourTypeKey,
                country_id: tourTypeCountry,
                region_id: tourTypeRegion,
                page: current_page,
                sort: current_sort
            },
            error: function() {
                alert('Произошла ошибка');
            },
            success: function(json) {
                $('.tour_types_tbl').empty().append(json.d).find('.popup').remove();
            }
        });

        return false;
    });


});

// out of popup click, maybe you should stop click event before popup showing
;   function stopEvent(e){if(e.preventDefault){e.preventDefault();e.stopPropagation();}else{e.returnValue=false;e.cancelBubble=true;}return false;}
; (function($) {
    $.event.special.clickOriginal = $.event.special.click;
    
    $.hideOnOuterClickHandle = null;
    
    $.event.special.click = {
	add: function( handleObj ) {
		var handler = handleObj.handler;
		handleObj.handler = function(e) {
			if (typeof $.hideOnOuterClickHandle == 'function')
	    			$.hideOnOuterClickHandle(e);	
			return handler.apply(this, arguments);
		};
	}
    };
    
    $.fn.hideOnOuterClick = function(event, callback) {
    	if (typeof event !== 'undefined')
    		stopEvent(event);
    		
        return this.each(function() {
            var $popup = $(this);

            var hide = function() {
                if (typeof callback == 'function')
                    callback($popup);
                $popup.hide();
                off();
            };
		
	    var check = function(e) {
	        var trgt = e.target;
                var curElements = $popup.find('*').andSelf();
                if ($.inArray(trgt, curElements) < 0) {
                    hide();
                }
	    }		
		
            var blur = function(e) {
                check(e);
            };
            
            var on = function() {
		$(document).bind('click', blur);
		$.hideOnOuterClickHandle = check;
	    };
	    
	    var off = function() {
	    	$(document).unbind('click', blur);
	    	$.hideOnOuterClickHandle = null;
	    };

            if (!$(this).is(':visible')) {
                off();
                return;
            }
            
            on();
            
        });
    };
})(jQuery);


function getMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
	return window[movieName];
    } else {
	return document[movieName];
    }
}

// index animations
$(function() {

    var $propositions = $('.propositions-index');
    $('ul', $propositions).each(function() {
        var $lis = $('li', this);
        var width = $lis.eq(0).outerWidth(true);
        $(this).width(width * $lis.length + 8);
    });

    var $index_banners = $('.overflow', $propositions),
        jsp_api = $index_banners.jScrollPane().data('jsp');

    if (jsp_api && jsp_api.getIsScrollableH()) {
        setInterval(function() {
            var pos = jsp_api.getContentPositionX(),
                time;
            if (pos + 1008 < jsp_api.getContentWidth()) {
                pos += 199;
                pos = Math.floor(pos / 199) * 199;
                time = 250;
            } else {
                pos = 0;
                time = 2000;
            }
            jsp_api.scrollToXdur(pos, true, time);
            setTimeout(function() {
                uncomment_next($index_banners);
            }, 2500);
        }, 5000);

        setTimeout(function() {
            uncomment_next($index_banners);
        }, 2500);
    }

    setTimeout(function() {
        $('.jspTrack, .jspDrag', $propositions).one('mousedown', function() {
            $('.uncomment', $index_banners).each(function() {
                uncomment($(this));
            });
        });
    }, 100);

    // index banner
    var $bigbanner = $('.bigbanner'),
        $bigbanners = $('.overflow .a', $bigbanner),
        bigbanner_animated = false;

    if ($bigbanner.length) {
        var $prev = $('.prev', $bigbanner),
	        $next = $('.next', $bigbanner),
	        $car = $('.carousel', $bigbanner),
	        $slides = $('.a', $car),
	        $wrap = $('#wrap'); ;

        function bigbanner_arrows() {
            var width = $wrap.width(),
			        shift;
            if (width < 1200) {
                shift = Math.floor((1200 - width) / 2);
            } else {
                shift = 0;
            }
            $prev.css({ left: shift });
            $next.css({ right: shift });
        }
        $(window).resize(bigbanner_arrows);
        bigbanner_arrows();
    }


    $('.prev, .next', $bigbanner).bind('click mouseover', function(e) {
        if (e.type == 'click' && bigbanner_animated)
            return false;

        reset_index_banner_interval();

        var $active = $('.a.active', $bigbanner),
            $next = null;

        if ($(this).hasClass('prev')) {
            $next = $active.prev('.a');
            if (!$next.length)
                $next = $bigbanners.eq($bigbanners.length - 1);
        } else {
            $next = $active.next('.a');
            if (!$next.length)
                $next = $bigbanners.eq(0);
        }

        uncomment($next);

        if (e.type != 'click') {
            return;
        }


        bigbanner_animated = true;

        if ($.browser.msie && $.browser.version < 8) {
            $('strong', $active).hide();
            $('strong', $next).hide();
        } else {
            $('strong', $active)
                .animate({ opacity: 0 }, 200);
            $('strong', $next)
                .css({ opacity: 0 }).delay(200).animate({ opacity: 1 }, 200, function() {
                    $(this).clearTypeFix();
                });
        }

        $active.animate({
            opacity: 0
        }, 600);

        $next.css({
            display: 'block',
            opacity: 0
        }).animate({
            opacity: 1
        }, 600, function() {
            $active.removeClass('active').hide();
            $next.addClass('active').clearTypeFix();
            $('strong', $next).show();
            bigbanner_animated = false;
        });
        return false;
    });

    var index_banner_interval = null;
    function reset_index_banner_interval() {
        if (index_banner_interval !== null)
            clearInterval(index_banner_interval);

        index_banner_interval = setInterval(function() {
            $('.next', $bigbanner).click();
        }, 5000);

        if ($('.uncomment', $bigbanner).length)
            setTimeout(function() {
                uncomment_next($bigbanner);
            }, 2500);
    }
    reset_index_banner_interval();
});

/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);


/*
* Cookie plugin
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses.
*/
jQuery.cookie = function(name, value, options) { if (typeof value != 'undefined') { options = options || {}; var expires = ''; if (options.expires && (typeof options.expires == 'number' || options.expires.toGMTString)) { var date; if (typeof options.expires == 'number') { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); } else { date = options.expires; } expires = '; expires=' + date.toGMTString(); } var path = options.path ? '; path=' + options.path : ''; var domain = options.domain ? '; domain=' + options.domain : ''; var secure = options.secure ? '; secure' : ''; document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); } else { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } };

// cleartype fix for IE
;(function($) {
	$.fn.clearTypeFix = function() {
		if ($.browser.msie)
			return this.each(function() {
				if (this.style.filter != 'undefined' &&
					this.style.removeAttribute)
					this.style.removeAttribute('filter');
			});
	};
})(jQuery);



// ie fixes
$(function() {
    if ($.browser.msie && $.browser.version < 9) {

        if ($('.requests-content').length) {
            function requests_resize() {
                if ($(window).width() >= 1070)
                    $('.requests-content').addClass('requests-content-auto');
                else
                    $('.requests-content').removeClass('requests-content-auto');
            }
            $(window).resize(requests_resize);
            requests_resize();
        }

    }

    if ($.browser.msie && $.browser.version < 7) {
        $('.submenu').append('<iframe />');
    }
});

// delete search cookie
$(function() {
    if ($.cookie('formCookie'))
        $.cookie('formCookie', null, {path: '/', expires: -1});
});

// contacts map
$(function() {
    if ($('#contactmap').length) {
        window.contacts_icon = true;

        $('#contactmap').text('');

        $.getScript('/js/gmap.js', function() {
            setTimeout(function() {
                CreateContactMap();
            }, 1000);
        });

    }
});

function CreateContactMap() {
    window.onunload = function() { GUnload(); }

    mparam.lng = 55.781955;
    mparam.lat = 37.596974;
    mparam.zoom = parseInt(16);
    mparam.maptype = 'm';
    icon = 'http://' + document.location.host + '/i/gmaps-contacts1-icon.png';
    loadMap('contactmap');
    markers.add(55.781955, 37.596974, '<strong>Центральный офис</strong><br />ул. Новослободская, дом 31, стр. 2', 'Центральный офис');
    icon = 'http://' + document.location.host + '/i/gmaps-contacts2-icon.png';
    markers.add(55.781955, 37.597836, '<strong>Дополнительный офис продаж<br />(отдел Китая)</strong><br />ул. Новослободская, дом 31, стр. 1', 'Дополнительный офис');
}

/* offline spo */
$(function() {
    $('.spos, .tour_types_tbl').delegate('a.order-popup', 'click', function() {
        var $popup = $('#order-popup');
        $('body').append('<div id="fader" />');
        $('#fader').css({
            cursor: 'pointer'
        }).click(function() {
            $('.popup').css({
                left: -10000,
                top: -10000
            });
            $('#fader').remove();
        });
        $popup.css({
            left: '50%',
            top: $(window).scrollTop() + Math.ceil(($(window).height() - $popup.outerHeight()) / 2)
        });

        $('input, textarea', $popup).val('');

        $('#send_spo_order').show();
        $('#send_spo_order_ok').hide();

        window.spo_id = $(this).attr('rel');

        return false;
    });

    $('#send_spo_order_ok a').click(function() {
        $(this).parents('.popup').find('.close').click();
        return false;
    });

    $('#send_spo_order .button-grey').click(function() {
        if ($('#send_spo_order #s_name').val().replace(/\s/g, '') == '') {
            alert('Введите имя');
            $('#send_spo_order #s_name').focus();
            return false;
        }
        if ($('#send_spo_order #s_email').val().replace(/\s/g, '') == '') {
            alert('Введите e-mail');
            $('#send_spo_order #s_email').focus();
            return false;
        }
        var re = /^([0-9a-zA-Z\.\-_]+)@([0-9a-zA-Z\.\-_]+)\.(.)+$/;
        if ($('#send_spo_order #s_email').val().match(re) == null) {
            alert('Введите корректный e-mail');
            $('#send_spo_order #s_email').focus();
            return false;
        }
        if ($('#send_spo_order #s_phone').val().replace(/\s/g, '') == '') {
            alert('Введите номер телефона');
            $('#send_spo_order #s_phone').focus();
            return false;
        }
        //        if ($('#send_spo_order #s_comment').val().replace(/\s/g, '') == '') {
        //            alert('Введите комментарии');
        //            $('#send_spo_order #s_comment').focus();
        //            return false;
        //        }

        $.ajax({
            url: '/ws/spo.asmx/send_spo_order',
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json',
            data: "{" +
                "spo_id:" + spo_id + "," +
                "name:" + '"' + encodeURIComponent($('#send_spo_order #s_name').val()) + '",' +
                "email:" + '"' + encodeURIComponent($('#send_spo_order #s_email').val()) + '",' +
                "phone:" + '"' + encodeURIComponent($('#send_spo_order #s_phone').val()) + '",' +
                "comment:" + '"' + encodeURIComponent($('#send_spo_order #s_comment').val()) + '"' +
            "}",
            error: function() {
                alert('Произошла ошибка');
            },
            success: function(json) {
                //json.d = 1;
                if (json.d == 1) {
                    if ($('#send_spo_order').parents('.popup').length) {
                        $('#send_spo_order').hide();
                        $('#send_spo_order_ok').show();
                    } else {
                        $('#send_spo_order').html('<h2>Спасибо!</h2><p style="margin:0 0 15px;">Ваша заявка отправлена менеджерам.</p>');
                    }
                } else {
                    alert('Произошла ошибка, проверьте введённые данные');
                }
            }
        });
        return false;
    });
});

$(function() {
    $('.spos, .info, .tour_types_tbl').delegate('a.online', 'click', function() {
        if (!$(this).attr('rel').length)
            return true;

        var json_string = $(this).attr('rel').replace('}', ",cityTo:'',hotel:'',room:-1,hotel_category:'',pansion:'',hotel_quote:'',avia_quote:'',currency:2}");

        $.ajax({
            type: "POST",
            url: "/ws/search_tml.asmx/setSearchParams_tml",
            data: json_string,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(evt, request, settings) {
                window.location.href = '/search/' + evt.d + '/';
            },
            error: function(event, request, settings) {
                alert("Error requesting page!" + settings + "");
            }
        });

        return false;
    });
});


/* send_order */
/* offline spo */
$(function() {
    $('#send_order .button-grey').click(function() {
        if ($('#send_order #s_name').val().replace(/\s/g, '') == '') {
            alert('Введите имя');
            $('#send_order #s_name').focus();
            return false;
        }
        if ($('#send_order #s_email').val().replace(/\s/g, '') == '') {
            alert('Введите e-mail');
            $('#send_order #s_email').focus();
            return false;
        }
        var re = /^([0-9a-zA-Z\.\-_]+)@([0-9a-zA-Z\.\-_]+)\.(.)+$/;
        if ($('#send_order #s_email').val().match(re) == null) {
            alert('Введите корректный e-mail');
            $('#send_order #s_email').focus();
            return false;
        }
        if ($('#send_order #s_phone').val().replace(/\s/g, '') == '') {
            alert('Введите номер телефона');
            $('#send_order #s_phone').focus();
            return false;
        }
        if ($('#send_order .datepicker input').val().replace(/\s/g, '') == '') {
            alert('Введите дату заезда');
            $('#send_order .datepicker input').focus();
            return false;
        }
        //        if ($('#send_order #s_comment').val().replace(/\s/g, '') == '') {
        //            alert('Введите комментарии');
        //            $('#send_order #s_comment').focus();
        //            return false;
        //        }

        $.ajax({
            url: '/ws/order.asmx/send_order',
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json',
            data: "{" +
                "country_id:" + (typeof country_id != 'undefined' ? country_id : 0) + ',' +
                "city_id:" + (typeof city_id != 'undefined' ? city_id : 0) + ',' +
                "hotel_id:" + (typeof hotel_id != 'undefined' ? hotel_id : 0) + ',' +
                "data:" + '"' + $('#send_order .datepicker input').val() + '",' +
                "nights:" + $('#send_order #s_nights').val() + ',' +
                "name:" + '"' + encodeURIComponent($('#send_order #s_name').val()) + '",' +
                "email:" + '"' + encodeURIComponent($('#send_order #s_email').val()) + '",' +
                "phone:" + '"' + encodeURIComponent($('#send_order #s_phone').val()) + '",' +
                "comment:" + '"' + encodeURIComponent($('#send_order #s_comment').val()) + '"' +
            "}",
            error: function() {
                alert('Произошла ошибка');
            },
            success: function(json) {
                if (json.d == 1) {
                    $('#send_order').html('<h2>Спасибо!</h2>');
                } else {
                    alert('Произошла ошибка, проверьте введённые данные');
                }
            }
        });
        return false;
    });
});

// text search
var form_nosubmit = false;
$(function() {

    $('form').submit(function() {
        if (form_nosubmit) {
            form_nosubmit = false;
            return false;
        }
    });
    
    $('.textsearch input[type=text], .searchform input[type=text]').attr({ autocomplete: 'off' }).bind('keydown', function(e) {
        if (e.keyCode == 13) {
            go_search($(this));
            return false;
        }
    });

    $('.searchform input[type=submit]').click(function(e) {
        stopEvent(e);
        go_search($('.searchform input[type=text]'));
        return false;
    });

    $('.textsearch #research').click(function(e) {
        stopEvent(e);
        go_search($('.textsearch input[type=text]'));
        return false;
    });

    function go_search($query) {
        var query = $query.val();
        var query_clean = query.replace(/\s/g, '');
        if (query_clean.length == 0 || query_clean == 'Поиск') {
            $query.focus();
            return false;
        }
        query = query.replace(/[^\d\sа-яa-z]+/gi, ' ').replace(/(^\s+|\s+$)/g, '').replace(/\s{2,}/g, ' ');
        form_nosubmit = true;
        document.location = '/find/' + encodeURIComponent(query) + '/';
        return false;
    }

});

// unwrap comment nodes
function uncomment($parent) {
    if (!$parent.hasClass('uncomment'))
        return;
    $parent.removeClass('uncomment').contents().filter(function() {
        return this.nodeType == 8; // comment
    }).each(function() {
        //console.log($(this).get(0).nodeValue);
        $(this).replaceWith($(this).get(0).nodeValue);
    });
}
function uncomment_next($wrap, count) {
    if (typeof count == 'undefined' || parseInt(count) < 1)
        count = 1;
    else
        count = parseInt(count);
        
    $('.uncomment', $wrap).slice(0, count).each(function(){
        uncomment($(this));
    });
}
