﻿/*  @@ INDEX
    ----------------------------------

    @@ SETUP - ADD TO COMPARATION
    @@ SETUP - COMPARATOR GRID
    @@ SETUP - ALERT DEFINER
    @@ SETUP - FAVORITE MARKING
    @@ SETUP - ACCOUNT STATUS
    @@ SETUP - LOGIN
    @@ SETUP - USER REGISTERING
    @@ SETUP - MYCASAYES ACCOUNT DETAIL
    @@ SETUP - OPERATION FEEDBACK
    @@ SETUP - DASHBOARD
    @@ SETUP - ACCOUNT DETAILS NAVIGATION
    @@ SETUP - ALERT REMOVE
    @@ SETUP - ALERT EXTEND

*/

var _keyboard = {left:37, up:38, right:39, down:40, enter:13, escape:27, backspace:8 };


/* @@ SETUP - ADD TO COMPARATION
   ==================================================================== */

var _currentComparerIDs = 0;
var _suggestedTitle = '';
(function($) {
    $.fn.Setup_ComparerSessionProperty = function(pluginSettings) {
        var defaultSettings = {
            property_ids: '',
            currentSession_id: 0,
            handlerURL: '',
            userHistoryID: '',
            requestTimeout: 5000,
            resources: '',
            suggestedTitle: ''
        };
        var settings = $.extend(defaultSettings, pluginSettings);

        return this.each(function() {

            var _processing = false;

            var $control = $(this);
            var $overlayDiv = $('#overlayAddToComparer');
            var $overlayDivChildren = $overlayDiv.children('div');

            var $comparerForm = $('#comparerForm', $overlayDiv),
                $comparerFeedback = $('#comparerFeedback', $overlayDiv);

            var $newSessionForm = $('#newSession', $overlayDiv),
                $existingSessionForm = $('#existingSession', $overlayDiv);

            var $btn_newSession = $('.lnkNewSession', $overlayDiv),
                $btn_existingSession = $('.lnkExistingSession', $overlayDiv),
                $btn_addToSession = $('#submitComparerArea a', $overlayDiv);

            var $ddlComparerSessions = $('#ddlComparerSessions', $overlayDiv),
                $hdfComparerSessions = $('#ddlComparerSessions input:first', $overlayDiv);

            var $txtComparerSession = $('#txtComparerSession', $overlayDiv);

            var $operationSuccess = $('.opSuccess', $overlayDiv),
                $operationFailed = $('.opFailed', $overlayDiv);

            var $btn_FeedbackOk = $('#comparerFeedback a.ok', $overlayDiv);

            var $mandatoryFieldsFeedback = $('#mandatoryFieldsFeedback', $overlayDiv),
                $loader = $(".loader", $overlayDiv);
            var $wExistingSession = $('#wExistingSession', $overlayDiv),
                $wNewSession = $('#wNewSession', $overlayDiv);


            var $containerTitle = $('#comparerTitle', $overlayDiv),
                $containerTitle_sub = $('#comparerTitle_sub', $overlayDiv);

            var $feedbackSuccessTitle = $('.opSuccess .hTitle', $overlayDiv),
                $feedbackSuccessTitle_sub = $('.opSuccess .hSubTitle a', $overlayDiv),
                $feedbackFailedTitle = $('.opFailed .hTitle', $overlayDiv),
                $feedbackFailedTitle_sub = $('.opFailed .hSubTitle a', $overlayDiv);

            var $resources = $.parseJSON(settings.resources);

            var propertyIds = settings.property_ids.split(",");
            //var suggestedTitle = settings.suggestedTitle;

            var cookieID = "lastSession_" + settings.userHistoryID;
            function SETUP_FORM() {

                function INIT() {

                    $comparerForm.show();
                    $comparerFeedback.hide();
                    $operationSuccess.hide();
                    $operationFailed.hide();
                    $mandatoryFieldsFeedback.hide();
                    $wExistingSession.hide();
                    $wNewSession.hide(); 
                                      

                };
                INIT();

                $control.click(function() {
                   
                    var lastUsedSession = 0;
                    if ($.cookies.get(cookieID) != null) {
                        lastUsedSession =  $.cookies.get(cookieID);
                    }                    
                    
                    SetupOverlayDivPositioning();

                    _currentComparerIDs = settings.property_ids; // shared ID, para comparar apenas um ID de imovel de cada vez
                    _suggestedTitle = settings.suggestedTitle;
                    $txtComparerSession.val(_suggestedTitle);

                    if (propertyIds.length == 0)
                        return false;

                    // se só há um imóvel, dou a possibilidade de adicioná-lo a uma sessão existente, ou de criar uma nova
                    if (propertyIds.length == 1) {
                        
                        if ($ddlComparerSessions.children("div.options").children().length == 0) {
                            $btn_existingSession.hide();
                            $existingSessionForm.hide();
                            $newSessionForm.show();
                        } 
                        else {
                            if (lastUsedSession > 0) {
                                $ddlComparerSessions.trigger('SelectValue', lastUsedSession);
                            }
                            $btn_existingSession.show();
                            $existingSessionForm.show();
                            $newSessionForm.hide();
                        }

                        //change resources
                        $containerTitle.text($resources.property.title);
                        $containerTitle_sub.text($resources.property.title_sub);
                        $feedbackFailedTitle.text($resources.property.feedbackFailed);
                        $feedbackFailedTitle_sub.text($resources.property.feedbackFailed_sub);
                        $feedbackSuccessTitle.text($resources.property.feedbackSuccess);
                        $feedbackSuccessTitle_sub.text($resources.property.feedbackSuccess_sub);

                    } 
                    // se há vários imóveis, será sempre necessário criar uma sessão nova
                    else {
                        
                        $btn_existingSession.hide();
                        $existingSessionForm.hide();
                        $newSessionForm.show();

                        /*change resources*/
                        $containerTitle.text($resources.session.title);
                        $containerTitle_sub.text($resources.session.title_sub);
                        $feedbackFailedTitle.text($resources.session.feedbackFailed);
                        $feedbackFailedTitle_sub.text($resources.session.feedbackFailed_sub);
                        $feedbackSuccessTitle.text($resources.session.feedbackSuccess);
                        $feedbackSuccessTitle_sub.text($resources.session.feedbackSuccess_sub);
                    }


                    //Se o user não está registado, então não poderá criar mais sessoes de comparação
                    
                    if(settings.userHistoryID==""){
                   
                        $txtComparerSession.val(settings.suggestedTitle);
                        $txtComparerSession.attr("disabled","disabled");
                        $btn_existingSession.hide();
                        $existingSessionForm.hide();
                        $newSessionForm.show();

                    }

                    $overlayDiv.fadeIn(function() {
                        //$overlayDiv.one('click', function() { $overlayDiv.hide(); });
                    });

                    $(window).scroll(function() {
                        SetupOverlayDivPositioning();
                    });

                    return false;
                });

                // close button
                $('.closeOverlay', $overlayDivChildren).unbind('click').click(function() {
                    if (!_processing) {
                        $overlayDiv.hide();
                    }
                    return false;
                });

                $(window).bind('resize', function() { SetupOverlayDivPositioning(); });

                $overlayDivChildren.click(function(e) { /*e.stopPropagation();*/ });

                $(document).keydown(function(e) {
                    if (e.keyCode == _keyboard.escape) {
                        $overlayDiv.hide();
                    }
                });

                function SetupOverlayDivPositioning() {
                    $overlayDiv.css('top', $(window).scrollTop());
                    $overlayDiv.css('height', $(window).height());
                };

                $btn_existingSession.click(function() {

                    if ($.browser.msie) {
                        $newSessionForm.hide();
                        $btn_newSession.show();
                        $existingSessionForm.show();

                    }
                    else {
                        $newSessionForm.fadeOut("slow", function() {
                            $btn_newSession.show();
                            $existingSessionForm.fadeIn();
                        });
                    }

                    $mandatoryFieldsFeedback.hide();
                    $wExistingSession.hide();
                    $wNewSession.hide();
                    return false;
                });

                $btn_newSession.click(function() {

                    if ($.browser.msie) {
                        $existingSessionForm.hide();
                        $btn_existingSession.show();
                        $newSessionForm.show();
                    }
                    else {
                        $existingSessionForm.fadeOut("slow", function() {
                            $btn_existingSession.show();
                            $newSessionForm.fadeIn();
                        });
                    }

                    $mandatoryFieldsFeedback.hide();
                    $wExistingSession.hide();
                    $wNewSession.hide();
                    return false;
                });

                $btn_FeedbackOk.click(function() {
                    $overlayDiv.hide();
                    INIT();
                    return false;
                });



                $btn_addToSession.unbind('click').click(function() {
                    AddToComparation();
                    return false;
                });

                $txtComparerSession.keypress(function(e) {
                    if (e.keyCode == _keyboard.enter) {
                        $txtComparerSession.blur();
                        if (!_processing) {
                            AddToComparation();
                        }
                    }
                });

                function AddToComparation() {

                    _processing = true;

                    $btn_addToSession.hide();
                    $loader.show();

                    $mandatoryFieldsFeedback.hide();
                    $wExistingSession.hide();
                    $wNewSession.hide();

                    var _title = $txtComparerSession.val();
                    var _comparationID = $hdfComparerSessions.val();

                    if ($existingSessionForm.is(":visible")) {
                        _title = "";
                    } else {
                        _comparationID = 0;
                    }

                    if (_title != "" || _comparationID > 0) {


                        $.ajax({
                            type: 'GET',
                            dataType: 'json',
                            processData: true,
                            timeout: settings.requestTimeout,
                            url: settings.handlerURL,
                            data: {
                                title: _title,
                                comparationid: _comparationID,
                                propertyids: _currentComparerIDs,
                                userHistoryID: settings.userHistoryID
                            },
                            error: function(request, status, error) {
                                _processing = false;
                                $comparerForm.hide();
                                $comparerFeedback.show();
                                $operationFailed.show();
                                $operationSuccess.hide();
                                $loader.hide();
                                $btn_addToSession.show();
                            },
                            success: function(data) {

                                _processing = false;

                                $loader.hide();
                                $btn_addToSession.show();

                                if (data.success != "0") {
                                    $comparerForm.hide();
                                    $comparerFeedback.show();
                                    $operationFailed.hide();
                                    $operationSuccess.show();
                                    
                                    // guardo a ultima opção seleccionada (para ajudar o utilizador na proxima vez)
                                    $.cookies.set(cookieID, data.success);
                                    
                                    // faço o reload à dropdown que lista as sessões existentes, para dar ao utilizador a possibilidade de adicionar algo novamente a essa sessão
                                    //TriggerDependentDropDowns("ddlComparerSessions", 0);                    
                                    $('#ddlComparerSessions').trigger('ReloadControl', 0);

                                } else {
                                    $comparerForm.hide();
                                    $comparerFeedback.show();
                                    $operationFailed.show();
                                    $operationSuccess.hide();
                                }

                                $('body').trigger('ReloadMyCasaYesAccountStatus');
                            }

                        });
                    }
                    else {

                        $mandatoryFieldsFeedback.show();
                        if ($existingSessionForm.is(":visible")) {
                            $wExistingSession.show();
                            $wNewSession.hide();
                        } else {
                            $wExistingSession.hide();
                            $wNewSession.show();
                        }
                        $loader.hide();
                        $btn_addToSession.show();

                        _processing = false;
                        return false;
                    }

                };


            };
            SETUP_FORM();

        });

    };
})(jQuery);



/* @@ SETUP - COMPARATOR GRID
   ==================================================================== */

function Setup_ComparatorGrid(sessionID, url_databaseHandler, userHistoryID,requestTimeout, propertiesFoundResource, propertyFoundResource) {

    $(document).ready(function() {

        var $control = $('#dComparation');
        var $btn_removeSession = $('#btnRemoveSession');
        function Setup_RowsBackgrounds() {

            // Comparation Parameters
            $('#comparationParameters .group_body', $control).each(function() {
                $(this).children('div:odd').each(function() {
                    $(this).addClass('odd');
                });
                $(this).children('div:even', $control).each(function() {
                    $(this).addClass('even');
                });
            });

            // Dummy Column
            $('#dummyColumn .group_body', $control).each(function() {
                $(this).children('div:odd').each(function() {
                    $(this).addClass('odd');
                });
                $(this).children('div:even').each(function() {
                    $(this).addClass('even');
                });
            });

            // Comparation Properties
            $('#comparationProperties .group_body', $control).each(function() {
                $(this).children('div:odd').each(function() {
                    $(this).addClass('odd');
                });
                $(this).children('div:even').each(function() {
                    $(this).addClass('even');
                });
            });

        };
        Setup_RowsBackgrounds();

        function Setup_RowsHeight() {

            var numRows = 0;

            // atribuir classes comuns a cada linha
            $('.dataColumn').each(function() {
                var count = 0;
                numRows = 0;
                $(this).children('.group_body').each(function() {
                    $(this).children('div').each(function() {
                        $(this).addClass('row_' + count++);
                        numRows++;
                    });
                });
            });

            // definir a altura para cada linha
            for (var i = 0; i < numRows; i++) {
                var maxHeight = 0;
                $('.row_' + i).each(function() {
                    var cellHeight = $(this).outerHeight();
                    if (cellHeight > maxHeight) {
                        maxHeight = cellHeight;
                    }
                });

                if ($('.row_' + i).height() < maxHeight) {
                    $('.row_' + i).css('line-height', '18px');
                }
                $('.row_' + i).height(maxHeight);
            }


        };
        Setup_RowsHeight();

        function Setup_Navigation() {

            var $stage = $('#comparationPropertiesWrapper', $control);
            var $scroller = $('#comparationProperties', $control);

            var columnWidth = $('.propertyItem').outerWidth();
            var propertyCount = $('.propertyItem', $scroller).size();
            var visibleProperties = 3;

            var $navigation = {
                backward: $('#backward', $control),
                forward: $('#forward', $control)
            };

            $scroller.width(columnWidth * propertyCount);

            $navigation.forward.click(function() {
                $stage.animate({
                    scrollLeft: '+=' + columnWidth
                },
			250,
			function() {
			    Setup_ArrowVisibility();
			});
                return false;
            });

            $navigation.backward.click(function() {
                $stage.animate({
                    scrollLeft: '-=' + columnWidth
                },
			250,
			function() {
			    Setup_ArrowVisibility();
			});
                return false;
            });

            function Setup_ArrowVisibility() {

                $navigation.backward.show();
                $navigation.forward.show();

                if ($stage.scrollLeft() == 0) {
                    $navigation.backward.hide();
                }

                if ($stage.scrollLeft() + (columnWidth * (visibleProperties + 1)) > columnWidth * propertyCount) {
                    $navigation.forward.hide();
                }

            };
            Setup_ArrowVisibility();

        };
        Setup_Navigation();

        var _dummyColumn_originalWidth = $('#dummyColumn', $control).width();
        var _propertyColumn_originalWidth = $('.propertyItem').outerWidth();

        function Setup_DummyColumn() {

            var $stage = $('#comparationPropertiesWrapper', $control);
            var $scroller = $('#comparationProperties', $control);
            var $dummyColumn = $('#dummyColumn', $control);

            var columnWidth = _propertyColumn_originalWidth;
            var numProperties = $('.propertyItem', $scroller).size();
            var slots = 3;
            
            if (numProperties < slots) {
            
                var usedWidth = columnWidth * numProperties;
                var freeWidth = columnWidth * slots - usedWidth;
                
                $stage.width(usedWidth);
                $dummyColumn.width(_dummyColumn_originalWidth + freeWidth + 1);
                
            }

        };
        Setup_DummyColumn();

        function Remove() {

            //Remove a Property
            $control.find(".remove").children("a").each(function() {

                var $btnRemove = $(this);
                var propertyID = $(this).siblings("input").val();

                $btnRemove.click(function() {
                    $.ajax({
                        type: 'GET',
                        dataType: 'json',
                        processData: true,
                        timeout: requestTimeout,
                        url: url_databaseHandler,
                        data: {
                            propertyid: propertyID,
                            comparationid: sessionID,
                            userHistoryID: userHistoryID
                        },
                        error: function(request, status, error) {
                            ShowOperationFeedback(operationFeedback.status.error, operationFeedback.operations.removing, operationFeedback.types.comparer_remove_property);
                        },
                        success: function(data) {

                            if (Boolean(data.success)) {
                                UpdateGrid($btnRemove);
                                ShowOperationFeedback(operationFeedback.status.success, operationFeedback.operations.removing, operationFeedback.types.comparer_remove_property);
                            }
                            else {
                                ShowOperationFeedback(operationFeedback.status.error, operationFeedback.operations.removing, operationFeedback.types.comparer_remove_property);
                            }
                        }

                    });
                    return false;
                });


            });


            //Remove Session
            $btn_removeSession.click(function() {
                $.ajax({
                    type: 'GET',
                    dataType: 'json',
                    processData: true,
                    timeout: requestTimeout,
                    url: url_databaseHandler,
                    data: {
                        propertyid: 0,
                        comparationid: sessionID,
                        userHistoryID: userHistoryID
                    },
                    error: function(request, status, error) {
                        ShowOperationFeedback(operationFeedback.status.error, operationFeedback.operations.removing, operationFeedback.types.comparer_remove_session);
                    },
                    success: function(data) {

                        if (Boolean(data.success)) {

                            ShowOperationFeedback(operationFeedback.status.success, operationFeedback.operations.removing, operationFeedback.types.comparer_remove_session);

                        } else {
                            ShowOperationFeedback(operationFeedback.status.error, operationFeedback.operations.removing, operationFeedback.types.comparer_remove_session);
                        }
                    }

                });

                return false;
            });

        }
        Remove();

        function UpdateGrid($btn_remove) {
            
            var $propertyItem = $btn_remove.closest(".propertyItem");

            $propertyItem.fadeOut();
            $propertyItem.remove();

            //Change number of results (-1 é por causa da dummy collumn)
            var numberOfProperties = $(".propertyItem").length - 1;
            var phrase = propertiesFoundResource;
            if (numberOfProperties == 1) {
                phrase = propertyFoundResource;
            }
            if (numberOfProperties > 1) {
                phrase = propertiesFoundResource;
            }

            $("#dTitle cite").text(numberOfProperties + " " + phrase);

            //Actualizar layout da grid
            var $stage = $('#comparationPropertiesWrapper', $control);
            var $scroller = $('#comparationProperties', $control);
            var usedWidth = _propertyColumn_originalWidth * $('.propertyItem', $scroller).size(); 
            $scroller.width(usedWidth);
            $stage.scrollLeft(0);
            Setup_Navigation();

            Setup_DummyColumn();

        }


    });

};  
     

/* @@ SETUP - ALERT DEFINER
   ==================================================================== */

function Setup_AlertDefiner(searchID, userHistoryID, jsonControlIDs, jsonResources, jsonWarnings, url_databaseHandler, jsonUserInfo, url_sendEmailHandler) {
    
    var _processing = false;
    
    var requestTimeout = 5000;
    var controlIDs = $.parseJSON(jsonControlIDs);
    var $controls = {
        trigger_btn: $('#' + controlIDs.trigger_btn),
        overlay_area: $('#' + controlIDs.overlay_area),
        stage_area: $('#' + controlIDs.stage_area),
        submit_btn: $('#' + controlIDs.submit_btn),
        ok_btn: $('#' + controlIDs.ok_btn),
        view_inputForm: $('#' + controlIDs.view_inputForm),
        view_feedback: $('#' + controlIDs.view_feedback),
        view_feedback_success: $('#' + controlIDs.view_feedback_success),
        view_feedback_error: $('#' + controlIDs.view_feedback_error),
        txtAlertTitle: $('#' + controlIDs.txtAlertTitle),
        ddlPeriod: $('#' + controlIDs.ddlPeriod),
        hdfPeriod: $('#' + controlIDs.hdfPeriod),
        txtName: $('#' + controlIDs.txtName),
        txtEmail: $('#' + controlIDs.txtEmail),
        lblInputFeedback: $('#' + controlIDs.lblInputFeedback),
        loader: $('.loader', $('#' + controlIDs.stage_area))
    };

    var _resources = $.parseJSON(jsonResources);
    var $resources = {
        mandatory_fields: _resources.mandatory_fields,
        invalid_email: _resources.invalid_email
    };

    var _warnings = $.parseJSON(jsonWarnings);
    var $warnings = {
        wEmail:$('#' + _warnings.wEmail),
        wName:$('#' + _warnings.wName),
        wAlertTitle:$('#' + _warnings.wAlertTitle),
        wPeriod:$('#' + _warnings.wPeriod)
    };

   
    var $userInfo = $.parseJSON(jsonUserInfo);
    
    function Setup_OverlayDisplay(){

        $controls.trigger_btn.click(function() {
            SetupPositioning();

            // initial state
            $controls.view_inputForm.show();
            $controls.view_feedback.hide();
            $controls.view_feedback_success.hide();
            $controls.view_feedback_error.hide();
            $controls.loader.hide();
            $controls.submit_btn.show();
            //hide warnings
            $warnings.wEmail.hide();
            $warnings.wName.hide();
            $warnings.wPeriod.hide();
            $warnings.wAlertTitle.hide();
            $controls.lblInputFeedback.text('');

            // Clear form
            $controls.txtName.val($userInfo.Name);
            $controls.txtEmail.val($userInfo.Email);
            //$controls.ddlPeriod.val('');

            $controls.overlay_area.fadeIn();
            /*
            $controls.overlay_area.one('click', function() {
                $controls.overlay_area.hide();
            });
            */
            return false;
        });
        
        $(window).bind('resize', function() {
            SetupPositioning();
        });  
            
        $(document).keydown(function(e) {
            if (e.keyCode == _keyboard.escape) {
                $controls.overlay_area.hide();
            }
        });        
        
        $controls.ok_btn.click(function(){
            $controls.overlay_area.hide();
            return false;
        }); 
        
        // anulo o (F1)
        /*
        $controls.stage_area.click(function(e) {
            e.stopPropagation();
        });          
        */
        
        function SetupPositioning(){
            $controls.overlay_area.css('top', $(window).scrollTop());
            $controls.overlay_area.css('height', $(window).height());
        };    
        
        $(window).scroll(function(){
            SetupPositioning();
        });
        
        // close button
        $('.closeOverlay', $controls.overlay_area).unbind('click').click(function(){
            if (!_processing) {
                $controls.overlay_area.hide();
            }
            return false;
        });    
    
    };
    Setup_OverlayDisplay();
        
    function Setup_Submit(){

        $controls.submit_btn.click(function() {
            Define_Alert();
            return false;
        });
        
        $('input', $controls.stage_area).each(function(){
            $(this).keypress(function(e){
                if (e.keyCode == _keyboard.enter) {
                    $(this).blur();
                    if (!_processing) {
                        Define_Alert();
                    }
                }
            });
        });
        

        function Define_Alert(){
            
            var success = false;
            var alertID = '';
            //hide warnings
            $warnings.wEmail.hide();
            $warnings.wName.hide();
            $warnings.wPeriod.hide();
            $warnings.wAlertTitle.hide();
            $controls.lblInputFeedback.text('');

            $controls.loader.show();
            $controls.submit_btn.hide();

            if (IsSubmitValid()) {
                if (IsEmailValid($controls.txtEmail.val())) {
                    
                    _processing = true;

                    $.ajax({
                        type: 'GET',
                        dataType: 'json',
                        processData: true,
                        timeout: requestTimeout,
                        url: url_databaseHandler,
                        data: {
                            alertTitle: $controls.txtAlertTitle.val(),
                            period: $controls.hdfPeriod.val(),
                            name: $controls.txtName.val(),
                            email: $controls.txtEmail.val(),
                            userHistoryID: userHistoryID,
                            searchID: searchID
                        },
                        error: function(request, status, error) {

                            $controls.loader.hide();
                            $controls.submit_btn.show();
                            
                            _processing = false;

                            $controls.view_feedback_success.hide();
                            $controls.view_feedback_error.show();

                            $controls.view_inputForm.hide();
                            $controls.view_feedback.show();

                        },
                        success: function(data) {

                            $controls.loader.hide();
                            $controls.submit_btn.show();

                            _processing = false;

                            if (data.success!="0") {
                               
                                //Send Email
                                alertID=data.success;
                                SendEmail(alertID);
                                
                                $controls.view_feedback_success.show();
                                $controls.view_feedback_error.hide();

                                $controls.view_inputForm.hide();
                                $controls.view_feedback.show();
                                
                                 

                            } else {
                                $controls.view_feedback_success.hide();
                                $controls.view_feedback_error.show();

                                $controls.view_inputForm.hide();
                                $controls.view_feedback.show();

                            }

                            $('body').trigger('ReloadMyCasaYesAccountStatus');
                        }

                    });
                } else { //Invalid Email
                    $controls.lblInputFeedback.text($resources.invalid_email);
                    $warnings.wEmail.show();

                    $controls.loader.hide();
                    $controls.submit_btn.show();

                    return false;
                }

            }
            else {//Mandatory Fields
                $controls.lblInputFeedback.text($resources.mandatory_fields);

                $controls.loader.hide();
                $controls.submit_btn.show();

                return false;
            }

        };
        
        function SendEmail(alertID) { 
        // - chamar o handler que envia o e-mail

            $.ajax({
                type: 'POST',
                dataType: 'json',
                processData: true,
                timeout: requestTimeout,
                url: url_sendEmailHandler,
                data: {
                    alertID: alertID,
                    userHistoryID:userHistoryID
                },
                error: function(request, status, error) {

                },
                success: function(data) {

                    if (Boolean(data.success)) {
                    }
                    else {

                    }
                }
            });
  
        }
        
    };
    Setup_Submit();

    
    
    function IsSubmitValid() {
        var isValid = true;

        if ($controls.txtAlertTitle.val() == "")
        { isValid = false; $warnings.wAlertTitle.show(); }

        if ($controls.txtName.val() == "") 
        { isValid = false; $warnings.wName.show(); }

        if ($controls.txtEmail.val() == "")
        { isValid = false; $warnings.wEmail.show(); }

        if ($controls.hdfPeriod.val() < 0)
        { isValid = false; $warnings.wPeriod.show(); }
        
       return isValid;
   }

   function IsEmailValid(email) {
       if (email != "") {
           var regExp = /^.+@.+\..{2,3}$/;
           return regExp.test(email);
       } else {
           return true;
       }
   }

};


/* @@ SETUP - FAVORITE MARKING
   ==================================================================== */

(function($) {
    $.fn.Setup_FavoriteHandler = function(pluginSettings) {
        var defaultSettings = {
            data_id: 0,
            isFavoriteClass: '',
            loadingClass: '',
            languageID: '',
            requestTimeout: 10000,
            url_dataTarget: '',
            markFavoriteLabel: '',
            unmarkFavoriteLabel: '',
            isMarked: 0,
            propertyType: true, // os propertyType or searchType,
            autoRemoveElement: false,
            userHistoryID: ''
        };
        var settings = $.extend(defaultSettings, pluginSettings);
        return this.each(function() {

            // marcar estado inicial do favorito
            if (settings.isMarked) {
                $(this).addClass(settings.isFavoriteClass).attr('title', settings.unmarkFavoriteLabel);
            }
            else {
                $(this).attr('title', settings.markFavoriteLabel);
            }

            // click no favorito
            $(this).click(function() {

                var $parentElement = $(this).parent().parent().parent().parent();
                
                var $favLink = $(this);
                $favLink.addClass(settings.loadingClass);

                var wasFavorite;
                if ($(this).hasClass(settings.isFavoriteClass)) {
                    wasFavorite = 1;
                }
                else {
                    wasFavorite = 0;
                }
                
                var feedbackType;
                if(settings.propertyType) 
                    feedbackType = operationFeedback.types.favorite_properties
                else 
                    feedbackType =  operationFeedback.types.favorite_searches

                if (settings.url_dataTarget != '') {
                    $.ajax({
                        type: 'GET',
                        dataType: 'json',
                        processData: true,
                        timeout: settings.requestTimeout,
                        url: settings.url_dataTarget,
                        data: {
                            wasFavorite: wasFavorite,
                            dataID: settings.data_id,
                            userHistoryID: settings.userHistoryID
                        },
                        error: function(request, status, error) {
                            
                            if (wasFavorite) {
                                    ShowOperationFeedback(operationFeedback.status.error, operationFeedback.operations.removing, feedbackType);
                            }
                            else{
                                ShowOperationFeedback(operationFeedback.status.error, operationFeedback.operations.adding, feedbackType);
                            }

                            $favLink.removeClass(settings.loadingClass);
                        },
                        success: function(data) {
                            $favLink.removeClass(settings.loadingClass);
                            if(settings.autoRemoveElement) {
                                if ($parentElement.siblings('.groupItem').size() == 0) 
                                    $parentElement.parent().remove();
                                else 
                                    $parentElement.remove();
                            }
                            if (Boolean(data.success)) {
                                if (wasFavorite) {
                                    $favLink.removeClass(settings.isFavoriteClass);
                                    $favLink.attr('title', settings.markFavoriteLabel);
                                    ShowOperationFeedback(operationFeedback.status.success, operationFeedback.operations.removing, feedbackType);
                                }
                                else {
                                    $favLink.addClass(settings.isFavoriteClass);
                                    $favLink.attr('title', settings.unmarkFavoriteLabel);
                                    ShowOperationFeedback(operationFeedback.status.success, operationFeedback.operations.adding, feedbackType);

                                }
                            }
                            else{
                                if (wasFavorite) {
                                     ShowOperationFeedback(operationFeedback.status.error, operationFeedback.operations.removing, feedbackType);
                                }
                                else{
                                    ShowOperationFeedback(operationFeedback.status.error, operationFeedback.operations.adding, feedbackType);
                                }
                                
                            }
                            $('body').trigger('ReloadMyCasaYesAccountStatus');
                        }
                    });
                }
                else {
                    alert('DataSource URL not defined!');
                }

                return false;

            });

        });
    };
})(jQuery);




/* @@ SETUP - ACCOUNT STATUS
   ==================================================================== */

function Setup_AccountStatusControls(json_controlIDs, json_settings) {

    var controlIDs = $.parseJSON(json_controlIDs),
        settings = $.parseJSON(json_settings);

    var $controls = {
        lastSearches: $('#' + controlIDs.lastSearches).children('span'),
        lastProperties: $('#' + controlIDs.lastProperties).children('span'),
        favoriteProperties: $('#' + controlIDs.favoriteProperties).children('span'),
        favoriteSearches: $('#' + controlIDs.favoriteSearches).children('span'),
        comparator: $('#' + controlIDs.comparator).children('span'),
        alerts: $('#' + controlIDs.alerts).children('span')
    };

    function ReloadControl() {

        if (settings.url_dataTarget != '') {
            $.ajax({
                type: 'GET',
                dataType: 'json',
                processData: true,
                timeout: settings.requestTimeout,
                url: settings.url_dataTarget,
                cache: false,
                data: {
                    userHistoryID: settings.userHistoryID
                },
                error: function(request, status, error) {
                    alert(status);
                },
                success: function(counters) {
               
                    $controls.lastSearches.text(counters.searchesOnHistory);
                    $controls.lastProperties.text(counters.propertiesOnHistory);
                    $controls.favoriteProperties.text(counters.propertiesOnFavorites);
                    $controls.favoriteSearches.text(counters.searchesOnFavorites);
                    $controls.comparator.text(counters.comparationSessions);
                    $controls.alerts.text(counters.alerts);
                }
            });
        }
        else {
            alert('DataSource URL not defined!');
        }

    };
    ReloadControl();

    function UpdateValue() { 
    
    };

    $('body').bind('ReloadMyCasaYesAccountStatus', function(event, dependencyID) {
        ReloadControl();
    });    
    
    
};



/* @@ SETUP - LOGIN
   ==================================================================== */

function Setup_LoginControl(control_id, languageID, Login_dataSourceURL, RecoverPassword_dataSourceURL, requestTimeout,
                            overlayDivID, _loginWindowLinkID, _emailLoginTextboxID, _passwordLoginTextboxID, _emailRecoverPasswordTextboxID,
                            _loginButtonID, _loginButtonName, _recoverPasswordLink, _recoverPasswordButtonID, _cancelButtonID, _okButtonID,
                            _recoverPasswordFeedbackLabel,loginFeedbackMsg,recoverPasswordResources,_loginFormID,_recoverPasswordFormID) {

    $(document).ready(function() {

        var _processing = false;

        var $control = $('#' + control_id);
        var $overlayDiv = $('#' + overlayDivID);
        var $overlayLoginControl = $('.dLogin', $overlayDiv);
        var $loginWindowLink = $('#' + _loginWindowLinkID);

        var $controls = {
            loginForm: {
                formID: $('#' + _loginFormID),
                email: $('#' + _emailLoginTextboxID),
                password: $('#' + _passwordLoginTextboxID),
                loginButton: $('#' + _loginButtonID),
                loader: $('.loader', $overlayLoginControl),
                accessDenied: $('.accessDenied', $overlayLoginControl),
                recoverPasswordLink: $('#' + _recoverPasswordLink)
            },
            recoverPasswordForm: {
                formID: $('#' + _recoverPasswordFormID),
                email: $('#' + _emailRecoverPasswordTextboxID),
                recoverButton: $('#' + _recoverPasswordButtonID),
                feedback: $('.' + _recoverPasswordFeedbackLabel),
                loader: $('.loader', $overlayLoginControl),
                okButton: $('#' + _okButtonID),
                cancelButton: $('#' + _cancelButtonID),
                resources: $.parseJSON(recoverPasswordResources)
            }
        };

        var $settings = {
            language_ID: languageID,
            urlLogin_dataTarget: Login_dataSourceURL,
            urlRecoverPassword_dataTarget: RecoverPassword_dataSourceURL,
            requestTimeout: requestTimeout,
            loginButtonName: _loginButtonName,
            loginFeedbackMsg: loginFeedbackMsg
        };

        function Setup_LoginWindowDisplay() {

            // ajustar altura do div overlay
            SetupOverlayDivPositioning();

            // ao clicar no link login, mostrar o overlayDiv
            $loginWindowLink.click(function() {
                $controls.recoverPasswordForm.formID.hide();
                $controls.loginForm.email.val('');
                $controls.loginForm.password.val('');
                $overlayDiv.fadeIn(function() {
                    $controls.loginForm.email.focus();
                });



                // ao clicar na area preta, escondo o controlo (F1)
                /*
                $overlayDiv.one('click', function() {
                $overlayDiv.hide();
                });
                */

                return false;
            });

            // anulo o (F1)
            /*
            $overlayLoginControl.click(function(e) {
            e.stopPropagation();
            });
            */

            // ao carregar em ESC, escondo o overlayDiv
            $(document).keydown(function(e) {
                if (e.keyCode == _keyboard.escape) {
                    $overlayDiv.hide();
                }
            });

            // ao fazer resize tenho que ajustar as dimensões do overlay
            $(window).bind('resize', function() {
                SetupOverlayDivPositioning();
            });

            // close button
            var $closeButton = $('.closeOverlay', $overlayLoginControl);
            $closeButton.unbind('click').click(function() {
                if (!_processing) {
                    $overlayDiv.hide();
                }
                return false;
            });

            function SetupOverlayDivPositioning() {
                $overlayDiv.css('top', $(window).scrollTop());
                $overlayDiv.css('height', $(window).height());
            };

            $(window).scroll(function() {
                SetupOverlayDivPositioning();
            });

        };
        Setup_LoginWindowDisplay();

        function Setup_LoginProcess() {

            // ao carregar no ENTER, activo o login
            $($controls.loginForm.password).keydown(function(e) {
                if (e.keyCode == _keyboard.enter) {
                    if ($controls.loginForm.email.val() != "" && $controls.loginForm.password.val() != "") {
                        Login();
                    }
                }
            });

            $($controls.loginForm.password).focus(function() {
                ShowLogin_Form(false);
            });

            $($controls.loginForm.email).focus(function() {
                ShowLogin_Form(false);
            });

            // ao carregar no botao de login, activo o logi
            $controls.loginForm.loginButton.click(function() {
                if ($controls.loginForm.email.val() != "" && $controls.loginForm.password.val() != "") {
                    Login();
                }
                return false;
            });

            // ao carregar no botao de recuperar password, activo o form de recuperar password
            $controls.loginForm.recoverPasswordLink.click(function() {
                ShowRecoverPassword_Form(true);
                return false;
            });


            function Login() {

                $controls.loginForm.accessDenied.hide();
                $controls.loginForm.loginButton.hide();
                $controls.loginForm.loader.show();
                $controls.loginForm.recoverPasswordLink.hide();

                _processing = true;

                if ($settings.urlLogin_dataTarget != '') {
                    $.ajax({
                        type: 'GET',
                        dataType: 'json',
                        processData: true,
                        timeout: $settings.requestTimeout,
                        url: $settings.urlLogin_dataTarget,
                        data: {
                            email: $controls.loginForm.email.val(),
                            password: $controls.loginForm.password.val()
                        },
                        error: function(request, status, error) {
                            _processing = false;
                            $controls.loginForm.accessDenied.show();
                            $controls.loginForm.loader.hide();
                            $controls.loginForm.recoverPasswordLink.show();
                        },
                        success: function(data) {
                            _processing = false;
                            if (data.success == "1") {
                                //alert($settings.loginFeedbackMsg);
                                __doPostBack($settings.loginButtonName, '');
                            }
                            else {
                                $controls.loginForm.accessDenied.show();
                                $controls.loginForm.loader.hide();
                                $controls.loginForm.recoverPasswordLink.show();
                            }
                        }
                    });
                }
                else {
                    alert('DataSource URL not defined!');
                }
            };

        };
        Setup_LoginProcess();

        function Setup_RecoverPasswordProcess() {

            // ao carregar no ENTER, activo o login
            $($controls.recoverPasswordForm.email).keydown(function(e) {
                if (e.keyCode == _keyboard.enter) {
                    if ($controls.recoverPasswordForm.email.val() != "") {
                        RecoverPassword();
                    }
                }
            });

            // ao carregar no botao de recuperar password, activo o recuperar password
            $controls.recoverPasswordForm.recoverButton.click(function() {
                if ($controls.recoverPasswordForm.email.val() != "") {
                    RecoverPassword();
                }
                return false;
            });

            // ao carregar no botao de cancelar, volto ao form de Login
            $controls.recoverPasswordForm.cancelButton.click(function() {
                ShowLogin_Form(false);
                return false;
            });

            // ao carregar no botao de ok, volto ao form de Login
            $controls.recoverPasswordForm.okButton.click(function() {
                ShowLogin_Form(true);
                return false;
            });

            function RecoverPassword() {

                $controls.recoverPasswordForm.feedback.hide();
                $controls.recoverPasswordForm.recoverButton.hide();
                $controls.recoverPasswordForm.okButton.hide();
                $controls.recoverPasswordForm.cancelButton.hide();
                $controls.recoverPasswordForm.loader.show();

                _processing = true;

                if ($settings.urlRecoverPassword_dataTarget != '') {
                    $.ajax({
                        type: 'GET',
                        dataType: 'json',
                        processData: true,
                        cache:false,
                        timeout: $settings.requestTimeout,
                        url: $settings.urlRecoverPassword_dataTarget,
                        data: {
                            email: $controls.recoverPasswordForm.email.val()
                        },
                        error: function(request, status, error) {
                            _processing = false;
                            $controls.recoverPasswordForm.feedback.text($controls.recoverPasswordForm.resources.generalError);
                            $controls.recoverPasswordForm.feedback.show();
                            $controls.recoverPasswordForm.recoverButton.show();
                            $controls.recoverPasswordForm.loader.hide();
                            $controls.recoverPasswordForm.cancelButton.show();
                        },
                        success: function(data) {
                            _processing = false;
                            if (data.success == "1") {
                                //alert($settings.loginFeedbackMsg);
                                $controls.recoverPasswordForm.feedback.text($controls.recoverPasswordForm.resources.success);
                                $controls.recoverPasswordForm.feedback.show();
                                $controls.recoverPasswordForm.okButton.show();
                                $controls.recoverPasswordForm.recoverButton.hide();
                                $controls.recoverPasswordForm.loader.hide();
                            }
                            else {
                                $controls.recoverPasswordForm.feedback.text(data.success);
                                $controls.recoverPasswordForm.feedback.show();
                                $controls.recoverPasswordForm.recoverButton.show();
                                $controls.recoverPasswordForm.loader.hide();
                                $controls.recoverPasswordForm.cancelButton.show();
                            }
                        }
                    });
                }
                else {
                    alert('DataSource URL not defined!');
                }

            };
        };
        Setup_RecoverPasswordProcess();


        function ShowRecoverPassword_Form(clearFields) {

            if (clearFields) {
                $controls.recoverPasswordForm.email.val('');
            }

            $controls.recoverPasswordForm.okButton.hide();
            $controls.recoverPasswordForm.cancelButton.show();
            $controls.recoverPasswordForm.feedback.hide();
            $controls.recoverPasswordForm.recoverButton.show();

            $controls.loginForm.formID.hide();
            $controls.recoverPasswordForm.formID.show();
        }

        function ShowLogin_Form(clearFields) {

            if (clearFields) {
                $controls.loginForm.email.val('');
                $controls.loginForm.password.val('');
            }

            $controls.loginForm.loginButton.show();
            $controls.loginForm.accessDenied.hide();

            $controls.recoverPasswordForm.formID.hide();
            $controls.loginForm.formID.show();
        }
    });
};   

   

/* @@ SETUP - USER REGISTERING
   ==================================================================== */

function SetupUserRegister(_clientID, url_dataTarget) {
    $('#locationSuggestions').SetupRegister({
        maxResults: 6,
        clientID: _clientID,
        databaseHandler_URLs: { locations: url_dataTarget}
    });
}

(function($) {
    $.fn.SetupRegister = function(pluginSettings) {

        var defaultSettings = {
            parameter: 'parameter_value',
            databaseHandler_URLs: {
                locations: 'App_Handlers/MyCasaYes/locations.ashx'
            },
            queryDelay: 250, 		// milisegundos
            requestTimeout: 5000, 	//milisegundos
            mininumChars: 3, 	// valor tido em conta apenas para o primeiro request de localizações.
            maxResults: 6,
            currentItem_class: 'current',
            clientID: ''


        };
        var $settings = $.extend(defaultSettings, pluginSettings);

        return this.each(function() {



            // ============================================================================================
            // ============================================================================================
            // ============================================================================================

            // INDEX

            // DECLARATIONS
            // INIT
            // TEXT INPUT
            // SUGGESTIONS
            // ============================================================================================
            // ============================================================================================
            // ============================================================================================


            // ============================================================================================
            // ============================================================================================
            // ============================================================================================

            // @@ DECLARATIONS

            // ============================================================================================
            // ============================================================================================
            // ============================================================================================
            var txtbox = "#" + $settings.clientID + "_txtLocation";
            var $textbox = $(txtbox),
                $suggestionsDiv = $('#dSuggestions', $(this)),
				$loader = $('.loader', $(this)),
				$notfound = $('.notfound', $(this)),
				$error = $('.error', $(this)),
				$pickedID = $('#dPickedID input', $(this));

            var _delayID = -1;
            var currentIndex = 0;
            

            // ============================================================================================
            // ============================================================================================
            // ============================================================================================

            // @@ INIT

            // ============================================================================================
            // ============================================================================================
            // ============================================================================================

            // ============================================================================================
            // ============================================================================================
            // ============================================================================================

            // @@ TEXT INPUT

            // ============================================================================================
            // ============================================================================================
            // ============================================================================================
            // 2.2. faço com que cada click fora da àrea de sugestões, as apague
            $(document).bind('click', function() {
                ClearSuggestions();
                if ($pickedID.val() == "") {
                    // 1. retiro o focus da textbox, pois só assim consigo alterar o seu valor
                    $textbox.blur();
                    // 2. reset ao valor da textbox
                    $textbox.val('');
                }
            });

            // ----------------------------------------------------------------------
            // > Ao escrever na caixa de texto, solicito à BD os dados adequados
            $textbox.keyup(function(event) {

                // 1. obter o token introduzido na textbox
                var token = $textbox.val();

                // 2. apenas invocar a base de dados se: for um caracter válido + houverem caracteres suficientes
                if (IsIgnoredKey(event.keyCode) == false) {
                    $pickedID.val('');
                    if (HasEnoughChars(token) == true) {

                        // 2.1. apresentar o loader
                        $loader.show();

                        // 2.2. garantir que só são feitos pedidos à BD de x em x segundos

                        // 2.2.1. apagar possiveis timeouts a decorrer
                        if (_delayID != -1) {
                            clearTimeout(_delayID);
                        }

                        // 2.2.2 criar novo timeout
                        _delayID = setTimeout(function() {
                            RequestSuggestions(token);
                        }, $settings.queryDelay);

                    }
                    else {

                        // 2.3. apaga as sugestões
                        ClearSuggestions();
                    }
                }

            });


            // ----------------------------------------------------------------------

            // ----------------------------------------------------------------------
            // > evita que um clique em cima da caixa de texto, faça desaparecer as sugestões
            $textbox.click(function(event) {
                // ClearSuggestions();
                event.stopPropagation();
            });
            // ----------------------------------------------------------------------

            // ----------------------------------------------------------------------
            // > verifica se existem caracteres suficientes para iniciar uma pesquisa
            function HasEnoughChars(token) {
                return (token.length >= $settings.mininumChars);
            };
            // ----------------------------------------------------------------------

            // ----------------------------------------------------------------------
            // > verifica se determinada tecla pressionada deve ser considerada para solicitar dados à BD
            function IsIgnoredKey(nKeyCode) {
                if ((nKeyCode == 9) || (nKeyCode == 13) || // tab, enter
    			        (nKeyCode == 16) || (nKeyCode == 17) || // shift, ctl
    			        (nKeyCode >= 18 && nKeyCode <= 20) || // alt, pause/break,caps lock
    			        (nKeyCode == 27) || // esc
    			        (nKeyCode >= 33 && nKeyCode <= 35) || // page up,page down,end
                /*(nKeyCode >= 36 && nKeyCode <= 38) || // home,left,up
                (nKeyCode == 40) || // down*/
    			        (nKeyCode >= 36 && nKeyCode <= 40) || // home,left,up, right, down
    			        (nKeyCode >= 44 && nKeyCode <= 45) || // print screen,insert
    			        (nKeyCode == 224) || // print screen,insert
    			        (nKeyCode == 229) // Bug 2041973: Korean XP fires 2 keyup events, the key and 229
    			    ) {
                    return true;
                }
                return false;
            };
            // ----------------------------------------------------------------------

            // ----------------------------------------------------------------------
            function CloseBecauseError() {

                // 1. Limpar a textbox
                $textbox.val('');
                $textbox.attr('readonly', 'true');
                $textbox.blur();


            }
            // ----------------------------------------------------------------------


            // ============================================================================================
            // ============================================================================================
            // ============================================================================================

            // @@ SUGGESTIONS

            // ============================================================================================
            // ============================================================================================
            // ============================================================================================


            // ----------------------------------------------------------------------
            // > Pedido de sugestões à BD
            function RequestSuggestions(_token) {


                // 0. faço o pedido assincrono ao handler
                $.ajax({
                    type: 'GET',
                    timeout: $settings.requestTimeout,
                    url: $settings.databaseHandler_URLs.locations,
                    processData: true,
                    data: {
                        token: encodeURI(_token),
                        maxResults: $settings.maxResults
                    },
                    dataType: 'json',
                    error: function(request, status, error) {
                        // 1.2. escondo o loader
                        $loader.hide();

                    },
                    success: function(data) {

                        // 2.1. carrego as sugestões
                        DisplaySuggestions(data.suggestions, _token);

                        // 2.2. escondo o loader
                        $loader.hide();

                    }
                });

            };
            // ----------------------------------------------------------------------

            // ----------------------------------------------------------------------
            // > Apresento as sugestões, lista de DIVs
            function DisplaySuggestions(suggestions, token) {

                // 1. Apago as sugestões que possam existir na lista
                ClearSuggestions();
                // 2. Se existirem sugestões a apresentar
                if (suggestions.length > 0) {

                    // 2.1 para cada uma delas
                    $.each(suggestions, function(index, results) {
                        // 2.1.1. construo a descrição a apresentar por cada sugestão, Se fizer match com a outra caixa de texto, irá ser apresentada essa informação(icone)
                        var line = results.description;

                        // 2.1.2. construo o objecto (sugestão) a ser adicionado à lista de sugestões
                        var linkTemplate = $('<a href="#">' + line + '</a>');

                        // 2.1.3. anexo-lhe os dados (JSON) relativos à informação que ele representa
                        linkTemplate.data('resultItemInfo', results);

                        // 2.1.4. anexo-lhe o indice da lista respectivo
                        linkTemplate.data('itemIndex', index);
                        // 2.1.5. preparo o efeito de hovering no objecto
                        linkTemplate.hover(
                            function() {

                                // 2.1.5.1. ao passar o rato por cima devo marcar o objecto como seleccionado
                                currentIndex = $(this).data("itemIndex");
                                SetSelected(currentIndex);
                                $textbox.blur();

                            }, function() {

                                // 2.1.5.2. ao retirar o rato de cima devo desmarcá-lo como objecto seleccionado
                                linkTemplate.removeClass($settings.currentItem_class);
                                currentIndex = -1;
                                $textbox.blur();
                            }
                        );

                        // 2.1.6. preparo o click no objecto
                        linkTemplate.click(function(event) {

                            // 2.1.6.1. chamo a função de selecção de item
                            PickValue(results);

                            // 2.1.6.2. evito a propagação do evento
                            event.stopPropagation();
                            return false;
                        });

                        // 2.1.7. sublinho a existencia do token especificado em cada sugestão
                        linkTemplate.highlight(token);

                        // 2.1.8. adiciono o objecto ao div de sugestões
                        $suggestionsDiv.append(linkTemplate);

                    });


                    // 2.3. depois de preparado, mostro o div de sugestões se a caixa de texto ainda tiver o numero mínimo de caracteres
                    if (HasEnoughChars($textbox.val())) {
                        $suggestionsDiv.show();
                    }
                    else {
                        ClearSuggestions();
                    }

                }

            };


            // ----------------------------------------------------------------------

            // ----------------------------------------------------------------------
            // > Limpa todas as sugestões activas
            function ClearSuggestions() {

                // 1. escondo o div com as sugestões
                $suggestionsDiv.hide();

                // 2. apago o seu conteudo, para na próxima vez que for apresentado, não levar com valores obsoletos
                $suggestionsDiv.children().remove();
            };
            // ----------------------------------------------------------------------

            // ----------------------------------------------------------------------
            // > Limpa a textbox
            function ClearTextbox() {

                // 1. retiro o focus da textbox, pois só assim consigo alterar o seu valor
                $textbox.blur();
                // 2. reset ao valor da textbox
                $textbox.val('');

                // 3. volto a atribuir o focus à textbox
                $textbox.focus();

                $pickedID.val('');
            };
            // ----------------------------------------------------------------------

            // ----------------------------------------------------------------------
            // > Para cada tecla 
            $(document).keydown(function(e) {
                BindKeyPress(e);
            });
            // ----------------------------------------------------------------------

            function BindKeyPress(e) {
                var pressed = false;

                // 1. Se estão a ser apresentadas sugestoes
                if ($suggestionsDiv.is(':visible')) {

                    switch (e.keyCode) {

                        // up arrow                                                                  
                        case _keyboard.up:
                            if ($loader.is(':visible')) return false;
                            Navigate('up', $suggestionsDiv, $textbox);
                            pressed = true;
                            break;

                        // down arrow                                                                  
                        case _keyboard.down:
                            if ($loader.is(':visible')) return false;
                            Navigate('down', $suggestionsDiv, $textbox);
                            pressed = true;
                            break;

                        // enter key                                                                  
                        case _keyboard.enter:
                            if ($loader.is(':visible')) return false;
                            // 1. Get location info JSON object
                            var results = $suggestionsDiv.children('a').eq(currentIndex).data('resultItemInfo');

                            // 2. Pick Location
                            if (results != undefined)
                            { PickValue(results); }
                            pressed = true;
                            break;

                        // escape key                      
                        case _keyboard.escape:
                            ClearTextbox();
                            ClearSuggestions();
                            pressed = true;
                            break;

                    }
                }

                if (pressed)
                    return false;
            }

            // ----------------------------------------------------------------------
            function Navigate(direction) {

                if ($suggestionsDiv.children('a').filter('.' + $settings.currentItem_class).size() == 0) {
                    currentIndex = -1;

                }

                if (direction == 'up' && currentIndex != -1) {
                    if (currentIndex != 0) {
                        currentIndex--;
                    }
                    else {
                        $suggestionsDiv.children('a').removeClass($settings.currentItem_class);
                        $textbox.focus();
                        currentIndex = -1;
                        return;
                    }
                } else if (direction == 'down') {
                    if (currentIndex != $suggestionsDiv.children('a').size() - 1) {
                        currentIndex++;
                    }
                }

                SetSelected(currentIndex, $suggestionsDiv);

            };
            // ----------------------------------------------------------------------

            // ----------------------------------------------------------------------
            function SetSelected(itemIndex) {
                if (itemIndex >= 0) {
                    $suggestionsDiv.children('a').removeClass($settings.currentItem_class);
                    $suggestionsDiv.children('a').eq(itemIndex).addClass($settings.currentItem_class);
                }
            };
            // ----------------------------------------------------------------------


            // ============================================================================================
            // ============================================================================================

            // ============================================================================================
            // ============================================================================================


            // ----------------------------------------------------------------------
            function PickValue(result) {

                // 0. Limpar nodes existentes
                $textbox.val();

                if (result.description != "") {
                    // 1. attach de toda a informação relativa à sugestão
                    $textbox.data('resultItemInfo', result);

                    $pickedID.val(result.id);

                    var line = '';
                    // 1. Atribuo a descrição à textbix
                    line = result.description;
                    $textbox.val(line);
                } else {
                    $pickedID.val("");
                }

                // 1.2. Apagar sugestões
                ClearSuggestions();
            };
            // ----------------------------------------------------------------------

        });

    };
})(jQuery);



/* @@ SETUP - MYCASAYES ACCOUNT DETAIL
   ==================================================================== */

function SetupAccountDetails() {
    var delay;
    var $accountDetails = $('.dAccountDetails');
    $('.details', $accountDetails).hide();
    $accountDetails.each(function() {
        $('.groupItem', $(this)).each(function() {
            // ao passar o rato por cima do item
            $(this).mouseenter(function() {
                var $item = $(this);
                delay = setInterval(function() {
                    $('.details', $item).stop(true, true).slideDown(function() {
                    });
                    clearInterval(delay);
                }, 500);
            });
            // ao retirar o rato de cima do item
            $(this).mouseleave(function() {
                var $item = $(this);
                clearInterval(delay);
                $('.details', $item).slideUp();
            });
        });
    });
};


/* @@ SETUP - CHANGE USER INFO FEEDBACK
==================================================================== */
function Setup_ChangeUserInfoFeeback() {
    ShowOperationFeedback(operationFeedback.status.success, 0, operationFeedback.types.update_account_info);
}



/* @@ SETUP - OPERATION FEEDBACK (Overlay)
   ==================================================================== */
var $feedbackResources;
var feedbackComparerResources;

var operationFeedback = {
    status: {
        success: 1,
        error: 2,
        warning: 3
    },
    operations: {
        adding: 1,
        removing: 2
    },
    types: {
        favorite_properties: 1,
        favorite_searches: 2,
        comparer_remove_session: 3,
        comparer_remove_property: 4,
        update_account_info:5,
        finder_mandatory_fields:6,
        sell_property:7,
        alerts_remove:8,
        alerts_extend:9
    }
};
function Setup_OperationFeedback(_resources, comparerResources) {
    $feedbackResources = _resources;
}


function ShowOperationFeedback(status, operation, type) {

    var $overlayDiv = $('#overlayOperationFeedback');
    var $overlayDivChildren = $('> div', $overlayDiv);

    var $okButton = $('#lnkOk', $overlayDiv),
        $okButtonText = $('#lnkOk cite', $overlayDiv);

    var $icon = $("#icon", $overlayDiv);

    var $title = $("#operationResult .title", $overlayDiv),
        $title_sub = $("#lnkTitle_sub", $overlayDiv),
        $title_link = $("#lnkTitle_sub", $overlayDiv);

    var $marketing = $(".registerMarketing", $overlayDiv),
        $marketingTitle = $(".registerMarketing .title", $overlayDiv),
        $marketingTitle_sub = $(".registerMarketing .subTitle", $overlayDiv);

    var $MarketingReasonA = $(".registerMarketing #reasonA", $overlayDiv),
        $MarketingReasonB = $(".registerMarketing #reasonB", $overlayDiv),
        $MarketingReasonC = $(".registerMarketing #reasonC", $overlayDiv);

    var $lnkOtherAdvantages = $("#lnkOtherAdvantages", $overlayDiv),
        $lnkRegisterOrLogin = $("#lnkRegisterOrLogin", $overlayDiv);

    var operationDivClasses = {
        registered: 'operation_registeredUsers',
        unRegistered: 'operation_unregisteredUsers'
    };

    function SetupVisibleFeedbacks() {
    
        var title = '';
        var title_sub = '';
        var title_link = '';
        var marketingTitle = '';
        var marketingTitle_sub = '';
        var reasonA = '';
        var reasonB = '';
        var reasonC = '';
        var ok = '';
        var ok_link = '';
        var register = '';
        var register_link = '';
        var otherAdvantages = '';
        var otherAdvantages_link = '';
        var icon_class = '';

        switch (type) {

            //Favorite Properties 
            case operationFeedback.types.favorite_properties:
                //Adding
                if (operation == operationFeedback.operations.adding) {
                    //Success
                    if (status == operationFeedback.status.success) {
                        title = $feedbackResources.favorite_property_add.success.title;
                        title_sub = $feedbackResources.favorite_property_add.success.title_sub;
                        title_link = $feedbackResources.favorite_property_add.success.link;
                        icon_class = $feedbackResources.favorite_property_add.success.icon_class;
                        //Error
                    } else {
                        title = $feedbackResources.favorite_property_add.error.title;
                        title_sub = $feedbackResources.favorite_property_add.error.title_sub;
                        title_link = $feedbackResources.favorite_property_add.error.link;
                        icon_class = $feedbackResources.favorite_property_add.error.icon_class;
                    }

                    //Removing
                } else {
                    //Success
                    if (status == operationFeedback.status.success) {
                        title = $feedbackResources.favorite_property_remove.success.title;
                        title_sub = $feedbackResources.favorite_property_remove.success.title_sub;
                        title_link = $feedbackResources.favorite_property_remove.success.link;
                        icon_class = $feedbackResources.favorite_property_remove.success.icon_class;
                        //Error
                    } else {
                        title = $feedbackResources.favorite_property_remove.error.title;
                        title_sub = $feedbackResources.favorite_property_remove.error.title_sub;
                        title_link = $feedbackResources.favorite_property_remove.error.link;
                        icon_class = $feedbackResources.favorite_property_remove.error.icon_class;

                    }
                }

                //General
                marketingTitle = $feedbackResources.favorite_property_remove.marketing.title;
                marketingTitle_sub = $feedbackResources.favorite_property_remove.marketing.title_sub;
                reasonA = $feedbackResources.favorite_property_remove.marketing.reasonA;
                reasonB = $feedbackResources.favorite_property_remove.marketing.reasonB;
                reasonC = $feedbackResources.favorite_property_remove.marketing.reasonC;
                register = $feedbackResources.favorite_property_remove.marketing.register;
                register_link = $feedbackResources.favorite_property_remove.marketing.register_link;
                otherAdvantages = $feedbackResources.favorite_property_remove.marketing.otheradvantages;
                otherAdvantages_link = $feedbackResources.favorite_property_remove.marketing.otheradvantages_link;
                ok = $feedbackResources.favorite_property_remove.buttons.ok;
                ok_link = $feedbackResources.favorite_property_remove.buttons.ok_link;
                break;

            //Favorite Searches 
            case operationFeedback.types.favorite_searches:
                //Adding
                if (operation == operationFeedback.operations.adding) {
                    //Success
                    if (status == operationFeedback.status.success) {
                        title = $feedbackResources.favorite_search_add.success.title;
                        title_sub = $feedbackResources.favorite_search_add.success.title_sub;
                        title_link = $feedbackResources.favorite_search_add.success.link;
                        icon_class = $feedbackResources.favorite_search_add.success.icon_class;
                        //Error
                    } else {
                        title = $feedbackResources.favorite_search_add.error.title;
                        title_sub = $feedbackResources.favorite_search_add.error.title_sub;
                        title_link = $feedbackResources.favorite_search_add.error.link;
                        icon_class = $feedbackResources.favorite_search_add.error.icon_class;
                    }

                    //Removing
                } else {
                    //Success
                    if (status == operationFeedback.status.success) {
                        title = $feedbackResources.favorite_search_remove.success.title;
                        title_sub = $feedbackResources.favorite_search_remove.success.title_sub;
                        title_link = $feedbackResources.favorite_search_remove.success.link;
                        icon_class = $feedbackResources.favorite_search_remove.success.icon_class;
                        //Error
                    } else {
                        title = $feedbackResources.favorite_search_remove.error.title;
                        title_sub = $feedbackResources.favorite_search_remove.error.title_sub;
                        title_link = $feedbackResources.favorite_search_remove.error.link;
                        icon_class = $feedbackResources.favorite_search_remove.error.icon_class;

                    }
                }

                //General
                marketingTitle = $feedbackResources.favorite_search_remove.marketing.title;
                marketingTitle_sub = $feedbackResources.favorite_search_remove.marketing.title_sub;
                reasonA = $feedbackResources.favorite_search_remove.marketing.reasonA;
                reasonB = $feedbackResources.favorite_search_remove.marketing.reasonB;
                reasonC = $feedbackResources.favorite_search_remove.marketing.reasonC;
                register = $feedbackResources.favorite_search_remove.marketing.register;
                register_link = $feedbackResources.favorite_search_remove.marketing.register_link;
                otherAdvantages = $feedbackResources.favorite_search_remove.marketing.otheradvantages;
                otherAdvantages_link = $feedbackResources.favorite_search_remove.marketing.otheradvantages_link;
                ok = $feedbackResources.favorite_search_remove.buttons.ok;
                ok_link = $feedbackResources.favorite_search_remove.buttons.ok_link;
                break;

            case operationFeedback.types.comparer_remove_session:
                //Success
                if (status == operationFeedback.status.success) {
                    title = $feedbackResources.comparer_remove_session.success.title;
                    title_sub = $feedbackResources.comparer_remove_session.success.title_sub;
                    title_link = $feedbackResources.comparer_remove_session.success.link;
                    icon_class = $feedbackResources.comparer_remove_session.success.icon_class;
                    //Error
                } else {
                    title = $feedbackResources.comparer_remove_session.error.title;
                    title_sub = $feedbackResources.comparer_remove_session.error.title_sub;
                    title_link = $feedbackResources.comparer_remove_session.error.link;
                    icon_class = $feedbackResources.comparer_remove_session.error.icon_class;
                }
                //General
                marketingTitle = $feedbackResources.comparer_remove_session.marketing.title;
                marketingTitle_sub = $feedbackResources.comparer_remove_session.marketing.title_sub;
                reasonA = $feedbackResources.comparer_remove_session.marketing.reasonA;
                reasonB = $feedbackResources.comparer_remove_session.marketing.reasonB;
                reasonC = $feedbackResources.comparer_remove_session.marketing.reasonC;
                register = $feedbackResources.comparer_remove_session.marketing.register;
                register_link = $feedbackResources.comparer_remove_session.marketing.register_link;
                otherAdvantages = $feedbackResources.comparer_remove_session.marketing.otheradvantages;
                otherAdvantages_link = $feedbackResources.comparer_remove_session.marketing.otheradvantages_link;
                ok = $feedbackResources.comparer_remove_session.buttons.ok;
                ok_link = $feedbackResources.comparer_remove_session.buttons.ok_link;

                break;

            case operationFeedback.types.comparer_remove_property:
                //Success
                if (status == operationFeedback.status.success) {
                    title = $feedbackResources.comparer_remove_property.success.title;
                    title_sub = $feedbackResources.comparer_remove_property.success.title_sub;
                    title_link = $feedbackResources.comparer_remove_property.success.link;
                    icon_class = $feedbackResources.comparer_remove_property.success.icon_class;
                    //Error
                } else {
                    title = $feedbackResources.comparer_remove_property.error.title;
                    title_sub = $feedbackResources.comparer_remove_property.error.title_sub;
                    title_link = $feedbackResources.comparer_remove_property.error.link;
                    icon_class = $feedbackResources.comparer_remove_property.error.icon_class;
                }
                //General
               
                marketingTitle = $feedbackResources.comparer_remove_property.marketing.title;
                marketingTitle_sub = $feedbackResources.comparer_remove_property.marketing.title_sub;
                reasonA = $feedbackResources.comparer_remove_property.marketing.reasonA;
                reasonB = $feedbackResources.comparer_remove_property.marketing.reasonB;
                reasonC = $feedbackResources.comparer_remove_property.marketing.reasonC;
                register = $feedbackResources.comparer_remove_property.marketing.register;
                register_link = $feedbackResources.comparer_remove_property.marketing.register_link;
                otherAdvantages = $feedbackResources.comparer_remove_property.marketing.otheradvantages;
                otherAdvantages_link = $feedbackResources.comparer_remove_property.marketing.otheradvantages_link;
                ok = $feedbackResources.comparer_remove_property.buttons.ok;
                ok_link = $feedbackResources.comparer_remove_property.buttons.ok_link;
                break;


            case operationFeedback.types.update_account_info:
            
                title = $feedbackResources.update_account_info.success.title;
                title_sub = $feedbackResources.update_account_info.success.title_sub;
                title_link = $feedbackResources.update_account_info.success.link;
                icon_class = $feedbackResources.update_account_info.success.icon_class;

                ////
                marketingTitle = $feedbackResources.update_account_info.marketing.title;
                marketingTitle_sub = $feedbackResources.update_account_info.marketing.title_sub;
                reasonA = $feedbackResources.update_account_info.marketing.reasonA;
                reasonB = $feedbackResources.update_account_info.marketing.reasonB;
                reasonC = $feedbackResources.update_account_info.marketing.reasonC;
                register = $feedbackResources.update_account_info.marketing.register;
                register_link = $feedbackResources.update_account_info.marketing.register_link;
                otherAdvantages = $feedbackResources.update_account_info.marketing.otheradvantages;
                otherAdvantages_link = $feedbackResources.update_account_info.marketing.otheradvantages_link;
                ////

                ok = $feedbackResources.update_account_info.buttons.ok;
                ok_link = $feedbackResources.update_account_info.buttons.ok_link;
                break;
                
            case operationFeedback.types.finder_mandatory_fields:
            
                // configurar o container. nunca aparecerá a area do marketing do registo casaYES
                $overlayDivChildren.removeClass(operationDivClasses.unRegistered);
                $overlayDivChildren.addClass(operationDivClasses.registered);
                $marketing.hide();
                       
                if (status == operationFeedback.status.error) {
                    title = $feedbackResources.finder_mandatory_fields.error.title;
                    title_sub = $feedbackResources.finder_mandatory_fields.error.title_sub;
                    title_link = $feedbackResources.finder_mandatory_fields.error.link;
                    icon_class = $feedbackResources.finder_mandatory_fields.error.icon_class;
                } else if (status == operationFeedback.status.warning) {
                    title = $feedbackResources.finder_mandatory_fields.warning.title;
                    title_sub = $feedbackResources.finder_mandatory_fields.warning.title_sub;
                    title_link = $feedbackResources.finder_mandatory_fields.warning.link;
                    icon_class = $feedbackResources.finder_mandatory_fields.warning.icon_class;
                }


                ////
                marketingTitle = $feedbackResources.finder_mandatory_fields.marketing.title;
                marketingTitle_sub = $feedbackResources.finder_mandatory_fields.marketing.title_sub;
                reasonA = $feedbackResources.finder_mandatory_fields.marketing.reasonA;
                reasonB = $feedbackResources.finder_mandatory_fields.marketing.reasonB;
                reasonC = $feedbackResources.finder_mandatory_fields.marketing.reasonC;
                register = $feedbackResources.finder_mandatory_fields.marketing.register;
                register_link = $feedbackResources.finder_mandatory_fields.marketing.register_link;
                otherAdvantages = $feedbackResources.finder_mandatory_fields.marketing.otheradvantages;
                otherAdvantages_link = $feedbackResources.finder_mandatory_fields.marketing.otheradvantages_link;
                ////

                ok = $feedbackResources.finder_mandatory_fields.buttons.ok;
                ok_link = $feedbackResources.finder_mandatory_fields.buttons.ok_link;
                
                
                break;
                
            case operationFeedback.types.sell_property:
               
                // configurar o container. nunca aparecerá a area do marketing do registo casaYES
                $overlayDivChildren.removeClass(operationDivClasses.unRegistered);
                $overlayDivChildren.addClass(operationDivClasses.registered);
                $marketing.hide();
                
                title = $feedbackResources.sell_property.success.title;
                title_sub = $feedbackResources.sell_property.success.title_sub;
                title_link = $feedbackResources.sell_property.success.link;
                icon_class = $feedbackResources.sell_property.success.icon_class;

                ////
                marketingTitle = $feedbackResources.sell_property.marketing.title;
                marketingTitle_sub = $feedbackResources.sell_property.marketing.title_sub;
                reasonA = $feedbackResources.sell_property.marketing.reasonA;
                reasonB = $feedbackResources.sell_property.marketing.reasonB;
                reasonC = $feedbackResources.sell_property.marketing.reasonC;
                register = $feedbackResources.sell_property.marketing.register;
                register_link = $feedbackResources.sell_property.marketing.register_link;
                otherAdvantages = $feedbackResources.sell_property.marketing.otheradvantages;
                otherAdvantages_link = $feedbackResources.sell_property.marketing.otheradvantages_link;
                ////

                ok = $feedbackResources.sell_property.buttons.ok;
                ok_link = $feedbackResources.sell_property.buttons.ok_link;
                break;
            //Favorite Properties 
            case operationFeedback.types.alerts_remove :
                //Adding
                if (operation == operationFeedback.operations.removing) {
                    //Success
                    if (status == operationFeedback.status.success) {
                        title = $feedbackResources.alert_remove.success.title;
                        title_sub = $feedbackResources.alert_remove.success.title_sub;
                        title_link = $feedbackResources.alert_remove.success.link;
                        icon_class = $feedbackResources.alert_remove.success.icon_class;
                        //Error
                    } else {
                        title = $feedbackResources.alert_remove.error.title;
                        title_sub = $feedbackResources.alert_remove.error.title_sub;
                        title_link = $feedbackResources.alert_remove.error.link;
                        icon_class = $feedbackResources.alert_remove.error.icon_class;
                    }

                    //Removing
                } 

                //General
                marketingTitle = $feedbackResources.alert_remove.marketing.title;
                marketingTitle_sub = $feedbackResources.alert_remove.marketing.title_sub;
                reasonA = $feedbackResources.alert_remove.marketing.reasonA;
                reasonB = $feedbackResources.alert_remove.marketing.reasonB;
                reasonC = $feedbackResources.alert_remove.marketing.reasonC;
                register = $feedbackResources.alert_remove.marketing.register;
                register_link = $feedbackResources.alert_remove.marketing.register_link;
                otherAdvantages = $feedbackResources.alert_remove.marketing.otheradvantages;
                otherAdvantages_link = $feedbackResources.alert_remove.marketing.otheradvantages_link;
                ok = $feedbackResources.alert_remove.buttons.ok;
                ok_link = $feedbackResources.alert_remove.buttons.ok_link;
                break;
          case operationFeedback.types.alerts_extend :
                //Adding
                
                //Success
                if (status == operationFeedback.status.success) {
                    title = $feedbackResources.alert_extend.success.title;
                    title_sub = $feedbackResources.alert_extend.success.title_sub;
                    title_link = $feedbackResources.alert_extend.success.link;
                    icon_class = $feedbackResources.alert_extend.success.icon_class;
                    //Error
                } else {
                    title = $feedbackResources.alert_extend.error.title;
                    title_sub = $feedbackResources.alert_extend.error.title_sub;
                    title_link = $feedbackResources.alert_extend.error.link;
                    icon_class = $feedbackResources.alert_extend.error.icon_class;
                }


                //General
                marketingTitle = $feedbackResources.alert_extend.marketing.title;
                marketingTitle_sub = $feedbackResources.alert_extend.marketing.title_sub;
                reasonA = $feedbackResources.alert_extend.marketing.reasonA;
                reasonB = $feedbackResources.alert_extend.marketing.reasonB;
                reasonC = $feedbackResources.alert_extend.marketing.reasonC;
                register = $feedbackResources.alert_extend.marketing.register;
                register_link = $feedbackResources.alert_extend.marketing.register_link;
                otherAdvantages = $feedbackResources.alert_extend.marketing.otheradvantages;
                otherAdvantages_link = $feedbackResources.alert_extend.marketing.otheradvantages_link;
                ok = $feedbackResources.alert_extend.buttons.ok;
                ok_link = $feedbackResources.alert_extend.buttons.ok_link;
                break;

        }


        $okButtonText.text(ok);
        $okButton.attr("href", ok_link);
        $icon.addClass(icon_class);

        $title.text(title);
        $title_sub.text(title_sub);
        $title_link.attr("href", title_link);

        $marketingTitle.text(marketingTitle);
        $marketingTitle_sub.text(marketingTitle_sub);

        $MarketingReasonA.text(reasonA);
        $MarketingReasonB.text(reasonB);
        $MarketingReasonC.text(reasonC);

        $lnkOtherAdvantages.text(otherAdvantages);
        $lnkOtherAdvantages.attr("href", otherAdvantages_link);

        $lnkRegisterOrLogin.text(register);
        $lnkRegisterOrLogin.attr("href", register_link);


    };
    SetupVisibleFeedbacks();


    SetupOverlayDivPositioning();
    
    $overlayDiv.fadeIn(function () {
        //$controls.loginForm.email.focus();
        // ao clicar na area preta, escondo o controlo (F1)
        $overlayDiv.one('click', function () {
           // $overlayDiv.hide();
        });
    });
    
    $(window).scroll(function(){
        SetupOverlayDivPositioning();
    });    
    

    // anulo o (F1)
    $overlayDivChildren.click(function (e) {
        e.stopPropagation();
    });

    $(document).keydown(function (e) {
        if (e.keyCode == _keyboard.escape) {
            //$overlayDiv.hide();
        }
    });

    $okButton.click(function () {
        $overlayDiv.hide();
        if ($(this).attr("href") == "#")
            return false;
    });

    // ao fazer resize tenho que ajustar as dimensões do overlay
    $(window).bind('resize', function () {
        SetupOverlayDivPositioning();
    });

    function SetupOverlayDivPositioning() {
        $overlayDiv.css('top', $(window).scrollTop());
        $overlayDiv.css('height', $(window).height());
    };


};

/* @@ SETUP - DASHBOARD
   ==================================================================== */
function Setup_Dashboard(emailText,overlayDivID,_loginFormID, _recoverPasswordFormID, _emailLoginClass, _passwordLoginClass){
    
    var $overlayDiv = $('#' + overlayDivID);
    var $controls = {
            loginForm: {
                formID: $('#' + _loginFormID),
                email: $('input.' + _emailLoginClass),
                password: $('input.' + _passwordLoginClass)
            },
            recoverPasswordForm: {
                formID: $('#' + _recoverPasswordFormID)
            }
     };
        
    $controls.recoverPasswordForm.formID.hide();
    $controls.loginForm.email.val(emailText );
    $controls.loginForm.password.val('');
    $overlayDiv.fadeIn(function() {
        $controls.loginForm.email.focus();
    });
 
}




/* @@ SETUP - ALERT REMOVE
   ==================================================================== */

(function($) {
    $.fn.Setup_RemoveAlert = function(pluginSettings) {
        var defaultSettings = {
            data_id: 0,
            requestTimeout: 10000,
            url_dataTarget: '',
            userHistoryID:''
        };
        var settings = $.extend(defaultSettings, pluginSettings);
        return this.each(function() {

            // click 
            $(this).click(function() {

           
                var $removeLink = $(this);
            
                if (settings.url_dataTarget != '') {
                    $.ajax({
                        type: 'GET',
                        dataType: 'json',
                        processData: true,
                        timeout: settings.requestTimeout,
                        url: settings.url_dataTarget,
                        data: {
                            alertid: settings.data_id,
                            userhistoryID: settings.userHistoryID
                        },
                        error: function(request, status, error) {
                        
                            ShowOperationFeedback(operationFeedback.status.error, operationFeedback.operations.removing, operationFeedback.types.alerts_remove);
                        },
                        success: function(data) {
                            if (Boolean(data.success)) {
                                ShowOperationFeedback(operationFeedback.status.success, operationFeedback.operations.removing , operationFeedback.types.alerts_remove);
                            }
                            else{
                               ShowOperationFeedback(operationFeedback.status.error, operationFeedback.operations.removing, operationFeedback.types.alerts_remove);
                                
                            }
                            $('body').trigger('ReloadMyCasaYesAccountStatus');
                        }
                    });
                }
                else {
                    alert('DataSource URL not defined!');
                }

                return false;

            });

        });
    };
})(jQuery);


/* @@ SETUP - ALERT EXTEND
   ==================================================================== */

(function($) {
    $.fn.Setup_ExtendAlert = function(pluginSettings) {
        var defaultSettings = {
            data_id: 0,
            requestTimeout: 10000,
            url_dataTarget: '',
            userHistoryID:'',
            ddlPeriodID:''
        };
        var settings = $.extend(defaultSettings, pluginSettings);
        return this.each(function() {

            // click 
            $(this).click(function() {

           
                var $extendLink = $(this);
                var $ddlPeriodID = $("#" + settings.ddlPeriodID);
                var daysToExtend = $ddlPeriodID.val();
                
                
                if (settings.url_dataTarget != '') {
                    $.ajax({
                        type: 'GET',
                        dataType: 'json',
                        processData: true,
                        timeout: settings.requestTimeout,
                        url: settings.url_dataTarget,
                        data: {
                            alertid: settings.data_id,
                            userhistoryID: settings.userHistoryID,
                            daystoextend:daysToExtend
                        },
                        error: function(request, status, error) {
                        
                            ShowOperationFeedback(operationFeedback.status.error, 0, operationFeedback.types.alerts_extend);
                        },
                        success: function(data) {
                            if (Boolean(data.success)) {
                                ShowOperationFeedback(operationFeedback.status.success, 0 , operationFeedback.types.alerts_extend);
                            }
                            else{
                               ShowOperationFeedback(operationFeedback.status.error, 0, operationFeedback.types.alerts_extend);
                            }
                            $('body').trigger('ReloadMyCasaYesAccountStatus');
                        }
                    });
                }
                else {
                    alert('DataSource URL not defined!');
                }

                return false;

            });

        });
    };
})(jQuery);




/* @@ SETUP - ACCOUNT DETAILS NAVIGATION
   ==================================================================== */

/*
var myURL = ''; 
    
$(function() {

    var newHash      = "",
        $mainContent = $("#dMainContent"),
        $pageWrap    = $("#dMainContent"),
        baseHeight   = 0,
        $el;

    $pageWrap.height($pageWrap.height());
    baseHeight = $pageWrap.height() - $mainContent.height();
    
    $(".navigator").delegate("a", "click", function() {
        myURL = $(this).attr("href");
        window.location.hash = 'aa';
        return false;
    });

    $(window).bind('hashchange', function(){

        newHash = myURL;
                
        if (newHash) {
        
            $mainContent
                .find("#dynamicContent")
                .fadeOut(200, function() {
                    console.log('faded');
                    $mainContent.hide().load(newHash + " #dynamicContent > *", function() {
                        $mainContent.fadeIn(200, function() {
                            $pageWrap.animate({
                                height: baseHeight + $mainContent.height() + "px"
                            });
                            SetupAccountDetails();
                        });
                    });
                });
        };

    });

    $(window).trigger('hashchange');

});

*/


/* @@ AUXILIAR PLUGINS
   ==================================================================== */

// ------------------------------------------------
(function($) {
    $.fn.highlight = function(pat) {
        function innerHighlight(node, pat) {
            var skip = 0;
            if (node.nodeType == 3) {
                var pos = node.data.toUpperCase().indexOf(pat);
                if (pos >= 0) {
                    var spannode = document.createElement('span');
                    spannode.className = 'highlight';
                    var middlebit = node.splitText(pos);
                    var endbit = middlebit.splitText(pat.length);
                    var middleclone = middlebit.cloneNode(true);
                    spannode.appendChild(middleclone);
                    middlebit.parentNode.replaceChild(spannode, middlebit);
                    skip = 1;
                }
            }
            else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
                for (var i = 0; i < node.childNodes.length; ++i) {
                    i += innerHighlight(node.childNodes[i], pat);
                }
            }
            return skip;
        }
        return this.each(function() {
            innerHighlight(this, pat.toUpperCase());
        });
    };
})(jQuery);
// ------------------------------------------------
