(function($){
    if(window.location.hash != '') {
        window.location.hash = window.location.hash.replace(/%26/g,'&').replace(/%3A/g,':').replace(/%2F/g,'/');
    }
    $.eturas = function(settings){
        // Settings
        $.eturas.hosturl = '';
        $.eturas.loadingstr = '';
        $.eturas.tips_elements = '.tips';
        $.eturas.no_tips_elements = '.no_tips';
        $.eturas.resizeURL = document.referrer;
        $.eturas.parentWindow = (window.parent && window.parent.length);
        $.eturas.parentWindow_ob = (window.parent && window.parent.length)?window.parent:[];

        // PopUp
        $.eturas.win = function(page,wid,hit){
            var  windo=eval('window.open("'+page+'","_blank","status=no,toolbar=no,resizable=yes,scrollbars=yes,menubar=no,width='+wid+',height='+hit+',top=100,left=100")');
            return windo;
        };
        $.eturas.holidayDays = [];
        $.eturas.setScheduledDays = function(date){
            var isHoliday = false;
            // Check for holidays
            if ($.eturas.holidayDays != null){
                for (i = 0; i < $.eturas.holidayDays.length; i++) {
                  if (date.getMonth() == $.eturas.holidayDays[i][0] - 1 && date.getDate() == $.eturas.holidayDays[i][1] && date.getFullYear() == $.eturas.holidayDays[i][2]) isHoliday = true;
                }
            }
            if (isHoliday) return [false, 'CLOSED'];
            else return [true, ''];
        };
        $.eturas.holidayDays_2 = [];
        $.eturas.setScheduledDays_2 = function(date){
            var isHoliday = false;
            // Check for holidays
            if ($.eturas.holidayDays_2 != null){
                for (i = 0; i < $.eturas.holidayDays_2.length; i++) {
                  if (date.getMonth() == $.eturas.holidayDays_2[i][0] - 1 && date.getDate() == $.eturas.holidayDays_2[i][1] && date.getFullYear() == $.eturas.holidayDays_2[i][2]) isHoliday = true;
                }
            }
            if (isHoliday) return [false, 'CLOSED'];
            else return [true, ''];

        };
        $.eturas.checkFormForEmpty = function(ob_id) {
            result = true;
            jQuery(ob_id+' input[type=text]').each(function(){
                if(jQuery(this).val() == '') result = false;
            });
            return result;
        };
        $.eturas.getValues = function(frm){
            result = '';
            jQuery('#'+frm+' input[type=text],#'+frm+' input[type=hidden],#'+frm+' select').each(function(){
                result += '/'+jQuery(this).attr('id')+':'+jQuery(this).val();
            });
            jQuery('#'+frm+' input[type=checkbox]:checked').each(function(){
                result += '/'+jQuery(this).attr('id')+':'+jQuery(this).val();
            });
            jQuery('#'+frm+' input[type=radio]').each(function(){
                if(jQuery(this).val() == jQuery('input[name='+jQuery(this).attr('name')+']').val()) result += '/'+jQuery(this).attr('id')+':'+jQuery(this).val();
            });
            return result;
        };
        $.eturas.selected_duration = 'all';
        $.eturas.durations = function(selected){
            if($("#lb_duration option:selected").val())
                $.eturas.selected_duration = $("#lb_duration option:selected").val();
            var url = $.eturas.hosturl+"webservices/durations/journey_type:"+$('#journey_type').val()+"/lb_country:"+$('#lb_country').val()+'/journey_airport:'+$('#journey_airport').val()+'/date:'+$('#lb_journey_start_date').val()+'/lb_dates:'+$('#lb_dates').val();

              $('#lb_duration').attr("disabled", true);
              $("#lb_duration").html('<option value="0">'+$.eturas.loadingstr+'</option>');
              $('#durationsC').attr("disabled", true);
              $("#durationsC").html('<option value="0">'+$.eturas.loadingstr+'</option>');
              $.get(url,{},function(dtf){
                $("#lb_duration, #durationsC").removeOption(0);
                dt = dtf.replace(/{/,'').replace(/}/,'').split(',"');
                for(var nm in dt){
                    if(dt[nm].substring(0,1) != '"') dt[nm] = '"'+dt[nm];
                    $("#lb_duration, #durationsC").addOption(eval(' n = {'+dt[nm]+'}'), false);
                };
                $('#lb_duration, #durationsC').attr("disabled", false);
                $('#lb_duration, #durationsC').val($.eturas.selected_duration);
              });
        };
        $.eturas.dont_set_date = false;
        $.eturas.changeCalendar = function(url,no_flights,dont_set_date){

            url = url+'/lb_country:'+jQuery('#lb_country').val()+'/journey_airport:'+jQuery('#journey_airport').val()+'/'+'journey_type:'+jQuery('#journey_type').val()

            if($("#transport_type").length > 0){
                url = url+'/transport_id:'+$("#transport_type").val();
            }

            $.getJSON(url,function(data){
                if(data == 0){
                    //alert(no_flights);
                }else{
                    eval($.eturas.holidayDays = data['dates']);
                    if($.eturas.holidayDays_2.length == 0) eval($.eturas.holidayDays_2 = data['dates']);

                    var set_date = new Date(data['first'][2],data['first'][0],data['first'][1]);

                    $("#lb_journey_start_date_replace").val(data['first'][2]+'-'+data['first'][0]+'-'+data['first'][1]);

                    var set_date = $.datepicker._defaults.dateFormat.replace("yy", data['first'][2]);
                    set_date = set_date.replace("mm", data['first'][0]);
                    set_date = set_date.replace("dd", data['first'][1]);

                    if(!$.eturas.dont_set_date){
                        $("#lb_journey_start_date").val(set_date);
                    }
                    $.eturas.dont_set_date = false;
                }
                $.eturas.durations();
            });
        };
        $.eturas.demoRedirectSubmit = function(tourl, form)
        {
            str = $.eturas.getFormValues(form);
            $.ajax({
                type: "GET",
                url: tourl,
                data: str,
                success: function(locat){
                    if($.eturas.parentWindow)
                         eval(window.parent.location = locat);
                    else
                         eval(window.location = locat);
                }
            });

        };
        $.eturas.getFormValues = function(form) {
             var str = "";
             var nL = form.elements.length;
             for (var i = 0; i < nL; i++) {
                if(form.elements[i].name)
                {
                  if ((form.elements[i].type == 'radio') || (form.elements[i].type == 'checkbox')) {
                       if (form.elements[i].checked) {
                            str += form.elements[i].name + "=" + escape(form.elements[i].value) + "&";
                       }
                  } else {
                       str += form.elements[i].name + "=" + escape(form.elements[i].value) + "&";
                  }
                }
             }
             return str;
        }
        $.eturas.postValues = function(frm){
            result = '';
            jQuery('#'+frm+' input[type=text],#'+frm+' input[type=hidden],#'+frm+' select').each(function(){
                if(jQuery(this).attr('id') != '')
                {
                    if(result != '') result += ',';
                    result += '"'+jQuery(this).attr('name')+'": "'+jQuery(this).val()+'"';
                }
            });
            jQuery('#'+frm+' input[type=checkbox]:checked').each(function(){
                if(jQuery(this).attr('id') != '')
                {
                    if(result != '') result += ',';
                    result += '"'+jQuery(this).attr('name')+'": "'+jQuery(this).val()+'"';
                }
            });
            jQuery('#'+frm+' input[type=radio]').each(function(){
                if(jQuery(this).val() == jQuery('input[name='+jQuery(this).attr('name')+']').val())
                {
                    if(result != '') result += ',';
                    result += '"'+jQuery(this).attr('name')+'": "'+jQuery(this).val()+'"';
                }
            });
            return result;
        };
        $.eturas.showTooltip = function(element) {
            move = '';
            if (!window._tooltip) {
                window._tooltip = jQuery('<div id="tooltip"></div>');
                jQuery(document.body).append(window._tooltip);
            };
            var $el = jQuery(element);

            window._tooltip.html('').removeClass('pad');

            if($el.attr('alt')) var body = $el.attr('alt');
            else if($el.attr('title')) var body = $el.attr('title');
            else return;
            if(body.replace(/#/,'') != body){
                window._tooltip.append(jQuery(''+body+'').html());
                if(jQuery(''+body+'').attr('align')) move = jQuery(''+body+'').attr('align');
            }else{
                if (body!=''){ window._tooltip.addClass('info_icon_drop').append('<ul>'+body+'</ul>'); };
                if($el.attr('align')) move = $el.attr('align');
            }
            if(move == 'right') jQuery(document).bind('mousemove', $.eturas.moveTooltip_right);
            else jQuery(document).bind('mousemove', $.eturas.moveTooltip_left);
        };
        $.eturas.moveTooltip_right = function (e){
            if (window._tooltip != undefined){
                lf = (e.clientX + document.body.scrollLeft);
                tp = (e.clientY + document.body.scrollTop + 25);
                if(lf < 5) lf = 5;
                if(lf > (jQuery(window).width()-window._tooltip[0].offsetWidth))
                    lf = jQuery(window).width()-window._tooltip[0].offsetWidth;

                if(tp > (jQuery(window).height()-window._tooltip[0].offsetHeight)){
                    tp = jQuery(window).height()-window._tooltip[0].offsetHeight;
                    lf += 10;
                }

                window._tooltip.css({
                    left: lf + 'px',
                    top: tp + 'px',
                    display: "block"
                });
            }
        };
        $.eturas.moveTooltip_left = function (e){
            if (window._tooltip != undefined){
                lf = (e.clientX + document.body.scrollLeft - window._tooltip[0].offsetWidth - 5);
                tp = (e.clientY + document.body.scrollTop + 25);
                if(lf < 5) lf = 5;
                if(lf > (jQuery(window).width()-window._tooltip[0].offsetWidth))
                    lf = jQuery(window).width()-window._tooltip[0].offsetWidth;

                if(jQuery(window).width()<window._tooltip[0].offsetWidth)
                    window._tooltip[0].offsetWidth = jQuery(window).width();

                if(tp > (jQuery(window).height()-window._tooltip[0].offsetHeight)){
                    tp = jQuery(window).height()-window._tooltip[0].offsetHeight;
                }
                window._tooltip.css({
                    left: lf + 'px',
                    top: tp + 'px',
                    display: "block"
                });
            }
        };
        $.eturas.hideTooltip = function (e){
            if (window._tooltip != undefined){
                jQuery(document).unbind('mousemove', $.eturas.moveTooltip);
                window._tooltip.hide();
            }
        };
        $.eturas.selected_airport = null;
        $.eturas.changeairport = function(id,url,text,url2,no_flights){
            $('#journey_airport').attr("disabled", true);
            $("#journey_airport").html('<option value="0">'+text+'</option>');

            $.get(url+"/"+id, function(dtf){
                $("#journey_airport").removeOption(0);
                $('#journey_airport').attr("disabled", false);
                dt = dtf.replace(/{/,'').replace(/}/,'').split(',');
                for(var nm in dt){
                    $("#journey_airport").addOption(eval(' n = {'+dt[nm]+'}'), false);
                };
                if($.eturas.selected_airport){
                    $('#journey_airport').val($.eturas.selected_airport);
                }
                $.eturas.changeCalendar(url2,no_flights);
                if(typeof( quick_hotel_search_country_filter ) == 'function') quick_hotel_search_country_filter(id);
            });
        };
        $.eturas.changecountry = function(id,url,text,selected){
            $('#city').attr("disabled", true);
            $("#city").html('<option value="0">'+text+'</option>');
            $("#city").ajaxAddOption(url+"/"+id,{},false,
                function(){
                    if(selected){
                        $("#city").selectOptions(selected);
                    }
                    $("#city").removeOption(0);
                    $('#city').attr("disabled", false);
                }
            );
        };
        $.eturas.activate_default_text = function(){
            jQuery('input[default=true]').each(function(){
                jQuery(this).bind('focus', function(){
                    if(jQuery(this).val() == jQuery(this).attr('default_text')){
                        jQuery(this).val('');
                    }
                });
                jQuery(this).bind('blur', function(){
                    if(jQuery(this).val() == ''){
                        jQuery(this).val(jQuery(this).attr('default_text'));
                    }
                });
                if(jQuery(this).val() == ''){
                    jQuery(this).val(jQuery(this).attr('default_text'));
                }
            });
        };
        $.eturas.updateTips = function(){
          jQuery(''+$.eturas.tips_elements+'').not(''+$.eturas.no_tips_elements+'').each(function(){
              if(jQuery(this).attr('alt')=='') return;
                jQuery(this).bind('mouseover', function(){
                    jQuery.eturas.showTooltip(this);
                }).bind('mouseout', function(){
                    jQuery.eturas.hideTooltip(this);
                });
            });
        };
        $.eturas.updateIframeHeight_repeat = false;
        $.eturas.updateIframeHeight_off = false;
        $.eturas.updateIframeHeight = function(repeat){
            if(!$.eturas.parentWindow) return;
            if($.eturas.updateIframeHeight_off) return;
            if(jQuery('div#container').length && $.eturas.parentWindow)
            {
                newHeight = jQuery('div#container').height();
                $.postmessage({
                    target: window.parent,
                    type: 'new_resize',
                    data: {height:""+newHeight+"", windowName:window.name, windowLocation:window.location.href.replace(window.location.hash,''), hash: window.location.hash.substring(1)},
                    url: jQuery.eturas.resizeURL,
                    success: function(data) {
                        if(!$.eturas.updateIframeHeight_repeat){
                            jQuery('body').attr('setHeight',newHeight);
                            newHeight_2 = jQuery('div#container').height();
                            $.eturas.updateIframeHeight_repeat = true;
//                            if(newHeight != newHeight_2)
                                setTimeout("jQuery.eturas.updateIframeHeight(1);",100);
                        }else{
                            jQuery('body').attr('setHeight_2',newHeight);
                            $.eturas.updateIframeHeight_repeat = false;
                        }
//
                    }
                });
                if(!repeat)setTimeout("jQuery.eturas.updateIframeHeight(1);",100);
            }
        };

        $.eturas.pageToTop = function(){
            if($.eturas.parentWindow){
                $.postmessage({
                    target: window.parent,
                    type: 'top',
                    data: {hash: window.location.hash.substring(1), windowName:window.name},
                    success: function(data){},
                    url: jQuery.eturas.resizeURL
                });
            }else{
                window.scroll(0,0);
            }
        };

        $.eturas.pageToiFrameTop = function(tP, wName){
            if($.eturas.parentWindow){
                if(typeof wName == 'undefined') wName = window.name;
                $.postmessage({
                    target: window.parent,
                    type: 'iframeTop',
                    data: {hash: window.location.hash.substring(1), windowName:wName, topPlius: tP},
                    success: function(data){},
                    url: jQuery.eturas.resizeURL
                });
            }else{
                window.scroll(0,tP);
            }
        };

        $.eturas.pageToiFrameElement = function(id, wName){
            tP = jQuery(id).position().top;
            if($.eturas.parentWindow){
                if(typeof wName == 'undefined') wName = window.name;
                $.postmessage({
                    target: window.parent,
                    type: 'iframeTop',
                    data: {hash: window.location.hash.substring(1), windowName:wName, topPlius: tP},
                    success: function(data){},
                    url: jQuery.eturas.resizeURL
                });
            }else{
                window.scroll(0,tP);
            }
        };

        $.eturas.div_class = function(){
            loadded = [];
            jQuery('input.div_class').each(function(){
                div_class = jQuery(this).attr('name');
                if(!loadded[div_class]) loadded[div_class] = 1;
                else return;
                div_class_id = jQuery('input[name='+div_class+']:checked').val();
                div_show = (jQuery('input[name='+div_class+']:checked').val() == div_class_id);
                jQuery('.'+div_class+'').each(function(){
                    c_div_class_id = jQuery(this).attr('div_class_id');
                    if(c_div_class_id){
                        classes = c_div_class_id.split(',');
                        hide = true;
                        for(i=0;i<classes.length;i++){
                            if(classes[i] == div_class_id) hide = false;
                        }
                        if(hide || !div_show) jQuery(this).hide();
                        else jQuery(this).show();
                    }
                });
            }).unbind('click').bind('click', function(){
                setTimeout('jQuery.eturas.div_class();',100);
                jQuery('input[name='+jQuery(this).attr('name')+']').next('label').removeClass('checked');
                jQuery(this).next('label').addClass('checked');
            });
            jQuery.eturas.updateIframeHeight();
        };
        $.eturas.photo_random_begin = function() {
            jQuery('.photo_random').hide();
            jQuery('.photo_random:first').show().addClass('act');
            setTimeout('jQuery.eturas.photo_random();', 5000);
        };
        $.eturas.photoBG_random_arr = {};
        $.eturas.photoBG_random_arr_loaded = {};
        $.eturas.photoBG_random_begin = function(ob_id, arr) {
            if(typeof $.eturas.photoBG_random_arr[ob_id] == 'undefined') {
                $.eturas.photoBG_random_arr[ob_id] = arr;
                // load all images
                jQuery('body').append('<div id="photoBG" style="display:none"></div>');
                for(var z in arr) jQuery('#photoBG').append('<img src="'+arr[z]+'" onload="jQuery.eturas.photoBG_random_arr_loaded['+z+']=true;" id="tmp_photoBG_'+ob_id+'_'+z+'">');
            }
            if(loaded_i = jQuery('#'+ob_id).attr('loaded_i')) {
                loaded_i_bef = loaded_i;
                loaded_i++;
                if(typeof arr[loaded_i] == 'undefined') loaded_i = 0;
                if(typeof $.eturas.photoBG_random_arr_loaded[loaded_i] == 'undefined') {
                    setTimeout('jQuery.eturas.photoBG_random_begin("'+ob_id+'", jQuery.eturas.photoBG_random_arr["'+ob_id+'"]);', 5000);
                    return;
                }
            } else {
                loaded_i_bef = -1;
                loaded_i = 0;
            }
            if(jQuery('#'+ob_id+' div.photoBG_random.photoBG_'+loaded_i).length == 0) {
                jQuery('#'+ob_id).append('<div class="photoBG_random photoBG_'+loaded_i+'" style="opacity:0;background:url(\''+arr[loaded_i]+'\') no-repeat scroll center center transparent;width:100%;height:100%"></div>');
            }
            jQuery('#'+ob_id+' div.photoBG_random.photoBG_'+loaded_i).fadeTo('slow',1,function(){
                jQuery('#'+ob_id).attr('loaded_i', loaded_i);
                setTimeout('jQuery.eturas.photoBG_random_begin("'+ob_id+'", jQuery.eturas.photoBG_random_arr["'+ob_id+'"]);', 5000);
            });
            jQuery('#'+ob_id+' div.photoBG_random.photoBG_'+loaded_i_bef).fadeTo('slow',0,function(){
                jQuery('#'+ob_id+' div.photoBG_random.photoBG_'+loaded_i_bef).hide();
            });
        };
        $.eturas.photo_random = function() {
            if(jQuery('.photo_random.act').next('img').length) {
                jQuery('.photo_random.act').removeClass('act').next('img').fadeTo('slow',1,function(){
                    setTimeout('jQuery.eturas.photo_random();', 5000);
                    jQuery('.photo_random.act').prev('img').hide();
                }).addClass('act');
            } else {
                jQuery('.photo_random:first').show();
                jQuery('.photo_random.act').removeClass('act').fadeTo('slow',0,function(){
                    setTimeout('jQuery.eturas.photo_random();', 5000);
                });
                jQuery('.photo_random:first').addClass('act');
            }
        };
        // When document ready
        $.eturas.onload = function(){
            if(jQuery('#lb_journey_start_date').length){
                startDate = new Date();
                endDate = new Date(startDate.getFullYear()+'/'+(startDate.getMonth()+10)+'/'+startDate.getDate());

                inp = jQuery("#lb_journey_start_date");
                inp.datepicker({
                    showOn: "both",
                    buttonImageOnly: false,
                    numberOfMonths: 1,
                    showButtonPanel: false,
                    minDate: startDate,
                    showAnim: 'slideDown',
                    showOptions: { speed: 50 },
                    beforeShowDay: jQuery.eturas.setScheduledDays,
                    onSelect: function(date,inst){ $.eturas.durations(); return; }
                });
                if(jQuery('#lb_journey_start_date_2').length){
                    $.eturas.activate_start_date(2, function(date,inst){});
                }
                jQuery('button.ui-datepicker-trigger').hide();
            }
            $.eturas.onAjaxload();
            if(jQuery('.photo_random').length > 0) $.eturas.photo_random_begin();
        };
        $.eturas.activate_start_date = function(num, func){
            startDate = new Date();
            endDate = new Date(startDate.getFullYear()+'/'+(startDate.getMonth()+10)+'/'+startDate.getDate());

            inp2 = jQuery("#lb_journey_start_date_"+num);
            inp2.datepicker({
                showOn: "both",
                buttonImageOnly: false,
                numberOfMonths: 1,
                showButtonPanel: false,
                minDate: startDate,
                showAnim: 'slideDown',
                showOptions: { speed: 50 },
                beforeShowDay: jQuery.eturas.setScheduledDays_2,
                onSelect: func
            });
            jQuery('button.ui-datepicker-trigger').hide();
        };
        $.eturas.activateHrefClass = function(){
            jQuery('tr.href').each(function(){
                jQuery(this).bind('mouseout', function(){
                    jQuery(this).removeClass('over');
                }).bind('mouseover', function(){
                    jQuery(this).addClass('over');
                });
            });
        };
        $.eturas.onAjaxload = function(){
            $.eturas.updateTips();
            $.eturas.activate_default_text();
            if(typeof( imagePreview ) == 'function') imagePreview();
            $.eturas.div_class();
            jQuery.eturas.updateIframeHeight();
            $.eturas.activateHrefClass();
        };
        $.eturas.log = function(text){
            if(jQuery('#debug_log').length > 0) {
                document.getElementById('debug_log').innerHTML += text+'<br>';
            }
        };
        $.eturas.changeCurrency = function(value){
            jQuery('#currency_select').attr('disabled',1);
            jQuery.get($.eturas.hosturl+"webservices/changeCurrency/"+value,function(){
                window.parent.location.href=document.referrer;
            });
        };
        $.eturas.strstr = function (haystack, needle, bool) {
            var pos = 0;
            haystack += '';
            pos = haystack.indexOf( needle );    if (pos == -1) {
                return false;
            } else{
                if (bool){
                    return haystack.substr( 0, pos );        } else{
                    return haystack.slice( pos );
                }
            }
        }
        jQuery(document).ready(function(){$.eturas.onload();});
    };
    function clearErrors(err,f,l) {
        if(typeof console != 'undefined') {
            console.log('Eturas: js error ('+err+', '+f+', line: '+l+')');
        }
        return true;
    }
    if(typeof window.onerror != 'undefined')window.onerror = clearErrors;
})(jQuery);
jQuery.eturas();
function demoRedirectSubmit(tourl, form){
    str = jQuery.eturas.getFormValues(form);
    $.ajax({
        type: "GET",
        url: tourl,
        data: str,
        success: function(locat){
             eval(window.parent.location = locat);
        }
    });
}
