
var WaitDialog = {
    show: function(){
        if (!$("#message_holder").length){
            $("body").prepend('<div id="message_holder" style="height:' + $("body").height() + 'px"><div class="message_box"></div></div>');
        $(".message_box").empty();
        
        $(".message_box").append('<img width="273" height="72" alt="SunnyRentals" src="/images/i/logo.gif"/><br /><div id="progressbar"></div><p>'+
            lang('Updating search results') +
            '</p><a href="#" class="message_cancel" id="message_box_close" onclick="RefineResults.isCancelled = true; WaitDialog.hide(); return false;">'+
            lang('Cancel')+'</a>');
        }
        
        
        var pb = $("#progressbar");
        if( pb.length && pb.progressbar) {
            pb.progressbar({value: 100});
        }
        $("#message_holder").fadeIn("fast");
    
    },
    hide: function(){
        $("#message_holder").fadeOut("fast");
    }
};

fakeSelect = function( selectHolder ) {

    var fakeSelect = {
        sourceID: '',
        source: '',
        visibleInput: '',
        list: '',

        init: function( selectHolder ){
            if ( $('select', $(selectHolder)).length == 0 ) {
                return;
            }

            fakeSelect.source = $('select', $(selectHolder));
            fakeSelect.sourceID = $(fakeSelect.source).attr('id');

            /* set all elements */
            fakeSelect.list = $('#' + fakeSelect.sourceID + '_list');
            fakeSelect.visibleInput = $('#' + fakeSelect.sourceID + '_visible');

            fakeSelect._bindEvents();

            fakeSelect._fixListPosition();
        },

        _bindEvents: function() {

            $(fakeSelect.visibleInput).click( function() {

                $('.fakeList:visible').not( $(fakeSelect.list) ).hide();
                $(fakeSelect.list).toggle();

            });

             $(fakeSelect.source).change( function() {
                var value = $(this).val();
                var label = $('option:selected', $(this)).html();

                $(fakeSelect.visibleInput).val(label);

                $('.option', $(fakeSelect.list)).removeClass('selected');
                var selectedDiv = $('.option', $(fakeSelect.list)).filter( function(){return $(this).attr('title') == value});
                $(selectedDiv, $(fakeSelect.list)).addClass('selected');

            });

            $('.option', $(fakeSelect.list)).click( function(e){
                e.preventDefault();
                var value = $(this).attr('rel');

                /* set real select value */
                $(fakeSelect.source).val( value );
                $('.option', $(fakeSelect.list)).removeClass('selected');
                $(this).addClass('selected');

                /* set fake select value */
                $(fakeSelect.visibleInput).removeClass('example');
                $(fakeSelect.visibleInput).val( $(this).html() );

                /* hide select list */
                $(fakeSelect.list).hide();
            });

        },

        _fixListPosition: function() {
            var rightPosition =  $("#wrapper").offset().left + $('#wrapper').width() - $(fakeSelect.visibleInput).offset().left - $(fakeSelect.visibleInput).width() + 3 ;
            var topPosition =  $(fakeSelect.visibleInput).offset().top  + $(fakeSelect.visibleInput).height() - $("#wrapper").offset().top + 2 ;
            $(fakeSelect.list).css( {"right": rightPosition + "px", "top": topPosition + "px"} );

            $(fakeSelect.list).appendTo($('#wrapper'));
        }


    };

    fakeSelect.init( selectHolder );

    return fakeSelect;
};

window.globalLoader = {
    ID: 'globalLoader',
    entity: null,

    init: function(){
        if ( $('#' + globalLoader.ID).length ) {
            globalLoader.entity = $('#' + globalLoader.ID);
            return globalLoader;
        }

        $('<div id="' + globalLoader.ID + '" class="hidden"><div class="inner"></div></div>').appendTo($('body'));
        globalLoader.entity = $('#' + globalLoader.ID);
        globalLoader.setDefaultMessage();
        return globalLoader;
    },

    setDefaultMessage: function(){
        globalLoader.setMessage(lang('Loading...'));
        return globalLoader;
    },

    setMessage: function( message ) {
        $('.inner', globalLoader.entity).html( message );
        return globalLoader; 
    },

    show: function() {
        globalLoader.entity.removeClass('hidden');
        return globalLoader;
    },

    hide: function() {
        globalLoader.entity.addClass('hidden');
        globalLoader.setDefaultMessage();
        return globalLoader;
    }

};

var popUpManager = {
    ID: 'popUpHolder',
    entity: null,
    backShadowID: 'backShadow',
    backShadow: null,
    collection: [],

    init: function(){
        /* create popUp holder if not exist */
        popUpManager.entity = !$('#' + popUpManager.ID).length ? $('<div id="' + popUpManager.ID + '"></div>') : $('#' + popUpManager.ID);
        $(popUpManager.entity).appendTo($('body'));

        /* create back shadow if not exist */
        popUpManager.backShadow = !$('#' + popUpManager.backShadowID).length ? $('<div id="' + popUpManager.backShadowID + '" style="display: none;"></div>') : $('#' + popUpManager.backShadowID);
        $(popUpManager.backShadow).appendTo($('body'));

        /* append all pop ups to holder */
        $('.popUpNew').appendTo( $(popUpManager.entity) );

        /* register all page popUps into collection */
        $('.popUpNew').each(function() {
            popUpManager.collection.push($(this));
        });

        popUpManager._bindEvents();
        popUpManager.closeAll();

        if (typeof(window.showPopUpOnLoad) === 'undefined' || window.showPopUpOnLoad === null) {
            return;
        }
        popUpManager.show(showPopUpOnLoad);
    },

    _bindEvents: function(){
        $(popUpManager.collection).each(function() {
            var popUp = $(this);

            /* bind close event */
            if ( $('.popUpClose', popUp).length ) {
                $('.popUpClose', popUp).live('click',function(e) {
                    e.preventDefault();
                    popUpManager.closeAll();
                });
            }
        });

        $('.popUpLink').live('click', function(e) {
            if ($.trim($(this).attr('rel')).length == 0) {
                return true;
            }

            e.preventDefault();
            var popUpID = $.trim($(this).attr('rel'));

            popUpManager.show( $('#' + popUpID) );
            return false;
        });
    },

    closeAll: function() {
        $(popUpManager.collection).each(function(){
            $(this).hide();
        });
        $(popUpManager.backShadow).hide();
    },

    show: function( element ) {
        var popUp = popUpManager._find( element );
        if (!popUp) return;

        $(popUpManager.backShadow).show();
        $(popUp).show();
        if ( window.scrollY > 100 ) {
            window.scroll(0, 100);
        }
    },

    _find: function( element ) {

        for (var i in popUpManager.collection) {
            var popUp = popUpManager.collection[i];

            if (null == popUp) {
                continue;
            }

            if ( $(popUp).attr('id') == $(element).attr('id') ){
                return element;
            }

        }

        return false;
    }
};

favouriteProperties = {
    targetID: 'fav',
    counter: 0,
    collection: [],
    locked: 0,

    init: function() {
        favouriteProperties.locked = 1;
        var guestID = $.cookie('guest_id');
        /* no guest cookie, some error happened */
        if ( null == guestID && 32 != guestID.length ) {
           favouriteProperties.locked = 0;
           return;
        }

        /* no fav indicator, wrong page  */
        if (!$('#' + favouriteProperties.targetID).length) {
            favouriteProperties.locked = 0;
            return;
        }
        $('#' + favouriteProperties.targetID).click(function(e){globalLoader.show();});

        favouriteProperties.getByGuest();
        
    },

    add: function( propertyID ) {
        $.post ( '/ajax/add-guest-favourite/', {'id': propertyID}, function (data, status) {
            if ( status == 'success' ) {
                if ( data.errors ) {
                    alert(data.errors);
                    favouriteProperties.locked = 0;
                    return;
                }

                favouriteProperties.collection.push( data.property );
                favouriteProperties.counter++;
                favouriteProperties.addTooltips();
                $('.favAdd[rel=' + propertyID +  ']').stop(true, true).effect(
                    "transfer",
                    { to: $("#" + favouriteProperties.targetID) },
                    1000,
                    function() {
                        favouriteProperties.showTarget();
                        favouriteProperties.locked = 0;
                    }
                );               
            }
        }, 'json');
    },

    remove: function( propertyID ) {

        var property = favouriteProperties._find( propertyID );
        if (!property) return;

        $.post ( '/ajax/remove-guest-favourite/', {'id': propertyID}, function (data, status) {
            if ( status == 'success' ) {
                if ( data.errors ) {
                    alert(data.errors);
                    favouriteProperties.locked = 0;
                    return;
                }
                favouriteProperties._removeFromCollection( propertyID );

                if ( favouriteProperties.counter > 0 ) {
                    favouriteProperties.counter--;
                }

                favouriteProperties.updateTarget();

                if ( favouriteProperties.counter == 0 ) {
                    favouriteProperties.hideTarget();
                }
                favouriteProperties.addTooltips();
                favouriteProperties.locked = 0;
            }
        }, 'json');

    },

    clearAll: function() {

        $.post ( '/ajax/remove-guest-favourites/', {}, function (data, status) {
            if ( status != 'success' ) return;
            if ( data.errors ) {
                alert(data.errors);
                favouriteProperties.locked = 0;
                return;
            }
            // favouriteProperties.collection = [];
            // favouriteProperties.counter = 0;
            // favouriteProperties.hideTarget();

            // favouriteProperties.addTooltips();
            // $('.favAdd').removeClass('success');
            //favouriteProperties.locked = 0;
            document.location.href = '/';
        }, 'json');

    },

    getByGuest: function() {
       $.post ( '/ajax/get-guest-favourites/', [], function (data, status) {
            if ( status == 'success' ) {

                if ( data.errors ) {
                    alert(data.errors);
                    favouriteProperties.locked = 0;
                    return;
                }

                favouriteProperties.collection = data.properties;
                favouriteProperties.counter = $(data.properties).length;
                if ( favouriteProperties.counter > 0 ) {
                    favouriteProperties.showTarget();
                }
                favouriteProperties._bindEvents();
                favouriteProperties.locked = 0;
            }
        }, 'json');
    },

    _find: function( propertyID ) {
        for (var i in favouriteProperties.collection) {
            var property = favouriteProperties.collection[i];
            if (null == property) {
                continue;
            }

            if ( property.id == propertyID ){
                return property;
            }
        }
        return false;
    },

    _removeFromCollection: function( propertyID ) {

        for (var i in favouriteProperties.collection) {
            var property = favouriteProperties.collection[i];

            if (null == property) {
                continue;
            }

            if ( property.id == propertyID ){
                favouriteProperties.collection[i] = null;
                return true;
            }
        }

        return false;
    },

    _bindEvents: function() {
        favouriteProperties.markFavedLinks();
        favouriteProperties.addTooltips();

        $('.favAdd').live('click', function(e) {
            e.preventDefault();
            /* some ajax processing */
            if (favouriteProperties.locked) {
                return;
            }

            var propertyID = Integer.parse( $(this).attr('rel'), 10 );
            
            /* if nothing to operate with return */
            if ( null === propertyID ||  propertyID < 1 ) {
                return;
            }

            /* already added, remove from fav */
            if ($(this).is('.success')) {
                favouriteProperties.locked = 1;
                favouriteProperties.remove( propertyID );
                $(this).removeClass('success');
                return;
            }

            favouriteProperties.locked = 1;
            favouriteProperties.add( propertyID );
            $(this).addClass('success');
        });

        $('#clearFav').live('click', function(e) {
            e.preventDefault();
            /* some ajax processing */
            if (favouriteProperties.locked) {
                return;
            }

            favouriteProperties.locked = 1;
            favouriteProperties.clearAll();
        });

    },

    updateTarget: function() {
        $('#' + favouriteProperties.targetID).html( favouriteProperties.counter );
    },

    showTarget: function() {
        $('#' + favouriteProperties.targetID).html( favouriteProperties.counter ).css('visibility', 'visible');
    },

    hideTarget: function() {
        $('#' + favouriteProperties.targetID).html( favouriteProperties.counter ).css('visibility', 'hidden');
    },

    markFavedLinks: function() {
        for (var i in favouriteProperties.collection) {
            var property = favouriteProperties.collection[i];

            if (null == property) {
                continue;
            }

            $('.favAdd[rel=' + property.id +  ']').addClass('success');
        }
    },

    addTooltips: function() {
         if (!$('#ezpz-content-favShow').length) {
             var messageShow = lang('Click to view your<br />favourite list');
             $('<div id="ezpz-content-favShow" class="tooltip-content">'  + messageShow + '</div>').appendTo($('body'));
             $('#' + favouriteProperties.targetID).ezpz_tooltip({contentId: 'ezpz-content-favShow'});
         }

         if (!$('#ezpz-content-favAdd').length) {
             var messageAdd = lang('Add this property<br />to your favourites');
             $('<div id="ezpz-content-favAdd" class="tooltip-content">'  + messageAdd + '</div>').appendTo($('body'));
         }

         if (!$('#ezpz-content-favRemove').length) {
             var messageRemove = lang('Remove this property<br />from your favourites');
             $('<div id="ezpz-content-favRemove" class="tooltip-content">'  + messageRemove + '</div>').appendTo($('body'));
         }

         $('.favAdd').unbind('mouseover mouseout mousemove');
         $('.tooltip-content').hide();

         $('.favAdd').each(function(){
            if ($(this).is('.success')) {
                $(this).ezpz_tooltip({contentId: 'ezpz-content-favRemove'});
            } else {
                $(this).ezpz_tooltip({contentId: 'ezpz-content-favAdd'});
            }
         });
    }

};

$(document).ready(function(){
    if ($('.pseudoSelect').length) {

        $('.pseudoSelect').each(function(e,i){
            fakeSelect( $(this) );
        });

        $(document).click(function(e) {
            /* do not procced if no opened fake select lists */
            if ( $('.fakeList:visible').length < 1 ) {
                return;
            };

            var target = e.target;

            var isFakeList = $(target).parents('.fakeList').length ||  $(target).hasClass('fakeList');
            /* do not close if event triggerred over opened fake list */
            if ( isFakeList ) {
                return;
            };

            var isFakeSelect = $(target).parents('.fakeSelect').length || $(target).hasClass('fakeSelect');
            /* fakeSelect handle list with own event */
            if ( isFakeSelect ) {
                return;
            };

            $('.fakeList:visible').hide();
        });

        $(document).click(function(e) {
            /* do not procced if no opened drop down */
            if ( $('#additonal_search_container:visible').length < 1 ) {
                return;
            };

            var target = e.target;

            var isDropDown = $(target).parents('#additonal_search_container').length ||  'additonal_search_container' == $(target).attr('id');
            /* do not close if event triggerred over opened drop down */
            if ( isDropDown ) {
                return;
            };

            var isOpenLink = $(target).parents('#additional_continent_search').length || 'additional_continent_search' == $(target).attr('id');
            /* fakeSelect handle list with own event */
            if ( isOpenLink ) {
                return;
            };

            $('#additonal_search_container:visible').hide();
        });
    }

    if ($('.DPHolder').length) {

        $('.DPHolder').each(function(e,i){

           bindDPHolderEvents( $(this) );

        });

    };

    globalLoader.init();

    popUpManager.init();

    favouriteProperties.init();

    $("#zopimChatShow").click(function(e){
        e.preventDefault();
        if ( typeof($zopim) === 'undefined' || $zopim === null) {
            return;
        }
        $zopim.livechat.window.show();

    });

    $('.destinations a', '#footer').click(function(){
        globalLoader.show();
    });
    
    $(".tooltip-content").appendTo('body');
    $(".tooltip-target").ezpz_tooltip();

});

