show_div = '';
params = null;
$dialog = null;

$(document).ready(function(){

/* Popup window */
var POPUP = $('a.popup');
    if(POPUP){
        POPUP.click(function(e){
            e.preventDefault();
            window.open (this.href,"mywindow","menubar=1,resizable=1,width=550,height=550");
        });
    }

/* Contacts */
    var CLOSE_TIPS = $('#close_tips');
    if(CLOSE_TIPS){
        CLOSE_TIPS.click(function(e){
            e.preventDefault();
            $('div.contact-tips').css('top', '-500px');
            $('div.contact-tips').css('left', '-500px');
            $('#tips-container').empty();
            $('#tips-container').addClass('height');
            $('#tips-container').addClass('ajax-form-white');

        });
    }

    var IMAGCONTACTS = $('.view_city');
    if(IMAGCONTACTS){

        IMAGCONTACTS.click(function(e){
            e.preventDefault();
            url = e.target;

            var coord = e.target.coords.split(",");
            img_contact = $("img.ContactsMap");

            if(img_contact){
                coordinates = img_contact.position();
                var X = 0;
                var Y = 0;

                //if(img_contact){
                    X = coordinates.left;

                    Y = coordinates.top;

                    $('div.contact-tips').css('top', (parseInt(Y) + parseInt(coord[1])) + 'px');
                    $('div.contact-tips').css('left', (parseInt(X) + parseInt(coord[0]) - 22) + 'px');
                    test = $('div.contact-tips');

                    //$('#tips-container').load(url+"?Event=AjaxRequest");
                    $.post( url.href+"?Event=AjaxRequest",  '',
                        function(params){
                            //eval("params = "+response);
                            //alert(params.asd);
                            if(params){
                                $('#tips-container').html('');
                                $('#tips-container').removeClass('height');
                                $('#tips-container').removeClass('ajax-form-white');
                                $('#tips-container').html(params);
                            }else{
                                $('#tips-container').removeClass('height');
                                $('#tips-container').removeClass('ajax-form-white');
                                $('#tips-container').html('');
                            }
                        }
                    );

            }
        });
    }

/* End Contacts */


    $('.not-active-fp').css({opacity: 0.0});
    var left_divs = $('.LeftContentContainer div');
    var right_divs = $('.RightContentContainer div');
    var bottom_divs = $('.bottomBlocks div');

    var current_middle = $.cookie("MiddleBlock");
    var main_block = $("."+current_middle);
    var small_block = $("#"+current_middle);
    if(main_block.length && !main_block.hasClass('active-fp') && small_block.length){
        $('.MiddleContentContainer .active-fp').css('opacity', 0).addClass('not-active-fp').removeClass('active-fp');
        $("."+current_middle).css('opacity', 1.0);
        $("."+current_middle).removeClass('not-active-fp').addClass('active-fp');
        var pos = small_block.position();
        $('div.disabled',small_block.parent()).css({'left':pos.left,'top': pos.top,'display':'block','margin-top':small_block.css('margin-top')})
    }

    if(bottom_divs){
        bottom_divs.click(function(e){
            if(!$(e.target).hasClass('clickable'))e.preventDefault();
            var pos = $(this).position();
            //alert(pos.left + '-->'+pos.top);

            if(!$(this).hasClass('disabled')){
                show_div = this.id;
                $('.MiddleContentContainer .active-fp').animate({opacity: 0}, 500).addClass('not-active-fp').removeClass('active-fp');
                $("."+show_div).animate({opacity: 1.0}, 500);
                $("."+show_div).removeClass('not-active-fp').addClass('active-fp');
                var right_div_dis = $('.RightContentContainer div.disabled');
                right_div_dis.css({'display':'none'});
                var bottom_div_dis = $('.bottomBlocks div.disabled');
                bottom_div_dis.css({'left':pos.left,'top': pos.top,'display':'block','margin-top':$(this).css('margin-top')});
                var left_div_dis = $('.LeftContentContainer div.disabled');
                left_div_dis.css({'display':'none'});
            }else{
                show_div = this.id;
                $('.MiddleContentContainer .active-fp').animate({opacity: 0}, 500).addClass('not-active-fp').removeClass('active-fp');
                $("."+show_div).animate({opacity: 1.0}, 500);
                $("."+show_div).removeClass('not-active-fp').addClass('active-fp');

                var right_div_dis = $('.RightContentContainer div.disabled');
                right_div_dis.css({'display':'none'});
                var bottom_div_dis = $('.bottomBlocks div.disabled');
                bottom_div_dis.css({'display':'none'});
                var left_div_dis = $('.LeftContentContainer div.disabled');
                left_div_dis.css({'display':'none'});
            }
            $.cookie("MiddleBlock", show_div, {expires: 31,path: "/"});
        })
    }

    if(left_divs){
        left_divs.click(function(e){
            if(!$(e.target).hasClass('clickable'))e.preventDefault();
            var pos = $(this).position();
            //alert(pos.left + '-->'+pos.top);

            if(!$(this).hasClass('disabled')){
                show_div = this.id;
                $('.MiddleContentContainer .active-fp').animate({opacity: 0}, 500).addClass('not-active-fp').removeClass('active-fp');
                $("."+show_div).animate({opacity: 1.0}, 500);
                $("."+show_div).removeClass('not-active-fp').addClass('active-fp');
                var right_div_dis = $('.RightContentContainer div.disabled');
                right_div_dis.css({'display':'none'});
                var bottom_div_dis = $('.bottomBlocks div.disabled');
                bottom_div_dis.css({'display':'none'});
                var left_div_dis = $('.LeftContentContainer div.disabled');
                left_div_dis.css({'left':pos.left,'top': pos.top,'display':'block','margin-top':$(this).css('margin-top')});
            }else{
                show_div = this.id;
                $('.MiddleContentContainer .active-fp').animate({opacity: 0}, 500).addClass('not-active-fp').removeClass('active-fp');
                $("."+show_div).animate({opacity: 1.0}, 500);
                $("."+show_div).removeClass('not-active-fp').addClass('active-fp');

                var right_div_dis = $('.RightContentContainer div.disabled');
                right_div_dis.css({'display':'none'});
                var bottom_div_dis = $('.bottomBlocks div.disabled');
                bottom_div_dis.css({'display':'none'});
                var left_div_dis = $('.LeftContentContainer div.disabled');
                left_div_dis.css({'display':'none'});

            }
            $.cookie("MiddleBlock", show_div, {expires: 31,path: "/"});
        })
    }


    if(right_divs){
            right_divs.click(function(e){
            if(!$(e.target).hasClass('clickable'))e.preventDefault();
            var pos = $(this).position();
            //alert(pos.left + '-->'+pos.top);

            if(!$(this).hasClass('disabled')){
                show_div = this.id;
                $('.MiddleContentContainer .active-fp').animate({opacity: 0}, 500).addClass('not-active-fp').removeClass('active-fp')
                $("."+show_div).animate({opacity: 1.0}, 500).removeClass('not-active-fp').addClass('active-fp')

                var right_div_dis = $('.RightContentContainer div.disabled');
                right_div_dis.css({'left':pos.left,'top': pos.top,'display':'block','margin-top':$(this).css('margin-top')});

                var bottom_div_dis = $('.bottomBlocks div.disabled');
                bottom_div_dis.css({'display':'none'});

                var left_div_dis = $('.LeftContentContainer div.disabled');
                left_div_dis.css({'display':'none'});
            }else{
                show_div = this.id;
                $('.MiddleContentContainer .active-fp').animate({opacity: 0}, 500).addClass('not-active-fp').removeClass('active-fp');
                $("."+show_div).animate({opacity: 1.0}, 500);
                $("."+show_div).removeClass('not-active-fp').addClass('active-fp');

                var right_div_dis = $('.RightContentContainer div.disabled');
                right_div_dis.css({'display':'none'});
                var bottom_div_dis = $('.bottomBlocks div.disabled');
                bottom_div_dis.css({'display':'none'});
                var left_div_dis = $('.LeftContentContainer div.disabled');
                left_div_dis.css({'display':'none'});

            }
            $.cookie("MiddleBlock", show_div, {expires: 31,path: "/"});
        })
    }


    /*
      var params = {
            changedEl: ".lineForm select",
            visRows: 5,
            scrollArrows: true
        }
        cuSel(params);
    */
my_obj = null;
$('body').click(function(e){
//  alert(e.target());

    if(e.target.id != 'current_adr')
        $('#affiliates').css('display','none');
})
$("#current_adr").click(function(e){
    e.preventDefault();
    $('#affiliates').css('display','block');
})
$('#affiliates a').click(function(e){
    e.preventDefault();
    $(this).parent().parent().removeClass('display-none');
    $('#current_adr').html(this.innerHTML);
    blocks = this.title.split(";");
    $('#phone').html('');
    for(i = 0; i < blocks.length; i++){

        email = blocks[i].split('|');
        phone = email[0].split(')');
        em1 = '';
        em2 = '';
        if(email[2]){
            em1 += '<span class="adres"><br />'+email[2]+'</span>';
        }
        if(email[1]){
            em2 += '<br />'+'<a class="email" href="mailto:'+email[1]+'">'+email[1]+'</a>';
        }
        $('#phone').html($('#phone').html()+'<p><span class="phoneCode">'+phone[0]+')'+'</span><span class="phone">'+phone[1]+"</span>"+em1+em2+'</p>');
    }


    $.cookie("filial", $(this).attr('rel'), {expires: 31,path: "/"});
    $(this).parent().parent().css('display','none');
});
$('.dotted_line span').click(function(e){
    $(this).toggleClass('bottom');
    $('.dotted_next').first().toggle();
});

$('.validation-form').submit(function() {

        var validation = $(".valid",this);
        var error = false;

        if(validation){
            validation.removeClass('ui-state-error');
            validation.each(function(index, el){

                if($(this).hasClass('email')){
                     validRegExp = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
                     strEmail = el.value;
                     if (strEmail.search(validRegExp) == -1){
                        error = true;
                        $(this).addClass('ui-state-error');
                     }
                }else if($(this).hasClass('phone')){
                     validRegExp = /^\d{10,13}$/i;
                     strPhone = el.value;
                     if (strPhone.search(validRegExp) == -1){
                        error = true;
                        $(this).addClass('ui-state-error');
                     }
                }else if($(this).hasClass('rules')){
                    if(!el.checked){
                        error = true;
                        alert('Для регистрации необходимо принять условия использования сайта.');
                    }
                }else if($(this).hasClass('day') || $(this).hasClass('month') || $(this).hasClass('year')){
                    if(isNaN(el.value)){
                        error = true;
                        $('#err').attr('src', '/public/images/error.gif');
                    }
                }else{
                    if(!el.value || el.value == el.alt || el.value == el.title){
                        error = true;
                        $(this).addClass('ui-state-error');
                    }
                }
            });
        }
        if(!error){
            var form = $(this);
            if(form.length){
                var action = form.attr('action');
                if(action == '') action = '/';
                var str = form.serialize();
                $.post(action, str, function(response){
                    var params;
                    //eval("params = " + response);
                    params = response;
                    if (params.success) {
                        $('.form_content',form).hide();
                        if(params.text){
                            $('.thanks',form).html(params.text);
                        }
                        $('.thanks',form).show();
                        if(params.callback){
                            if (eval("typeof " + params.callback + " == 'function'")) {
                                eval(params.callback + '();');
                            }
                        }
                    }else{
                        $(params.errors).each(function(ind,el){$("input[name='"+el+"']",form).addClass('ui-state-error');});
                        $(".validateTips",form).html(params.errortext);
                    }
                },'json');
            }
        }else{
            //$('#captcha').load('/registration.html?Event=ChangeCaptcha');

        }
        return false;
    });


    $('a.bumpbox').click(function(e) {
        e.preventDefault();
        var $this = $(this);
        var horizontalPadding = 30;
        var verticalPadding = 30;
        $dialog = $('<iframe id="externalSite" class="externalSite" src="' + this.href + '" />').dialog({
            title: ($this.attr('title')) ? $this.attr('title') : '',
            autoOpen: true,
            width: 300,
            height: 450,
            modal: true,
            resizable: true,
            autoResize: true,
            overlay: {
                opacity: 0.5,
                background: "black"
            }
        }).width(300 - horizontalPadding).height(450 - verticalPadding);
    });


});
function closedialog(){
    $dialog.dialog('close');
}

function unset(el,text,textarea){

    if(textarea){
        if(el.innerHTML == text){
            el.innerHTML = '';
        }
    }
    else{
        if(el.value == text){
            el.value= '';
        }
    }

}

function set(el,text,textarea){

    if(textarea){
        if(el.innerHTML == ''){
            el.innerHTML = text;
        }
    }else{
        if(el.value == ''){
            el.value = text;
        }
    }

}

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            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.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        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 { // only name given, get cookie
        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]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/**
 * jCarouselLite - jQuery plugin to navigate images/any content in a carousel style widget.
 * @requires jQuery v1.2 or above
 *
 * http://gmarwaha.com/jquery/jcarousellite/
 *
 * Copyright (c) 2007 Ganeshji Marwaha (gmarwaha.com)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Version: 1.0.1
 * Note: Requires jquery 1.2 or above from version 1.0.1
 */

/**
 * Creates a carousel-style navigation widget for images/any-content from a simple HTML markup.
 *
 * The HTML markup that is used to build the carousel can be as simple as...
 *
 *  <div class="carousel">
 *      <ul>
 *          <li><img src="image/1.jpg" alt="1"></li>
 *          <li><img src="image/2.jpg" alt="2"></li>
 *          <li><img src="image/3.jpg" alt="3"></li>
 *      </ul>
 *  </div>
 *
 * As you can see, this snippet is nothing but a simple div containing an unordered list of images.
 * You don't need any special "class" attribute, or a special "css" file for this plugin.
 * I am using a class attribute just for the sake of explanation here.
 *
 * To navigate the elements of the carousel, you need some kind of navigation buttons.
 * For example, you will need a "previous" button to go backward, and a "next" button to go forward.
 * This need not be part of the carousel "div" itself. It can be any element in your page.
 * Lets assume that the following elements in your document can be used as next, and prev buttons...
 *
 * <button class="prev">&lt;&lt;</button>
 * <button class="next">&gt;&gt;</button>
 *
 * Now, all you need to do is call the carousel component on the div element that represents it, and pass in the
 * navigation buttons as options.
 *
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev"
 * });
 *
 * That's it, you would have now converted your raw div, into a magnificient carousel.
 *
 * There are quite a few other options that you can use to customize it though.
 * Each will be explained with an example below.
 *
 * @param an options object - You can specify all the options shown below as an options object param.
 *
 * @option btnPrev, btnNext : string - no defaults
 * @example
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev"
 * });
 * @desc Creates a basic carousel. Clicking "btnPrev" navigates backwards and "btnNext" navigates forward.
 *
 * @option btnGo - array - no defaults
 * @example
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev",
 *      btnGo: [".0", ".1", ".2"]
 * });
 * @desc If you don't want next and previous buttons for navigation, instead you prefer custom navigation based on
 * the item number within the carousel, you can use this option. Just supply an array of selectors for each element
 * in the carousel. The index of the array represents the index of the element. What i mean is, if the
 * first element in the array is ".0", it means that when the element represented by ".0" is clicked, the carousel
 * will slide to the first element and so on and so forth. This feature is very powerful. For example, i made a tabbed
 * interface out of it by making my navigation elements styled like tabs in css. As the carousel is capable of holding
 * any content, not just images, you can have a very simple tabbed navigation in minutes without using any other plugin.
 * The best part is that, the tab will "slide" based on the provided effect. :-)
 *
 * @option mouseWheel : boolean - default is false
 * @example
 * $(".carousel").jCarouselLite({
 *      mouseWheel: true
 * });
 * @desc The carousel can also be navigated using the mouse wheel interface of a scroll mouse instead of using buttons.
 * To get this feature working, you have to do 2 things. First, you have to include the mouse-wheel plugin from brandon.
 * Second, you will have to set the option "mouseWheel" to true. That's it, now you will be able to navigate your carousel
 * using the mouse wheel. Using buttons and mouseWheel or not mutually exclusive. You can still have buttons for navigation
 * as well. They complement each other. To use both together, just supply the options required for both as shown below.
 * @example
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev",
 *      mouseWheel: true
 * });
 *
 * @option auto : number - default is null, meaning autoscroll is disabled by default
 * @example
 * $(".carousel").jCarouselLite({
 *      auto: 800,
 *      speed: 500
 * });
 * @desc You can make your carousel auto-navigate itself by specfying a millisecond value in this option.
 * The value you specify is the amount of time between 2 slides. The default is null, and that disables auto scrolling.
 * Specify this value and magically your carousel will start auto scrolling.
 *
 * @option speed : number - 200 is default
 * @example
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev",
 *      speed: 800
 * });
 * @desc Specifying a speed will slow-down or speed-up the sliding speed of your carousel. Try it out with
 * different speeds like 800, 600, 1500 etc. Providing 0, will remove the slide effect.
 *
 * @option easing : string - no easing effects by default.
 * @example
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev",
 *      easing: "bounceout"
 * });
 * @desc You can specify any easing effect. Note: You need easing plugin for that. Once specified,
 * the carousel will slide based on the provided easing effect.
 *
 * @option vertical : boolean - default is false
 * @example
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev",
 *      vertical: true
 * });
 * @desc Determines the direction of the carousel. true, means the carousel will display vertically. The next and
 * prev buttons will slide the items vertically as well. The default is false, which means that the carousel will
 * display horizontally. The next and prev items will slide the items from left-right in this case.
 *
 * @option circular : boolean - default is true
 * @example
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev",
 *      circular: false
 * });
 * @desc Setting it to true enables circular navigation. This means, if you click "next" after you reach the last
 * element, you will automatically slide to the first element and vice versa. If you set circular to false, then
 * if you click on the "next" button after you reach the last element, you will stay in the last element itself
 * and similarly for "previous" button and first element.
 *
 * @option visible : number - default is 3
 * @example
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev",
 *      visible: 4
 * });
 * @desc This specifies the number of items visible at all times within the carousel. The default is 3.
 * You are even free to experiment with real numbers. Eg: "3.5" will have 3 items fully visible and the
 * last item half visible. This gives you the effect of showing the user that there are more images to the right.
 *
 * @option start : number - default is 0
 * @example
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev",
 *      start: 2
 * });
 * @desc You can specify from which item the carousel should start. Remember, the first item in the carousel
 * has a start of 0, and so on.
 *
 * @option scrool : number - default is 1
 * @example
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev",
 *      scroll: 2
 * });
 * @desc The number of items that should scroll/slide when you click the next/prev navigation buttons. By
 * default, only one item is scrolled, but you may set it to any number. Eg: setting it to "2" will scroll
 * 2 items when you click the next or previous buttons.
 *
 * @option beforeStart, afterEnd : function - callbacks
 * @example
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev",
 *      beforeStart: function(a) {
 *          alert("Before animation starts:" + a);
 *      },
 *      afterEnd: function(a) {
 *          alert("After animation ends:" + a);
 *      }
 * });
 * @desc If you wanted to do some logic in your page before the slide starts and after the slide ends, you can
 * register these 2 callbacks. The functions will be passed an argument that represents an array of elements that
 * are visible at the time of callback.
 *
 *
 * @cat Plugins/Image Gallery
 * @author Ganeshji Marwaha/ganeshread@gmail.com
 */

(function($) {                                          // Compliant with jquery.noConflict()
$.fn.jCarouselLite = function(o) {
    o = $.extend({
        btnPrev: null,
        btnNext: null,
        btnGo: null,
        mouseWheel: false,
        auto: null,
        hoverPause: false,

        speed: 200,
        easing: null,

        vertical: false,
        circular: true,
        visible: 3,
        start: 0,
        scroll: 1,

        beforeStart: null,
        afterEnd: null
    }, o || {});

    return this.each(function() {                           // Returns the element collection. Chainable.

        var running = false, animCss=o.vertical?"top":"left", sizeCss=o.vertical?"height":"width";
        var div = $(this), ul = $("ul", div), tLi = $("li", ul), tl = tLi.size(), v = o.visible;

        if(o.circular) {
            ul.prepend(tLi.slice(tl-v+1).clone())
              .append(tLi.slice(0,o.scroll).clone());
            o.start += v-1;
        }

        var li = $("li", ul), itemLength = li.size(), curr = o.start;
        div.css("visibility", "visible");

        li.css({overflow: "hidden", float: o.vertical ? "none" : "left"});
        ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
        div.css({overflow: "hidden", position: "relative", "z-index": "2", left: "0px"});

        var liSize = o.vertical ? height(li) : width(li);   // Full li size(incl margin)-Used for animation
        var ulSize = liSize * itemLength;                   // size of full ul(total length, not just for the visible items)
        var divSize = liSize * v;                           // size of entire div(total length for just the visible items)

        li.css({width: li.width(), height: li.height()});
        ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));

        div.css(sizeCss, divSize+"px");                     // Width of the DIV. length of visible images

        if(o.btnPrev) {
            $(o.btnPrev).click(function() {
                return go(curr-o.scroll);
            });
            if(o.hoverPause) {
                $(o.btnPrev).hover(function(){stopAuto();}, function(){startAuto();});
            }
        }


        if(o.btnNext) {
            $(o.btnNext).click(function() {
                return go(curr+o.scroll);
            });
            if(o.hoverPause) {
                $(o.btnNext).hover(function(){stopAuto();}, function(){startAuto();});
            }
        }

        if(o.btnGo)
            $.each(o.btnGo, function(i, val) {
                $(val).click(function() {
                    return go(o.circular ? o.visible+i : i);
                });
            });

        if(o.mouseWheel && div.mousewheel)
            div.mousewheel(function(e, d) {
                return d>0 ? go(curr-o.scroll) : go(curr+o.scroll);
            });

        var autoInterval;

        function startAuto() {
          stopAuto();
          autoInterval = setInterval(function() {
                  go(curr+o.scroll);
              }, o.auto+o.speed);
        };

        function stopAuto() {
            clearInterval(autoInterval);
        };

        if(o.auto) {
            if(o.hoverPause) {
                div.hover(function(){stopAuto();}, function(){startAuto();});
            }
            startAuto();
        };

        function vis() {
            return li.slice(curr).slice(0,v);
        };

        function go(to) {
            if(!running) {

                if(o.beforeStart)
                    o.beforeStart.call(this, vis());

                if(o.circular) {            // If circular we are in first or last, then goto the other end
                    if(to<0) {           // If before range, then go around
                        ul.css(animCss, -( (curr + tl) * liSize)+"px");
                        curr = to + tl;
                    } else if(to>itemLength-v) { // If beyond range, then come around
                        ul.css(animCss, -( (curr - tl) * liSize ) + "px" );
                        curr = to - tl;
                    } else curr = to;
                } else {                    // If non-circular and to points to first or last, we just return.
                    if(to<0 || to>itemLength-v) return;
                    else curr = to;
                }                           // If neither overrides it, the curr will still be "to" and we can proceed.

                running = true;

                ul.animate(
                    animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
                    function() {
                        if(o.afterEnd)
                            o.afterEnd.call(this, vis());
                        running = false;
                    }
                );
                // Disable buttons when the carousel reaches the last/first, and enable when not
                if(!o.circular) {
                    $(o.btnPrev + "," + o.btnNext).removeClass("disabled");
                    $( (curr-o.scroll<0 && o.btnPrev)
                        ||
                       (curr+o.scroll > itemLength-v && o.btnNext)
                        ||
                       []
                     ).addClass("disabled");
                }

            }
            return false;
        };
    });
};

function css(el, prop) {
    return parseInt($.css(el[0], prop)) || 0;
};
function width(el) {
    return  el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
};
function height(el) {
    return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
};

})(jQuery);

        $(function(){
            $('#slides').slides({
                preload: true,
                preloadImage: 'img/loading.gif',
                play: 5000,
                pause: 1500,
                hoverPause: true,
                animationStart: function(current){
                    $('.caption').animate({
                        bottom:-35
                    },100);
                    if (window.console && console.log) {
                        // example return of current slide number
                        console.log('animationStart on slide: ', current);
                    };
                },
                animationComplete: function(current){
                    $('.caption').animate({
                        bottom:0
                    },200);
                    if (window.console && console.log) {
                        // example return of current slide number
                        console.log('animationComplete on slide: ', current);
                    };
                },
                slidesLoaded: function() {
                    $('.caption').animate({
                        bottom:0
                    },200);
                }
            });
        });

function loadframe(){
    if(window.location.replace)
        window.frames.bookframe.location.replace(get('framepage'));
    else
        window.frames.bookframe.location.href=get('framepage');
    }

function get(key_str) {
    var query = window.location.search.substr(1);
    var pairs = query.split("&");
    for(var i = 0; i < pairs.length; i++) {
        var pair = pairs[i].split("=");
        if(unescape(pair[0]) == key_str)
            return unescape(pair[1]);
    }
    return null;
}

if (location.search&&get('framepage')!=null)
    if ( typeof window.addEventListener != "undefined" )
        window.addEventListener( "load", loadframe, false );
    else if ( typeof window.attachEvent != "undefined" )
        window.attachEvent( "onload", loadframe );
    else {
        if ( window.onload != null ) {
            var oldOnload = window.onload;

            window.onload = function ( e ) {
                oldOnload( e );
                loadframe();
            };
        }
    else
        window.onload = loadframe;
    }

 $(document).ready(function(){
            var tabs = $(".tabs").accessibleTabs({
                fx:"fadeIn",
                syncheights:false
            });
        });

/*
* Slides, A Slideshow Plugin for jQuery
* Intructions: http://slidesjs.com
* By: Nathan Searles, http://nathansearles.com
* Version: 1.1.8
* Updated: June 1st, 2011
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function(A){A.fn.slides=function(B){B=A.extend({},A.fn.slides.option,B);return this.each(function(){A("."+B.container,A(this)).children().wrapAll('<div class="slides_control"/>');var V=A(this),J=A(".slides_control",V),Z=J.children().size(),Q=J.children().outerWidth(),M=J.children().outerHeight(),D=B.start-1,L=B.effect.indexOf(",")<0?B.effect:B.effect.replace(" ","").split(",")[0],S=B.effect.indexOf(",")<0?L:B.effect.replace(" ","").split(",")[1],O=0,N=0,C=0,P=0,U,H,I,X,W,T,K,F;function E(c,b,a){if(!H&&U){H=true;B.animationStart(P+1);switch(c){case"next":N=P;O=P+1;O=Z===O?0:O;X=Q*2;c=-Q*2;P=O;break;case"prev":N=P;O=P-1;O=O===-1?Z-1:O;X=0;c=0;P=O;break;case"pagination":O=parseInt(a,10);N=A("."+B.paginationClass+" li."+B.currentClass+" a",V).attr("href").match("[^#/]+$");if(O>N){X=Q*2;c=-Q*2;}else{X=0;c=0;}P=O;break;}if(b==="fade"){if(B.crossfade){J.children(":eq("+O+")",V).css({zIndex:10}).fadeIn(B.fadeSpeed,B.fadeEasing,function(){if(B.autoHeight){J.animate({height:J.children(":eq("+O+")",V).outerHeight()},B.autoHeightSpeed,function(){J.children(":eq("+N+")",V).css({display:"none",zIndex:0});J.children(":eq("+O+")",V).css({zIndex:0});B.animationComplete(O+1);H=false;});}else{J.children(":eq("+N+")",V).css({display:"none",zIndex:0});J.children(":eq("+O+")",V).css({zIndex:0});B.animationComplete(O+1);H=false;}});}else{J.children(":eq("+N+")",V).fadeOut(B.fadeSpeed,B.fadeEasing,function(){if(B.autoHeight){J.animate({height:J.children(":eq("+O+")",V).outerHeight()},B.autoHeightSpeed,function(){J.children(":eq("+O+")",V).fadeIn(B.fadeSpeed,B.fadeEasing);});}else{J.children(":eq("+O+")",V).fadeIn(B.fadeSpeed,B.fadeEasing,function(){if(A.browser.msie){A(this).get(0).style.removeAttribute("filter");}});}B.animationComplete(O+1);H=false;});}}else{J.children(":eq("+O+")").css({left:X,display:"block"});if(B.autoHeight){J.animate({left:c,height:J.children(":eq("+O+")").outerHeight()},B.slideSpeed,B.slideEasing,function(){J.css({left:-Q});J.children(":eq("+O+")").css({left:Q,zIndex:5});J.children(":eq("+N+")").css({left:Q,display:"none",zIndex:0});B.animationComplete(O+1);H=false;});}else{J.animate({left:c},B.slideSpeed,B.slideEasing,function(){J.css({left:-Q});J.children(":eq("+O+")").css({left:Q,zIndex:5});J.children(":eq("+N+")").css({left:Q,display:"none",zIndex:0});B.animationComplete(O+1);H=false;});}}if(B.pagination){A("."+B.paginationClass+" li."+B.currentClass,V).removeClass(B.currentClass);A("."+B.paginationClass+" li:eq("+O+")",V).addClass(B.currentClass);}}}function R(){clearInterval(V.data("interval"));}function G(){if(B.pause){clearTimeout(V.data("pause"));clearInterval(V.data("interval"));K=setTimeout(function(){clearTimeout(V.data("pause"));F=setInterval(function(){E("next",L);},B.play);V.data("interval",F);},B.pause);V.data("pause",K);}else{R();}}if(Z<2){return ;}if(D<0){D=0;}if(D>Z){D=Z-1;}if(B.start){P=D;}if(B.randomize){J.randomize();}A("."+B.container,V).css({overflow:"hidden",position:"relative"});J.children().css({position:"absolute",top:0,left:J.children().outerWidth(),zIndex:0,display:"none"});J.css({position:"relative",width:(Q*3),height:M,left:-Q});A("."+B.container,V).css({display:"block"});if(B.autoHeight){J.children().css({height:"auto"});J.animate({height:J.children(":eq("+D+")").outerHeight()},B.autoHeightSpeed);}if(B.preload&&J.find("img:eq("+D+")").length){A("."+B.container,V).css({background:"url("+B.preloadImage+") no-repeat 50% 50%"});var Y=J.find("img:eq("+D+")").attr("src")+"?"+(new Date()).getTime();if(A("img",V).parent().attr("class")!="slides_control"){T=J.children(":eq(0)")[0].tagName.toLowerCase();}else{T=J.find("img:eq("+D+")");}J.find("img:eq("+D+")").attr("src",Y).load(function(){J.find(T+":eq("+D+")").fadeIn(B.fadeSpeed,B.fadeEasing,function(){A(this).css({zIndex:5});A("."+B.container,V).css({background:""});U=true;B.slidesLoaded();});});}else{J.children(":eq("+D+")").fadeIn(B.fadeSpeed,B.fadeEasing,function(){U=true;B.slidesLoaded();});}if(B.bigTarget){J.children().css({cursor:"pointer"});J.children().click(function(){E("next",L);return false;});}if(B.hoverPause&&B.play){J.bind("mouseover",function(){R();});J.bind("mouseleave",function(){G();});}if(B.generateNextPrev){A("."+B.container,V).after('<a href="#" class="'+B.prev+'">Prev</a>');A("."+B.prev,V).after('<a href="#" class="'+B.next+'">Next</a>');}A("."+B.next,V).click(function(a){a.preventDefault();if(B.play){G();}E("next",L);});A("."+B.prev,V).click(function(a){a.preventDefault();if(B.play){G();}E("prev",L);});if(B.generatePagination){if(B.prependPagination){V.prepend("<ul class="+B.paginationClass+"></ul>");}else{V.append("<ul class="+B.paginationClass+"></ul>");}J.children().each(function(){A("."+B.paginationClass,V).append('<li><a href="#'+C+'">'+(C+1)+"</a></li>");C++;});}else{A("."+B.paginationClass+" li a",V).each(function(){A(this).attr("href","#"+C);C++;});}A("."+B.paginationClass+" li:eq("+D+")",V).addClass(B.currentClass);A("."+B.paginationClass+" li a",V).click(function(){if(B.play){G();}I=A(this).attr("href").match("[^#/]+$");if(P!=I){E("pagination",S,I);}return false;});A("a.link",V).click(function(){if(B.play){G();}I=A(this).attr("href").match("[^#/]+$")-1;if(P!=I){E("pagination",S,I);}return false;});if(B.play){F=setInterval(function(){E("next",L);},B.play);V.data("interval",F);}});};A.fn.slides.option={preload:false,preloadImage:"/img/loading.gif",container:"slides_container",generateNextPrev:false,next:"next",prev:"prev",pagination:true,generatePagination:true,prependPagination:false,paginationClass:"pagination",currentClass:"current",fadeSpeed:350,fadeEasing:"",slideSpeed:350,slideEasing:"",start:1,effect:"slide",crossfade:false,randomize:false,play:0,pause:0,hoverPause:false,autoHeight:false,autoHeightSpeed:350,bigTarget:false,animationStart:function(){},animationComplete:function(){},slidesLoaded:function(){}};A.fn.randomize=function(C){function B(){return(Math.round(Math.random())-0.5);}return(A(this).each(function(){var F=A(this);var E=F.children();var D=E.length;if(D>1){E.hide();var G=[];for(i=0;i<D;i++){G[G.length]=i;}G=G.sort(B);A.each(G,function(I,H){var K=E.eq(H);var J=K.clone(true);J.show().appendTo(F);if(C!==undefined){C(K,J);}K.remove();});}}));};})(jQuery);


    function togg_news(){ //открыть/закрыть блок
        if ($("#arrow_up").css('display')=='inline')
        {
            $("#arrow_up").css('display','none')
            $("#arrow_down").css('display','inline');
        }
        else
        {
            $("#arrow_up").css('display','inline')
            $("#arrow_down").css('display','none');
        }
        $("#avisreis").toggle(500);
    }

    function other_categ_open() //открыть/закрыть блок
    {
        $("div.category_additional").toggle(500);
    }
    // Run the script on DOM ready:
    var line_cnt = 1;
    $(function(){
        $('input').customInput();

        $('#check-1,#check-2').click(function(){
            if (line_cnt==1)
            {
                if ($(this).attr('checked'))
                {
                    $('.when_back').show().find('input, select').attr('disabled',false);
                    $('.journey_type').val('RT');
                    $('#refresh').attr('src','/ufsa/user/img/refresh.png');

                    $('#online_form').append('<input type="hidden" name="DEP_1" id="dep_1" value="'+$('#arr_0').val()+'">')
                    $('#online_form').append('<input type="hidden" name="ARR_1" id="arr_1" value="'+$('#dep_0').val()+'">')

                }
                else
                {
                    $('.when_back').hide().find('input, select').attr('disabled',true);
                    $('#refresh').attr('src','/ufsa/user/img/arrow.png');
                    $('.journey_type').val('OW');
                    $('#dep_1').remove();
                    $('#arr_1').remove();
                }
            }
        })
        $('.autofill_from').click(function(){
            $(this).parents('td').find('.autofill_from_field').val('Киев - IEV (Украина)');
            $(this).parents('td').find('.autofill_from_field').next().val('IEV');
        })
        $('.autofill_from2').click(function(){
            $(this).parents('.av_lines_item').find('.autofill_from_field').val('Киев - IEV (Украина)');
            $(this).parents('.av_lines_item').find('.autofill_from_field').next().val('IEV');
        })
        $('.autofill_to').click(function(){
            $(this).parents('td').find('.autofill_to_field').val('Москва - MOW (Россия)');
            $(this).parents('td').find('.autofill_to_field').next().val('MOW');
        })


        $('.autofill_to2').click(function(){
            $(this).parents('.av_lines_item').find('.autofill_to_field').val('Москва - MOW (Россия)');
            $(this).parents('.av_lines_item').find('.autofill_to_field').next().val('MOW');
        })


        $('#add_punkt').click(function(){
            if (line_cnt < 2)
            {
                $('#clon_template').clone(true).show().attr('id','line'+line_cnt).appendTo('#reic_table');
                $('#line'+line_cnt).find('input').each(function(){
                    var new_name = $(this).attr('name').replace(/NUMBER/,line_cnt);
                    $(this).attr('name',new_name)
                })
                line_cnt++;
                $('.when_back').hide().find('input, select').attr('disabled',true);
                $('#check-1').click();
                if ($('#check-1').next().hasClass('checked'))
                    $('#check-1').click();
                $('.journey_type').val('OJ');
                $('#refresh').attr('src','/ufsa/user/img/arrow.png');
            }
        })

        $('.del_row').live('click',function(){
            $(this).parents('tr').remove();
            line_cnt--;
            if (line_cnt==1)
            {
                $('.journey_type').val('OW');
                $('#refresh').attr('src','/ufsa/user/img/arrow.png');
            }
        })
        $('.date').live('focus',function(){
            $(this).datepicker({ dateFormat: 'dd.mm.yy', minDate: 0, maxDate: "+1Y", showButtonPanel: true, firstDay: 1,dayNamesMin:['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'], monthNames: ['Январь','Февраль','Март','Апрель','Май', 'Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],  dayNames: ['Восскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четвер', 'Пьятница', 'Суббота'] , currentText: 'Сегодня', closeText: 'Закрыть',
            onClose: function(dateText, inst) {
                        var data = dateText.split('.');
                        $(this).next().val(data[0])
                        $(this).next().next().val(data[1]+'/'+data[2])
                     }
            });
        })
        $( ".autocomplete" ).live('focus',function(){
            $(this).autocomplete({ source:'/ufsa/autocomplete.php' , minLength: 2,
                                    select: function( event, ui ) {
                                         $(this).next().val(ui.item.id);

                                    }
            });
        })
        $('.exchange').click(function(){
            var text_left = $(this).prev().find('input[type=text]').val();
            var code_left = $(this).prev().find('input[type=hidden]').val();

            var text_right = $(this).next().find('input[type=text]').val();
            var code_right = $(this).next().find('input[type=hidden]').val();

            $(this).prev().find('input[type=text]').val(text_right);
            $(this).prev().find('input[type=hidden]').val(code_right);
            $(this).next().find('input[type=text]').val(text_left);
            $(this).next().find('input[type=hidden]').val(code_left);

        })
        $('#online_form').click(function(){

            if ($("#avisreis").css('display')=='none')
            {
                $("#arrow_up").css('display','none')
                $("#arrow_down").css('display','inline');
            }
            $("#avisreis").show();
        })

        $('#online_form, #online_form_block').submit(function(){

            var error = '';
            if ($('#dep_0').val()=='')
                error += "Укажите пункт отправления\n";
            if ($('#arr_0').val()=='')
                error += "Укажите пункт прибытия\n";
            if ($('#day_0').val()=='')
                error += "Укажите дату полета\n";
            if (  $('.journey_type').val()=='OJ' && $('#day_0').val()=='')
                error += "Укажите дату второго полета\n";
            if ( $('.journey_type').val()=='RT' && $('#day_0').val()=='')
                error += "Укажите дату возвращения\n";
            if (error != '')
            {
                alert(error);
                return false;
            }
            var action = 'http://ufsa.com.ua/booking-online'+'?framepage='+encodeURIComponent('http://ufsa-kiev.symphony.cz/ru_UA/index.php?')+encodeURIComponent($(this).serialize());
            location.href = action;
            return false;
        })

    });
var TINY={};

function T$(i){return document.getElementById(i)}
function T$$(e,p){return p.getElementsByTagName(e)}

TINY.accordion=function(){
    function slider(n){this.n=n; this.a=[]}
    slider.prototype.init=function(t,e,m,o,k){
        var a=T$(t), i=s=0, n=a.childNodes, l=n.length; this.s=k||0; this.m=m||0;
        for(i;i<l;i++){
            var v=n[i];
            if(v.nodeType!=3){
                this.a[s]={}; this.a[s].h=h=T$$(e,v)[0]; this.a[s].c=c=T$$('div',v)[0]; h.onclick=new Function(this.n+'.pr(0,'+s+')');
                if(o==s){h.className=this.s; c.style.height='auto'; c.d=1}else{c.style.height=0; c.d=-1} s++
            }
        }
        this.l=s
    };
    slider.prototype.pr=function(f,d){
        for(var i=0;i<this.l;i++){
            var h=this.a[i].h, c=this.a[i].c, k=c.style.height; k=k=='auto'?1:parseInt(k); clearInterval(c.t);
            if((k!=1&&c.d==-1)&&(f==1||i==d)){
                c.style.height=''; c.m=c.offsetHeight; c.style.height=k+'px'; c.d=1; h.className=this.s; su(c,1)
            }else if(k>0&&(f==-1||this.m||i==d)){
                c.d=-1; h.className=''; su(c,-1)
            }
        }
    };
    function su(c){c.t=setInterval(function(){sl(c)},20)};
    function sl(c){
        var h=c.offsetHeight, d=c.d==1?c.m-h:h; c.style.height=h+(Math.ceil(d/5)*c.d)+'px';
        c.style.opacity=h/c.m; c.style.filter='alpha(opacity='+h*100/c.m+')';
        if((c.d==1&&h>=c.m)||(c.d!=1&&h==1)){if(c.d==1){c.style.height='auto'} clearInterval(c.t)}
    };
    return{slider:slider}
}();

function visible_reviews(self,id) {
    $.post('/sources/classes/front-review-add.php',{revisible:true , id:id},function(resp) {
        if( resp == 0 )
            self.innerHTML = 'Сделать видимым';
        else
            self.innerHTML = 'Сделать невидимым';
    });
}


function send_review_form ( self ) {
    var sel = $(self);

    var author = sel.children('input:eq(0)')
    var comment = sel.children('textarea')
    var review = sel.find('input:eq(2)')

    var error = false

    if( author.val().length == 0 ) {
        author.css( { border : '#f66 1px solid' } )
        error = true
    } else {
        author.css( { border : '' } )
    }

    if( comment.val().length == 0 ) {
        comment.css( { border : '#f66 1px solid'  } )
        error = true
    } else {
        comment.css( { border : ''  } )
    }

    if( ! error )
        $.post( '/' , {
            comment : comment.val() ,
            author : author.val() ,
            review :review.val() ,
            evaluation : window.evaluation,
            send : 'requestMain'
        } , function(q) {
            if( q == '{}' )
                return
            if( q == '{"done":true}' ) {
                $('#reviewForm').html('<p>Спасибо, ваше сообщение успешно добавлено. В ближайшее время его рассмотрят и подтвердят</p>')
            } else if( q == '{"done":false}') {
                $('#reviewForm').html('<p>Упс, мы не смогли корректно добавить в базу данных Ваш комментарий. Попробуйте это сделать через 5 минут</p>')
            } else {
                alert(q);
            }
        } )


    return false
}

$(document).ready( function() {
        $('.description_tab').show();
        $('.review_tab').hide();
        $('#description_tab').addClass('active');
        window.evaluation = 4

    $('#description_tab').click( function() {
        $('#review_tab').removeClass('active');
        $(this).addClass('active');

        $('.description_tab').show();
        $('.review_tab').hide();
    })

    $('#review_tab').click( function() {
        $('#description_tab').removeClass('active');
        $(this).addClass('active');

        $('.description_tab').hide();
        $('.review_tab').show();
    });
} )


function hide_evaluation(self) {
    $(self).children('.help-evaluation').hide()
}

function show_evaluation(self) {
    $(self).children('.help-evaluation').show()
}

function set_evaluation(num,self) {
    var obj = $(self).parent();
    obj.children('.radiob').removeClass('selectb');
    window.evaluation = num
    obj.children('.radiob').each( function() {
        if( num != 0 ) {

            $(this).addClass('selectb')
            num--;
        }
    } )
}

