
var FCEAptSearch = {

    beds : null,
    filter_avail : true,
    currApt: null, //Current apartment key (into JSON obj)
    currUnitID: null,  //current unitid (realpage)/non-user-friendly
    timer1 : null,

    scrollbarOpts : {scrollbarWidth:9, scrollbarMargin:2, showArrows:true, arrowSize:9},
    scrollbarOpts2 : {scrollbarWidth:9, scrollbarMargin:3, showArrows:true, arrowSize:9},


    /**
     * initialize search for all apartments
     */
    searchAll: function() {
        this.filter_avail = false;
        this.search();
        this.searchTriggerAvail.removeClass('sel');
        this.searchTriggerAll.addClass('sel');
    },

    /**
     * initialize search for only available apartments
     */
    searchAvailable: function() {
        this.filter_avail = true;
        this.search();
        this.searchTriggerAll.removeClass('sel');
        this.searchTriggerAvail.addClass('sel');
    },

    /**
     * search the apartment listings by the #beds in this.beds currently.
     * append results as table rows to #aptSearchResults/tbody.
     */
    search: function() {
        $('#aptPanelSearchIntro, #aptPanelChooseNotice').hide();

        var apts = FCEAptDataRetriever.fetchAptListings(this.beds, this.filter_avail);

        $('#aptSearchResultsW, #aptPanel2, #aptPanel3').show();

        if (apts.length > 0) {
            $('#aptSearchResults > tbody').empty();
            $('#aptPanelW3 > div.filter').show();

            var rowCount = 1;
            for (var a in apts) {
                var row = '<td class="col1'+ ((apts[a].avail)? ' avail' : '')  +'">' + apts[a].plan + '</td>';
                   row += '<td class="col2">' + apts[a].bed + '</td>';
                   row += '<td class="col3">' + apts[a].bath + '</td>';
                   row += '<td class="col4">' + apts[a].sqft + '</td>';
                   row += '<td class="col5">' + apts[a].floor + '</td>';
                   row += '<td class="col6">' + ((apts[a].avail)? apts[a].rent : 'LEASED') + '</td>'; // todo loop it

                $('#aptSearchResults > tbody').append('<tr key="'+ apts[a].aptkey +'" floor="'+ apts[a].floor +'">' + row + '</tr>');
                rowCount++;
            }
            $('#aptSearchResults > tbody > tr').bind('click', FCEAptSearch.select);
            $('#aptPanelW3').find('table').show();

            // click the first item, per req:
            window.setTimeout("$('#aptSearchResults > tbody').children(':first').click()", 100);
            $('#outW1').addClass('searchActive');
            /* reloads the scrollbar, will appear only when needed */
            $('#aptPanelW1 div.scrollContainer').jScrollPane(this.scrollbarOpts);
        } else {
            $('#aptSearchResults > tbody').empty();
            $('#aptSearchResults > tbody').append('<tr><td>Please contact us for apartment<br /> availability</td></tr>');
            $('#aptPanelW3').find('table').show();
        }

        $('#outW2').addClass('aptSearchIsActive'); // for OFT because it needs a new background when details are showing

        /* reloads the scrollbar, will appear only when needed */
        $('#aptSearchResultsW div.scrollContainer').jScrollPane(this.scrollbarOpts);
    },

    /**
     * one of the apartments in the search result listing has been selected.
     * Show the whole detail pane and then pass on the info for display.
     */
    select: function() {
        $('#aptSearchResults > tbody > tr.sel').removeClass('sel');
        $(this).addClass('sel');

        $('#aptPanelSearchDetailW').show();

        var aptkey = $(this).attr('key');
        var floor = $(this).attr('floor');

        FCEAptSearch.renderAptDetails(aptkey, floor);

        /* for LP, hack to make all columns the same height if the description is longer */
        // $('#aptPanel2, #aptPanel3').equalizeCols(); // not needed on Lofts
    },

    /**
     * utility function to populate and position details and images for a selected apartment.
     * @param aptkey str the aptkey for the apartment
     * @param floor int we need to know the floor too, because there is no reliable aptkey->floor lookup yet
     */
    renderAptDetails : function(aptkey, floor) {

        var aptDetails = FCEAptDataRetriever.fetchAptDetails(aptkey);

        if (aptDetails) {
            this.currApt = aptkey;
            //All aptkeys will have a k in front of them.
            var rpunitid = aptkey.replace(/^k/, '');
            this.currUnitID = rpunitid;

            /* set the apt plan image */
            $('#aptPlan').show().find('img').attr('src', FCEAptDataRetriever.fetchAptPlanImg(aptkey));

            /* setup detail window - set header */
            $('#aptDetail > h4').empty().prepend(aptDetails.shortHeader);

            /* print and email buttons */
            $('#wIconPE').show();
            
            /* add listing info the the <UL> list in aptDetail window */
            var listing = $('#aptDetail').find('div.listing > ul');
            listing.empty();
            
            for (var i in aptDetails.detailedList) {
                listing.append('<li>'+aptDetails.detailedList[i]+'</li>');
            }
            listing.show();

            /* add details text to aptDetail window */
            $('#aptDetail').find('div.descr').empty().prepend(aptDetails.description).show();

            /* the zoom link */
            $('#aptPlanEnlargeLink > a').attr('href', FCEAptDataRetriever.fetchAptPlanImg(aptkey, true));

            // set 'title' and other attrs of the enlarge link so thickbox will pick it up. */
            $('#aptPlanEnlargeLink > a').attr('title', aptDetails.shortHeader)
                                        .attr('name', aptDetails.detailedList.join( ' // '))
                                        .attr('rel', 'print/print_apt_detail.aspx?apt='+rpunitid);
            $('#aptPlanEnlargeLink').show();

            // append ?apt=209 to the print URL
            $('#iconPrint > a').attr('href', $('#iconPrint > a').attr('href').replace(/\?.*$/, '') + '?apt=' + rpunitid);
            $('#iconEmail > a').attr('href', $('#iconEmail > a').attr('href').replace(/\?.*$/, '') + '?apt=' + rpunitid);
            // load the scrollbar on the apt-detail text if needed
            $('#aptDetail div.scrollContainer').jScrollPane(this.scrollbarOpts2); 
        }
        else { // bail.
            $('#aptDetail > h4').text("- no details available -");
            $('#aptDetail').find('div.descr').empty().hide();
            $('#aptDetail').find('div.listing > ul').empty().hide();
            $('#aptPlan > img').attr('src', '');
            $('#aptPlan').hide();
            $('#aptPointerW').hide();
            this.currApt = 0;
        }

        /* set the floor plate based only on the floor */
        this.renderFloorPlate(floor);

        if (floor != 'ph') {
            $('#aptPanel2 > h3 > span').text('Floor ' + floor);
        }
        else {
            $('#aptPanel2 > h3 > span').text('Penthouse');
        }
    },


    /**
     * populate and position the "aptInfoDialog" (grey box pointing to apartment on top of floor plate)
     * @param aptkey str the aptkey for the apartment
     */
    renderAptInfoDialog : function(aptkey) {
        if (!aptkey) aptkey = this.currApt;

        var aptInfo = FCEAptDataRetriever.fetchAptInfo(aptkey);

        $('#aptInfoDialog').attr('class', '');

        /* position and populate the little pointer to the the apartment on top of floor plate */
        if (aptInfo) {
            var subunit = aptInfo.aptnum.replace(/^.*(\d\d[A-Z]?)$/, '$1');
            FCEAptPointerPositioning.positionDialog('#aptPointer', aptInfo.floor, subunit);
        }
        else {
            $('#aptPointerW').hide();
        }
    },


    /**
     * how many beds is user currently interested in (state of 1bed/2bed/penthouse selector)
     * @param beds string
     */
    set_beds: function(beds) {
        this.beds = beds;
    },

    renderFloorPlate : function(floor) {
        if (FCE_FLOORS_PLATES[floor]) {
            var plate = FCE_FLOORS_PLATES[floor]; // see map object in FCEAptPointerPositioning.js

            /* assign the imagemap to the floor plate and update with the correct GIF */
            $('#aptFloorPlate > img').remove(); // clean the slate, msie/saf need to do this.

            /* prepend the image and make it visible */
            $('#aptFloorPlate').prepend('<img src="'+plate[1].src+'" usemap="#'+plate[0]+'" alt="">');

            /* but we have to re-attach the things that should happen when the image is loaded... not very DRY */
            $('#aptFloorPlate > img').bind('load', function() {
                                                    FCEAptSearch.renderAptInfoDialog(0); 
                                                    if (document.body.id == 'page_apartments_browse') {
                                                        $(this).vertCenterContainer();
                                                    }
                                                    $(this).parent().addClass('loaded');
                                                   } );
            
        }
    },


    /**
     * setup handlers and scrollers
     */
    init: function() {

        $('#aptTypeSelections a.btn').bind('click', function(e) { 

            FCEAptSearch.set_beds($(this).attr('id').split('_')[1]);

            if (FCEAptSearch.filter_avail) FCEAptSearch.searchAvailable();
            else FCEAptSearch.searchAll();

            $('#aptTypeSelections a.btn').removeClass('sel');
            $(this).addClass('sel').blur();
            return false;
         });

        this.searchTriggerAvail = $('#aptAvailSelectorW > a.avail').bind('click', function(e) { FCEAptSearch.searchAvailable(); return false; });
        this.searchTriggerAll = $('#aptAvailSelectorW > a.all').bind('click', function(e) { FCEAptSearch.searchAll(); return false; });

        // init scrollbar structures.
        //$('#aptDetail div.scrollContainer').jScrollPane(this.scrollbarOpts2);

        $('#aptPanelSearchIntro > div.innerw > div').bind('click', function(e) { 
            var beds = $(this).find('a.search').attr('href').match(/beds=(.*)$/)[1];
            if (beds) {
                FCEAptSearch.set_beds(beds);
                FCEAptSearch.search();

                $('#aptTypeSelections').children('a.btn').removeClass('sel');
                $('#aptSearchTrigger_'+beds).addClass('sel');
            }
            e.stopPropagation();
            return false;
        });


        $('#aptPanelSearchIntro > div.innerw > div').hoverClass('hover');

        if (jQuery.browser.mozilla) {  /* only FF handles this the way we want */
            //$('#aptFloorPlate > img').bind('load', function() { FCEAptSearch.renderAptInfoDialog(); } );
        }

        if (jQuery.browser.msie && jQuery.browser.version < 7) { // this is bizarre but gets around a weird bug in msie6
             $('#aptPanelSearchIntro').css('height', $('#aptPanelSearchIntro').css('height'));

        }

        // DEBUG ONLY
        //$('#aptPanelSearchIntro').find('div.one').click();
    }

};



$(document).ready(function(){
     if (document.body.id == 'page_apartments_search') FCEAptSearch.init();

});


