var id_ship = 0;

var ferriesEnabledDays = Cfg.ferriesEnableDates || {};

var ferryDirection = 2;

function enableDates(date) {
    var now = new Date(), lastDate = new Date(Cfg.ferriesLastDate);
    var s = '';
    var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
    var a = ($.inArray(y + '-' + ((m > 8)? '' : '0') + (m+1) + '-' + ((d > 9)? '' : '0') + d, ferriesEnabledDays[ferryDirection]) != -1);
    /*if ((date.getTime() >= (now.getTime() + 21*24*60*60*1000)) && a && (date.getTime() < lastDate.getTime()))
        s = 'eb';*/
    return [a, s];
}
                            
$('#container').ready(function(){

    if($.isFunction($.fn.autocomplete)) {
    	
		(function( $ ) {
			$.widget( "ui.combobox", {
				_create: function() {
					var self = this,
						select = this.element.hide(),
						selected = select.children("[selected=selected]"),
						value = selected.length ? selected.text() : ( select.attr('default') ? select.attr('default') : ''  );
					var input = this.input = $( "<input>" )
						.insertAfter( select )
						.val( value )
						.focus( function() {
							var curVal =  $.trim(input.val()), defVal = input.attr('default');
							if(curVal == defVal) {
								input.val('');
							}
						})
						.blur( function() {
							var curVal = $.trim(input.val()), defVal = input.attr('default');
							if(curVal == '') {
								input.val(defVal);
							}
						})						
						.autocomplete({
							delay: 0,
							minLength: 0,
							source: function( request, response ) {
								var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
								response( select.children( "option" ).map(function() {
									var text = $( this ).text();
									if ( this.value && ( !request.term || matcher.test(text) ) )
										return {
											label: text.replace(
												new RegExp(
													"(?![^&;]+;)(?!<[^<>]*)(" +
													$.ui.autocomplete.escapeRegex(request.term) +
													")(?![^<>]*>)(?![^&;]+;)", "gi"
												), "<strong>$1</strong>" ),
											value: text,
											option: this
										};
								}) );
							},
							select: function( event, ui ) {
								ui.item.option.selected = true;
								self._trigger( "selected", event, {
									item: ui.item.option
								});
								select.trigger('change');
							},
							change: function( event, ui ) {
								if ( !ui.item ) {
									var curVal = $.trim($(this).val());
									var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( curVal ) + "$", "i" ),
									valid = false;
									select.children( "option" ).each(function() {
										if ( $( this ).text().match( matcher ) ) {
											this.selected = valid = true;
											return false;
										}
									});
									if ( !valid ) {
										// remove invalid value, as it didn't match anything
										if(!curVal || curVal == input.attr('default')) { 
											$( this ).val( input.attr('default') );								
											select.val( "" );
											input.data( "autocomplete" ).term = "";
											return false;
										}
									}
								}
								select.trigger('change');
							}
						})
						.attr('default', value)
						.addClass( "field text combo-text" );

					input.data( "autocomplete" )._renderItem = function( ul, item ) {
						return $( "<li></li>" )
							.data( "item.autocomplete", item )
							.append( "<a>" + item.label + "</a>" )
							.appendTo( ul );
					};

					this.button = $( "<a class='icon'>&nbsp;</a>" )
						.attr( "tabIndex", -1 )
						.attr( "title", "Show All Items" )
						.insertAfter( input )
						.click(function() {
							// close if already visible
							if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
								input.autocomplete( "close" );
								return;
							}

							// work around a bug (likely same cause as #5265)
							$( this ).blur();

							// pass empty string as value to search for, displaying all results
							input.autocomplete( "search", "" );
							input.focus();
						});
				},

				destroy: function() {
					this.input.remove();
					this.button.remove();
					this.element.show();
					$.Widget.prototype.destroy.call( this );
				}
			});
		})( jQuery );

		$(".combo.autocomplete").combobox({});
	}
    if($.isFunction($.fn.jcombox)) {
        $('.search-inner select[name=travellers_number]').jcombox({'width':'50'});   
        $('select.direction-combo').jcombox({});   
	    $('select.custom-select').jcombox({
	        fx: 'slide'
	    });
	}
    
    var now = new Date();
    
    $('.search-block').click(function(){
        $(this).parents('.switcher-group').trigger('stopplay').addClass('stopped');
    });
	
    $('#group-tours-form .date-pick').datepicker({
        showOn: "both",
        buttonImage: "/img/calendar.gif",
        showOtherMonths: true,
        minDate: new Date(now.getTime() + 3*24*60*60*1000) ,
        beforeShow: function(input, inst) {        
            $(input).parents('.switcher-group').trigger('stopplay');
            window.setTimeout(function(){
                $(inst.dpDiv).find('.ui-state-active').removeClass('ui-state-active');      
            },0);            
        },
        onChangeMonthYear: function(year, month, inst) {
            window.setTimeout(function(){
                $(inst.dpDiv).find('.ui-state-active').removeClass('ui-state-active');      
            },0);
        }
    });
    
    $('#searchCitybreaksForm .date-pick').datepicker({
        showOn: "both",
        buttonImage: "/img/calendar.gif",
        showOtherMonths: true,
        minDate: new Date(now.getTime() + 3*24*60*60*1000) ,
        beforeShow: function(input, inst) {        
            $(input).parents('.switcher-group').trigger('stopplay');
            window.setTimeout(function(){
                $(inst.dpDiv).find('.ui-state-active').removeClass('ui-state-active');      
            },0);            
        },
        onChangeMonthYear: function(year, month, inst) {
            window.setTimeout(function(){
                $(inst.dpDiv).find('.ui-state-active').removeClass('ui-state-active');      
            },0);
        }
    });
    
    $('.date-pick').datepicker({
		showOn: "both",
		buttonImage: "/img/calendar.gif",
		showOtherMonths: true,
		minDate: now,
		beforeShow: function(input, inst) {		
			$(input).parents('.switcher-group').trigger('stopplay');
            window.setTimeout(function(){
                $(inst.dpDiv).find('.ui-state-active').removeClass('ui-state-active');      
            },0);            
		},
		onChangeMonthYear: function(year, month, inst) {
			window.setTimeout(function(){
				$(inst.dpDiv).find('.ui-state-active').removeClass('ui-state-active');      
			},0);
		}
    }); 
    
    $("#ferry-date-to")
    .datepicker('option', 'maxDate', new Date(Cfg.ferriesLastDate))
    .datepicker('option', 'beforeShowDay', enableDates);
    
	$('*[name=ferry_direction]').change(function(){
		ferryDirection = $(this).val();
		$("#ferry-date-to").datepicker("show");
	});    

    $('.date-pick[name=date_arrival]').datepicker("option", "onSelect", function(dateText, inst){
        var dateReturn = $('.date-pick[name=date_departure]');
        if(dateReturn.length) {
	        dateReturn.datepicker('setDate',$(this).datepicker('getDate'));
	        dateReturn.datepicker('option', 'minDate', $(this).datepicker('getDate'));
	        dateReturn.val(dateText);
		}
    });

    $('a.buttonEnterShipDetails').click(function(event){
    	var block = $(this).parents('form');
        event.preventDefault();
        block.find('.departure').slideToggle();
        block.find('.arrival').slideToggle();
        block.find('.selectName').slideToggle();
        block.find('.select').slideToggle();
        block.find('.inputName').slideToggle('normal', function(){
            block.find('input.inputShipName').focus();
        });
        $(this).toggleHtml("Select your ship name", "Can't find your ship in the list?");
        block.find('.customShip').toggleValue('0', '1');
    });

    $('.search-inner form.searchBox').submit(function(event){

        var errors = [];
        var $this = $(this);
        custom = parseInt($this.find('.customShip').val());
        if(custom){
            if (!$this.find('.inputShipName').val()){
                errors.push('Please, enter ship name.');
                $this.find('inputShipName').focus();
            } else {
                date_arrival = parseInt($this.find('.date_icon1').val(), 10);
                date_departure = parseInt($this.find('.date_icon2').val(), 10);

                if(!date_arrival){
                    errors.push('Please, enter arrival date.');
                }

                if(!date_departure){
                    errors.push('Please, enter day of departure.');
                }
            }
        } else if (!parseInt($this.find('.selectShipName').val())){
            errors.push('Please, type in or select your ship.');
            $this.find('selectShipName').focus();
        }

        if(errors.length){
            event.preventDefault();
            alert(errors.join('\n'));
        }
    });
    
    
	/*$('.date-pick').mask("19/39/2999", {
        label: 'mm/dd/yyyy'
    });*/
    $('.selectShipName').change(function(event){
    	var form = $(this).parents('form');
    	var $select_startdate = form.find('[id^=id_voyage]');
    	
        if(parseInt($(this).val()) && $(this).val() != id_ship){
            id_ship = $(this).val();
			
            $select_startdate.jcClear("Loading dates...");
            $select_startdate.jcDisable();
            $.post('/ships/schedule/',
            {
                id_ship: id_ship
            },
            function(data){
                if(data.ok){
                    var first = true;
                    $select_startdate.jcClear();
                    $.each(data.voyages, function(i){
                        var cl = this.discount ? "hot-deal" : "";
/*                        var date = new Date();

                        // Учёт смещения по часовм поясам
                        var offset = 0;
                        if (date.getTimezoneOffset() > -240)
                            // Часовой пояс западнее Спб
                            offset = (date.getTimezoneOffset() + 240 ) * 60;
                        else if (date.getTimezoneOffset() < -240)
                            // Часовой пояс восточнее Спб
                            offset = (date.getTimezoneOffset() + 240) * -60

                        this.date = parseInt(this.date) + offset;
                        date.setTime(parseInt(this.date) * 1000);
*/

                        $select_startdate.jcAdd(this.id, this.date, first, cl);
                        first = false;
                    });
                    $select_startdate.jcEnable();
                }
            }, 'json');
			
        } else if(!parseInt($(this).val())) {
            $select = form.find('.select-arrival');
            $select.html('<option>Type in or select your ship</option>');
            $select.disable();
            id_ship = $(this).val();
        }
    });
    
    $('.search-block').each(function(){
        $this = $(this);
        $('h2', $this).click(function(event){
            event.preventDefault();
            var id = $(this).parents('.section').attr('id').split('-')[1];
            showBlock(id);
        });

        function showBlock(id){
            var idStr = '#search-' + id;
            $('.section', $this).filter(idStr).removeClass('closed').end().not(idStr).addClass('closed');
        }

        showBlock('baltic');
    });
	
    $('#searchCitybreaksForm').submit(function(event){
        var errors = [];
		
        var date_start = parseInt($('#cb_start').val(), 10);

        if(!date_start){
            errors.push('Please, enter tour start date.');
        }
		
        if(errors.length){
            event.preventDefault();
            alert(errors.join('\n'));
        }
    });
});

/**
 * jCombox
 */
(function ($) {
    $.fn.setOffCss = function (a) {
        var b = this.parent();
        if ($(window).height() + (document.documentElement.scrollTop || document.body.scrollTop) < b.offset().top
            + this.height() + b.height()) {
            objTop = b.offset().top - ($.browser.msie ? 3 : 1) - this.height()
        } else {
            objTop = b.offset().top + ($.browser.msie ? -1 : 1) + b.height()
        }  
        return this.css({
            //left: b.offset().left - ($.browser.msie ? 2 : 0),
            //top: objTop,
            width: b.width() + ($.browser.msie ? 2 : 0)
        });
    };
    $.fn.fadesTo = function (o) {
        return this.animate({
            opacity: o
        },
        0,
        function () {
            if (o == 1 && $.browser.msie) {
                this.style.removeAttribute("filter");
            }
        });
    };
    $.fn.addClassAll = function(cssClass){
        $(this).addClass('disabled');
        $('*', $(this)).addClass('disabled');
    };
    $.fn.removeClassAll = function(cssClass){
        $(this).removeClass('disabled');
        $('*', $(this)).removeClass('disabled');
    };

    $.fn.jcombox = function (o) {
        o = $.extend({
            fn: null,
            fx: "toggle",
            fxType: "easeOutBounce",
            fxDelay: 0,
            set: false,
            theme: "default",
            linkUrl: null
        },
        o || {});
        return this.each(function () {
            var b = $(this),
            _7 = "",
            _8 = b.attr("name"),
            _9 = $("option:selected", b).text(),
            _a = b.val(),
            _b = "#" + _8,
            _id = _8,
            _c = b.attr("size"),
            _d = b.attr("rows") || 0,
            _e = b.attr("width") || 0,
            _f = b.attr("disabled") || 0,
            _10 = b.attr("onchange") || b.attr("onChange") || 0;
			
            //if(b.attr('id')) _b = '#' + b.attr('id');
            
            if($('*[name=' + _8 + ']').length > 1) {
            	var ind = $('*[name=' + _8 + ']').index(b);
            	_id += '_' + ind;
            	_b += '_' + ind;
			}
			
            $("option", b).each(function () {
                if ($(this).attr("selected")) {
                    _9 = $(this).text();
                    _a = $(this).val()
                }
                _7 += ("<a href='" + (o.linkUrl != null ? "?" + _8 + "=" + $(this).val() : "#") + "' rel='"
                    + $(this).val() + "' class='item "+this.className+"'>" + $(this).text() + "</a>");
            });
            if (_c > 0) {
                b.replaceWith("<div class='jcombox-m " + o.theme + "' id='" + _id + "'><input type='hidden' name='" + _8
                    + "' value='" + _a + "' /><div>" + _7 + "</div></div>");
                $(_b).css("background-image", "none");
                if (!$("div a", _b).eq(0).text()) {
                    $("div a", _b).eq(0).text("-");
                }
                $(_b).width($("div", _b).width() + 40 + "px");
                $(_b).height($("div a", _b).height() * _c + ($.browser.msie ? 4 : 2) + "px")
            } else {
                b.replaceWith("<div class='jcombox " + o.theme + "' id='" + _id + "'><span class='field' style='width:'" + _e + "px'>" + _9
                    + "</span><input type='hidden' /><div class='menu'>" + _7
                    + "</div><a class='icon'></a></div>");
                var c = $(_b);
                c.find('input').val(_a).attr('name', _8).attr('id', _8 + "-field");
                if ($("span", _b).width() > $("div", _b).width()) {
                //$(_b).width($("span", _b).width() + 35 + "px");
                } else {
                //$(_b).width($("div", _b).width() + 40 + "px");
                }
                if (_d > 1) {
                    $("div", _b).height($("span", _b).height() * _d + ($.browser.msie ? 2 : 0) + "px");
                }
                $(document).click(function (e) {
                    if ($("div", _b).css("display") == "block") {
                        $("div", _b).hide();
                    }
                });
				
                c.hover(function () {
                    clearTimeout(this.timeout);
                },
                function () {
                    this.timeout = setTimeout(function () {
                        if ($("div", _b).css("display") == "block") {
                            c.trigger("click");
                        }
                    },
                    750);
                });
                if (!$("span.field", _b).text()) {
                    $("span.field", _b).text("-");
                }
                if (o.set) {
                    c.css({
                        "border": "transparent",
                        "background-color": "transparent",
                        "padding-right": "2px"
                    });
                    $("span", _b).css({
                        "border": "transparent",
                        "background-image": c.css("background-image"),
                        "background-position": "left center",
                        "padding": "0 0px 3px 5px"
                    })
                }
            }
            $("div", _b).find("a[rel='" + $("input", _b).val() + "']").addClass("current");
            $(_b).bind("jcDisable", function () {
                $("input", _b).val("").trigger("change");
                if ($("div", _b).css("display") == "block" && !_c > 0) {
                    $("div", _b).hide();
                }
				
                $(_b).unbind("click");
                $(_b).addClassAll("disabled");
                $("div a", _b).unbind("click").bind("click", function () {
                    return false;
                });
            });
			
            $(_b).bind("jcEnable", function () {
                $(_b).removeClassAll("disabled");
                $("input", this).val($(".current", this).attr("rel"));
                if (!_c > 0) {
                    $(_b).unbind("click").bind("click", function (e) {
                        var a = $("div", _b);
                        switch (o.fx) {
                            case "toggle":
                                a.setOffCss().toggle();
                                break;
                            case "slide":
                                a.setOffCss().slideToggle(o.fxDelay);
                                break;
                            case "fade":
                                a.setOffCss().animate({
                                    opacity:
                                    "toggle"
                                },
                                o.fxDelay).fadesTo(1);
                                break;
                            case "slideFade":
                                a.setOffCss().animate({
                                    opacity:
                                    "toggle",
                                    height: "toggle"
                                },
                                o.fxDelay).fadesTo(1);
                                break;
                            case "easing":
                                a.setOffCss().slideToggle(o.fxDelay, o.fxType);
                                break
                        }
                        e.stopPropagation();
                    });
                }
                $("a.item", _b).unbind("click").bind("click", function () {
                    if ($(this).hasClass("disabled")) {
                        return false;
                    }
                    $("a", _b).removeClass("current");
                    $(this).addClass("current");
                    if ($.browser.safari) {
                        $(this).fadesTo(0.99).fadesTo(1);
                    }
                    if (!_c > 0) {
                        $("span.field", _b).text($(this).text());
                        $(_b).trigger("click");
                    }
					
                    if($(this).hasClass('hot-deal')){
                        $("span.field", _b).addClass('hot-deal');
                    } else {
                        $('span.field', _b).removeClass('hot-deal');
                    }
					
                    $("input", _b).val($(this).attr("rel")).trigger("change");
                    if (o.fn) {
                        o.fn();
                    }
                    if ($.browser.msie && _10) {
                        eval(_10());
                    } else {
                        if (_10) {
                            eval(_10);
                        }
                    }
                    return false;
                });
                $("a", this).css("color", $("." + o.theme).css("color"));
                $("span.field", this).css("overflow", "hidden");
            });
            if (b.attr("disabled")) {
                $(_b).trigger("jcDisable");
            } else {
                $(_b).trigger("jcEnable");
            }
            $(_b).bind("selectstart mousedown", function () {
                return false
            }).css("MozUserSelect", "none");
            $(_b).hover(function () {
                $(this).addClass(o.theme + "-hover");
                if (o.set) {
                    $("span", _b).css("background-image", c.css("background-image"));
                }
            },
            function () {
                $(this).removeClass(o.theme + "-hover");
                if (o.set) {
                    $("span", _b).css("background-image", $("." + o.theme).css("background-image"));
                }
            });
            if (_e) {
         //       debugger;
                $(_b).width(_e + "px");
                $('span', _b).width(_e + "px");
                var diff = $('.icon', _b).offset().left - parseInt($('.icon', _b).css('left').replace('px', ''));
                if(diff < 0) diff = 0;
                $('.icon', _b).css('left', $('span', _b).offset().left - diff + parseInt(_e) + ($.browser.msie ? 4 : 2));
            }
			
            $("div", _b).mouseover(function(){
                $('.current', $(this)).removeClass('current');
            });
        })
    };
    var d = ["jcEnable", "jcDisable", "jcClear"];
    for (var i = 0; i < d.length; i++) {
        $.fn[d[i]] = (function (a) {
            return function () {
                this.trigger(a);
            }
        })(d[i])
    }
    $.fn.jcSelected = function (a) {
        if (a) {
            return $(".current", this).text();
        } else {
            return $("input", this).val();
        }
    };
	
    $.fn.jcAdd = function (a, b, c, cl) {
        if (c) {
            $("a.current", this).removeClass()
        }
        $("div", this).append("<a class='item " + (c ? "current ": "") + cl + "' href='#' rel='" + a + "' >" + b + "</a>");
        if (c) {
            $("span.field", this).text($(".current", this).text());
            if(cl) {
                $("span.field", this).addClass(cl);
            } else {
                $("span.field", this).removeClass('hot-deal');
            }
        }
    };
	
    $.fn.jcEdit = function (a, b) {
        $(".current", this).replaceWith("<a class='current' href='#' rel='" + a + "' >" + b + "</a>");
        this.jcEnable();
        if ($(".current", this).text()) {
            $("span.field", this).text($(".current", this).text());
        }
    };
	
    $.fn.jcClear = function (a) {
        if (parseInt(a)) {
            $("a.current", this).removeClass()
        } else {
            $(".current", this).slideUp(function () {
                $(this).remove();
            })
        }
        this.jcEnable();
        $("span.field", this).text(a?a:"-");
        $("input", this).val("");
        $('a.item', this).each(function(){
            $(this).remove();
        });
    }

})(jQuery);

