
var FCEAptSearch = {

    beds: null,
    filter_avail: true,
    currApt: null, //Current apartment key (into JSON obj)
    currUnitID: null,  //current unitid (realpage)/non-user-friendly


    scrollbarOpts: { scrollbarWidth: 7, scrollbarMargin: 20, showArrows: true, arrowSize: 10 },
    scrollbarOpts2: { scrollbarWidth: 7, scrollbarMargin: 3, showArrows: true, arrowSize: 8 },


    /**
    * 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() {
        $('#aptPanelChooseNotice').hide();

        var apts = FCEAptDataRetriever.fetchAptListings(this.beds, this.filter_avail);

        if (apts.length > 0) {
            $('#aptSearchResults > tbody').empty();
            $('#aptPanelW3 > div.filter').show();

            for (var a in apts) {
                var row ='';
                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>');
            }
            $('#aptSearchResults > tbody > tr').bind('click', FCEAptSearch.select);
            $('#aptPanelW3').find('table').show();

            // click the first item, per req:
            var kids = $('#aptSearchResults > tbody').children();
            $(kids[0]).click();
        } else {
            $('#aptSearchResults > tbody').empty();
            $('#aptSearchResults > tbody').append('<tr><td>Please contact us for apartment<br /> availability</td></tr>');
            $('#aptPanelW3').find('table').show();
        }
        /* reloads the scrollbar, will appear only when needed */
        $('#aptPanelW3').find('div.scrollContainer').jScrollPane(this.scrollbarOpts);
        $('#outW2').addClass('aptSearchIsActive'); // for OFT because it needs a new background when details are showing

    },

    /**
    * 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');
        $('#aptPanelSearchIntro').hide();

        $('#aptPanelSearchDetailW').show();

        var aptkey = $(this).attr('key');
        var floor = $(this).attr('floor');

        FCEAptSearch.renderAptDetails(aptkey, floor);
        FCEAptSearch.renderAptInfoDialog(aptkey, floor);
    },

    /**
    * 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);
            // re-initializes the scroller
            $('#aptDetail').find('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();
        }
    },


    /**
    * 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) {

        var aptInfo = FCEAptDataRetriever.fetchAptInfo(aptkey);

        $('#aptPointer').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 pos = FCEAptPointerPositioning.getPosByApt(aptInfo.floor, 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 {
            $('#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;
    },

    /**
    * setup handlers and scrollers
    */
    init: function() {

        $('#aptTypeSelections').children('div.btn').bind('click', function(e) {
            FCEAptSearch.set_beds($(this).attr('id').split('_')[1]);

            if (FCEAptSearch.filter_avail) FCEAptSearch.searchAvailable();
            else FCEAptSearch.searchAll();

            $('#aptTypeSelections').children('div.btn').removeClass('sel');
            $(this).addClass('sel');
        });

        this.searchTriggerAvail = $('#aptPanelW3 > div.filter > div.avail');
        this.searchTriggerAvail.bind('click', function(e) { FCEAptSearch.searchAvailable(); });

        this.searchTriggerAll = $('#aptPanelW3 > div.filter > 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').find('a.search').bind('click', function(e) {
            var beds = $(this).attr('href').match(/beds=(.*)$/)[1];
            if (beds) {
                FCEAptSearch.set_beds(beds);
                FCEAptSearch.search();

                $('#aptTypeSelections').children('div.btn').removeClass('sel');
                $('#aptSearchTrigger_' + beds).addClass('sel');
            }
            return false;
        });
    },

    renderFloorPlate: function(floor) {
        $('#aptFloorPlate').css('background-image', 'url(resources/Merc_' + floor + '_color.gif)');
        this.renderFloorIndicator(floor, '#aptPanelSearchDetailW > h3');
    },

    /* for OFT - make the <h3> here say "3rd FLOOR" or whatever */
    renderFloorIndicator: function(floor, selector) {
        var suf = 'th';
        if (floor % 10 == 1 && floor != 11) suf = 'st';
        if (floor % 10 == 2 && floor != 12) suf = 'nd';
        if (floor % 10 == 3 && floor != 13) suf = 'rd';
        $(selector).text(floor + suf + ' FLOOR')
    }

};



$(document).ready(function(){
     FCEAptSearch.init();
});


