﻿var oldonload = window.onload;
window.onload = function() {
    if (typeof (oldonload) == 'function') {
        oldonload();
    }
    prepareLinks();
}

var prepareLinks = function() {
    $('matrix').select('a').collect(function(a) {
        if ((a.readAttribute('href') || '').startsWith('/ajax.svc')) {
            a.observe('click', function(event) {
                propertylist(this);
                event.stop();
            });
        } return;
    });
}

var matrix = {
    a: null,
    o: null,
    d: null,
    dg: null,
    rt: new Template('<b>#{count} properties found for:</b> #{markets}, in #{area}'),
    pmRe: /pm=([\d,]+)&/i,
    dgRe: /dg=([\d]+)/i
}

var markets =
{
    1: 'College',
    2: 'Residential Rental',
    3: 'Residential Sales',
    4: 'Short Term Let',
    5: 'Holiday Home Rental',
    6: 'Property Abroad Sales',
    7: 'Commercial Rental',
    8: 'Commercial Sales',
    9: 'Land Site Rental',
    10: 'Land Site Sales',
    11: 'New Developments',
    12: 'Parking Let',
    13: 'Industrial New Developments'
}

var propertylist = function(a) {


    var href = a.readAttribute('href');
    var order = a.readAttribute('class').substr(5);
    if (matrix.a == null || matrix.d == null || href != matrix.a.readAttribute('href')) {
        Effect.Appear('loading');
        matrix.dg && Effect.Fade('dg_' + matrix.dg + '_tr');
        new Ajax.Request(href, {
            onSuccess: function(response) {
                Effect.Fade('loading');
                matrix.a = a;
                matrix.o = order;
                matrix.d = response.responseJSON.d;
                matrix.dg = matrix.dgRe.exec(matrix.a.readAttribute('href'))[1];
                buildList();
            },
            method: "get"
        });
    }
    else if (order != (matrix.o || '')) {
        matrix.a = a;
        matrix.o = order;
        matrix.dg = matrix.dgRe.exec(matrix.a.readAttribute('href'))[1];
        buildList();
    }
}

var buildList = function() {
    var m = matrix.pmRe.exec(matrix.a.readAttribute('href'))[1].split(',').collect(function(n) { return (markets[n] || ''); }).join(', ');
    $('resultcount').update(matrix.rt.evaluate({ count: matrix.d.length, markets: m, area: matrix.a.readAttribute('title') }));
    matrix.d.sort(compare);

    var table = Builder.node('table', { className: 'matrix-innertb' });

    var tbody = Builder.node('tbody', matrix.d.collect(function(n) {
        var a = $(Builder.node('a', { href: '/show-prop.aspx?id=' + n.Id }, [n.DisplayAddress]));
        return Builder.node('tr', { className: 'matrix-mouse' },
    [
        Builder.node('td', { className: 'matrix-inner-address' }, [a]),
        Builder.node('td', { className: 'matrix-inner-price' }, [n.PriceList[1] && a.clone(false).update(n.PriceList[1]) || '-']),
        Builder.node('td', { className: 'matrix-inner-price' }, [n.PriceList[2] && a.clone(false).update(n.PriceList[2]) || '-']),
        Builder.node('td', { className: 'matrix-inner-price' }, [n.PriceList[3] && a.clone(false).update(n.PriceList[3]) || '-']),
        Builder.node('td', { className: 'matrix-inner-price' }, [n.PriceList[4] && a.clone(false).update(n.PriceList[4]) || '-']),
        Builder.node('td', { className: 'matrix-inner-price' }, [n.PriceList[5] && a.clone(false).update(n.PriceList[5]) || '-']),
        Builder.node('td', { className: 'matrix-inner-price' }, [n.PriceList[6] && a.clone(false).update(n.PriceList[6]) || '-'])
    ]
    );
    }));
    table.appendChild(tbody);
    $('dg_' + matrix.dg + '_td').update(table);
    Effect.Appear('dg_' + matrix.dg + '_tr');

    var num = 0;
    var ul = Builder.node('ul', { className: 'repeater' }, matrix.d.collect(function(n) {
        return Builder.node('li', [Builder.node('div', { className: 'numeration' }, [++num]),
                                   Builder.node('div', { className: 'thumbs' }, [Builder.node('div', { className: 'main' }, [Builder.node('a', { href: '/show-prop.aspx?id=' + n.Id }, [Builder.node('div', { className: 'banner', style: n.Type[0] != 11 ? 'background-image: none;' : '' }),
                                                                                                                                                                                        Builder.node('img', { alt: 'View Property Details', border: '0', src: n.ThreePics[0] })
                                                                                                                                                                                       ]
                                                                                                                                         )
                                                                                                                            ]
                                                                                             ),
                                                                                 n.ThreePics[1] && Builder.node('div', { className: 'thumb' }, [Builder.node('a', { href: '#TODO_ADD_MOUSEOVER_JSCRIPT_HERE' }, [Builder.node('img', { src: n.ThreePics[1], style: ' width: 60px; height:40px' })])]) || '',
                                                                                 n.ThreePics[2] && Builder.node('div', { className: 'thumb' }, [Builder.node('a', { href: '#TODO_ADD_MOUSEOVER_JSCRIPT_HERE' }, [Builder.node('img', { src: n.ThreePics[2], style: ' width: 60px; height:40px' })])]) || '',
                                                                                 n.PicNum > 1 && Builder.node('span', [Builder.node('a', { href: '/show-prop.aspx?id=' + n.Id }, ['(', n.PicNum, ') photos'])]) || ''
                                                                                ]
                                               ),
                                   Builder.node('p', { className: 'display-address' }, [Builder.node('a', { href: '/show-prop.aspx?id=' + n.Id }, [n.DisplayAddress])]),
                                   Builder.node('p', { className: 'other-address' }, [n.District, ', ', n.County]),
                                   Builder.node('p', { className: 'bedroom' }, [n.Type[5]]),
                                   Builder.node('p', { className: 'description' }, [n.Description]),
                                   Builder.node('div', { className: 'prices-area' }, [Builder.node('div', [price(n)]),
                                                                                      Builder.node('a', { className: 'btn-add-favourites', onclick: 'openWin(this.href,425,325);return false;', href: '/save-prop.aspx?id=' + n.Id, target: '_blank', title: 'Add to Favourites' }, [Builder.node('span', { className: 'hidden' }, ['Add to Favourites'])]),
                                                                                      Builder.node('a', { className: 'btn-view-details', href: '/show-prop.aspx?id=' + n.Id }, [Builder.node('span', { className: 'hidden' }, ['View Details'])])
                                                                                     ])
                                  ]
                           );
    }));

    $('resultlist').update(ul);
}

var compare = function(a, b) {
    var result = 0;
    if (matrix.o != 0 && a.BedroomList[matrix.o] != b.BedroomList[matrix.o]) {
        result = matrix.o == a.BedroomList[matrix.o] ? -1 : 1;
    }
    else {
        result = a.DisplayAddress < b.DisplayAddress ? -1 : 1;
    }
    return result;
}

var status = function(type) {
    var r = type[3].replace('Has been Let', 'Rented');
    /*r = type[0] == 11 ? r + ' by Auction'*/
    r = type[0] == 11 ? r + ' '
    : r == 'For Sale' ? r + ' by Private Treat'
    : r == 'To Let' ? 'Letting'
    : r;
    return r;
}

var price = function(n) {
    var s = n.Type[3].replace('Has been Let', 'Rented');
    var m = n.Type[0];
    var r = n.Price;
    r = m == 11 ? [Builder.node('span', ['Prices From']), r]
    : [/*2,*/4, 5, 7, 9, 12].include(m) ? [r, ' (', n.Type[4], ')']
    : m == 2 ? [Builder.node('span', { style: 'line-height: 9px' }).update('&nbsp;'), r, Builder.node('span', ['Monthly'])]
    : ['Sale Agreed', 'Sold', 'Rented', 'Reserved'].include(s) ? [s]
    : [r];

    return r;
}
