﻿if (typeof (RE) == 'undefined')
{ Ext.namespace('RE'); }

if (typeof (RE.Forms) == 'undefined')
{ Ext.namespace('RE.Forms'); }

var bDetailPageIsInitialized = false;
/* handle image thumbnails */
var arImages;
var arThumbs;

var iImgIndex = 0;
var iThmbIndex = 0;
var iImgCnt = 0;
var thumbLeftArrow;
var thumbRightArrow;
var emailwin;
var rec;
function initializeEmail() {

    var button = Ext.get('emailLink');
    if (typeof (button) != 'undefined' && button != null) {
        button.on('click', function() {
            form_content = new Ext.FormPanel({
                labelWidth: 75, // label settings here cascade unless overridden
                url: '/handlers/email.ashx',
                frame: true,
                bodyStyle: 'padding:5px 5px 0',
                width: 550,

                items:
                [
                    {
                        xtype: 'fieldset',
                        title: 'Your Information',
                        autoHeight: true,
                        defaults: { width: 210 },
                        defaultType: 'textfield',
                        items:
                        [
                            { fieldLabel: 'Name', name: 'sender_name', allowBlank: false },
                            { fieldLabel: 'Email', name: 'sender_address', allowBlank: false, vtype: 'email' }
                        ]
                    },
                    {
                        xtype: 'fieldset',
                        title: 'Your Friend\'s Information',
                        autoHeight: true,
                        defaults: { width: 210 },
                        defaultType: 'textfield',
                        items:
                        [
                            { fieldLabel: 'Name', name: 'recipient_name', allowBlank: false },
                            { fieldLabel: 'Email', name: 'recipient_address', allowBlank: false, vtype: 'email' }
                        ]
                    },
                    {
                        cls: 'x-plain',
                        title: 'Comments',
                        layout: 'fit',
                        items: { xtype: 'htmleditor', id: 'comments', fieldLabel: 'Comments' }
                    }
                ],

                buttons:
                [
                    { text: 'Send', handler:
                        function() {
                            sender_name = form_content.getForm().findField('sender_name');
                            if (!sender_name.isValid())
                                return false;

                            sender_address = form_content.getForm().findField('sender_address');
                            if (!sender_address.isValid())
                                return false;

                            recipient_name = form_content.getForm().findField('recipient_name');
                            if (!recipient_name.isValid())
                                return false;

                            recipient_address = form_content.getForm().findField('recipient_address');
                            if (!recipient_address.isValid())
                                return false;

                            comments = form_content.getForm().findField('comments');

                            Ext.Ajax.request({
                                url: '/handlers/email.ashx',
                                params:
                                {
                                    listingid: listingId,
                                    sender_name: sender_name.getValue(),
                                    sender_address: sender_address.getValue(),
                                    recipient_name: recipient_name.getValue(),
                                    recipient_address: recipient_address.getValue(),
                                    comments: comments.getValue()
                                },
                                method: 'POST',
                                scope: this,
                                success: function(result, request) {
                                    responseObject = Ext.decode(result.responseText);

                                    if (responseObject.success) {
                                        Ext.MessageBox.alert('Success', 'Email has been succesfully sent');
                                    }
                                    else {
                                        Ext.MessageBox.alert('Failed', responseObject.errors.reason);
                                    }
                                },
                                failure: function(result, request) {
                                    Ext.MessageBox.alert('Failed', 'Failed posting to');
                                    this.el.unmask();
                                }
                            });
                            emailwin.close();
                        }
                    },
                    { text: 'Close', handler: function() { emailwin.close(); } }
                ]
            });

            emailwin = new Ext.Window({
                shadow: true,
                modal: true,
                width: 560,
                title: 'Email Listing',
                items: form_content,
                border: false,
                draggable: false,
                resizable: false,
                plain: true,
                hideBorders: true,
                animateTarget: 'emailLink'
            });

            emailwin.show(button);
        });
    }
}

function populateImageArray() {
    var imgCntElem = getAnElement('ImageCount');
    if (imgCntElem) {
        iImgCnt = imgCntElem.value;
    }
    var imagesElem = getAnElement('ImageArr');
    if (imagesElem) {
        var sImages = imagesElem.value;
        var thumbImagesElem = getAnElement('ThumbImageArr');
        if (thumbImagesElem) {
            var sThumbImages = thumbImagesElem.value;
            arImages = sImages.split(";");
            arThumbs = sThumbImages.split(";");
            var currentThumbElem = document.getElementById('currentThumb');
            if (currentThumbElem != null) {
                currentThumbElem.innerHTML = '1 ';
            }
            var totalThumbElem = document.getElementById('totalThumb');
            if (totalThumbElem != null) {
                totalThumbElem.innerHTML = iImgCnt;
            }
        }
    }
}

function setImageIndex(sImgUrl) {
    var sThumb;
    sThumb = sImgUrl.replace(/\\/g, "\\\\");
    for (index = 0; index < iImgCnt; index++) {
        if (arThumbs[index] == sThumb) {
            iImgIndex = index;
            break;
        }
    }

}

function moveImage(increment) {
    if (!bDetailPageIsInitialized) {
        populateImageArray();
        bDetailPageIsInitialized = true;
    }
    var newIndex = iImgIndex + increment;

    if (newIndex < 0) {
        return;
    } else if (newIndex > iImgCnt - 1) {
        return;
    }

    showImage(arThumbs[newIndex]);
    moveThumbs(increment);
}

function moveThumbs(increment) {
    if (!bDetailPageIsInitialized) {
        populateImageArray();
        bDetailPageIsInitialized = true;
    }

    if (iImgCnt > 5) {
        iThmbIndex += increment;
        for (index = 0; index < 5; index++) {
            var element = document.getElementById("thumbImage" + (index + 1));
            element.src = (arThumbs[iThmbIndex + index]).replace(/\\\\/g, "\\");
            element.onclick = new Function("showImage('" + arThumbs[iThmbIndex + index] + "')");
            if (element.captureEvents) element.captureEvents(Event.CLICK);
            element.onmouseover = new Function("showImage('" + arThumbs[iThmbIndex + index] + "')");
            if (element.captureEvents) element.captureEvents(Event.MOUSEOVER);
        }
        if (increment > 0) {
            showImage(arThumbs[iThmbIndex + 4]);
        }
        else {
            showImage(arThumbs[iThmbIndex]);
        }

        if (iThmbIndex == 0) {
            if (thumbLeftArrow)
            { thumbLeftArrow.setVisible(false); }
            showImage(arThumbs[0]);
        }
        else {
            if (thumbLeftArrow)
            { thumbLeftArrow.setVisible(true); }
        }
        if (iThmbIndex + 5 >= iImgCnt) //last 
        {
            if (thumbRightArrow)
            { thumbRightArrow.setVisible(false); }
        }
        else {
            if (thumbRightArrow)
            { thumbRightArrow.setVisible(true); }
        }
    }
    else {
        if (thumbRightArrow)
        { thumbRightArrow.setVisible(false); }
        if (thumbLeftArrow)
        { thumbLeftArrow.setVisible(false); }
    }

}

function showImage(sImgUrl) {
    if (!bDetailPageIsInitialized) {
        populateImageArray();
        bDetailPageIsInitialized = true;
    }

    setImageIndex(sImgUrl);
    var elem = Ext.get('property_thumb_big');
    var img = elem.child('img', true);
    img.src = arImages[iImgIndex];
}


function renderMapPanel(visibleMapType) {
    pnl = Ext.get("re-listing-mapview");
    this.mapPanel = new Ext.Panel({
        collapsible: true,
        collapsed: false,
        autoHeight: 300,
        baseCls: 're-listing-panel',
        applyTo: pnl,
        width: 617
    });

    var wrap = Ext.get("mapbox");
    if (!wrap) {
        wrap = this.mapPanel.body.createChild({
            tag: "div",
            cls: "re-map-wrap",
            id: "mapbox",
            height: 300,
            width: 617,
            style: "width:617px;height:300px;position:relative;"
        });
    }

    new Ext.util.DelayedTask(function() {
        renderMap(visibleMapType)
    }).delay(50);
}
function renderMap(visibleMapType) {
    svMap = new RE.Map({
        height: 300,
        width: 617,
        latitude: listings[0].lat,
        longitude: listings[0].lng,
        enableScrollWheelZoom: false,
        enableDragging: false,
        markerImage: '/ListingsWeb/App_Themes/RealEstate/Images/map/orangepin_blank.gif',
        renderTo: "mapbox",
        visibleMapType: (typeof (visibleMapType) != 'undefined' && visibleMapType != null) ? visibleMapType : VEMapStyle.Road
    });
    svMap.addMarker(listings[0].lat, listings[0].lng);
    svMap.setZoom(13);
}



function mapBtn_Click(evt, t, o) {
    if (!this.mapPanel) {
        renderMapPanel();

        var s = t.innerText.toggle('Show Map', 'Hide Map');
        t.innerText = s;
    }
    else {
        var s = t.innerText.toggle('Show Map', 'Hide Map');
        t.innerText = s;

        this.mapPanel.toggleCollapse(false);
    }
}

function initializePage() {

    initializeEmail();

    var mapBtn = Ext.get("re-button-mapview");
    if (mapBtn) {
        mapBtn.on('click', mapBtn_Click, this);
    }

    var pnl = Ext.get("re-listing-photos");
    if (pnl) {
        this.photos = new Ext.Panel({
            collapsible: true,
            collapsed: false,
            autoHeight: 300,
            baseCls: 're-listing-panel',
            applyTo: pnl
        });
    }

    populateImageArray();
    moveThumbs(0);
}

function addFavoriteAlert(listing) {
    if (RE.session.userName === 'anonymous') {

        RE.Login(null, function() { addFavoriteAlert(listing); });
        return;
    }

    var store = Ext.StoreMgr.lookup('SavedListingStore');
    var i = store.find('listingId', listing.id);
    var rec;

    if (i === -1) {
        rec = new RE.data.SavedListing({
            alertname: listing.full_address,
            listingId: listing.id,
            frequency: 2
        });
    }
    else {
        rec = store.getAt(i);
    }

    RE.form.SavedListing.load(rec);
}

function bindStoreEvents() {
    var store = Ext.StoreMgr.lookup('SavedListingStore');
    if (store) {
        store.on({
            load: dataChangedHandler,
            update: dataChangedHandler,
            remove: dataChangedHandler,
            add: dataChangedHandler
        });
    }
}
function dataChangedHandler(store) {
    if (RE.session.userName === 'anonymous')
        return;

    var listing = listings[0];
    var i = store.find('listingId', listing.id);
    var favEl = Ext.get('hrefCreateBookmark');
    var commentsEl = Ext.get('comments_ph');
    var rec;

    if (i === -1) {
        rec = new RE.data.SavedListing({ alertname: listing.full_address, listingId: listing.id, frequency: 2 });

        if (favEl)
            favEl.update('(+) Add To Favorites');

        if (commentsEl)
            commentsEl.update('');
    }
    else {
        rec = store.getAt(i);

        if (favEl)
            favEl.update('(+) Edit Favorite');

        if (commentsEl) {
            var commentsdh = {
                tag: 'div',
                id: 'alert_comments',
                cls: 'block comments',
                children: {
                    tag: 'div',
                    cls: 'squeeze',
                    children:
                [
                    { tag: 'p', cls: 'title', html: 'MyComments' },
                    {
                        tag: 'div',
                        cls: 'body',
                        children:
                        {
                            tag: 'ul',
                            children:
                            [
                                { tag: 'li', cls: 'item', html: rec.data.comments },
                                {
                                    tag: 'li',
                                    cls: 'item',
                                    children:
                                    [
                                        { tag: 'br' },
                                        { tag: 'a', html: 'Edit Comment', href: 'javascript:void(0);' }
                                    ]
                                }
                            ]
                        }
                    }
                ]
                }
            };
            Ext.DomHelper.overwrite(commentsEl, commentsdh);
            commentsEl.child('a').on('click', function() { addFavoriteAlert(listing); });
        }
    }
}
function calculateMortgagePayment(listing) {

    var listingPrice = 0;
    if (typeof(listing) != 'undefined' && typeof(listing.price) != 'undefined')
        listingPrice = listing.price.replace(/[^0-9]/g, '');
    OpenPopup('/HomeLoans/Calculators/SingleCalculator.aspx?tab=Mortgage-Payment&bare=1&loan_type=1&loan_term=30&interest_rate=5&loan_amount=' + listingPrice,
        null, 500, 700, 'no');
//    this.calcWin = new Ext.Window({
//        width: 500,
//        height: 700,
//        baseCls: 're-nowindow',
//        cls: 're-calculator',
//        closeAction: 'close',
//        shadow: false,
//        modal: true,
//        autoLoad: { url: '/HomeLoans/Calculators/BareCalculator.aspx?tab=Mortgage-Payment&bare=1&loan_type=1&loan_term=30&interest_rate=5&loan_amount=' + listingPrice},
//        border: false,
//        draggable: false,
//        resizable: false,
//        plain: true
//    });
//    this.calcWin.show();
//    this.calcWin.setActive(true);
}

Ext.onReady(function() {

    bindStoreEvents();

    initializePage();
});

Ext.addBehaviors({
'.toolbar #hrefCreateBookmark@click': function() { addFavoriteAlert(listings[0]); }
,'.toolbar #hrefCalcMortgage@click': function() { calculateMortgagePayment(listings[0]); }
});

RE.EventManager.onLoggedIn(function(options) {
    bindStoreEvents();
});


