﻿var _culture = Sys.CultureInfo.CurrentCulture.name.toLowerCase();
var ie = $.browser.msie;
var ie7 = ($.browser.msie && $.browser.version == 7);

function stickyFooter(recall) {
    return;
    $("#ui-footer").stickyFooter();
    if (recall) {
        setTimeout(function () {
            stickyFooter(true);
        }, 2000);
    }
}

function setupSupportWidget() {
    $("#SupportWidget").hover(function () {
        $("#SupportWidget").stop(true, false).animate({ left: "0px" }, "medium");
    }, function () {
        $("#SupportWidget").stop(true, false).animate({ left: "-225px" }, "medium");
    }, 500);
}

function setBlueSectionVisibility() {
    if ($('div#blue-section').size() > 0) {
        if ($('div#blue-section').html().length > 70)
            $('div#blue-section').removeClass('hidden');
    }
}

function zIndexFix()
{
    if(ie7)
    {
        var zIndexNumber = 1000;
        // Put your target element(s) in the selector below!
        $("div").each(function() {
                $(this).css('zIndex', zIndexNumber);
                zIndexNumber -= 10;
        });
    }
}

function removeNativeTooltips()
{
    $('#ui-topapps a[title]').each(function(){
        var $link = $(this);
        $link.data('title',$link.attr('title'))
             .removeAttr('title');
    });
}

function initDatePicker() {
    //var d = return new Date(Date.now().setDate(Date.now().getDate() + days))
    var d = new Date();
    var out = new Date().getDate() + 3;
    d.setDate(out);

    $.datepicker.setDefaults(
	{
	    numberOfMonths: 5
		, minDate: d//(new Date()).addDays(3)
		, maxDate: '+1Y'
		, showOtherMonths: true
		, selectOtherMonths: true
		, showWeek: true
		, firstDay: 1
		, showOn: 'both'
		, buttonImage: '/cmstemplates/vivatravelaspx/images/calendar.gif'
		, buttonImageOnly: true
	});

    // set culture for all jquery ui controls
    var twoLettersLanguage = _culture.substring(0, 2);
    $.datepicker.setDefaults($.datepicker.regional[twoLettersLanguage]);

    $('input[_datepicker]').each(function () {
        $.metadata.setType('attr', '_datepicker');

        var meta = $(this).metadata();
        var before = (meta.beforeShow == null ? function () { } : meta.beforeShow);
        var onSelect = (meta.onSelect == null ? function () { } : meta.onSelect);
        var onClose = (meta.onClose == null ? datepicker_onClose : meta.onClose);
        var showMonth = (meta.showMonth == null ? true : meta.showMonth);
        var showYear = (meta.showYear == null ? false : meta.showYear);
        var size = (meta.size == null ? 2 : meta.size);
        var range = meta.range;

        $(this).data('_datepicker', meta).datepicker(
		{
		    beforeShow: before
			, onSelect: onSelect
			, onClose: onClose
			, changeMonth: showMonth
			, changeYear: showYear
			, numberOfMonths: size
			, yearRange: range
		});

        if (meta.min != null) {
            var min = String.toDate(meta.min, 'yyyy-MM-dd');
            $(this).datepicker('option', 'minDate', min);
        }

        if (meta.max != null) {
            var max = String.toDate(meta.max, 'yyyy-MM-dd');
            $(this).datepicker('option', 'maxDate', max);
        }

        var defaultDate = $(this).data('_datepicker').defaultDate;

        ///////////////////if it is German replace "." with "/"///////////////////////////////////
        if (twoLettersLanguage == 'de' || twoLettersLanguage == 'ru' || twoLettersLanguage == 'ja') {
            var intIndexOfMatch = defaultDate.indexOf(".");

            // Loop over the string value replacing out each matching
            // substring.
            while (intIndexOfMatch != -1) {
                // Relace out the current instance.
                defaultDate = defaultDate.replace(".", "/");
                // Get the index of any next matching substring.
                intIndexOfMatch = defaultDate.indexOf(".");
            }
        }
        //////////////////////////////////////////////////////

        if (defaultDate != null)
            this.value = defaultDate;

    });
}

function initAutocomplete() {
    $.metadata.setType('attr', '_autocomplete');

    $('input[_autocomplete]').each(function () {
        var data = $(this).metadata();
        var target = $(this);
        var _change = (data.onchange == null ? function () { } : data.onchange);
        var cache = {};

        if (data.cache != null) {
            var key = String.format('cache-{0}', data.cache);
            cache = (window[key] || (window[key] = {}));
        }

        $(this).data('_autocomplete', data)
		.attr('valid', false)
		.change(function () {
		    // set this item validity to false
		    var box = $(this);
		    box.attr('valid', false);

		    if (box.val() == null || box.val().length == 0)
		        box.next('input[type=hidden]').val('');
		})
		.keydown(function (ev) { return (ev.keyCode != 13); })
		.mouseup(function (event) {
		    if (this.focused == 'enter') {
		        var me = this;
		        setTimeout(function () { me.select(); }, 0);
		    }
		    this.focused = 'done';
		})
		.blur(function () { this.focused = 'clear'; })
		.focusin(function () { this.focused = 'enter'; })
		.autocomplete(
		{
		    delay: 300
			, minLength: 2
			, source: function (request, response) {
			    var term = request.term;
			    if (term in cache)
			        response(cache[term]);
			    else {
			        var query = String.format('{0}?{1}', data.url, 'q=' + escape(request.term) + '&rnd=' + Math.random());
			        $.getJSON(query, function (data) {
			            if (data.length > 0 && typeof (data[0].value) == 'undefined') {
			                var out = ($.map(data, function (item) {
			                    return {
			                        label: (request.term.charCodeAt(0) > 912 ? item.rNm : item.rNm + ' - ' + item.rAb),
			                        value: item.rId
			                    }
			                }));

			                response(out); // show response
			                cache[term] = out; // cache
			            }
			            else {
			                response(data); // show response
			                cache[term] = data; // cache
			            }
			        });
			    }
			}

			, change: function (event, ui) {
			    var box = $(event.target);
			    var data = box.data('_autocomplete');

			    if (data.onchange != null) {
			        setTimeout(function () {
			            // if not selection is valid then fire validate_selection
			            if (box.attr('valid').toString() != 'true')
			                validate_selection(box);
			        }, 210);
			    }
			}

			, focus: function (event, ui) {
			    var label = ui.item.label;
			    if (label.indexOf('- [') >= 0)
			        label = label.substr(0, label.indexOf('- [') - 1);

			    $(event.target).val(label);
			    return false;
			}

			, select: function (event, ui) {
			    var label = ui.item.label;
			    var textbox = $(event.target);

			    if (label.indexOf('- [') >= 0)
			        label = label.substr(0, label.indexOf('- [') - 1);

			    // set label
			    textbox.val(label).attr('valid', true);

			    // set value to hidden field
			    var hid = textbox.next('input[type=hidden]').first();
			    hid.val(ui.item.value);

			    var container = $(event.target).closest('.regions');
			    var inputs = container.find('input');
			    var filter = function () { return this.type == 'text'; };
			    var fromRegion = inputs.filter(filter).first();
			    var toRegion = inputs.filter(filter).last();

			    if (data.direction == 'from') {
			        // set focus on next field
			        setTimeout(function () {
			            //container.find('input[type=text]:last').get(0).focus();
			            toRegion.focus();
			        }, 10);
			    }

			    if (typeof (data.validation) == 'function') {
			        if (fromRegion.val().length > 0 && toRegion.val().length > 0) {
			            var from = { textbox: fromRegion, hidden: container.find('input[type=hidden]:first') };
			            var to = { textbox: toRegion, hidden: container.find('input[type=hidden]:last') };

			            if (from.hidden.val().length > 0 && to.hidden.val().length > 0)
			                data.validation(from, to, data.direction);
			        }
			    }

			    return (false);
			}
		});
    });
}

function initDefaultValues() {
    $('input[_defaultValue]').each(function () {
        var auto = $(this).attr('_autoSelect');
        $(this).defaultValue({ autoSelect: (auto != null && auto.toString() == 'true') });
    });
}

function datepicker_beforeShow() {
    var data = $(this).data('_datepicker');
    var fieldId = this.id;
    var min = 0;

    if (data.direction == 'to') {
        var from = $(this).closest('.dates').find('input[_datepicker]').filter(function () { return $(this).data('_datepicker').direction == 'from'; });
        var dateFrom = from.datepicker('getDate');

        if (dateFrom == null)
            dateFrom = new Date();

        from.datepicker('setDate', dateFrom);
        min = dateFrom;
    }

    if (data.min == null) {
        var now = new Date();
        var def = $.extend({}, {}, __viva);
        var days = (def.d == null ? 2 : def.d);
        now.setDate(now.getDate() + days);
        min = now;
    }
    else {
        var dt = String.toDate(data.min, 'yyyy-MM-dd');
        min = dt;
    }

    return { minDate: min };
}

function datepicker_onSelect(datetext) {
    var data = $(this).data('_datepicker');
    var fields = $(this).closest('.dates').find('input[_datepicker]');

    var dateFrom = fields.first().datepicker('getDate');
    var dateTo = fields.last().datepicker('getDate');

    var twoLettersLanguage = _culture.substring(0, 2);

    if (dateFrom > dateTo) {
        dateFrom.setDate(dateFrom.getDate() + 3);
        if (twoLettersLanguage == 'en')
            fields.last().val($.datepicker.formatDate('mm/dd/yy', dateFrom));
        else if (twoLettersLanguage == 'ja')
            fields.last().val($.datepicker.formatDate('yy/mm/dd', dateFrom));
        else
            fields.last().val($.datepicker.formatDate('dd/mm/yy', dateFrom));
        ////dateFrom.setDate(dateFrom.getDate() + 3);
        ////fields.last().val($.datepicker.formatDate('dd/mm/yy', dateFrom));
    }
}

function datepicker_onClose() { toggle_active_result(false); }
function toggle_active_result(hide) {
    var results = $('div#results');
    var position = (hide ? 'static' : 'relative');
    results.find('div[_whitebox=yes]:visible').first().children().css('position', position);
    results.find('div[_flightheader]:visible').first().children().css('position', position);
    results.find('div[_summary]:visible').css('visibility', (hide ? 'hidden' : 'visible'));
}

function datepicker_onHotelDateChanged() {
    //Validate
    var data = $(this).data('_datepicker');
    var fields = $(this).closest('.dates').find('input[_datepicker]');

    var dateFrom = fields.first().datepicker('getDate');
    var dateTo = fields.last().datepicker('getDate');

    if (dateFrom > dateTo) {
        dateFrom.setDate(dateFrom.getDate() + 3);
        fields.last().val($.datepicker.formatDate('dd/mm/yy', dateFrom));
    }

    //Split
    var todate = $.datepicker.formatDate('dd/mm/yy', dateTo);
    var fromdate = $.datepicker.formatDate('dd/mm/yy', dateFrom);

    $('input[name=checkin_monthday]').val(fromdate.split('/')[0]);
    $('input[name=checkin_year_month]').val(fromdate.split('/')[2] + '-' + fromdate.split('/')[1]);

    $('input[name=checkout_monthday]').val(todate.split('/')[0]);
    $('input[name=checkout_year_month]').val(todate.split('/')[2] + '-' + todate.split('/')[1]);

    //Check Availability
    $('#b_availcheck').attr('checked', true);
}

function doValidateHotels() {
    var destination = $('input#b_destination'); //.val();
    if (destination.val().length > 0 && destination.val() != destination.attr('_defaultValue')) {
        //$('input#doHotelsSearch').click();
        var container = destination.closest('[role=hotel-search]');
        var elements = container.find('input[type=hidden],input[type=text],input[type=checkbox]').filter(function () {
            return !$(this).hasClass('hasDatepicker');
        });

        var url = _urlMappings.hotels_booking + '?' + $.param(elements);

        if (self != top)
            window.open(url);
        else
            document.location.href = url;
    }
    else {
        alert_message(ferries_resources.Caution, ferries_resources.PleaseFillTheDestinationNotification, { resizable: false, height: 100 });
        return false;
    }
}

function validate_combination(fromRegion, toRegion, direction) {
    var same = (fromRegion.hidden.val().toLowerCase() == toRegion.hidden.val().toLowerCase());
    if (same) {
        var fields = (direction == 'from' ? toRegion : (direction == 'to' ? fromRegion : null));
        if (fields != null) {
            fields.textbox.val('');
            fields.hidden.val('');

            setTimeout(function () {
                fields.textbox.focus();
            }, 10);
        }
    }
    else {
        var hid = toRegion.hidden;
        var fromText = fromRegion.textbox;
        var suggestionDiv = '';

        var url = _urlMappings.combination_handler + '?arrRID=' + toRegion.hidden.val() + '&rnd=' + Math.random();

        // block ui
        fromRegion.textbox.closest('div[_searchbox=yes]').block();

        $.ajax(
	    {
	        url: url
		    , dataType: 'json'
		    , success: function (data) {
		        var found = false;
		        $.each(data, function () {
		            var rName = (_culture == 'el-gr' ? this.rNm : this.rNmEn);

		            suggestionDiv = suggestionDiv + "<div><b><a href=\"javascript:\" onclick=\"set_region('"
								    + fromRegion.textbox.get(0).id + "', '" + rName + "', " + this.rId + ");\">" + this.rAb + ' - ' + rName + "</a></b></div>";

		            if (fromRegion.hidden.val() == this.rId)
		                found = true;
		        });

		        var divHeight = 100;
		        var divResizable = false;

		        if (suggestionDiv.length == 0)
		            suggestionDiv = String.format(ferries_resources.NoHarborToThisDestination, toRegion.textbox.val());
		        else {
		            suggestionDiv = String.format(ferries_resources.ItineraryCanNotBeExecuted, toRegion.textbox.val()) + suggestionDiv;
		            divHeight = 200;
		            divResizable = true;
		        }

		        if (!found) {
		            var dg = get_dialog();
		            alert_message(ferries_resources.Caution, suggestionDiv, { resizable: divResizable, height: divHeight });
		        }

		        fromRegion.textbox
				    .closest('div[_searchbox=yes]')
				    .unblock()
				    .find('[_trigger=yes]').find('a').attr('disabled', !found);

		    }
		    , error: function (jqXHR, textStatus, errorThrown) {
		        //alert(errorThrown);
		        fromRegion.textbox.closest('div[_searchbox=yes]').unblock();
		    }
	    });
    }
}

function set_region(target, label, value) {
    $('#' + target, 'div[_search=ferries]').val(label)
		.next(':hidden')
		.val(value)
		.closest('div[_searchbox=yes]')
		.unblock()
		.find('[_trigger=yes]')
		.find('a')
		.attr('disabled', false);

    var dg = $('div#dialog-modal');
    dg.dialog('close');
}

function go_air() {
    if (document.location.href.toLowerCase().indexOf('#air') > -1)
        $('a[href=#air').click();
    else
        document.location.href = '/#air';
    return (false);
}

function loadFlashMovies() {
    $('#air-counter').flash({
        src: '/media/swf/Countdown.swf'
		, width: 437
		, height: 267
    });
}

function _hideBeforeExpand(id) {
    var c = $(id).attr('className');
    var visible = $('div.' + c).filter(function () { return $(this).is(':visible') });
    var onCompleted = function () {
        $(id).slideDown('normal');
    };

    if (visible.size() > 0)
        visible.slideUp('fast');

    onCompleted();
}

function make_tooltips() {
    $('*[tooltip]').each(function () {
        var position = 'top center';

        if ($(this).attr('position') != null)
            position = $(this).attr('position');

        var def = $(this).attr('def');

        $(this).attr('title', function () { return unescape($(this).attr('tooltip')); })
		.tooltip(
		{
		    //tip: '#temp'
		    tipClass: 'tooltip' + (def != null && def.length > 0 ? ' ' + def : '')
			, delay: 0
			, effect: 'toggle'
			, position: position
		}).dynamic({ bounce: true });

        $(this).removeAttr('tooltip');
    });

    // resize explicitly
    $(window).bind('resize', function () { $().popup('reposition'); });

    $('*[jtip]').livequery(function () {
        var tipClass = 'frz-details',
	        raiser = $(this);

        if (raiser.attr('className') != '')
            tipClass = raiser.attr('className');

        if (tipClass = 'frz-details') {
            raiser.hover(function () {
                var rel = raiser.attr('rel');
                if (typeof (raiser.data('results')) == 'undefined') {
                    $.get(rel, function (results) {
                        raiser.data('results', results);
                        $('.tooltip_blue_ferries_content').html(results);
                        $().popup('reposition');
                    });
                }
                else {
                    $('.tooltip_blue_ferries_content').html(raiser.data('results'));
                    $().popup('reposition');
                }
            },
            function () {
                //raiser.removeAttr('rel');
            });

            $('#ferry-details')
              .popup({ htmlBlock: 'p' })
              .popup('assign', raiser, 'mouseenter', 'show', {
                  position: {
                      relativeTo: raiser,
                      x: 'right',
                      y: 'top',
                      offsetX: -60
                  },
                  showOptions: { opacity: 1, duration: 0 },
                  hideOptions: { duration: 0 }
              })
              .popup('assign', raiser, 'mouseleave', 'hide')
        }
        else {
            var api2 = raiser.simpletip(
		    {
		        position: 'left'
			    , baseClass: tipClass
			    , persistent: true
			    , fixed: false
			    , content: ferries_resources.NoInformation
		    }).simpletip();

            raiser.hover(function () {
                var rel = raiser.attr('rel');
                if (rel.length > 0)
                    api2.load(rel);
            },
            function () {
                raiser.removeAttr('rel');
            });
        }

        raiser.removeAttr('jtip');
    });
}

function initLanguageSelection() {
    $(".langslkt").click(function (e) {
        e.preventDefault();
        $("fieldset#langselection_menu").slideToggle('normal')
										.find('a.langslkt')
										.toggleClass("menu-open");
    });
    $("fieldset#langselection_menu").mouseup(function () { return false });
    $(document).mouseup(function (e) {
        if ($(e.target).parent("a.langslkt").length == 0) {
            $("fieldset#langselection_menu").slideUp(500)
											.find('a.langslkt')
											.removeClass("menu-open");
        }
    });
}

function initLastRequestsAccordion() {
    if (window['_useaccordion'] != null && window['_useaccordion'].toLowerCase() == 'true') {
        $('#accdr dd').bind('click', function () {
            location.href = $(this).find('a:first').attr('href');
        })
        $('#accdr dd').hide();
        $('#accdr dt a').bind('click', function () {
            if (!$(this).hasClass('actv')) {
                $('#accdr dd').slideUp();
                $('#accdr dt a').removeClass('actv');
                $(this).addClass('actv').parent().next().slideDown();
            }
            return false;
        });
    }
}

function init_liveSupport() {
    var el = $('#_livesupport');
    if (self == top) {
        setTimeout(function () {
            var img = $(String.format('<img src="/cmstemplates/vivatravelaspx/data/common/wo-tracker.ashx?rnd={0}" />', Math.random().toString())).css({
                position: 'absolute'
				, zIndex: 100
				, left: -1000
				, top: -1000
            });

            // append to page tracking image
            $('body').append(img);

            // remove after image load
            $(img).load(function () {
                // online
                var online = ($(this).width() > 1);
                if (online)
                    el.fadeIn(2000);

                setTimeout(function () {
                    // remove from collection
                    $(img).remove();
                }, 100);
            });

        }, 135 * 1000);
    }
}

function init_searchbox_scrolling() {
    var container = $('div[scope=searchbox-container]');
    var win = $(window);
    var _maximumTop = 136;

    if (container.size() > 0) {
        var handler = function (event) {
            var fullHeight = ($('#ui-header').height() + $('#main').height());
            var scrollTop = $(this).scrollTop();
            var currentHeight = scrollTop + container.height();
            var results = $('#results').children().size();
            var advertisments = $('#results').find('div#loadingAds').size();

            if (scrollTop > _maximumTop && (results > 0 && advertisments == 0)) {
                container.removeClass('sbt-fixed').removeClass('sbt-absolute').addClass(function () {
                    return (fullHeight >= currentHeight ? 'sbt-fixed' : 'sbt-absolute');
                });
            }
            else {
                container
					.removeClass('sbt-fixed')
					.removeClass('sbt-absolute');
            };
        };

        win.bind('scroll', handler);
    }
}

function rotateAds() {
    _dw.sort(function () { return 0.5 - Math.random() });
    $("#WaitingAds div[_adHolder]").hide().siblings('[_adHolder=' + _dw[0] + ']').show();
}

function show_aircraft_details(caller) {
    var element = $(caller);
    var id = element.data('target');
    if (id == null) {
        id = 'div_' + Math.random().toString().substring(2);
        element.data('target', id);
    }

    var details = $('div#' + id); //element.next('div');
    $('div[scope=details-container]').not(details).hide();
    if (details.size() == 0) {
        details = $('<div class="arctype-details" style="display:none;" scope="details-container"></div>')
			.attr('id', id)
			.appendTo($('body'));
    }

    /* Checking whether the AJAX fetched page has been cached: */
    if (!element.data('cache')) {
        var url = element.attr('relnk');
        details.load((url), function () {
            /* After page was received, add it to the cache for the current hyperlink: */
            element.data('cache', details.html());
        });
    }
    else
        details.html(element.data('cache'));

    var position = element.offset();
    var h = element.height() + 5;

    details.css(
	{
	    left: position.left - 150
		, top: position.top + h
	}).toggle('fast');

    if (element.data('eventHandlers') == null) {
        details.click(function (ev) {
            ev.stopPropagation();
        });

        element.click(function (ev) {
            show_aircraft_details(this);
            ev.stopPropagation();
        });

        // mark event handlers as created
        element.data('eventHandlers', true);
    }
}

$(document).click(function (ev) {
    $('div[scope=details-container]').hide();
});

function init_aircraft_details() {
    $('.details-duration a[relnk]').live('click', function (ev) {
        show_aircraft_details(this);
        ev.stopPropagation();
    });
}

function hide_aircraft_details(caller) {
    if (!caller)
        $('div[scope=details-container]').hide();
    else
        $(caller).closest('div[scope=details-container]').hide();
}

function trackAnalyticsEvent(obj, category, label) {
    _gaq.push(['_trackEvent', category, 'click', label]);
    location.href = $(obj).attr('href');
}

function onChange_GetOrderDetails() {
    $('input[id$=txtOrderId]').bind('keyup', function () {
        if ($(this).val().replace(/^\s*((?:[\S\s]*\S)?)\s*$/, '$1').length == 10) {
            $('input[id$=TriggerUpdate]').click();
        }
    });
}

function setBookingPanelScope() {
    var tmp = $.extend({}, {}, __viva);
    $('#searchbox').find('a[_menu=yes][scope=' + tmp.pscope + ']').click();
}

function hprotate() {
    //Get the first image
    var current = ($('div#hpBanners div.hprotator ul li.show') ? $('div#hpBanners div.hprotator ul li.show') : $('div#hpBanners div.hprotator ul li:first'));

    if (current.length == 0) current = $('div.rotator ul li:first');

    //Get next image, when it reaches the end, rotate it back to the first image
    var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('div#hpBanners div.hprotator ul li:first') : current.next()) : $('div#hpBanners div.hprotator ul li:first'));

    //Un-comment the 3 lines below to get the images in random order

    //var sibs = current.siblings();
    //var rndNum = Math.floor(Math.random() * sibs.length );
    //var next = $( sibs[ rndNum ] );

    //Set the fade in effect for the next image, the show class has higher z-index
    next.css({ opacity: 0.0 })
    .addClass('show')
    .animate({ opacity: 1.0 }, 1000);

    //Hide the current image
    current.animate({ opacity: 0.0 }, 1000)
    .removeClass('show');
}

function theHpRotator() {
    //Set the opacity of all images to 0
    $('div#hpBanners div.hprotator ul li').css({ opacity: 0.0 });

    //Get the first image and display it (gets set to full opacity)
    $('div#hpBanners div.hprotator ul li:first').css({ opacity: 1.0 });

    //Call the rotator function to run the slideshow, 12000 = change to next image after 6 seconds
    setInterval('hprotate()', 9000);
}

function initHomePageSlider() {
    if (self != top)
        $('div#hpBanners div.hprotator ul li a').attr('target', '_blank');

    if ($('div#hpBanners div.hprotator ul li').size() > 1) {
        //Load the slideshow
        theHpRotator();
        $('div#hpBanners div.hprotator').fadeIn(1000);
        $('div#hpBanners div.hprotator ul li').fadeIn(1000); // tweek for IE
    }
}

var SmartNavigation = {
    _handler: '/cmstemplates/vivatravelaspx/data/support/SmartNavigation.ashx?action='
    , _action: { checkIfEnabled: 0, connect: 1, disconnect: 2 }
    , _container: null
    , _connect: null
    , _disconnect: null
    , _inactive: null
    , _active: null
    , _clientId: null

    , _initialize: function () {
        this._container = $('div#SmartNavigationClient');
        this._connect = $('a#clientConnect');
        this._disconnect = $('a#clientDisconnect');
        this._inactive = $('div#caInactive');
        this._active = $('div#caActive');
        this._clientId = $('span#clientId', 'div#caActive');
    }
    , _isEnabled: function () {
        this._addEventHandlers();

        SmartNavigation._doAction(this._action.checkIfEnabled);
    }
    , _addEventHandlers: function () {
        this._initialize();

        this._connect.click(function () {
            SmartNavigation._doAction(SmartNavigation._action.connect);
        });

        this._disconnect.click(function () {
            SmartNavigation._doAction(SmartNavigation._action.disconnect);
        });
    }
    , _doAction: function (action) {
        $.ajax({
            type: 'POST',
            url: this._handler + action,
            dataType: 'text',
            success: function (clientId) {
                SmartNavigation._setTemplate(clientId)

                //Start/Stop Timer
                if (clientId > 0)
                    startDistribution();
                else
                    clearTimeout(SmartNavigationTimer);
            },
            failure: function (ex) { }
        });
    }
    , _setTemplate: function (clientId) {
        this._initialize();

        var isActive = (clientId != 0);

        this._container.attr('class', isActive ? 'connected' : '');
        this._inactive.attr('style', isActive ? 'display:none;' : '');
        this._active.attr('style', isActive ? '' : 'display:none;');
        this._clientId.text(clientId);
    }
};

var SmartNavigationTimer = null;

function startDistribution() {
    SmartNavigationTimer = setTimeout(function () {
        $.loadScript('/cmstemplates/vivatravelaspx/data/support/SmartNavigationDistributor.ashx', function () {
            startDistribution();
        });
    }, 5000);
}

var AdCarousel =
{
    carouselTimer: null
    , _initialize: function () {
        var lis = $('#carousel_container ul#carousel_ul li').size()
        if (lis > 2) {
            $('#carousel_container').show();

            if (lis > 3) {
                this._startCarousel();
                this._attachHandlers();
                $('a[role=arrow]').removeClass('removebg');
            }
        }
    }
    , _attachHandlers: function () {
        //move he last list item before the first item. The purpose of this is if the user clicks to slide left he will be able to see the last item.
        $('#carousel_ul li:first').before($('#carousel_ul li:last'));


        //when user clicks the image for sliding right
        $('#right_scroll').click(function () {

            //get the width of the items ( i like making the jquery part dynamic, so if you change the width in the css you won't have o change it here too ) '
            var item_width = $('#carousel_ul li').outerWidth() + 10;

            //calculae the new left indent of the unordered list
            var left_indent = parseInt($('#carousel_ul').css('left')) - item_width;

            //make the sliding effect using jquery's anumate function '
            $('#carousel_ul:not(:animated)').animate({ 'left': left_indent }, 700, 'easeOutQuad', function () {

                $('#carousel_ul li:last').after($('#carousel_ul li:first'))

                //get the first list item and put it after the last list item (that's how the infinite effects is made) '
                $('#carousel_ul').css({ 'left': '2px' });
            });
        });

        //when user clicks the image for sliding left
        $('#left_scroll').click(function () {

            var item_width = $('#carousel_ul li').outerWidth() + 10;

            /* same as for sliding right except that it's current left indent + the item width (for the sliding right it's - item_width) */
            var left_indent = parseInt($('#carousel_ul').css('left')) + item_width;

            $('#carousel_ul li:first').before($('#carousel_ul li:last'));

            $('#carousel_ul:not(:animated)').animate({ 'left': left_indent }, 700, 'easeOutQuad', function () {

                /* when sliding to left we are moving the last item before the first list item */
                $('#carousel_ul').css({ 'left': '2px' });
            });
        });

        $("div#carousel_container").hover(function () {
            clearTimeout(AdCarousel.carouselTimer);
        },
          function () {
              AdCarousel._startCarousel();
          }
        );

        $("#carousel_ul li").click(function () {
            var a = $(this).find('a:first');
            if (a.size() > 0) {
                if (self != top)
                    window.open(a.attr('href'));
                else
                    document.location.href = a.attr('href');
            }
        });
    }
    , _startCarousel: function () {
        this.carouselTimer = setTimeout(function () {
            $('#right_scroll').click();
            AdCarousel._startCarousel();
        }, 5000);
    }
}

function init_sb() {
    var items = $('.globalsearch-container #main-tabs #tab li').each(function (i) {
        var lis = $('.globalsearch-container #main-tabs #tab li')
			, li = $(this)
			, slides = $('.tabContainer div[_panel]')
			, arrow = $('.globalsearch-container #main-tabs #tab div#arrow')
			, arrowOffsetTop = 0
			, step = (ie7 ? 44 : 42)
			, myDuration = 250;

        li.click(function () {
            var $link = li.find('a[onclick]:first');

            if ($link.size() == 0) {
                arrow.animate(
			    {
			        top: (arrowOffsetTop + (step * i))
			    }
			    , myDuration, function () {
			        // Animation complete.
			        var id = li.attr('id');
			        slides.hide();
			        slides.filter('#' + id).show();

			        // change hash and scroll to top
			        //				if(!ie)
			        //				{
			        //				    var scrollTop = $(document).scrollTop();
			        //				    location.hash = '#' + id;
			        //				    $(document).scrollTop(scrollTop);
			        //				}
			    });
            }
            else {
                search_taxi();
            }
        });
    });

    //	if(location.hash != null && location.hash.length > 0)
    //	{
    //		var selected = items.filter('#' + location.hash);
    //		if(selected.size() > 0)
    //			selected.first().click();
    //	}
}

function _chat(query) {
    setTimeout(function () {
        var url = 'http://click2chat.viva.gr/travel/chatstart.aspx?domain=travel.viva.gr&lang=' + _culture.substring(0, 2) + (query != null ? query : '');
        var nw = window.open(url, 'new_win', 'width=484,height=361');

        nw.focus();
        return (false);
    }, 0);

    return (false);
}

function initTopAppsAnimation() {
    $('#ui-topapps li a:not(.active)').bind('mouseenter', function (e) {
        $(this).animate({ 'height': '65px' }, 'fast');
    }).bind('mouseleave', function () {
        $(this).animate({ 'height': '54px' }, 'fast');
    });
}

function _initsocial() {

    if (location.protocol != 'https:') {
        $(document).ready(function () {
            // initialize google plus one
            var po = document.createElement('script');
            po.type = 'text/javascript';
            po.async = true;
            po.src = 'https://apis.google.com/js/plusone.js';
            var s = document.getElementsByTagName('script')[0];
            s.parentNode.insertBefore(po, s);

            // initialize facebook
            window.fbAsyncInit = function () {
                FB.init(
				{
				    appId: '23a1c8c05f61c62cea8140f2b086b077'
					, status: true
					, cookie: true
					, xfbml: true
					, oauth: true
				})
			;
            };

            //            var fbs = document.createElement('script');
            //            fbs.src = document.location.protocol + '//static.ak.fbcdn.net/connect.php/js/FB.Share';
            //            //fbs.async = true;
            //            document.getElementById('fb-root').appendChild(fbs);

            var e = document.createElement('script');
            e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
            e.async = true;
            document.getElementById('fb-root').appendChild(e);

            $('a#fb_share').click(function () {
                var options = {};
                options['method'] = 'feed';
                options['name'] = 'Name';
                options['link'] = 'www.viva.gr';
                options['picture'] = 'http://www.viva.gr/tickets/getattachment/b93f6439-dcab-4238-a9e4-2a3fbe2b6a9d/viva-tickets.png';
                options['caption'] = 'Test';
                options['description'] = 'Test';
                options['message'] = 'Test';

                FB.ui(options);
            });
        });
    }
}

// update your browser
function _initbu() {
    var $buoop = {};
    $buoop.ol = window.onload;
    window.onload = function () { try { if ($buoop.ol) $buoop.ol(); } catch (e) { } };
}

function _setup() {
    // install click2chat tracking
    $(document).ready(_click2chat);

    // social
    _initsocial();
    initTopAppsAnimation();

    // bu
    _initbu();
}

//////////////////////////////////////////////////////////////////
//                         PAGE EVENTS                          //
//////////////////////////////////////////////////////////////////

$(document).ready(function () {
    SmartNavigation._isEnabled();

    setTimeout(function () {
        stickyFooter(true);
    }, 10000);

    zIndexFix();
    removeNativeTooltips();
    AdCarousel._initialize();
    setBlueSectionVisibility();
    initDatePicker();
    initAutocomplete();
    initDefaultValues();
    loadFlashMovies();
    setupSupportWidget();
    initLastRequestsAccordion();
    init_searchbox_scrolling();
    init_aircraft_details();
    _initsocial();
    initTopAppsAnimation();
    initLanguageSelection();
    make_tooltips();

    init_liveSupport();
    init_sb();
});

$(window).load(function () {
    if (document.location.href.toLowerCase().indexOf('#air') > -1)
        $('a[href=#air]').click();

    setBookingPanelScope();
});
