
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: 5, scrollbarMargin: 2, showArrows: true, arrowSize: 11 },
    scrollbarOpts2: { scrollbarWidth: 5, scrollbarMargin: 3, showArrows: false },


    /**
    * 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();
        $('#aptAvailSelectorW').show();

        var apts = FCEAptDataRetriever.fetchAptListings(this.beds, this.filter_avail);

        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].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 + '" class="' + ((apts[a].avail) ? 'avail' : '') + '">' + 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);
        } 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 */
        $('#aptPanelW3').find('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);
        FCEAptSearch.renderAptInfoDialog(aptkey, floor);

        /* for LP, hack to make all columns the same height if the description is longer */
        $('#aptPanel2, #aptPanel3').equalizeCols();
    },

    /**
    * 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) {

        /* set the floor plate based only on the floor */
        this.renderFloorPlate(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 > img').attr('src', FCEAptDataRetriever.fetchAptPlanImg(aptkey));
            $('#aptPlan').show();

            /* 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 and email URLs (email for conveinence only)
            $('#iconPrint > a').attr('href', $('#iconPrint > a').attr('href').replace(/\?.*$/, '') + '?apt=' + rpunitid);
            $('#iconEmail > a').attr('href', $('#iconEmail > a').attr('href').replace(/\?.*$/, '') + '?apt=' + rpunitid);
        }
        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();
            $('#aptInfoDialogW').hide();
        }
    },


    /**
    * 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) {
            FCEAptPointerPositioning.positionDialog('#aptPointer', aptInfo.floor, aptInfo.aptnum);
        }
        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 */
            var img = $('#aptFloorPlate').prepend('<img src="' + plate[1].src + '" usemap="#' + plate[0] + '" alt="">');
            if (plate[1].width) {
                $('#aptFloorPlate > img').width(plate[1].width).height(plate[1].height);
            }
            /* ???????????????????????????????????????????????????????????????????????? */
            if (FCE_FLOORPLATE_OFFSETS[floor]) {
                $('#aptFloorPlate').css('left', FCE_FLOORPLATE_OFFSETS[floor]);
            }
            else {
                $('#aptFloorPlate').css('left', 0);
            }

            /* 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();
                $(this).parent().addClass('loaded');
            });

        }
    },


    /**
    * setup handlers and scrollers
    */
    init: function() {

        $('#aptTypeSelections').find('div.btn').bind('click', function(e) {

            //$('#aptTypeSelections > div.selections').hide();
            //$('#aptTypeSelections > div.hdr').text($(this).text());

            FCEAptSearch.set_beds($(this).attr('id').split('_')[1]);

            if (FCEAptSearch.filter_avail) FCEAptSearch.searchAvailable();
            else FCEAptSearch.searchAll();

            $(this).addClass('sel').blur().siblings().removeClass('sel');
        });

        this.searchTriggerAvail = $('#aptAvailSelectorW > div.avail');
        this.searchTriggerAvail.bind('click', function(e) { FCEAptSearch.searchAvailable(); });

        this.searchTriggerAll = $('#aptAvailSelectorW > div.all');
        this.searchTriggerAll.bind('click', function(e) { FCEAptSearch.searchAll(); });

        // init scrollbar structures.
        //$('#aptPanelW3 > div.scrollContainer').jScrollPane(this.scrollbarOpts);
        /* $('#aptDetail/.scrollContainer').jScrollPane(this.scrollbarOpts2); // not needed anymore? */

        $('#aptPanelSearchW2 > 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('div.btn').removeClass('sel');
                $('#aptSearchTrigger_' + beds).addClass('sel');
            }
            e.stopPropagation();
            return false;
        });

        /* for LP only - has this custom dropdown thing for the bedroom selector. */

        /* **** brilliant code is no longer needed due to redesign :(  ******** */

        /* show the selections when the select bar gets a clicky */
        /* $('#aptTypeSelections > div.hdr').bind('click', function() {
        *                                                  $('#aptTypeSelections > div.selections').toggle();
        *                                              });
        */

        /* auto-close the selections when the mouse goes away, after a brief pause to be sure */
        /* $('#aptTypeSelections').hover(function() { if (FCEAptSearch.timer1) window.clearTimeout(FCEAptSearch.timer1); }, 
        *                            function() { FCEAptSearch.timer1 = window.setTimeout("$('#aptTypeSelections > div.selections').hide()", 460 ); });
        */

        // DEBUG ONLY
        //$('#aptPanelSearchW2 > div.onebed').click();
    }


};


//SEE apartment_search.aspx
/* 
$(document).ready(function(){
     if (document.body.id == 'page_apartments_search') FCEAptSearch.init();

     $('#aptPanelSearchW2 > div').hoverClass('hover');

});
*/

