
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: 20, showArrows: true, arrowSize: 10 },
    scrollbarOpts2: { scrollbarWidth: 5, scrollbarMargin: 20, showArrows: true, arrowSize: 10 },


    /**
    * 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').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].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 : '-') + '</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);
            var bedblock = $('#aptSearchTrigger_' + this.beds);

            $('#aptPanelW3').appendTo(bedblock).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();
        }

    },

    /**
    * 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');

        $('#aptPanel2').show();

        var aptkey = $(this).attr('key');
        var floor = $(this).attr('floor');

        FCEAptSearch.renderAptDetails(aptkey, floor);

        // load the scrollbar on the apt-detail text if needed
        $('#aptDetail div.scrollContainer').jScrollPane(FCEAptSearch.scrollbarOpts2);

        /* for LC only: saf2 won't move the "make appointment" button if it needs to */
        if (jQuery.browser.safari && jQuery.browser.version < 500) {
            $('#btnMakeAppt').css('top', $('#aptPanelSearchDetail').height() + 10);
        }


    },

    /**
    * 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 */
            $('#aptPanel3').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));
            $('#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);
            FCEAptSearch.renderAptInfoDialog(aptkey);
            
        }
        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', '');
            $('#aptPanel3').hide();
            $('#aptPointerW').hide();
        }

        /* set the floor plate based only on the floor */
       

    },


    /**
    * 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');
            var building = aptInfo.aptnum.substr(0, 2);
            this.renderFloorPlate(building);
            var pos = FCEAptPointerPositioning.getPosByApt(building, subunit);
            if (!pos) {
                $('#aptPointer').hide();
            }
            else {
                $('#aptPointerW').css('left', pos.x + parseInt($('#aptPointerOffset').css('left')));
                $('#aptPointerW').css('top', pos.y + parseInt($('#aptPointerOffset').css('top')));
                $('#aptPointer').addClass(pos.ord).show();
            }
            $('#aptPointer/h4').empty().prepend(aptInfo.hdr);
            $('#aptPointerW').show();
        }
        else {
            $('#aptInfoDialogW').hide();
            $('#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(building) {
        if (FCE_FLOORS_PLATES[building]) {
        var plate = FCE_FLOORS_PLATES[building]; // 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="">');
        }
    },


    renderFloorplanOverlay: function() {

        // create overlay and panel nodes
        $('#contentW').append('<div id="ssOverlayW"><div id="ssOverlay"><div class="inset" id="fpOverlayPanel"></div></div></div>');
        // copy header listing and description to panel
        $('#aptDetail h4').clone().appendTo('#ssOverlay .inset');
        var listingDetail = $('#aptDetail .scrollContainer').html();
        $('#ssOverlay .inset').append(listingDetail);

        // mark the last list item for css
        $('#ssOverlay .inset .listing li:last').addClass('last');

        // wrap a .scrollContainer around the panel contents and initiate the scroller
        $('#ssOverlay .inset').wrapInner('<div class="scrollContainer"></div>');
        // no delay on scroller causes it to have height=0 in FF
        window.setTimeout("$('#ssOverlay .scrollContainer').jScrollPane(FCEAptSearch.scrollbarOpts2);", 100);

        // append CLOSE btn last
        $('#ssOverlay .inset').append('<div class="closewin">CLOSE</div>');

        // add floorplan image
        $('#ssOverlay').append('<img class="floorplan" src="' + $(this).attr('href') + '" />');
        $('#ssOverlayW').fadeIn('fast');

        // bind close link to fade out the overlay and then remove the whole overlay from the DOM when complete.
        $('#ssOverlay .inset .closewin').bind('click', function() { $('#ssOverlayW').fadeOut('fast', function() { $(this).remove(); }) });
        return false;
    },

    /**
    * setup handlers and scrollers
    */
    init: function() {

        $('#aptPanelW1 div.aptBedsSelect *').bind('click', function(e) {

            $(this).blur();

            var bedsNode = $(this).parents('.aptBedsSelect');
            FCEAptSearch.set_beds(bedsNode.attr('id').split('_')[1]);

            if (FCEAptSearch.filter_avail) FCEAptSearch.searchAvailable();
            else FCEAptSearch.searchAll();

            $('#aptPanelW1 div.aptBedsSelect').removeClass('sel').addClass('deselected').find('p').show();
            $(bedsNode).addClass('sel').removeClass('deselected').find('p').hide();
            return false;
        });

        this.searchTriggerAvail = $('#aptPanelW3 > div.filter > div.avail');
        this.searchTriggerAvail.bind('click', function(e) {
            if (!FCEAptSearch.filter_avail) {
                FCEAptSearch.searchAvailable();
            }
        });

        this.searchTriggerAll = $('#aptPanelW3 > div.filter > div.all');
        this.searchTriggerAll.bind('click', function(e) {
            if (FCEAptSearch.filter_avail) {
                FCEAptSearch.searchAll();
            }
        });


        $('#aptPlanEnlargeLink a').bind('click', FCEAptSearch.renderFloorplanOverlay);

    }

};



$(document).ready(function(){
     if (document.body.id == 'page_apartments_search') FCEAptSearch.init();
});


