﻿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;

    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 addFavorite() {
        this.favoritePanel.add({ url: listings[0].url, description: String.format('{0} {1}, {2}, {3} {4}', listings[0].street_num, listings[0].street, listings[0].city, listings[0].state, listings[0].zip) });
        Ext.MessageBox.alert('Favorites', 'Listing Added Succesfully');
    }

    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);

        if (Ext.get('userSearch_container')) {
            favoritePanel = new RE.CookiePanel({
                collapsible: false,
                title: 'Favorite Listings',
                key: "url",
                renderTo: 'userSearch_container',
                tpl: new Ext.Template('<li class="re-favorite-item"><a href="{url}" title="{description}">{description:ellipsis(40)}</a></li>'),
                width: 300,
                baseCls: 're-panel'
            });
            favoritePanel.load('favorite_listings');

            recentPanel = new RE.CookiePanel({
                collapsible: false,
                title: 'Recent Searches',
                key: "url",
                max: 10,
                renderTo: 'userSearch_container',
                tpl: new Ext.Template('<li class="re-recent-item"><a href="{url}" title="{description}">{index}. {description:ellipsis(40)}</a></li>'),
                width: 300,
                baseCls: 're-panel'
            });
            recentPanel.load('recent_search');
        }
    }
    Ext.onReady(function() {
        initializePage();
    });