﻿/*  @@ INDEX
    ----------------------------------

    @@ Refiner
    @@ Property Carousel
    @@ Property Scroller
    @@ Similar Properties List
    @@ Near Properties
    @@ ImagesSetup
    @@ SmartMap
    @@ ThumbnailSlideshow
    @@ Features
    @@ VideoPlayer

*/


/* @@ REFINER
   ==================================================================== */
   
    function Setup_Refiner(cid, dataSource, dataIDs, settings, resources, searchID, queryStringRootSearchID, queryStringParentSearchID) {

        var $control = $('#' + cid);
        var $featuresPicker = $('#SearchRefiner #refinerfeaturesCtrl'),
            $booleanFeatures = $('#SearchRefiner #refinerBooleansCtrl'),
            $pricesRanges = $('#SearchRefiner #refinerPricesCtrl'),
            $energyRatings = $('#SearchRefiner #refinerEnergyRating'),
			$reloadControl = $('.errorMsg a',$control);
                                
        var $feedbacks = {
            loader: $('.loader', $control),
            errorIcon: $('.errorIcn', $control),
			 errorControl: $('.errorMsg',$control)
        };   

		$featuresPicker.hide();
        $booleanFeatures.hide()
        $pricesRanges.hide();
        $energyRatings.hide();
		$feedbacks.errorControl.hide();

        function DataRequest() {

            if (dataSource.handler_url != '') {
                $.ajax({
                    type: 'GET',
                    dataType: 'json',
                    processData: true,
                    timeout: dataSource.request_timeout,
                    url: dataSource.handler_url,
                    data: {
                        searchID: dataIDs.searchID,
                        agencyID: dataIDs.agencyID,
                        cultureID: settings.cultureID,
                        userHistoryID: settings.userHistoryID,
                        showZeroCounters: settings.showZeroCounters,
                        showZeroCountersOnLocations: settings.showZeroCountersOnLocations,
                        currentURL: settings.currentURL
                    },
                    error: function(request, status, error) {
                        $feedbacks.loader.hide();
                        $feedbacks.errorIcon.show();
						$feedbacks.errorControl.show();
                    },
                    success: function(data) {
                        $feedbacks.loader.hide();

                        if(data.refinerData!=undefined){ //if json return an empty object, the DataBind will not occur
                            DataBind(data.refinerData);
                        }
                        else{
                            $feedbacks.errorIcon.show();
                            $feedbacks.errorControl.show();
                        }
                    }
                });
            } 
            else {
                alert('DataSource URL not defined!');
            }
        
        };
        DataRequest();
        
		 //Reload the refiner
        $reloadControl.click(function(){
            $feedbacks.loader.show();
            $feedbacks.errorIcon.hide();
            $feedbacks.errorControl.hide();
            dataSource.request_timeout += 10000; // Add more 10 seconds to timeout
            DataRequest();
            
            return false;
        });
		
        function DataBind(refinerData){               
                        
            // para cada grupo de refinação
            $.each(refinerData, function (index, refinerInfo) {

                var $filters_div = $('<div>');

                // build simple links <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
                if (!refinerInfo.isRangeControl) {

                    // 1. group of refinerFilters setup                  
                    $.each(refinerInfo.filters, function (index2, filterInfo) {

                        // 0. declarations
                        var nodeDescription = '',
                            nodeTooltip,
                            nodeLink;
                        var $linkNode; // linkNode = <a> x (nodeDescription + nodeLink)

                        // 1. nodeDescription setup
                        if (Boolean((filterInfo.parentID != '0' && filterInfo.parentID != '') && filterInfo.isSelected == false)) {
                            nodeDescription += '- ';
                        }
                        nodeDescription += filterInfo.description

                        // 2. nodeLink setup
                        nodeLink = filterInfo.navigateURL;

                        // 3. nodeTooltip setup
                        if (filterInfo.isSelected) {
                            nodeTooltip = resources.removeFilter + ': ' + filterInfo.description;
                        }
                        else {
                            nodeTooltip = resources.appendFilter + ': ' + filterInfo.description;
                        }

                        // 4. linkNode setup
                        $linkNode = $('<a>');
                        if (nodeDescription != '' && nodeLink != '' && nodeTooltip != '') {
                            $linkNode.text(nodeDescription)
                                     .attr('href', nodeLink)
                                     .attr('title', nodeTooltip);
                            if (filterInfo.isSelected) {
                                $linkNode.addClass(resources.activeCssClass);
                            }
                            if (settings.displayCounters) {
                                $linkNode.append($('<cite>').text('(' + filterInfo.counter + ')'))
                            }
                        }

                        // 5. append linkNode to group
                        $filters_div.append($linkNode);

                    }); // end:  $.each(refinerInfo.filters, function(index2, filterInfo)

                }
                // build checboxs controls <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
                else {

                    var isAtLeastOneSelected = false;
                    $.each(refinerInfo.filters, function (index2, filterInfo) {
                        if (filterInfo.isSelected)
                            isAtLeastOneSelected = true;
                    });

                    // 1. group of refinerFilters setup                  
                    $.each(refinerInfo.filters, function (index2, filterInfo) {

                        var $ckNode_input = $('<input>').attr('type', 'checkbox');
                        var $ckNode_label = $('<label>');
                        var $ckLine = $('<p>').append($ckNode_input).append($ckNode_label);


                        $ckNode_label.attr('for', 'ck' + filterInfo.id)
                                     .text(filterInfo.description);

                        if (settings.displayCounters) {
                            if (filterInfo.isSelected) {
                                $ckNode_label.append($('<cite>').text('(' + filterInfo.counter + ')'))
                            }
                            else {
                                if (!isAtLeastOneSelected) {
                                    $ckNode_label.append($('<cite>').text('(' + filterInfo.counter + ')'))
                                }
                            }
                        }


                        $ckNode_input.attr('id', 'ck' + filterInfo.id)
                                     .attr('name', filterInfo.description)
                                     .data('value', filterInfo.id);

                        if (filterInfo.isSelected) {
                            $ckNode_input.attr('checked', true)
                        }

                        $ckNode_input.change(function () {

                            var $checkboxs = $('input', $(this).parent().parent());

                            // 1. obter as checkbox (minima e máxima) seleccionadas

                            var minValue = -1,
                                maxValue = -1;

                            minValue = $('input:checked', $(this).parent().parent()).first().data('value');
                            maxValue = $('input:checked', $(this).parent().parent()).last().data('value');

                            if (minValue == undefined) minValue = -1;
                            if (maxValue == undefined) maxValue = -1;


                            if ($(this).is(':checked')) {
                                // estou a marcar (aumentar o range), tenho que chekar os controlos que fikaram pelo meio

                                var $unCheckedBetweenCTRLs = $checkboxs.not(':checked').filter(function () {
                                    return ($(this).data('value') > minValue && $(this).data('value') < maxValue);
                                });

                                $unCheckedBetweenCTRLs.each(function () {
                                    $(this).attr('checked', true);
                                });

                            }
                            else {
                                // estou a desmarcar (diminuir o range), tenho que des-checkar os controlos que fikaram entre o mesmo e a extremidade mais proxima

                                var referenceValue = $(this).data('value');

                                var $previousUncheckedCTRLs = $checkboxs.filter(function () {
                                    return ($(this).data('value') < referenceValue && $(this).data('value') >= minValue);
                                });

                                var $nextUncheckedCTRLs = $checkboxs.filter(function () {
                                    return ($(this).data('value') > referenceValue && $(this).data('value') <= maxValue);
                                });

                                if ($previousUncheckedCTRLs.size() > $nextUncheckedCTRLs.size()) {
                                    $nextUncheckedCTRLs.each(function () {
                                        $(this).attr('checked', false);
                                    });
                                }
                                else {
                                    $previousUncheckedCTRLs.each(function () {
                                        $(this).attr('checked', false);
                                    });
                                }
                            }


                            minValue = $('input:checked', $(this).parent().parent()).first().data('value');
                            maxValue = $('input:checked', $(this).parent().parent()).last().data('value');

                            if (minValue == ($('input', $(this).parent().parent()).first().data('value'))) minValue = -1;
                            if (maxValue == ($('input', $(this).parent().parent()).last().data('value'))) maxValue = -1;

                            if (minValue == undefined) { minValue = -1 }
                            if (maxValue == undefined) { maxValue = -1 }

                            // 3. construir o novo URL

                            var qsObj = {};
                            qsObj[refinerInfo.querystring_beds] = minValue + refinerInfo.rangeUnion_token + maxValue;
                            qsObj[refinerInfo.querystring_source] = refinerInfo.querystring_source_value;
                            qsObj['page'] = -1

                            // search trail
                            qsObj[queryStringParentSearchID] = searchID;
                            if ($.jqURL.get(queryStringRootSearchID) == undefined) {
                                qsObj[queryStringRootSearchID] = searchID;
                            }

                            var newURL = $.jqURL.set(qsObj);

                            var oldURL = location.href;
                            if (oldURL.endsWith('/')) {
                                oldURL = oldURL.substr(0, oldURL.length - 1);
                            }

                            // 4. redirect 
                            if (oldURL != newURL) {

                                // 4.1 desabilitar controlo para evitar mais cliques enquanto o pedido não é processado
                                $(this).parent().parent().fadeTo('fast', 0.7);
                                /*
                                $(this).parent().parent().bind('click', function() {
                                return false;
                                });
                                */

                                // 4.2 redirecciono
                                window.location = newURL;
                                //console.log(newURL);

                            }


                        });

                        $filters_div.append($ckLine);

                    }); // end: $.each(refinerInfo.filters, function(index2, filterInfo)


                }

                var $refinerGroup_div = $('<div>')
                                        .addClass('group')
                                        .hide()
                                        .append(
                                            $('<strong>').text(refinerInfo.description)
                                        ).append(
                                            $filters_div
                                        );

                $control.append($refinerGroup_div);
                $refinerGroup_div.fadeIn();

            });
            
            $control.append($('<div>').addClass('divider'));
            $featuresPicker.fadeIn();
            $booleanFeatures.fadeIn();
            $pricesRanges.fadeIn();
            $energyRatings.fadeIn();
            
        };
        
    };   
   

/* @@ PROPERTY CAROUSEL
   ==================================================================== */

    function Setup_PropertyCarousel(cid_control, url_dataSource, requestTimeout, maxResults, delaySpeed, linkText, propertyID, originalID, databaseID, languageID, resourcesJSON, comparatorHandlerURL, userHistoryID, comparatorResourcesJSON, comparatorSuggestedTitle, defaultPurpose, allowReload) {
   
    var $control = $('#' + cid_control);
    $control.BuildCarousel({
        cid_control: cid_control,
        url_dataSource: url_dataSource,
        requestTimeout: Number(requestTimeout),
        maxResults: Number(maxResults),
        delaySpeed: delaySpeed,
        linkText: linkText,
        propertyID: propertyID,
        originalID: originalID,
        databaseID: databaseID,
        languageID: languageID,
        resources: $.parseJSON(resourcesJSON),
        comparatorHandlerURL: comparatorHandlerURL,
        comparatorResources: comparatorResourcesJSON,
        comparatorSuggestedTitle:comparatorSuggestedTitle,
        userHistoryID: userHistoryID,
        defaultPurpose:Number(defaultPurpose),
        allowReload:allowReload
    });

};

(function($) {
    $.fn.BuildCarousel = function(pluginSettings) {

        var defaultSettings = {
            cid_control: '',
            url_dataSource: '',
            requestTimeout: 5000,
            maxResults: 10,
            columns: 2,
            delaySpeed: 5000,
            linkText: '',
            propertyID: 0,
            originalID: 0,
            databaseID: 0,
            languageID: 'pt-PT',
            resources: '',
            comparatorHandlerURL: '',
            comparatorResources: '',
            comparatorSuggestedTitle: '',
            userHistoryID: '',
            defaultPurpose: 0,
            allowReload: "false"

        };
        var $settings = $.extend(defaultSettings, pluginSettings);

        return this.each(function() {

            /* @ Parameters ........................................................... */

            var purposeBoundary;
            var typeBoundary;
            var priceBoundary;
            var bedsBoundary;
            var bathsBoundary;
            var distanceBoundary;
            var yearBoundary;
            var purposeID;

            /* @ BUILD HTML ........................................................... */

            var $loader = $('.loader', $(this));
            var $errorIcn = $('.errorIcn', $(this));
            var $errorMsg = $('.errorMsg', $(this));
            var $noProperties = $('.noProperties', $(this));

            var $stage = $('<div class="dCarousel_stage" />');
            var $stage_ul = $('<ul>');
            var $previous_btn, $next_btn;
            var _containerWidth = 0;
            var rolling;

            $stage.append($stage_ul);
            $(this).append($stage);
            $noProperties.hide()

            $errorMsg.children('a').click(function() {

                $loader.show();
                $errorIcn.hide();
                $errorMsg.hide();

                RequestAndTriggerBindings(typeBoundary, purposeBoundary, priceBoundary, bedsBoundary, bathsBoundary, distanceBoundary, yearBoundary, purposeID);
                return false;
            });

            purposeID = $settings.defaultPurpose;
            RequestAndTriggerBindings(typeBoundary, purposeBoundary, priceBoundary, bedsBoundary, bathsBoundary, distanceBoundary, yearBoundary, purposeID);

            //oject ajaxRequest to know if a request is already occuring
            var ajaxRequest = null;

            //function to reload the properties with new purpose when the tab is changed
            $(this).bind('ReloadControl', function(event, _purposeId) {

                //if is the same tab, do nothing
                if (purposeID == _purposeId)
                    return false;

                //if the control is not affected with purpose, do nothing
                if ($settings.allowReload == "false")
                    return false;

                //if already exists a request, we need to abort them
                if (ajaxRequest) {
                    ajaxRequest.abort();
                }

                //new purposeID
                purposeID = _purposeId;

                //Request new properties
                RequestAndTriggerBindings(typeBoundary, purposeBoundary, priceBoundary, bedsBoundary, bathsBoundary, distanceBoundary, yearBoundary, purposeID);


            });

            function RequestAndTriggerBindings(typeBoundary, purposeBoundary, priceBoundary, bedsBoundary, bathsBoundary, distanceBoundary, yearBoundary, purposeID) {

                $loader.show();
                $errorIcn.hide();
                $errorMsg.hide();
                $noProperties.hide();
                $stage_ul.children().remove();

                try {
                    $previous_btn.remove();
                    $next_btn.remove();
                } catch (erro) {
                }

                if (typeBoundary === undefined) typeBoundary = 0;
                if (purposeBoundary === undefined) purposeBoundary = 0;
                if (priceBoundary === undefined) priceBoundary = -1;
                if (bedsBoundary === undefined) bedsBoundary = -1;
                if (bathsBoundary === undefined) bathsBoundary = -1;
                if (distanceBoundary === undefined) distanceBoundary = -1;
                if (yearBoundary === undefined) yearBoundary = -1;
                if (purposeID === undefined) purposeID = 0;

                if ($settings.url_dataSource != '') {
                    ajaxRequest = $.ajax({
                        type: 'GET',
                        dataType: 'json',
                        processData: true,
                        timeout: $settings.requestTimeout,
                        url: $settings.url_dataSource,
                        data: {
                            propertyID: $settings.propertyID,
                            originalID: $settings.originalID,
                            databaseID: $settings.databaseID,
                            typeBoundary: typeBoundary,
                            purposeBoundary: purposeBoundary,
                            priceBoundary: priceBoundary,
                            bedsBoundary: bedsBoundary,
                            bathsBoundary: bathsBoundary,
                            distanceBoundary: distanceBoundary,
                            yearBoundary: yearBoundary,
                            maxResults: $settings.maxResults,
                            languageID: $settings.languageID,
                            purposeID:purposeID
                        },
                        error: function(request, status, error) {
                            $errorIcn.show();
                            $errorMsg.show();
                            $loader.hide();
                        },
                        success: function(data) {
                            $loader.hide();
                            if (data != null) {
                                DataBind(data);
                            }
                            else {
                                $errorIcn.show();
                                $errorMsg.show();
                            }
                        }
                    });


                }
                else {
                    alert('DataSource URL not defined!');
                }

            };

            function DataBind(datasource) {

                var columnRuler = 0;

                // DATABIND DE IMÓVEIS
                if (datasource.properties.length > 0) {

                    var propertyIDs = ''; // "123445,505362,84825"

                    $.each(datasource.properties, function(index, property) {

                        propertyIDs += ',' + property.ID;

                        // group columns in li
                        if (columnRuler == 0) { $stage_ul.append('<li>'); }



                        var $property = $('<div class="dCarousel_item"/>');

                        var $property_photo = $('<div class="photo">').append($('<a>').attr('href', property.RedirectURL).attr('title', property.FullTitle).append($('<img>').attr('src', property.PhotoURL).attr('alt', property.Title).error(function() { $(this).hide(); })));
                        var $property_info = $('<div class="info">').append($('<h3>').text(property.Title))
                                                                    .append($('<strong>').text(property.Location).addClass('limitedWidth'))
                                                                    .append($('<span>').text(property.Purpose))
                                                                    .append($('<span class="price">').text(property.Price))
                                                                    .append($('<a>').text($settings.linkText).attr('href', property.RedirectURL).attr('title', property.FullTitle).addClass('details'));

                        $property.append($property_photo);
                        $property.append($property_info);


                        $stage_ul.children('li').filter(':last').append($property);

                        // group columns in li
                        columnRuler++; if (columnRuler == $settings.columns) { columnRuler = 0; }

                    });

                    // - se o numero de imóveis for impar, acrescento um dummy ao ultimo li item
                    if (columnRuler != 0) {
                        $stage_ul.children('li').filter(':last').append('<div class="dCarousel_item dummy"><div class="photo"></div><div class="info"></div></div>');
                    }

                    BuildNavigation();

                    // se existe mais do que um imóvel, sugiro a sua comparação
                    if (datasource.properties.length > 0) {
                        Build_Comparer(propertyIDs.substr(1));
                    }

                    if ($settings.allowReload == "true") {
                       /*
                        $(".limitedWidth", $stage).SetupLimitedWidth({
                            scrollSpeed: 2
                        });
                        */
                    }

                }
                else {
                    // - como não existem imoveis, escondo o controlo completamente
                    $loader.hide();
                    $noProperties.show()
                }

                // DATABIND DE SIMILARITY SETUP (se existir)
                if (datasource.similaritySetup !== undefined) {
                    Build_SimilaritySetuper(datasource.similaritySetup);
                }

            };


            /* @ SETUP NAVIGATION ........................................................... */

            function BuildNavigation() {

                var $slideshow_items = $stage_ul.children('li');
                var $slideshow_items_properties = $slideshow_items.children('div');

                if (_containerWidth == 0) {
                    _containerWidth = $slideshow_items.eq(0).outerWidth()
                }
                clearInterval(rolling);

                var _totalPages = $slideshow_items.length,
                    _currentIndex = 1;

                // - clonar items para o inicio e para o fim
                var $firstItem = $slideshow_items.filter(':first'),
            	    $lastItem = $slideshow_items.filter(':last');
                $firstItem.before($lastItem.clone().addClass('cloned'));
                $lastItem.after($firstItem.clone().addClass('cloned'));
                $slideshow_items = $stage.children('ul').children('li');

                // - configurar largura do container da lista de fotos
                $stage.children('ul').width(_containerWidth * ($slideshow_items_properties.size() + 4));


                // - acrescentar setas de navegação
                if (_totalPages > 1) {
                    $previous_btn = $('<span></span>').addClass('previous');
                    $next_btn = $('<span></span>').addClass('next');
                    $previous_btn.click(function() {
                        GoToPhoto(_currentIndex - 1);
                        return false;
                    });
                    $next_btn.click(function() {
                        GoToPhoto(_currentIndex + 1);
                        return false;
                    });
                    $stage.after($previous_btn)
            	          .after($next_btn);
                }


                // - init
                $stage.css('overflow', 'hidden');
                $slideshow_items.children('div').show();
                $stage.scrollLeft(_containerWidth);


                // - métodos de navegação
                function GoToPhoto(index) {

                    // - calculo dos deslocamentos
                    var direction = index < _currentIndex ? -1 : 1,
            	        n = Math.abs(_currentIndex - index),
            	        left = _containerWidth * direction * n;

                    // - delocar 
                    $stage.filter(':not(:animated)').animate({
                        scrollLeft: '+=' + left
                    }, 500, function() {

                        if (index == 0) {
                            $stage.scrollLeft(_containerWidth * _totalPages);
                            index = _totalPages;
                        } else if (index > _totalPages) {
                            $stage.scrollLeft(_containerWidth);
                            index = 1;
                        }

                        _currentIndex = index;

                    });

                    
                };

                // - autoscroll
                if (_totalPages > 1) {
                    var autoScrolling = true;
                    rolling = setInterval(function() {
                        if (autoScrolling) {
                            GoToPhoto(_currentIndex + 1);
                        }
                    }, $settings.delaySpeed);
                    $stage.parent().mouseover(function() {
                        autoScrolling = false;
                    }).mouseout(function() {
                        autoScrolling = true;
                    });
                }

                // Tratar as labels demasiado largas
                //$('.limitedWidth', $stage).SetupLimitedWidthLabels();

            }


            /* ..............................................................
            ..............................................................
            .............................................................. */

            function Build_Comparer(propertyIDs) {


                var $createSession_btn = $('<a>').text($settings.resources.CreateComparationSession)
                                                 .attr('title', $settings.resources.CreateComparationSession)
                                                 .addClass('setComparation')
                                                 .attr('href', '#');

                $createSession_btn.Setup_ComparerSessionProperty({
                    property_ids: propertyIDs, //'1424230,1087003',
                    requestTimeout: $settings.requestTimeout,
                    handlerURL: $settings.comparatorHandlerURL,
                    userHistoryID: $settings.userHistoryID,
                    resources: $settings.comparatorResources,
                    suggestedTitle: $settings.comparatorSuggestedTitle
                });

                $stage.after($createSession_btn);

            }



            /* ..............................................................
            ..............................................................
            .............................................................. */

            function Build_SimilaritySetuper(similaritySetup) {

                // - se o controlo já existia, removo-o para o poder reconstruir...
                var $oldControl = $('.dSimilaritySetuper');
                if ($oldControl.size() > 0) {
                    $oldControl.remove();
                }

                var $SimilaritySetuper = {
                    stage: $('<div class="dSimilaritySetuper">'),
                    expanded: $('<div class="expanded">'),
                    collapsed: $('<div class="collapsed">')
                };
                $SimilaritySetuper.stage.append($SimilaritySetuper.collapsed)
                                        .append($SimilaritySetuper.expanded);


                /*
                $SimilaritySetuper.stage.bind('click', function() {
                return false;
                })
                */


                var $buttons = {
                    expand: $('<a>').text($settings.resources.AdjustSimilarityParameters).addClass('setup').attr('href', '#'),
                    apply: $('<a>').text('» ' + $settings.resources.Apply).addClass('apply').attr('href', '#')
                };
                $SimilaritySetuper.collapsed.append($buttons.expand);

                var $sliders = {
                    price: $('<div class="slider sliderPrice">'),
                    distance: $('<div class="slider sliderDistance">'),
                    beds: $('<div class="slider sliderBeds">'),
                    baths: $('<div class="slider sliderWCs">'),
                    year: $('<div class="slider sliderYear">'),
                    purpose: $('<input type="checkbox" />').attr('id', 'ckPurpose').attr('value', '0'),
                    type: $('<input type="checkbox" />').attr('id', 'ckType').attr('value', '0')
                };

                var $slider_labels = {
                    price: $('<label>').text($settings.resources.Price + ':').addClass('sliderLabel'),
                    distance: $('<label>').text($settings.resources.Distance + ':').addClass('sliderLabel'),
                    beds: $('<label>').text($settings.resources.NumberBedRooms + ':').addClass('sliderLabel'),
                    baths: $('<label>').text($settings.resources.NumberBathRooms + ':').addClass('sliderLabel'),
                    year: $('<label>').text($settings.resources.ConstructionYear + ':').addClass('sliderLabel'),
                    purpose: $('<label>').text($settings.resources.AnyPurpose).attr('for', 'ckPurpose'),
                    type: $('<label>').text($settings.resources.AnyType).attr('for', 'ckType')
                };

                var $slider_values = {
                    price: $('<span>'),
                    distance: $('<span>'),
                    beds: $('<span>'),
                    baths: $('<span>'),
                    year: $('<span>'),
                    type: $('<span>'),
                    purpose: $('<span>')
                };

                $SimilaritySetuper.expanded.append(
				    $('<div class="parameterGroup">').append(
				        $('<div class="booleans">').append(
				            $('<span>').addClass('ck').append(
				                $sliders.purpose
				            ).append(
				                $slider_labels.purpose
				            )
				        ).append(
				            $('<span>').addClass('ck').append(
				                $sliders.type
				            ).append(
				                $slider_labels.type
				            )
				        )

				    )
				);

                $SimilaritySetuper.expanded.append($('<div class="parameterGroup">').append($slider_labels.price.append($slider_values.price)).append($sliders.price));
                $SimilaritySetuper.expanded.append($('<div class="parameterGroup">').append($slider_labels.distance.append($slider_values.distance)).append($sliders.distance));

                $SimilaritySetuper.expanded.append(
                    $('<div class="parameterGroup">')
                        .append(
                            $('<div class="doubleColumn" style="margin-right:21px;">')
                                .append($slider_labels.beds.append($slider_values.beds))
                                .append($sliders.beds)
                        )
                        .append(
                            $('<div class="doubleColumn">')
                                .append($slider_labels.baths.append($slider_values.baths))
                                .append($sliders.baths)
                        )
                );

                $SimilaritySetuper.expanded.append($('<div class="parameterGroup">').append($slider_labels.year.append($slider_values.year)).append($sliders.year));
                $SimilaritySetuper.expanded.append($('<div class="setupSubmit">').append($buttons.apply));

                $stage.after($SimilaritySetuper.stage);



                // methods . . . . . . . . . . 

                function Expand() {
                    $SimilaritySetuper.collapsed.slideUp('fast', function() {
                        $SimilaritySetuper.expanded.slideDown(function() {
                            $('body').one('click', function() {
                                Collapse(false);
                            });
                        });
                    });
                };

                $SimilaritySetuper.stage.click(function(e) {
                    e.stopPropagation();
                });

                function Collapse(reloading) {
                    $SimilaritySetuper.expanded.slideUp('fast', function() {
                        if (reloading) {
                            purposeBoundary = $slider_values.purpose.attr('name');
                            typeBoundary = $slider_values.type.attr('name');
                            priceBoundary = $slider_values.price.attr('name');
                            bedsBoundary = $slider_values.beds.attr('name');
                            bathsBoundary = $slider_values.baths.attr('name');
                            distanceBoundary = $slider_values.distance.attr('name');
                            yearBoundary = $slider_values.year.attr('name');
                            RequestAndTriggerBindings(typeBoundary, purposeBoundary, priceBoundary, bedsBoundary, bathsBoundary, distanceBoundary, yearBoundary);
                        }
                        else {
                            //$SimilaritySetuper.collapsed.slideDown();    
                        }
                        $SimilaritySetuper.collapsed.slideDown();
                    });
                };

                function Setup_PriceSlider(setup) {
                    if (HasSetupValues(setup)) {
                        $sliders.price.slider({
                            range: 'min',
                            value: Number(setup.Value),
                            min: Number(setup.MinValue),
                            max: Number(setup.MaxValue),
                            step: Number(setup.StepValue),
                            slide: function(event, ui) {
                                $slider_values.price.attr('name', ui.value).text('± ' + ui.value + ' €');

                            }
                        });
                        $slider_values.price.attr('name', $sliders.price.slider("value")).text('± ' + $sliders.price.slider("value") + ' €');
                    }
                    else {
                        $slider_labels.price.hide();
                        $slider_values.price.text($settings.resources.Unavailable);
                    }
                };

                function Setup_DistanceSlider(setup) {
                    if (HasSetupValues(setup)) {
                        $sliders.distance.slider({
                            range: 'min',
                            value: Number(setup.Value),
                            min: Number(setup.MinValue),
                            max: Number(setup.MaxValue),
                            step: Number(setup.StepValue),
                            slide: function(event, ui) {
                                $slider_values.distance.attr('name', ui.value).text(ui.value + ' km');
                            }
                        });
                        $slider_values.distance.attr('name', $sliders.distance.slider("value")).text($sliders.distance.slider("value") + ' km');
                    }
                    else {
                        //$slider_labels.distance.hide();
                        $slider_values.distance.text($settings.resources.Unavailable);
                    }
                };

                function Setup_BedsSlider(setup) {
                    if (HasSetupValues(setup)) {
                        $sliders.beds.slider({
                            range: 'min',
                            value: Number(setup.Value),
                            min: Number(setup.MinValue),
                            max: Number(setup.MaxValue),
                            step: Number(setup.StepValue),
                            slide: function(event, ui) {
                                $slider_values.beds.attr('name', ui.value).text('± ' + ui.value);
                            }
                        });
                        $slider_values.beds.attr('name', $sliders.beds.slider("value")).text('± ' + $sliders.beds.slider("value"));
                    }
                    else {
                        //$slider_labels.beds.hide();
                        $slider_values.beds.text($settings.resources.Unavailable);
                    }
                };

                function Setup_BathsSlider(setup) {
                    if (HasSetupValues(setup)) {
                        $sliders.baths.slider({
                            range: 'min',
                            value: Number(setup.Value),
                            min: Number(setup.MinValue),
                            max: Number(setup.MaxValue),
                            step: Number(setup.StepValue),
                            slide: function(event, ui) {
                                $slider_values.baths.attr('name', ui.value).text('± ' + ui.value);
                            }
                        });
                        $slider_values.baths.attr('name', $sliders.baths.slider("value")).text('± ' + $sliders.baths.slider("value"));
                    }
                    else {
                        //$slider_labels.baths.hide();
                        $slider_values.baths.text($settings.resources.Unavailable);
                    }
                };

                function Setup_YearSlider(setup) {
                    if (HasSetupValues(setup)) {
                        $sliders.year.slider({
                            range: 'min',
                            value: Number(setup.Value),
                            min: Number(setup.MinValue),
                            max: Number(setup.MaxValue),
                            step: Number(setup.StepValue),
                            slide: function(event, ui) {
                                $slider_values.year.attr('name', ui.value).text('± ' + ui.value);
                            }
                        });
                        $slider_values.year.attr('name', $sliders.year.slider("value")).text('± ' + $sliders.year.slider("value"));
                    }
                    else {
                        //$slider_labels.year.hide();
                        $slider_values.year.text($settings.resources.Unavailable);
                    }
                };

                function Setup_TypeCheckbox(setup) {
                    // default value
                    if (setup.Value == 'True') {
                        $slider_values.type.attr('name', '0');
                        $sliders.type.attr('checked', false)
                    }
                    else {
                        $slider_values.type.attr('name', '1');
                        $sliders.type.attr('checked', true)
                    }
                    // event for changing
                    $sliders.type.change(function() {
                        if ($(this).is(':checked')) {
                            $slider_values.type.attr('name', '1');
                        }
                        else {
                            $slider_labels.type.attr('name', '0');
                        }
                    });
                };

                function Setup_PurposeCheckbox(setup) {
                    // default value
                    if (setup.Value == 'True') {
                        $slider_values.purpose.attr('name', '0');
                        $sliders.purpose.attr('checked', false)
                    }
                    else {
                        $slider_values.purpose.attr('name', '1');
                        $sliders.purpose.attr('checked', true)
                    }
                    // event for changing
                    $sliders.purpose.change(function() {
                        if ($(this).is(':checked')) {
                            $slider_values.purpose.attr('name', '1');
                        }
                        else {
                            $slider_values.purpose.attr('name', '0');
                        }
                    });
                };

                function HasSetupValues(setup) {
                    if (setup.Value != '' && setup.MinValue != '' && setup.MaxValue != '' && setup.MinValue != '' && setup.StepValue) {
                        return true;
                    }
                    else {
                        return false;
                    }
                };

                function Init() {
                    $SimilaritySetuper.expanded.hide();
                    $SimilaritySetuper.collapsed.show();
                    $SimilaritySetuper.stage.show();
                    Setup_PriceSlider(similaritySetup.price);
                    Setup_DistanceSlider(similaritySetup.distance);
                    Setup_BedsSlider(similaritySetup.beds);
                    Setup_BathsSlider(similaritySetup.baths);
                    Setup_YearSlider(similaritySetup.year);
                    Setup_TypeCheckbox(similaritySetup.type);
                    Setup_PurposeCheckbox(similaritySetup.purpose)
                };

                // event handlers . . . . . . . . . . 

                $buttons.expand.click(function() {
                    Expand();
                    return false;
                });

                $buttons.apply.click(function() {
                    Collapse(true);
                    return false;
                });

                Init();

            }

        });

    };
})(jQuery);


/* @@ Property Scroller
   ==================================================================== */

    function Setup_PropertyScroller(cid_control, url_dataSource, requestTimeout, maxResults, delaySpeed, linkText, propertyID, originalID, databaseID, languageID, resourcesJSON, comparatorHandlerURL, userHistoryID, comparatorResourcesJSON, comparatorSuggestedTitle, defaultPurpose, allowReload) {
   
    var $control = $('#' + cid_control);
    $control.BuildScroller({
        cid_control: cid_control,
        url_dataSource: url_dataSource,
        requestTimeout: Number(requestTimeout),
        maxResults: Number(maxResults),
        delaySpeed: delaySpeed,
        linkText: linkText,
        propertyID: propertyID,
        originalID: originalID,
        databaseID: databaseID,
        languageID: languageID,
        resources: $.parseJSON(resourcesJSON),
        comparatorHandlerURL: comparatorHandlerURL,
        comparatorResources: comparatorResourcesJSON,
        comparatorSuggestedTitle:comparatorSuggestedTitle,
        userHistoryID: userHistoryID,
        defaultPurpose:Number(defaultPurpose),
        allowReload:allowReload
    });

};

(function($) {
    $.fn.BuildScroller = function(pluginSettings) {

        var defaultSettings = {
            cid_control: '',
            url_dataSource: '',
            requestTimeout: 5000,
            maxResults: 10,
            columns: 2,
            delaySpeed: 35,
            linkText: '',
            propertyID: 0,
            originalID: 0,
            databaseID: 0,
            languageID: 'pt-PT',
            resources: '',
            comparatorHandlerURL: '',
            comparatorResources: '',
            comparatorSuggestedTitle: '',
            userHistoryID: '',
            defaultPurpose: 0,
            allowReload: "false"

        };
        var $settings = $.extend(defaultSettings, pluginSettings);

        return this.each(function() {

            /* @ Parameters ........................................................... */

            var purposeBoundary;
            var typeBoundary;
            var priceBoundary;
            var bedsBoundary;
            var bathsBoundary;
            var distanceBoundary;
            var yearBoundary;
            var purposeID;

            /* @ BUILD HTML ........................................................... */

            var $loader = $('.loader', $(this));
            var $errorIcn = $('.errorIcn', $(this));
            var $errorMsg = $('.errorMsg', $(this));
            var $noProperties = $('.noProperties', $(this));

            var $stage = $('<div class="dScroller_stage" />');
            var $stage_ul = $('<ul>');
            var $previous_btn, $next_btn;
            var _containerWidth = 0;
            var rolling;

            $stage.append($stage_ul);
            $(this).append($stage);
            $noProperties.hide()

            $errorMsg.children('a').click(function() {

                $loader.show();
                $errorIcn.hide();
                $errorMsg.hide();

                RequestAndTriggerBindings(typeBoundary, purposeBoundary, priceBoundary, bedsBoundary, bathsBoundary, distanceBoundary, yearBoundary, purposeID);
                return false;
            });

            purposeID = $settings.defaultPurpose;
            RequestAndTriggerBindings(typeBoundary, purposeBoundary, priceBoundary, bedsBoundary, bathsBoundary, distanceBoundary, yearBoundary, purposeID);

            //oject ajaxRequest to know if a request is already occuring
            var ajaxRequest = null;

            //function to reload the properties with new purpose when the tab is changed
            $(this).bind('ReloadControl', function(event, _purposeId) {

                //if is the same tab, do nothing
                if (purposeID == _purposeId)
                    return false;

                //if the control is not affected with purpose, do nothing
                if ($settings.allowReload == "false")
                    return false;

                //if already exists a request, we need to abort them
                if (ajaxRequest) {
                    ajaxRequest.abort();
                }

                //new purposeID
                purposeID = _purposeId;

                //Request new properties
                RequestAndTriggerBindings(typeBoundary, purposeBoundary, priceBoundary, bedsBoundary, bathsBoundary, distanceBoundary, yearBoundary, purposeID);


            });

            function RequestAndTriggerBindings(typeBoundary, purposeBoundary, priceBoundary, bedsBoundary, bathsBoundary, distanceBoundary, yearBoundary, purposeID) {

                $loader.show();
                $errorIcn.hide();
                $errorMsg.hide();
                $noProperties.hide();
                $stage_ul.children().remove();

                try {
                    $previous_btn.remove();
                    $next_btn.remove();
                } catch (erro) {
                }

                if (typeBoundary === undefined) typeBoundary = 0;
                if (purposeBoundary === undefined) purposeBoundary = 0;
                if (priceBoundary === undefined) priceBoundary = -1;
                if (bedsBoundary === undefined) bedsBoundary = -1;
                if (bathsBoundary === undefined) bathsBoundary = -1;
                if (distanceBoundary === undefined) distanceBoundary = -1;
                if (yearBoundary === undefined) yearBoundary = -1;
                if (purposeID === undefined) purposeID = 0;

                if ($settings.url_dataSource != '') {
                    ajaxRequest = $.ajax({
                        type: 'GET',
                        dataType: 'json',
                        processData: true,
                        timeout: $settings.requestTimeout,
                        url: $settings.url_dataSource,
                        data: {
                            propertyID: $settings.propertyID,
                            originalID: $settings.originalID,
                            databaseID: $settings.databaseID,
                            typeBoundary: typeBoundary,
                            purposeBoundary: purposeBoundary,
                            priceBoundary: priceBoundary,
                            bedsBoundary: bedsBoundary,
                            bathsBoundary: bathsBoundary,
                            distanceBoundary: distanceBoundary,
                            yearBoundary: yearBoundary,
                            maxResults: $settings.maxResults,
                            languageID: $settings.languageID,
                            purposeID:purposeID
                        },
                        error: function(request, status, error) {
                            $errorIcn.show();
                            $errorMsg.show();
                            $loader.hide();
                        },
                        success: function(data) {
                            $loader.hide();
                            if (data != null) {
                                DataBind(data);
                            }
                            else {
                                $errorIcn.show();
                                $errorMsg.show();
                            }
                        }
                    });


                }
                else {
                    alert('DataSource URL not defined!');
                }

            };

            function DataBind(datasource) {

                // DATABIND DE IMÓVEIS
                if (datasource.properties.length > 0) {

                    var propertyIDs = '';
                    var nItems = datasource.properties.length;
                    
                    // 1. criar os elementos (li) para cada imovel
                    $.each(datasource.properties, function(index, property) {

                        // 1.1. coloeccionar os IDs dos imóveis
                        propertyIDs += ',' + property.ID;

                        // 1.2. criar o html
                        var $property = $('<div class="dScroller_item"/>');
                        var $property_photo = $('<div class="photo">').append($('<a>').attr('href', property.RedirectURL).attr('title', property.FullTitle).append($('<img>').attr('src', property.PhotoURL).attr('alt', property.Title).error(function() { $(this).hide(); })));
                        var $property_info = $('<div class="info">').append($('<h3>').text(property.Title))
                                                                    .append($('<strong>').text(property.County).addClass('limitedWidth'))
                                                                    .append($('<span>').text(property.Purpose + ' / '))
                                                                    .append($('<span>').text(property.Price).addClass('price'));
                        $property.append($property_photo);
                        $property.append($property_info);
                        
                        // 1.3. adicionar os elementos ao stage
                        $stage_ul.append('<li>');
                        $stage_ul.children('li').filter(':last').append($property);

                      });
                      
                      
                      var visible_width = $stage.width();
                      var stage_width = $stage_ul.children('li').eq(0).outerWidth() * $stage_ul.children('li').size();
                      
                      $stage_ul.width(stage_width);
                      $stage.scrollLeft(0);
                                            
                      // 2. verificar se há items suficientes para fazer a animação
                      if (stage_width > visible_width) {
                      
                        // 2.1. duplicar os (li) para fazer o scroller
                        $.each(datasource.properties, function(index, property) {

                            // 2.1.1. criar o html
                            var $property = $('<div class="dScroller_item"/>');
                            var $property_photo = $('<div class="photo">').append($('<a>').attr('href', property.RedirectURL).attr('title', property.FullTitle).append($('<img>').attr('src', property.PhotoURL).attr('alt', property.Title).error(function() { $(this).hide(); })));
                            var $property_info = $('<div class="info">').append($('<h3>').text(property.Title))
                                                                        .append($('<strong>').text(property.County).addClass('limitedWidth'))
                                                                        .append($('<span>').text(property.Purpose + ' / '))
                                                                        .append($('<span>').text(property.Price).addClass('price'));
                            $property.append($property_photo);
                            $property.append($property_info);

                            // 2.1.2. adicionar os elementos ao stage
                            $stage_ul.append('<li>');
                            $stage_ul.children('li').filter(':last').append($property);

                        });                      

                        // 2.2. criar animação
                        BuildNavigation();  
                      
                      }
                      

                    // se existe mais do que um imóvel, sugiro a sua comparação
                    if (datasource.properties.length > 0) {
                        Build_Comparer(propertyIDs.substr(1));
                    }

                    if ($settings.allowReload == "true") {
                       /*
                        $(".limitedWidth", $stage).SetupLimitedWidth({
                            scrollSpeed: 2
                        });
                        */
                    }

                }
                else {
                    // - como não existem imoveis, escondo o controlo completamente
                    $loader.hide();
                    $noProperties.show()
                }

                // DATABIND DE SIMILARITY SETUP (se existir)
                if (datasource.similaritySetup !== undefined) {
                    Build_SimilaritySetuper(datasource.similaritySetup);
                }

            };


            /* @ SETUP NAVIGATION ........................................................... */

            function BuildNavigation() {

                var $slideshow_items = $stage_ul.children('li');
                var $slideshow_items_properties = $slideshow_items.children('div');
                
                var nItems = $slideshow_items.size() / 2;
                var item_width = $slideshow_items.eq(0).outerWidth();
                var stage_width = item_width * $slideshow_items.size();
                                
                $stage.css('overflow', 'hidden');
                $stage_ul.width(stage_width);
                
                clearInterval(rolling);
                               
                 // - autoscroll
                if ($slideshow_items.size() > 1) {
                    var autoScrolling = true;
                    rolling = setInterval(function() {
                        if (autoScrolling) {
                            Slide();
                        }
                    }, $settings.delaySpeed);
                    $stage.parent().mouseover(function() {
                        autoScrolling = false;
                    }).mouseout(function() {
                        autoScrolling = true;
                    });
                }
                                
                var _x = 0;
                var item_width = $slideshow_items.eq(0).outerWidth();
                
                function Slide() {
                    
                    // 1. incrementar um pixel
                    _x = _x + 1;
                    
                    // 2. se deu a volta, voltar ao inicio
                    if (_x == (nItems * item_width)) {
                        _x = 0;
                    }
                    
                    // 3. desclocar
                    $stage.scrollLeft(_x);
                                        
                };
                

            }


            /* ..............................................................
            ..............................................................
            .............................................................. */

            function Build_Comparer(propertyIDs) {


                var $createSession_btn = $('<a>').text($settings.resources.CreateComparationSession)
                                                 .attr('title', $settings.resources.CreateComparationSession)
                                                 .addClass('setComparation')
                                                 .attr('href', '#');

                $createSession_btn.Setup_ComparerSessionProperty({
                    property_ids: propertyIDs, //'1424230,1087003',
                    requestTimeout: $settings.requestTimeout,
                    handlerURL: $settings.comparatorHandlerURL,
                    userHistoryID: $settings.userHistoryID,
                    resources: $settings.comparatorResources,
                    suggestedTitle: $settings.comparatorSuggestedTitle
                });

                $stage.after($createSession_btn);
                
 
            }



            /* ..............................................................
            ..............................................................
            .............................................................. */

            function Build_SimilaritySetuper(similaritySetup) {

                // - se o controlo já existia, removo-o para o poder reconstruir...
                var $oldControl = $('.dSimilaritySetuper');
                if ($oldControl.size() > 0) {
                    $oldControl.remove();
                }

                var $SimilaritySetuper = {
                    stage: $('<div class="dSimilaritySetuper">'),
                    expanded: $('<div class="expanded">'),
                    collapsed: $('<div class="collapsed">')
                };
                $SimilaritySetuper.stage.append($SimilaritySetuper.collapsed)
                                        .append($SimilaritySetuper.expanded);


                /*
                $SimilaritySetuper.stage.bind('click', function() {
                return false;
                })
                */


                var $buttons = {
                    expand: $('<a>').text($settings.resources.AdjustSimilarityParameters).addClass('setup').attr('href', '#'),
                    apply: $('<a>').text('» ' + $settings.resources.Apply).addClass('apply').attr('href', '#')
                };
                $SimilaritySetuper.collapsed.append($buttons.expand);

                var $sliders = {
                    price: $('<div class="slider sliderPrice">'),
                    distance: $('<div class="slider sliderDistance">'),
                    beds: $('<div class="slider sliderBeds">'),
                    baths: $('<div class="slider sliderWCs">'),
                    year: $('<div class="slider sliderYear">'),
                    purpose: $('<input type="checkbox" />').attr('id', 'ckPurpose').attr('value', '0'),
                    type: $('<input type="checkbox" />').attr('id', 'ckType').attr('value', '0')
                };

                var $slider_labels = {
                    price: $('<label>').text($settings.resources.Price + ':').addClass('sliderLabel'),
                    distance: $('<label>').text($settings.resources.Distance + ':').addClass('sliderLabel'),
                    beds: $('<label>').text($settings.resources.NumberBedRooms + ':').addClass('sliderLabel'),
                    baths: $('<label>').text($settings.resources.NumberBathRooms + ':').addClass('sliderLabel'),
                    year: $('<label>').text($settings.resources.ConstructionYear + ':').addClass('sliderLabel'),
                    purpose: $('<label>').text($settings.resources.AnyPurpose).attr('for', 'ckPurpose'),
                    type: $('<label>').text($settings.resources.AnyType).attr('for', 'ckType')
                };

                var $slider_values = {
                    price: $('<span>'),
                    distance: $('<span>'),
                    beds: $('<span>'),
                    baths: $('<span>'),
                    year: $('<span>'),
                    type: $('<span>'),
                    purpose: $('<span>')
                };

                $SimilaritySetuper.expanded.append(
				    $('<div class="parameterGroup">').append(
				        $('<div class="booleans">').append(
				            $('<span>').addClass('ck').append(
				                $sliders.purpose
				            ).append(
				                $slider_labels.purpose
				            )
				        ).append(
				            $('<span>').addClass('ck').append(
				                $sliders.type
				            ).append(
				                $slider_labels.type
				            )
				        )

				    )
				);

                $SimilaritySetuper.expanded.append($('<div class="parameterGroup">').append($slider_labels.price.append($slider_values.price)).append($sliders.price));
                $SimilaritySetuper.expanded.append($('<div class="parameterGroup">').append($slider_labels.distance.append($slider_values.distance)).append($sliders.distance));

                $SimilaritySetuper.expanded.append(
                    $('<div class="parameterGroup">')
                        .append(
                            $('<div class="doubleColumn" style="margin-right:21px;">')
                                .append($slider_labels.beds.append($slider_values.beds))
                                .append($sliders.beds)
                        )
                        .append(
                            $('<div class="doubleColumn">')
                                .append($slider_labels.baths.append($slider_values.baths))
                                .append($sliders.baths)
                        )
                );

                $SimilaritySetuper.expanded.append($('<div class="parameterGroup">').append($slider_labels.year.append($slider_values.year)).append($sliders.year));
                $SimilaritySetuper.expanded.append($('<div class="setupSubmit">').append($buttons.apply));

                $stage.after($SimilaritySetuper.stage);



                // methods . . . . . . . . . . 

                function Expand() {
                    $SimilaritySetuper.collapsed.slideUp('fast', function() {
                        $SimilaritySetuper.expanded.slideDown(function() {
                            $('body').one('click', function() {
                                Collapse(false);
                            });
                        });
                    });
                };

                $SimilaritySetuper.stage.click(function(e) {
                    e.stopPropagation();
                });

                function Collapse(reloading) {
                    $SimilaritySetuper.expanded.slideUp('fast', function() {
                        if (reloading) {
                            purposeBoundary = $slider_values.purpose.attr('name');
                            typeBoundary = $slider_values.type.attr('name');
                            priceBoundary = $slider_values.price.attr('name');
                            bedsBoundary = $slider_values.beds.attr('name');
                            bathsBoundary = $slider_values.baths.attr('name');
                            distanceBoundary = $slider_values.distance.attr('name');
                            yearBoundary = $slider_values.year.attr('name');
                            RequestAndTriggerBindings(typeBoundary, purposeBoundary, priceBoundary, bedsBoundary, bathsBoundary, distanceBoundary, yearBoundary);
                        }
                        else {
                            //$SimilaritySetuper.collapsed.slideDown();    
                        }
                        $SimilaritySetuper.collapsed.slideDown();
                    });
                };

                function Setup_PriceSlider(setup) {
                    if (HasSetupValues(setup)) {
                        $sliders.price.slider({
                            range: 'min',
                            value: Number(setup.Value),
                            min: Number(setup.MinValue),
                            max: Number(setup.MaxValue),
                            step: Number(setup.StepValue),
                            slide: function(event, ui) {
                                $slider_values.price.attr('name', ui.value).text('± ' + ui.value + ' €');

                            }
                        });
                        $slider_values.price.attr('name', $sliders.price.slider("value")).text('± ' + $sliders.price.slider("value") + ' €');
                    }
                    else {
                        $slider_labels.price.hide();
                        $slider_values.price.text($settings.resources.Unavailable);
                    }
                };

                function Setup_DistanceSlider(setup) {
                    if (HasSetupValues(setup)) {
                        $sliders.distance.slider({
                            range: 'min',
                            value: Number(setup.Value),
                            min: Number(setup.MinValue),
                            max: Number(setup.MaxValue),
                            step: Number(setup.StepValue),
                            slide: function(event, ui) {
                                $slider_values.distance.attr('name', ui.value).text(ui.value + ' km');
                            }
                        });
                        $slider_values.distance.attr('name', $sliders.distance.slider("value")).text($sliders.distance.slider("value") + ' km');
                    }
                    else {
                        //$slider_labels.distance.hide();
                        $slider_values.distance.text($settings.resources.Unavailable);
                    }
                };

                function Setup_BedsSlider(setup) {
                    if (HasSetupValues(setup)) {
                        $sliders.beds.slider({
                            range: 'min',
                            value: Number(setup.Value),
                            min: Number(setup.MinValue),
                            max: Number(setup.MaxValue),
                            step: Number(setup.StepValue),
                            slide: function(event, ui) {
                                $slider_values.beds.attr('name', ui.value).text('± ' + ui.value);
                            }
                        });
                        $slider_values.beds.attr('name', $sliders.beds.slider("value")).text('± ' + $sliders.beds.slider("value"));
                    }
                    else {
                        //$slider_labels.beds.hide();
                        $slider_values.beds.text($settings.resources.Unavailable);
                    }
                };

                function Setup_BathsSlider(setup) {
                    if (HasSetupValues(setup)) {
                        $sliders.baths.slider({
                            range: 'min',
                            value: Number(setup.Value),
                            min: Number(setup.MinValue),
                            max: Number(setup.MaxValue),
                            step: Number(setup.StepValue),
                            slide: function(event, ui) {
                                $slider_values.baths.attr('name', ui.value).text('± ' + ui.value);
                            }
                        });
                        $slider_values.baths.attr('name', $sliders.baths.slider("value")).text('± ' + $sliders.baths.slider("value"));
                    }
                    else {
                        //$slider_labels.baths.hide();
                        $slider_values.baths.text($settings.resources.Unavailable);
                    }
                };

                function Setup_YearSlider(setup) {
                    if (HasSetupValues(setup)) {
                        $sliders.year.slider({
                            range: 'min',
                            value: Number(setup.Value),
                            min: Number(setup.MinValue),
                            max: Number(setup.MaxValue),
                            step: Number(setup.StepValue),
                            slide: function(event, ui) {
                                $slider_values.year.attr('name', ui.value).text('± ' + ui.value);
                            }
                        });
                        $slider_values.year.attr('name', $sliders.year.slider("value")).text('± ' + $sliders.year.slider("value"));
                    }
                    else {
                        //$slider_labels.year.hide();
                        $slider_values.year.text($settings.resources.Unavailable);
                    }
                };

                function Setup_TypeCheckbox(setup) {
                    // default value
                    if (setup.Value == 'True') {
                        $slider_values.type.attr('name', '0');
                        $sliders.type.attr('checked', false)
                    }
                    else {
                        $slider_values.type.attr('name', '1');
                        $sliders.type.attr('checked', true)
                    }
                    // event for changing
                    $sliders.type.change(function() {
                        if ($(this).is(':checked')) {
                            $slider_values.type.attr('name', '1');
                        }
                        else {
                            $slider_labels.type.attr('name', '0');
                        }
                    });
                };

                function Setup_PurposeCheckbox(setup) {
                    // default value
                    if (setup.Value == 'True') {
                        $slider_values.purpose.attr('name', '0');
                        $sliders.purpose.attr('checked', false)
                    }
                    else {
                        $slider_values.purpose.attr('name', '1');
                        $sliders.purpose.attr('checked', true)
                    }
                    // event for changing
                    $sliders.purpose.change(function() {
                        if ($(this).is(':checked')) {
                            $slider_values.purpose.attr('name', '1');
                        }
                        else {
                            $slider_values.purpose.attr('name', '0');
                        }
                    });
                };

                function HasSetupValues(setup) {
                    if (setup.Value != '' && setup.MinValue != '' && setup.MaxValue != '' && setup.MinValue != '' && setup.StepValue) {
                        return true;
                    }
                    else {
                        return false;
                    }
                };

                function Init() {
                    $SimilaritySetuper.expanded.hide();
                    $SimilaritySetuper.collapsed.show();
                    $SimilaritySetuper.stage.show();
                    Setup_PriceSlider(similaritySetup.price);
                    Setup_DistanceSlider(similaritySetup.distance);
                    Setup_BedsSlider(similaritySetup.beds);
                    Setup_BathsSlider(similaritySetup.baths);
                    Setup_YearSlider(similaritySetup.year);
                    Setup_TypeCheckbox(similaritySetup.type);
                    Setup_PurposeCheckbox(similaritySetup.purpose)
                };

                // event handlers . . . . . . . . . . 

                $buttons.expand.click(function() {
                    Expand();
                    return false;
                });

                $buttons.apply.click(function() {
                    Collapse(true);
                    return false;
                });

                Init();

            }

        });

    };
})(jQuery);


/* @@ Similar Properties List
   ==================================================================== */

function Setup_SimilarPropertiesList(settings, dataSources, searchParameters, resources){

    var $control = $('#' + settings.controlID);
    var $loader = $('.dSimilarPropertiesLoader');
    var detailsDelay = 1000;
    
    function GetProperties(){
        if (dataSources.handlerURL != '') {
            $.ajax({
                type: 'GET',
                dataType: 'json',
                processData: true,
                timeout: dataSources.requestTimeout,
                url: dataSources.handlerURL,
                data: {
                    searchParameters: searchParameters,
                    maxResults: dataSources.maxResults
                },
                error: function(request, status, error) {
                    $loader.hide();
                },
                success: function(data) {
                   $loader.hide();
                   LoadProperties(data.properties);
                }
            });
        }
        else {
            alert('DataSource URL not defined!');
        }
    };
    GetProperties();
    
    function LoadProperties(properties) { 

            if ($control.children('#dNearProperties').size() > 0) {
                $control.children('#dNearProperties').remove();
            }
                        
            var $properties_stage = $('<div id="dSimilarPropertiesList">').hide();
                        
            $.each(properties, function(index, property){
                
                var $property = $('<div class="SimilarPropertiesListItem">');
                
                $property
                    .append($('<div class="general">')
                        .append($('<div class="photo">')
                            .append($('<a>').attr('href', property.RedirectURL).attr('title', resources.ViewProperty + ': ' + property.BusinessTitle)
                                .append($('<img>').attr('src', property.PhotoURL).attr('alt', '')
                                )
                            )
                        )
                        .append($('<div class="info">')
                            .append($('<p class="business">')
                                .append($('<a>').attr('href', property.RedirectURL).text(property.BusinessTitle).attr('title', resources.ViewProperty + ': ' + property.BusinessTitle)
                                )
                            )
                            .append($('<p class="location">').text(property.Location)
                            )
                            .append($('<p class="price">').text(property.Price)
                            )
                        )
                        .append($('<div class="components">')
                            .append($('<a class="beds">').text(property.NumBeds).attr('title', resources.Beds)
                            )
                            .append($('<a class="baths">').text(property.NumBaths).attr('title', resources.Baths)
                            )
                            .append($('<a class="garage">').text(property.NumGarages).attr('title', resources.Garages)
                            )
                        )
                        .append($('<div class="fClear">')
                        )
                    )
                    .append($('<div class="details">').hide()
                        .append($('<div class="details_info">')
                            .append($('<div class="fLeft">')
                                .append($('<p>')
                                    .append($('<label>').text(resources.Condition + ':')
                                    )
                                    .append($('<span>').text(property.Condition)
                                    )
                                )
                                .append($('<p>')
                                    .append($('<label>').text(resources.Year + ':')
                                    )
                                    .append($('<span>').text(property.Year)
                                    )
                                )
                            )
                            .append($('<div class="fLeft">')
                                .append($('<p>')
                                    .append($('<label>').text(resources.NettArea + ':')
                                    )
                                    .append($('<span>').text(property.NettArea.ReplaceAll('&sup2;', String.fromCharCode(178)))
                                    )
                                )
                                .append($('<p>')
                                    .append($('<label>').text(resources.FloorArea + ':')
                                    )
                                    .append($('<span>').text(property.FloorArea.ReplaceAll('&sup2;', String.fromCharCode(178)))
                                    )
                                )
                            )
                            .append($('<div class="fLeft">')
                            )
                            .append($('<a>').attr('href', property.RedirectURL).text(resources.ViewProperty).attr('title', resources.ViewProperty + ': ' + property.BusinessTitle)
                            )
                        )
                        .append($('<div class="details_components">')
                            .append($('<div class="components">')
                                .append($('<a class="photos">')
                                    .append($('<span>').text(resources.Photos)
                                    )
                                    .append($('<cite>').text('(' + property.NumPhotos + ')')
                                    )
                                )
                                .append($('<a class="photos360">')
                                    .append($('<span>').text(resources.Photos360)
                                    )
                                    .append($('<cite>').text('(' + property.NumPhotos360 + ')')
                                    )
                                )
                                .append($('<a class="videos">')
                                    .append($('<span>').text(resources.Videos)
                                    )
                                    .append($('<cite>').text('(' + property.NumVideos + ')')
                                    )
                                )
                            )
                            .append($('<a class="lnkFavorite">').text('fav').attr('href', '#')
                            )
                        )
                        .append($('<div class="fClear">')
                        )
                    )
                    .append($('<div class="fClear">'));
                
                $properties_stage.append($property);
                
            });
            
            $control.append($properties_stage);
            $properties_stage.fadeIn();
            SetupAnimation($properties_stage);
            
            // esconder icons (todos) com valores nulos
            $('.components',$properties_stage).children('a').each(function(){
                if($(this).text() == '-1') {
                    $(this).hide();
                }
            });
            
             // esconder icons (baths) com valores nulos
            $('.components .baths',$properties_stage).children('a').each(function(){
                if($(this).text() == '-1' || $(this).text() == '0') {
                    $(this).hide();
                }
            });
            
            
            // esconder icons (baths) com valores nulos --> Não devia estar a ser feito, mas é apenas para cumprir ordens superiores
            $('.components .baths',$properties_stage).each(function(){
                if($(this).text() == '-1' || $(this).text() == '0') {
                    $(this).hide();
                }
            });
            
            // esconder icons (garage) com valores nulos --> Não devia estar a ser feito, mas é apenas para cumprir ordens superiores
            $('.components .garage',$properties_stage).each(function(){
                if($(this).text() == '-1' || $(this).text() == '0') {
                    $(this).hide();
                }
            });            
            
            

            // activar a marcação de favoritos
            /*
            $('.lnkFavorite').Setup_FavoriteHandler({
            });
            */
            $('.lnkFavorite').hide();
            
        };
        
        function SetupAnimation(properties_stage) { 

            var delay;

        	properties_stage.children('.SimilarPropertiesListItem').each(function(){	            
        	    
                $(this).mouseenter(function(){
                    var $element = $(this);
                    delay = setInterval(function(){
                        $element.children('.details').stop(true, true).slideDown();
                        clearInterval(delay);
                    }, detailsDelay);
                });
                
                $(this).mouseleave(function(){
                    clearInterval(delay);
                    $(this).children('.details').slideUp();
                });
              
                /*       	 
                $(this).hover(
                    function () {
                      $(this).children('.details').stop(true, true).slideDown();
                    }, 
                    function () {
                      $(this).children('.details').slideUp();
                    }
                );
	            */  
	            
            });
            
        };
};   


/* @@ Near Properties
   ==================================================================== */
   
function Setup_NearProperties(cid_control, languageID, properties_dataSourceURL, mylocation_dataSourceURL, requestTimeout, maxResults, currentUserLocationID,  resourcesJSON, favoriteHandlingSettings, userHistoryID, defaultPurpose) {
  
    var $control = $('#' + cid_control);
    
    var $settings = { 
        cid_control: cid_control,
        languageID: languageID,
        dataSources: { 
            properties: properties_dataSourceURL,
            mylocation: mylocation_dataSourceURL
        },
        requestTimeout: requestTimeout,
        maxResults: maxResults,
        locationDropDown: '#ddlDistricts',
        detectedLocation: 0,
        locationCookieID: 'userLocation',
        detailsDelay: 300,
        resources: jQuery.parseJSON(resourcesJSON),
        defaultPurpose:defaultPurpose 
    };

    function PrintSettings() { 
        console.log($control);
        console.log('cid_control: ' + $settings.cid_control);
        console.log('languageID: ' + $settings.languageID);
        console.log('dataSources: ' + $settings.dataSources.properties);
        console.log('dataSources: ' + $settings.dataSources.mylocation);
        console.log('requestTimeout: ' + $settings.requestTimeout);
        console.log('maxResults: ' + $settings.maxResults);
    };
    
    var $myLocationStage = $('#dMyLocationConfirm');
    
    var $changeMyLocationStage=$('#dChangeMyLocation');
    var $btnChangeMyLocation=$('#dChangeMyLocation a');
    
    var $loader = $('.dSimilarPropertiesLoader');
    var $noNearProperties = $('.noNearProperties');
    var $title = $('#dTitle_nearProperties h3');

    var currentPurpose;
    function Init() {
        
        $loader.show();
        $myLocationStage.hide();
        $changeMyLocationStage.hide();
        
        // se o utilizador está logado e tem localização própria
        if (currentUserLocationID > 0) {
            // invoco directamente  a listagem de imóveis para a localização
            GetAndLoad_Properties(currentUserLocationID, false, $settings.defaultPurpose);
            $myLocationStage.hide()
            
            //Mostrar botão de alterar localização
            $changeMyLocationStage.show();
        }
        else { 

            var locationCookieValue = $.cookies.get($settings.locationCookieID);
            $settings.detectedLocation=locationCookieValue;        
            // o utilizador ainda não confirmou a sua localização
            if (locationCookieValue == null) {
                // invoco o serviço de localização e ele próprio irá disparar a listagem de imoveis para a localização que encontrar
                
               GetAndLoad_MyLocation();
            }
            // o utilizador já confirmou a sua localização previamente
            else { 
                // invoco directamente  a listagem de imóveis para a localização guardada no cookie
                GetAndLoad_Properties(locationCookieValue, false, $settings.defaultPurpose);            
            }

        }

        $btnChangeMyLocation.click(function () {
            $changeMyLocationStage.hide();
            $myLocationStage.slideDown();
            
            return false;
            
        });



    };
    Init();
        
    function GetAndLoad_MyLocation() { 
    
        if ($settings.dataSources.mylocation != '') {
            $.ajax({
                type: 'GET',
                dataType: 'json',
                processData: true,
                timeout: $settings.requestTimeout,
                url: $settings.dataSources.mylocation,
                error: function (request, status, error) {
                    $loader.hide();
                    $noNearProperties.show();
                    $myLocationStage.hide();
                    //Mostrar botão de alterar localização
                    $changeMyLocationStage.show();
                    Change_SubTitle(false);

                },
                success: function (locationInfo) {
                    
                    if (locationInfo != null && locationInfo.LocationID != 0) {
                        //Esconder botão de alterar localização
                        $changeMyLocationStage.hide();
                        $settings.detectedLocation = locationInfo.LocationID;

                        GetAndLoad_Properties(locationInfo.LocationID, true, $settings.defaultPurpose);
                        Change_SubTitle(true);
                    }
                    else {
                        $loader.hide();
                        $noNearProperties.show();
                        $myLocationStage.hide();
                        //Mostrar botão de alterar localização
                        $changeMyLocationStage.show();
                        Change_SubTitle(false);
                    }
                }
            });
            }
            else {
                alert('DataSource URL not defined!');
            }

        };

    function Change_SubTitle(positiveFeedback) {
            
            if (positiveFeedback) {
                $title.html($settings.resources.PropertiesTitle);
            } else {
                $title.html($settings.resources.NoPropertiesTitle);
                $myLocationStage.show();
                $noNearProperties.hide();
            }
            
        }
    
    //oject ajaxRequest to know if a request is already occuring
    var ajaxRequest = null;
    //function to reload the properties with new purpose when the tab is changed
    $control.bind('ReloadControl', function(event, purposeId) {

        //if is the same tab, do nothing
        if (currentPurpose == purposeId) {
            return false;
        }

        // if already exists a request, we will abort them
        if (ajaxRequest) {
            ajaxRequest.abort();
        }

        //show loader and hide current properties
        $noNearProperties.hide();
        $loader.show();
        $control.children('#dNearProperties').remove();
        
        //Load new properties with new purposeID
        GetAndLoad_Properties($settings.detectedLocation, false, purposeId);
    });

    function Setup_MyLocationConfirm() {

        var $btnConfirm = $('.confirmButton', $myLocationStage);
        if ($.cookies.get($settings.locationCookieID) == null) {

            $myLocationStage.show();
            //Esconder botão de alterar localização
            $changeMyLocationStage.hide();
            Change_SubTitle(false);
        }
        else {
            $myLocationStage.hide();
            //Mostrar botão de alterar localização
            $changeMyLocationStage.show();
        }

        $btnConfirm.click(function () {

            // obter o ID da localizacao presente na ddlDistricts
            var selectedLocationID = $($settings.locationDropDown).children('input:first').val();

            if (selectedLocationID > 0) {

                // armazenar a informação em cookies
                var today = new Date();
                //Expires in one year
                var expireDate = new Date(today.getTime() + 365 * 24 * 60 * 60 * 1000);

                $.cookies.set($settings.locationCookieID, selectedLocationID, { expiresAt: expireDate });

                // esconder o myLocationConfirm
                $myLocationStage.slideUp();

                $loader.slideDown();
                //Mostrar botão de alterar localização
                $changeMyLocationStage.slideDown();

                // se a localização é diferente da detectada, chamar novamente o GetAndLoad_Properties()
                if (Number(selectedLocationID) != Number($settings.detectedLocation)) {

                    var $nearPropertiesList = $control.children('#dNearProperties')
                    if ($nearPropertiesList.size() > 0) {

                        $nearPropertiesList.slideUp(function () {
                            $settings.detectedLocation = selectedLocationID;
                            GetAndLoad_Properties(selectedLocationID, false, currentPurpose);
                        });
                    }
                    else {
                        $settings.detectedLocation = selectedLocationID;
                        GetAndLoad_Properties(selectedLocationID, false, currentPurpose);
                    }
                }
            }
            return false;
        });

    };
    Setup_MyLocationConfirm();

    function GetAndLoad_Properties(locationID, triggerDdlLocation, purposeID) {
        currentPurpose = purposeID;
        GetProperties();
        
        function GetProperties(){
            if ($settings.dataSources.properties != '') {
                ajaxRequest = $.ajax({
                    type: 'GET',
                    dataType: 'json',
                    processData: true,
                    timeout: $settings.requestTimeout,
                    url: $settings.dataSources.properties,
                    data: {
                        locationID: locationID,
                        languageID: $settings.languageID,
                        maxResults: $settings.maxResults,
                        purposeID: purposeID
                    },
                    error: function (request, status, error) {
                        $myLocationStage.hide();
                        //Mostrar botão de alterar localização
                        $changeMyLocationStage.show();
                        $noNearProperties.show();
                        $loader.slideUp();
                        Change_SubTitle(false);
                    },
                    success: function (data) {
                        $loader.slideUp();
                        $noNearProperties.hide();
                       
                        if (data != null) {
                            if (data.properties.length == 0) {
                                $noNearProperties.show();
                                Change_SubTitle(false);
                            } else {
                                Change_SubTitle(true); 
                               }
                            LoadProperties(data.properties);
                            if (triggerDdlLocation) {
                                $($settings.locationDropDown).trigger('SelectValue', locationID);
                            }
                        } else {
                            Change_SubTitle(false);
                        }

                    }
                });
            }
            else {
                alert('DataSource URL not defined!');
            }
        };
                
        function LoadProperties(properties) { 

            if ($control.children('#dNearProperties').size() > 0) {
                $control.children('#dNearProperties').remove();
            }
                        
            var $properties_stage = $('<div id="dNearProperties">').hide();
                        
            $.each(properties, function(index, property){
                
                var $property = $('<div class="NearPropertyItem">');
                
                $property
                    .append($('<div class="general">')
                        .append($('<div class="photo">')
                            .append($('<a>').attr('href', property.RedirectURL).attr('title', $settings.resources.ViewProperty + ': ' + property.BusinessTitle)
                                .append($('<img>').attr('src', property.PhotoURL).attr('alt', property.BusinessTitle)
                                )
                            )
                        )
                        .append($('<div class="info">')
                            .append($('<h3>').addClass('business').text(property.BusinessTitle)
                            )
                            .append($('<p class="location">').text(property.Location)
                            )
                            .append($('<p class="price">').text(property.Price)
                            )
                        )
                        .append($('<div class="components">')
                            .append($('<a>').addClass('beds').text(property.NumBeds).attr('title', $settings.resources.Beds)
                            )
                            .append($('<a>').addClass('baths').text(property.NumBaths).attr('title', $settings.resources.Baths)
                            )
                            .append($('<a>').addClass('garage').text(property.NumGarages).attr('title', $settings.resources.Garages)
                            )
                        )
                        .append($('<div class="fClear">')
                        )
                    )
                    .append($('<div class="details">').hide()
                        .append($('<div class="details_info">')
                            .append($('<div class="fLeft">')
                                .append($('<p>')
                                    .append($('<label>').text($settings.resources.Condition + ':')
                                    )
                                    .append($('<span>').text(property.Condition)
                                    )
                                )
                                .append($('<p>')
                                    .append($('<label>').text($settings.resources.Year + ':')
                                    )
                                    .append($('<span>').text(property.Year)
                                    )
                                )
                            )
                            .append($('<div class="fLeft">')
                                .append($('<p>')
                                    .append($('<label>').text($settings.resources.NettArea + ':')
                                    )
                                    .append($('<span>').text(property.NettArea.ReplaceAll('&sup2;', String.fromCharCode(178)))
                                    )
                                )
                                .append($('<p>')
                                    .append($('<label>').text($settings.resources.FloorArea + ':')
                                    )
                                    .append($('<span>').text(property.FloorArea.ReplaceAll('&sup2;', String.fromCharCode(178)))
                                    )
                                )
                            )
                            .append($('<div class="fLeft">')
                            )
                            .append($('<a>').attr('href', property.RedirectURL).text($settings.resources.ViewProperty).attr('title', $settings.resources.ViewProperty + ': ' + property.BusinessTitle)
                            )
                        )
                        .append($('<div class="details_components">')
                            .append($('<div class="components">')
                                .append($('<a class="photos">')
                                    .append($('<span>').text($settings.resources.Photos)
                                    )
                                    .append($('<cite>').text('(' + property.NumPhotos + ')')
                                    )
                                )
                                .append($('<a class="photos360">')
                                    .append($('<span>').text($settings.resources.Photos360)
                                    )
                                    .append($('<cite>').text('(' + property.NumPhotos360 + ')')
                                    )
                                )
                                .append($('<a class="videos">')
                                    .append($('<span>').text($settings.resources.Videos)
                                    )
                                    .append($('<cite>').text('(' + property.NumVideos + ')')
                                    )
                                )
                            )
                            .append(
                                $('<a>').text('Favorito')
                                        .addClass('lnkFavorite')
                                        .attr('href', '#')
                                        .Setup_FavoriteHandler({
                                            data_id: property.ID,
                                            isFavoriteClass: favoriteHandlingSettings.isFavoriteClass,
                                            loadingClass: favoriteHandlingSettings.loadingClass,
                                            languageID: favoriteHandlingSettings.languageID,
                                            requestTimeout: favoriteHandlingSettings.requestTimeout,
                                            url_dataTarget: favoriteHandlingSettings.url_dataTarget,
                                            markFavoriteLabel: favoriteHandlingSettings.markFavoriteLabel,
                                            unmarkFavoriteLabel: favoriteHandlingSettings.unmarkFavoriteLabel,
                                            isMarked: property.IsFavorite,
                                            propertyType: true,
                                            autoRemoveElement: false,
                                            userHistoryID: userHistoryID
                                        })
                            )
                        )
                        .append($('<div class="fClear">')
                        )
                    )
                    .append($('<div class="fClear">'));
                
                $properties_stage.append($property);
                
            });
            
            $control.append($properties_stage);
            $properties_stage.fadeIn();
            SetupAnimation($properties_stage);
            
            // esconder icons (todos) com valores nulos
            $('.components',$properties_stage).children('a').each(function(){
                if($(this).text() == '-1') {
                    $(this).hide();
                }
            });
            
            // esconder icons (baths) com valores nulos --> Não devia estar a ser feito, mas é apenas para cumprir ordens superiores
            $('.components .baths',$properties_stage).each(function(){
                if($(this).text() == '-1' || $(this).text() == '0') {
                    $(this).hide();
                }
            });
            
            // esconder icons (garage) com valores nulos --> Não devia estar a ser feito, mas é apenas para cumprir ordens superiores
            $('.components .garage',$properties_stage).each(function(){
                if($(this).text() == '-1' || $(this).text() == '0') {
                    $(this).hide();
                }
            });
            
            
            
        };
        
        function SetupAnimation(properties_stage) { 

            var delay;

        	properties_stage.children('.NearPropertyItem').each(function(){	            
                
                $(this).mouseenter(function(){
                    var $element = $(this);
                    delay = setInterval(function(){
                        $element.children('.details').stop(true, true).slideDown();
                        clearInterval(delay);
                    }, $settings.detailsDelay);
                });
                
                $(this).mouseleave(function(){
                    clearInterval(delay);
                    $(this).children('.details').slideUp();
                });
	            
            });
            
        };
        
   
    };
    
};



/* @@ ImagesSetup
   ==================================================================== */

$(document).ready(function() {
    $('#dFeatures').SetupFeaturesTree();
    $('.logo img').FixImageSizes();
});




/* @@ SmartMap
   ==================================================================== */

function Load_SmartMap(_clientID, _latitude, _longitude, _mapWidth, _mapHeight, _language, _parish, _county, _district, _country, _address,_resources,_isExactLocation) {

    // USEFUL RESOURCE: http://thinkdrastic.tumblr.com/post/88217865/jquery-getscript-and-the-google-maps-api

    _latitude = _latitude.replace(',', '.');
    _longitude = _longitude.replace(',', '.');

    var delay = 3000;
    var divMap_ID = "dGoogleMap";
    var markersFolder = "App_Themes/propertykingdom/images/smartmap/markers/";
    
    // 2. carregar api da google maps
    window.LoadMapsAPI = function() {
      
        var googleMap_scriptURL = 'http://maps.google.com/maps/api/js?sensor=false&callback=LoadMapUtilities';
        $.getScript(googleMap_scriptURL, function() {        
        });
      
    }
    
    // 3. carregar o script googlemaps.utilities.js
    window.LoadMapUtilities = function() {
            
        var googleMapUtilities_scriptURL = 'App_Scripts/googlemaps.utilities.js';
        $.getScript(googleMapUtilities_scriptURL, function() {       
            LoadSmartMapScript();
        });
      
    }

    // 4. carregar script do smartmap
    window.LoadSmartMapScript = function() { 
        
        var smartMap_scriptURL = 'App_Scripts/casayes.smartmap.js';
        $.getScript(smartMap_scriptURL, function() {
            
            // 5. preciso de aguardar um pouco, para a api do google ser carregada
        SetupGoogleMaps(_clientID, parseFloat(_latitude), parseFloat(_longitude), Number(_mapWidth), Number(_mapHeight), _language, _parish, _county, _district, _country, _address, divMap_ID, markersFolder, _resources,_isExactLocation);
            
        });
        
    };
    

    // 1. obter a google developer key
    var googleKey_scriptURL = 'http://www.google.com/uds/api?file=uds.js&v=1.0&async=2&callback=LoadMapsAPI&key=ABQIAAAAyLlp_yINWC840VfuvvjMKBQ01xX7zjJUNGOZ1g2_JdpOcjJRwBRv5lVDrBo3A5XlUozsW_O8LPgb_w';
    $.getScript(googleKey_scriptURL, function() {
 
    });

};   


/* @@ ThumbnailSlideshow
   ==================================================================== */

function SetupThumbnailSlideshow() {
    $('#dSlideshow').ThumbnailSlideshow();
};


(function($) {
    $.fn.ThumbnailSlideshow = function(pluginSettings) {

        var defaultSettings = {
            noPhoto_path: 'App_Themes/propertykingdom/images/propertydetail/noPhoto.png',
            delaySpeed: 2500
        };
        var $settings = $.extend(defaultSettings, pluginSettings);

        return this.each(function() {
            
            var $lightBoxCurrentImg= $('img', $(this)).first();
            var _lightBoxWidth = 520;
            var _lightBoxHeight = 390;
            var $stage = $(this),
                $slideshow_items = $(this).children('ul').children('li');


           Setup_LightBox($lightBoxCurrentImg); 
            

            var _containerWidth = 292;
            var _containerHeight = 219;
           
            var _totalPages = $slideshow_items.length;
            var _currentIndex = 1;
            var _inLightBox = false;
            
            var _listContainerWidth = _containerWidth * (_totalPages + 1);
            // - configurar largura do container da lista de fotos
            $stage.children('ul').width(_listContainerWidth);
           
            
            // Criar os clones para poder fazer o loop	
            var $firstItem = $slideshow_items.filter(':first');
            var $lastItem = $slideshow_items.filter(':last');
            $firstItem.before($lastItem.clone().addClass('cloned'));
            $lastItem.after($firstItem.clone().addClass('cloned'));
            
            // actualizar a posicao inicial do scroll
            $stage.scrollLeft(_containerWidth);
            
            // actualizar os valores iniciais // provavelmente poderemos trocar a ordem, para n ter que atribuir novamente
            // *************************************
            $slideshow_items = $(this).children('ul').children('li');
            //_totalPages = $slideshow_items.length;
            _listContainerWidth = _containerWidth * ($slideshow_items.size() + 1);
            $stage.children('ul').width(_listContainerWidth);
            // *************************************


            
            // - obter o caminho de todas as fotos
            var photo_paths = new Array;
            try {
                $slideshow_items.each(function() {
                    photo_paths.push($(this).text());
                });
            } catch (e) { }
            
            
            // atribuir a largura por defeito a cada li...
            // quando as fotos são carregadas, eles ficam com a largura da foto (_containerWidth)
            // antes das fotos serem carregadas eles têm a largura do url
            $slideshow_items.each(function(){
                $(this).width(_containerWidth);
                $(this).height(_containerHeight);
            });


            // - acrescentar setas de navegação

            var $previous_btn = $('<span></span>').addClass('previous'),
                $next_btn = $('<span></span>').addClass('next');


            $previous_btn.click(function() {
                GoToPhoto(_currentIndex - 1);
                return false;
            });

            $next_btn.click(function() {
                GoToPhoto(_currentIndex + 1);
                return false;
            });

            $stage.after($previous_btn)
                  .after($next_btn);

             if (_totalPages <= 1){
                $next_btn.hide();
                $previous_btn.hide();
             }
             
            // - carregar a 1ª e a ultima foto            
            LoadPhotos(_currentIndex);
            
          
            // - métodos auxiliares
            
            function GoToPhoto(index) {
                // - deslocar a foto
                var direction = index < _currentIndex ? -1 : 1,
                    n = Math.abs(_currentIndex - index),
                    left = _containerWidth * direction * n;
                $stage.filter(':not(:animated)').animate({
                    scrollLeft: '+=' + left
                }, 500, function() {
                    if (index == 0) {
                        $stage.scrollLeft(_containerWidth * _totalPages);
                        index = _totalPages;
                    } else if (index > _totalPages) {
                        $stage.scrollLeft(_containerWidth);
                        index = 1;
                    }
    
                    _currentIndex = index;
                    
                });

                // - actualizar o carregamento de fotos necessárias
                LoadPhotos(index);  
               
                $lightBoxCurrentImg=$slideshow_items.eq(index).children('img');
                
            };

            function LoadPhotos(index) {
                if (ExistsPhoto(index)) {
  
                    // carregar a foto solicitada
                    if (!IsPhotoLoaded(index)) {
                        LoadPhoto(index); 
                    }
                    // carregar a foto seguinte
                    if(index < _totalPages){
                        if (ExistsPhoto(index + 1)) {
                            if (!IsPhotoLoaded(index + 1)) {
                                LoadPhoto(index + 1);
                            }
                        }
                    }
                   
                    // carregar a foto anterior
                    if(index > 0){
                        if (ExistsPhoto(index - 1)) {
                            if (!IsPhotoLoaded(index - 1)) {
                                LoadPhoto(index - 1);
                            }
                        }
                    }
                 }
                
                
                // carregar clones 
                $slideshow_items.each(function(auxIndex){
                    if ($(this).hasClass('cloned')) {
                       
                       // carregar a foto solicitada
                       if (ExistsPhoto(auxIndex)) {
                            if (!IsPhotoLoaded(auxIndex)) {
                                LoadPhoto(auxIndex);
                            }
                        }
                        
                    }
                });
                               

                function LoadPhoto(photoIndex) {
  
                    var img = new Image();

                    $(img).load(function(){
                        $(this).FixImageSizes({
                            max_width: 292,
                            max_height: 219,
                            fake_width: true,
                            force_full_height: true
                        });
                        $(this).fadeIn();
                       // Setup_LightBox($(this));
                    });
                    
                    $(img).error(function(){
                        $(this).remove();
                        var $no_photo = $('<img src="" alt="" />').attr('src', $settings.noPhoto_path);
                        $slideshow_items.eq(photoIndex).append($no_photo);
                    });
                    
                    $(img).attr('src', photo_paths[photoIndex]).attr('alt', 'CasaYES').hide();
                    
                    $slideshow_items.eq(photoIndex).text('');
                    $slideshow_items.eq(photoIndex).append($(img));
                    
                    // se a foto carregada é clone de alguma, carrego também a original
                    if ($slideshow_items.eq(photoIndex).hasClass('cloned')) {
                        
                        // obter o index da foto original
                        var originalIndex = -1;
                        for (var i=0; i<photo_paths.length; i++){
                            if (i != photoIndex) {
                                if (photo_paths[i] == photo_paths[photoIndex]) {
                                    originalIndex = i;
                                }
                            }
                        }
                        
                        if (originalIndex>-1){
                        
                            // carregar a foto original
                            if (ExistsPhoto(originalIndex)) {
                                if (!IsPhotoLoaded(originalIndex)) {
                                    LoadPhoto(originalIndex);
                                }
                            }
                            // carregar a foto seguinte
                            if(originalIndex < _totalPages){
                                if (ExistsPhoto(originalIndex + 1)) {
                                    if (!IsPhotoLoaded(originalIndex + 1)) {
                                        LoadPhoto(originalIndex + 1);
                                    }
                                }
                            }
                            
                            // carregar a foto anterior
                            if(originalIndex > 0){
                                if (ExistsPhoto(originalIndex - 1)) {
                                    if (!IsPhotoLoaded(originalIndex - 1)) {
                                        LoadPhoto(originalIndex - 1);
                                    }
                                }
                            }
                            
                        }
                        
                        
                    }

                };

                function ExistsPhoto(photoIndex) {
                    if(photoIndex < 0) return false;
                    return ($slideshow_items.eq(photoIndex).size() > 0)
                };

                function IsPhotoLoaded(photoIndex) {
                    if(photoIndex < 0) return false;
                    return ($slideshow_items.eq(photoIndex).children('img').size() > 0)
                };

            };
            
            
            function LightBox_GoToPhoto(direction){
                var $overlayDiv = $('.overlayLightbox');
                var $area = $('div',$overlayDiv);
                var $btnNext =$('span.next',$overlayDiv);
                var $btnPrev =$('span.previous',$overlayDiv);
                var imageURL;
                var index=1;
                var winH = $(window).height();

                if(direction==1){
                    index = $lightBoxCurrentImg.parent('li').next().index();
                    imageURL=$lightBoxCurrentImg.parent('li').next().children('img').attr('src');
                }else{
                    index = $lightBoxCurrentImg.parent('li').prev().index();
                    imageURL=$lightBoxCurrentImg.parent('li').prev().children('img').attr('src');
                }
                
                if (index == 0) {
                    index = _totalPages;
                    imageURL=$lightBoxCurrentImg.parent('li').siblings().eq(index-1).children('img').attr('src');
                } else if (index > _totalPages) {
                    index = 1;
                    imageURL=$lightBoxCurrentImg.parent('li').siblings().eq(index).children('img').attr('src');
                }

                var $newImg = new Image();
                $newImg = $overlayDiv.children('div').children('img');
                $newImg.unbind('FixImageSizes').unbind('load');
                $newImg.load(function(){
                    $newImg.FixImageSizes({
                        max_width: _lightBoxWidth,
                        max_height: _lightBoxHeight,
                        fake_width: false,
                        force_full_height: false
                    });

                    //setup the new dimensions for the area
                    $area.width($newImg.width()).height($newImg.height()).css('top',  winH/2-$newImg.height()/2);

                     //setup the new position for the area
                    var newTop=($area.height()/2)-5-($btnNext.height()/2);
                    $btnNext.css('top',newTop + 'px');
                    $btnPrev.css('top',newTop + 'px');
                       
                });
                
                $newImg.unbind('error');    
                $newImg.error(function(){
                    $(this).remove();
                    $newImg= $('<img src="" alt="" />').attr('src', '');
                });
                   
                $newImg.unbind('fadeOut').unbind('fadeIn');  
                $newImg.fadeOut(500, function () {
                    $newImg.css('width','auto').css('height','auto').attr('src', imageURL).fadeIn(500);

                });
                
                GoToPhoto(index);
            }


            function Setup_LightBox($img) {
                
                var $overlayDiv = $('.overlayLightbox');
                var $lightBoxImg = $('.img', $overlayDiv);
                var $btnNext =$('<span>').addClass('next');
                var $btnPrev =$('<span>').addClass('previous'); 
                var $closeOverlay = $('<a>').addClass('closeOverlay').attr('href','#'); 
                var $area = $('div', $overlayDiv);
                 //Get the window height and width
                var winH = $(window).height();
                var winW = $(window).width();

                //update box dimensions
                _lightBoxHeight = winH - 150;
                _lightBoxWidth= (_lightBoxHeight*4) /3 ;

                if ($overlayDiv.size() == 0) {

                    $area = $('<div>').width($img.width()).height($img.height()).css('visibility','hidden');
                    //Set the popup window to center
                    
                    $lightBoxImg = $('<img>').attr('src', $img.attr('src')).width($img.width()).height($img.height()).css('display','none');
                    $overlayDiv = $('<div>').addClass('overlayLightbox').append($area.append($lightBoxImg).append($btnNext).append($btnPrev).append($closeOverlay));
               
                    $('body').children('form').prepend($overlayDiv);

                }


                var $thumbImage =  $img.parent('li').parent('ul').parent('div');
                var $thumbHover=$('<span>').addClass('hover').css('display','none');
                $stage.after($thumbHover);
                
                $thumbHover.hover(function(){
                    $(this).show();
                });

                $thumbImage.hover( function () {
                    $thumbHover.show();
                },function () {
                    $thumbHover.hide();
                });

                $thumbImage.click(function(){      
                    Open_LightBox();
                });

                $thumbHover.click(function(){
                    Open_LightBox();
                });

                function Open_LightBox(){
                    // pause original slideshow
                    _inLightBox = true;
                   
                    if(_totalPages<=1){
                        $btnNext.hide();
                        $btnPrev.hide();
                    }

                    var imageURL = $lightBoxCurrentImg.attr('src');
                    var $newImg = $overlayDiv.children('div').children('img');
                    
                    $newImg.unbind('FixImageSizes').unbind('load');  
                    $newImg.load(function(){
                        $(this).hide();
                        
                        $newImg.fadeIn(500,function(){
                          
                            $(this).FixImageSizes({
                                max_width:_lightBoxWidth ,
                                max_height: _lightBoxHeight,
                                fake_width: false,
                                force_full_height: true
                            });
                       
                            //setup de new width for the area
                            $area.width($newImg.width()).height($newImg.height()).css('top',  winH/2 - $newImg.height()/2).css('visibility','visible');
                            
                            //setup the new position for the area
                            var newTop=($area.height()/2)-5-($btnNext.height()/2);
                            $btnNext.css('top',newTop + 'px');
                            $btnPrev.css('top',newTop + 'px');

                        });
                    });
                        
                    $newImg.unbind('error');  
                    $newImg.error(function(){
                        $(this).remove();
                        $newImg= $('<img src="" alt="" />').attr('src', '');
                    });
                    
                    $newImg.attr('src', imageURL).css('width','auto').css('height','auto');
                       
                    // show overlayDiv
                    SetupOverlayDivPositioning();
                    $overlayDiv.fadeIn();
                
                }
                
                $btnNext.click(function(){
                    LightBox_GoToPhoto(1);
                    return false;
                });
   
                $btnPrev.click(function(){
                   LightBox_GoToPhoto(-1);
                   return false;
                });

                

                $lightBoxImg.click(function(){
                    return false;
                });

                $overlayDiv.bind('click', function() {
                    if(_inLightBox){
                        $overlayDiv.hide();
                    _inLightBox = false;
                    }
                        
                });

                $closeOverlay.click(function(){
                    $overlayDiv.hide();
                    _inLightBox = false;
                    return false;
                });
                
                // ao carregar em ESC, escondo o overlayDiv
                $(document).keydown(function(e) {
                    if (e.keyCode == _keyboard.escape) {
                        $overlayDiv.hide();
                        _inLightBox = false;
                    }
                });
                
                // ao fazer resize tenho que ajustar as dimensões do overlay
                $(window).bind('resize', function() { SetupOverlayDivPositioning(); });      
                $(window).scroll(function() { SetupOverlayDivPositioning(); });                          
                 
                // ajustar altura do div overlay
                function SetupOverlayDivPositioning() {
                    $overlayDiv.css('top', $(window).scrollTop());
                    $overlayDiv.css('height', $(window).height());
                };
                
                
            };
            

            function Setup_AutoSlideshow() {

                if (_totalPages > 1) {

                    var getNext = true;
                    var autoSlideshow = true;
                    rolling = setInterval(function() {
                        if (autoSlideshow && !_inLightBox) {
                            GoToPhoto(_currentIndex + 1);
                        }
                    }, $settings.delaySpeed);

                    $stage.mouseover(function() {
                        autoSlideshow = false;
                    }).mouseout(function() {
                        autoSlideshow = true;
                    });
                    
                    $previous_btn.mouseover(function() {
                        autoSlideshow = false;
                    }).mouseout(function() {
                        autoSlideshow = true;
                    });
                    
                    $next_btn.mouseover(function() {
                        autoSlideshow = false;
                    }).mouseout(function() {
                        autoSlideshow = true;
                    });

                }
            };
            $(window).load(function() {
                setTimeout(function(){
                    Setup_AutoSlideshow();
                },500);
            });

        });

    };
})(jQuery);



/* @@ Features
   ==================================================================== */

(function($) {
    $.fn.SetupFeaturesTree = function(pluginSettings) {

        var defaultSettings = {
            css_activeOption: 'active'
        };
        var $settings = $.extend(defaultSettings, pluginSettings);

        return this.each(function() {

            var $features = $(this),
				$features_index = $('#featuresIndex', $(this)),
				$features_index_links = $('#featuresIndex a', $(this)),
				$features_details = $('#featuresDetails', $(this));

            // - configurar altura mínima do div de acordo com a altura ocupada pelo index
            $features.css('min-height', $features_index.height());

            // - se só existe um bloco de features, escondo o index
            if ($features_index_links.size() <= 1) {
                $features_index.hide();
            }

            // - configurar bloco apresentado por defeito
            $features_details.children('div').hide();
            $features_details.children(':first').show();
            $features_index_links.filter(':first').addClass($settings.css_activeOption);

            // - clique na opção do index	
            $features_index_links.click(function() {

                // - configurar o estilo da opção corrente
                $features_index_links.removeClass($settings.css_activeOption);
                $(this).addClass($settings.css_activeOption);

                // - apresentar o bloco correspondente ao link clikado (a.href === div.id)
                $features_details.children('div').hide();
                $($(this).attr('href')).fadeIn('fast');

                return false;
            });

        });

    };
})(jQuery);


/* @@ Video Player
   ==================================================================== */
   
function Setup_VideoPlayer(controlIDs, multimediaSettings) {
    
    var $controls = {
        overlay_area: $('#' + controlIDs.overlay),
        lnkShowTime: $('#' + controlIDs.lnkShowTime),
        player: $('#' + controlIDs.player),
        videoPlayer: $('#' + controlIDs.videoPlayer)
    };
    
    function Setup_OverlayDisplay(){
       
        $controls.lnkShowTime.click(function() {
            SetupPositioning();
            $controls.overlay_area.fadeIn(function(){
                Load_Player();
            });
            return false;
        });
       
        $(document).keydown(function(e) {
            if (e.keyCode == _keyboard.escape) {
                SetupClosing();
                $controls.overlay_area.hide();
            }
        });  
        
        $('.closeCinemaOverlay', $controls.overlay_area).unbind('click').click(function(){
            SetupClosing();
            $controls.overlay_area.hide();
            return false;
        }); 
       
        $(window).bind('resize', function() {
            SetupPositioning();
        }); 
        
        $(window).scroll(function(){
            SetupPositioning();
        });
        
        function SetupClosing(){                
            var $videoObj = $('object', $controls.videoPlayer);
            var $divObj = $('<div id="' + controlIDs.player + '">');
            $videoObj.remove();
            $controls.videoPlayer.append($divObj);
        };
    
        function SetupPositioning(){
            $controls.overlay_area.css('top', $(window).scrollTop());
            $controls.overlay_area.css('height', $(window).height());
        };
    
    };
    Setup_OverlayDisplay();
    
    function Load_Player(){
        LoadSwfObject(controlIDs.player, multimediaSettings.path, multimediaSettings.width, multimediaSettings.height, '', multimediaSettings.flashMinVersion);
    };
    
};   


/* @@ Video Player
   ==================================================================== */
   
function Setup_VirtualTourPlayer(controlIDs, multimediaSettings) {
    
    var $controls = {
        overlay_area: $('#' + controlIDs.overlay),
        lnkShowTime: $('#' + controlIDs.lnkShowTime),
        player: $('#' + controlIDs.player),
        videoPlayer: $('#' + controlIDs.videoPlayer)
    };
           
    function Setup_OverlayDisplay(){
       
        $controls.lnkShowTime.click(function() {
            SetupPositioning();
            $controls.overlay_area.fadeIn(function(){
                Load_Player();
            });
            return false;
        });
       
        $(document).keydown(function(e) {
            if (e.keyCode == _keyboard.escape) {
                SetupClosing();
                $controls.overlay_area.hide();
            }
        });  
        
        $('.closeCinemaOverlay', $controls.overlay_area).unbind('click').click(function(){
            SetupClosing();
            $controls.overlay_area.hide();
            return false;
        }); 
       
        $(window).bind('resize', function() {
            SetupPositioning();
        }); 
        
        $(window).scroll(function(){
            SetupPositioning();
        });
        
        function SetupClosing(){                
            var $videoObj = $('object', $controls.videoPlayer);
            var $divObj = $('<div id="' + controlIDs.player + '">');
            $videoObj.remove();
            $controls.videoPlayer.append($divObj);
        };
    
        function SetupPositioning(){
            $controls.overlay_area.css('top', $(window).scrollTop());
            $controls.overlay_area.css('height', $(window).height());
        };
    
    };
    Setup_OverlayDisplay();
    
    function Load_Player(){
        //$controls.player.append('<div id="script"><script type="text/javascript" src="' + multimediaSettings.path + '"></script></div>');
    };
    
};   
