// Copyright (c) 2007 Gregory SCHURGAST (http://www.negko.com, http://prototools.negko.com)
// 
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// VERSION 1.2.20090820
var TableOrderer = Class.create();
TableOrderer.prototype = {
    initialize: function (a, b) {
        this.element = a;
        this.options = b;
        this.options = Object.extend({
            data: false,
            url: false,
            allowMultiselect: true,
            unsortedColumn: [],
            dateFormat: 'd',
            filter: false,
            pageCount: 5,
            paginate: false,
            search: false
        },
        b || {});
        this.tools = {
            page: 1,
            pages: 1,
            filterCol: '',
            filterData: '',
            searchData: ''
        };
        this.msgs = {
            loading: 'Loading...',
            emptyResults: 'No matches found',
            errorURL: 'invalid data',
            errorData: 'no data',
            //searchLabel: 'Filter by keyword : ',
			searchLabel: 'Filter by Transaction Name : ',
            filterLabel: 'Filter Column : ',
            paginationOf: ' of ',
            paginationPages: '',
            paginationFirst: '',
            paginationPrev: '',
            paginationNext: '',
            paginationLast: ''
        };
        this.cache = [];
        this.isCached = false;
        this.container = $(a);
        this.orderField = false;
        this.order = 'asc';
        this.thClickbfx = this.thClick.bindAsEventListener(this);
        this.thOverbfx = this.thOver.bindAsEventListener(this);
        this.thOutbfx = this.thOut.bindAsEventListener(this);
        this.setData()
    },
    clearCache: function () {
        this.isCached = false;
        this.cache = this.data;
        if (this.orderField) {
            this.orderData(this.orderField);
            if (this.order == 'desc') {
                this.cache = this.cache.reverse()
            }
        }
    },
    perform: function () {
        this.tools.pages = Math.ceil(this.cache.size() / this.options.pageCount);
        this.setColumnsName();
        this.clearCache();
        this.createTable()
    },
    getData: function (b) {
        var c = new Ajax.Request(b, {
            onLoading: function () {
                $(this.element).update(this.msgs.loading)
            }.bind(this),
            onSuccess: function (a) {
                this.data = a.responseJSON;
                this.perform()
            }.bind(this),
            onFailure: function () {
                alert(this.msgs.errorURL)
            }
        })
    },
    setData: function () {
        if (!this.options.data && !this.options.url) {
            alert(this.msgs.errorData)
        }
        this.data = this.options.data ? this.options.data : false;
        if (this.data) {
            this.perform()
        } else {
            this.getData(this.options.url)
        }
    },
    orderRule: function (s) {
        
		var a = /^(\d{2})[\/\- ](\d{2})[\/\- ](\d{4}|\d{2})/;
        var b = new RegExp(a);
        
		if (b.test(s)) {
            s = this.options.dateFormat == 'd' ? s.replace(a, "$3$2$1") : s.replace(a, "$3$1$2");
			return s;
        }
		
		        

        return s
		
    },

	orderRuleForAmount: function (s) {
		
		var withCurrency = /^(EUR|GBP|USD)([0-9\-\.]*)m/;
        var withCurrencyRegExp = new RegExp(withCurrency);
		
        if (withCurrencyRegExp.test(s)) {
			//console.log(s);
            s = parseFloat(s.replace(withCurrency, "$2"));
			//console.log(s);
			return s;
        } else {
			return 0;
		}
			
	},
	
	defineOrderField: function (e) {
        this.previousOrderField = this.orderField;
        this.orderField = Event.element(e).id.replace(this.table.id + '-', '')
    },
    defineOrder: function () {
        if (this.previousOrderField == this.orderField) {
            this.order = this.order == 'desc' ? 'asc' : 'desc'
        } else {
            this.order = 'asc'
        }
    },
    orderData: function (a) {
		
        this.cache = this.cache.sortBy(function (s) {
            var v = Object.values(s)[Object.keys(s).indexOf(a)];
			if (a == 'Amount') {
				return this.orderRuleForAmount(v)
			} else {
            	return this.orderRule(v)
			}
			
        }.bind(this))
    },
    thClick: function (e) {
        this.defineOrderField(e);
        this.defineOrder();
        this.orderData(this.orderField);
        if (this.order == 'desc') {
            this.cache = this.cache.reverse()
        }
        this.updateTable()
    },
    thOver: function (e) {
        Event.element(e).addClassName('on')
    },
    thOut: function (e) {
        Event.element(e).removeClassName('on')
    },
    trClick: function (e) {
        this.setSelected(Event.findElement(e, 'tr'));
        var b;
        var c = Event.findElement(e, 'tr').descendants().pluck('innerHTML');
       /* var d = '{';
        var f = Object.keys(this.model);
        c.each(function (i, a) {
            d += a === 0 ? '' : ', ';
            d += '"' + f[a] + '": "' + i + '"'
        });
        d += '}';
        b = d.evalJSON()*/
		
		
		
    },
    trOver: function (e) {
        Event.findElement(e, 'tr').addClassName('on')
    },
    trOut: function (e) {
        Event.findElement(e, 'tr').removeClassName('on')
    },
    setSelected: function (a) {
        if (this.options.allowMultiselect) {
            if (a.hasClassName('selected')) {
                a.removeClassName('selected')
            } else {
                a.addClassName('selected');
            }
        } else {
		}
		
		var link = a.down('td.data-grid-project-container-column-ProjectLink').down().innerHTML;
		window.open('http://' + window.location.hostname + '/infradeals/' + link);
		
		
		
    },
    addToolsObserver: function () {
        var a = this.table.id;
        if (this.options.filter) {
            var b = this.filterData.bindAsEventListener(this);
            Event.observe(a + '-filter-column', 'change', b);
            Event.observe(a + '-filter-data', 'keyup', b)
        }
        if (this.options.search) {
            var c = this.searchData.bindAsEventListener(this);
            var d = this.searchFocus.bindAsEventListener(this);
            Event.observe(a + '-search-data', 'keyup', c);
            Event.observe(a + '-search-data', 'focus', d)
        }
        if (this.options.paginate) {
            var e = this.pagerData.bindAsEventListener(this);
            var f = this.pagerBtns.bindAsEventListener(this);
            Event.observe(a + '-page-prev', 'click', e);
            Event.observe(a + '-page-next', 'click', e);
            Event.observe(a + '-page-last', 'click', e);
            Event.observe(a + '-page-first', 'click', e);
            Event.observe(a + '-page-prev', 'mouseover', f);
            Event.observe(a + '-page-next', 'mouseover', f);
            Event.observe(a + '-page-last', 'mouseover', f);
            Event.observe(a + '-page-first', 'mouseover', f);
            Event.observe(a + '-page-prev', 'mouseout', f);
            Event.observe(a + '-page-next', 'mouseout', f);
            Event.observe(a + '-page-last', 'mouseout', f);
            Event.observe(a + '-page-first', 'mouseout', f)
        }
    },
    addTableObserver: function () {
        var a = this.table.id;
        $$('#' + a + ' th').invoke('observe', 'click', this.thClickbfx).invoke('observe', 'mouseover', this.thOverbfx).invoke('observe', 'mouseout', this.thOutbfx);
        $$('#' + a + ' tr.data').invoke('observe', 'click', this.trClick.bindAsEventListener(this)).invoke('observe', 'mouseover', this.trOver.bindAsEventListener(this)).invoke('observe', 'mouseout', this.trOut.bindAsEventListener(this))
    },
    filterData: function (e) {
        var a = this.table.id;
        var b = Event.element(e);
        if (b.id == a + '-filter-column' && this.tools.filterData === '') {
            this.tools.filterCol = $F(a + '-filter-column');
            return
        }
        this.tools.filterData = $F(a + '-filter-data');
        if (b.id == a + '-filter-column') {
            $(a + '-filter-data').clear();
            this.tools.filterCol = $F(a + '-filter-column');
            this.tools.filterData = ''
        }
        this.clearCache();
        if (this.options.paginate) {
            this.updateTable();
            return
        }
        $$('#' + a + ' td.' + a + '-column-' + this.tools.filterCol).each(function (i) {
            i.ancestors()[1].show();
            if (!i.innerHTML.toUpperCase().include(this.tools.filterData.toUpperCase())) {
                i.ancestors()[1].hide()
            }
        })
    },
    pagerData: function (e) {
        var a = this.table.id;
        var b = Event.element(e);
        switch (b.id) {
        case a + '-page-next':
            this.tools.page = ((++this.tools.page) > this.tools.pages) ? --this.tools.page : this.tools.page;
            break;
        case a + '-page-prev':
            this.tools.page = ((--this.tools.page) > this.tools.pages) ? ++this.tools.page : this.tools.page;
            break;
        case a + '-page-last':
            this.tools.page = this.tools.pages;
            break;
        default:
            this.tools.page = 1
        }
        b.blur();
        this.updateTable()
    },
    searchData: function (e) {
        var a = this.table.id;
        this.tools.searchData = $F(a + '-search-data');
        this.clearCache();
        this.updateTable()
    },
    pagerBtns: function (e) {
        var a = this.table.id;
        var b = Event.element(e);
        switch (b.id) {
        case a + '-page-next':
            b.toggleClassName('next-page-button');
            b.toggleClassName('next-page-button-hover');
            break;
        case a + '-page-prev':
            b.toggleClassName('prev-page-button');
            b.toggleClassName('prev-page-button-hover');
            break;
        case a + '-page-last':
            b.toggleClassName('last-page-button');
            b.toggleClassName('last-page-button-hover');
            break;
        default:
            b.toggleClassName('first-page-button');
            b.toggleClassName('first-page-button-hover')
        }
    },
    searchFocus: function (e) {
        var a = this.table.id;
        if (this.tools.searchData !== '') {
            $(a + '-search-data').select()
        }
    },
    makeColumnUnsortable: function (a) {
        a = this.table.id + '-' + a;
        $(a).setStyle({
            'backgroundImage': 'none'
        });
        Event.stopObserving($(a), 'click', this.thClickbfx);
        Event.stopObserving($(a), 'mouseover', this.thOverbfx);
        Event.stopObserving($(a), 'mouseout', this.thOutbfx)
    },
    makeUnsort: function () {
        this.options.unsortedColumn.each(function (i) {
            if ($(this.table.id + '-' + i)) {
                this.makeColumnUnsortable(i)
            }
        }.bind(this))
    },
    createTable: function () {
        this.container.update();
        this.container.insert({
            top: '<table cellspacing="1" cellpadding="0" id="data-grid-' + this.element + '" class="prototools-table"></table>'
        });
        this.table = $('data-grid-' + this.element);
        this.createTools();
        this.createRows();
        this.addToolsObserver();
        this.addTableObserver();
        this.makeUnsort();
    },
    updateTable: function () {
        this.table = $('data-grid-' + this.element);
        $(this.table.id).update();
        this.createRows();
        this.addTableObserver();
        this.makeUnsort()
    },
    createRow: function (b, c) {
        var d = c % 2;
        var e = '<tr class="data line' + d + '" id="' + this.table.id + '-' + c + '">\n';
        var f = Object.values(b);
		
        this.tableColumnsName.each(function (s, a) {
            e += '\t<td class="' + this.table.id + '-column-' + s + '"><span>' + f[a] + '</span></td>\n'
        }.bind(this));
        e += '\n</tr>';
		
        return e
		
		
    },
    createFirstRow: function (a) {
        var b = '<tr>\n';
        this.tableColumnsName.each(function (i) {
            b += '\t<th id="' + this.table.id + '-' + i + '">' + i.replace('_', ' ').capitalize() + '</th>'
        }.bind(this));
        b += '\n</tr>';
        this.model = Object.clone(a);
        return b
    },
    setColumnsName: function () {
        this.tableColumnsName = Object.keys(this.data[0])
    },
    createFilter: function () {
        var a = '';
        this.tableColumnsName.each(function (i) {
            a += '\t<option value="' + i + '">' + i.replace('_', ' ').capitalize() + '</option>\n'
        });
        $(this.table.id + '-options').insert({
            bottom: this.msgs.filterLabel
        }).insert({
            bottom: '<select id="' + this.table.id + '-filter-column">' + a + '</select>'
        }).insert({
            bottom: '<input type="text" id="' + this.table.id + '-filter-data"/>'
        });
        this.tools.filterCol = $F(this.table.id + '-filter-column');
        this.tools.filterData = $F(this.table.id + '-filter-data')
    },
    createPager: function () {
        $(this.table.id + '-pager').insert({
            bottom: '<input id="' + this.table.id + '-page-first" type="button" value="' + this.msgs.paginationFirst + '" class="first-page-button"/>'
        }).insert({
            bottom: '<input id="' + this.table.id + '-page-prev" type="button" value="' + this.msgs.paginationPrev + '" class="prev-page-button"/>'
        }).insert({
            bottom: '<span id="' + this.table.id + '-page-current' + '" class="currentpage">' + this.tools.page + '</span>'
        }).insert({
            bottom: this.msgs.paginationOf + '<span id="' + this.table.id + '-page-total' + '" class="totalpages">' + this.tools.pages + '</span>' + this.msgs.paginationPages
        }).insert({
            bottom: '<input id="' + this.table.id + '-page-next" type="button" value="' + this.msgs.paginationNext + '" class="next-page-button"/>'
        }).insert({
            bottom: '<input id="' + this.table.id + '-page-last" type="button" value="' + this.msgs.paginationLast + '" class="last-page-button"/>'
        })
    },
    createSearch: function () {
        $(this.table.id + '-search').insert({
            bottom: this.msgs.searchLabel
        }).insert({
            bottom: '<input type="text" id="' + this.table.id + '-search-data" value=""/>'
        });
        this.tools.searchData = ''
    },
    createTools: function () {
        var a, pagerDiv, searchDiv;
        if (this.options.filter) {
            if (this.options.filter == 'top') {
                this.table.insert({
                    before: '<div id="' + this.table.id + '-options" class="prototools-options"></div>'
                })
            } else {
                this.table.insert({
                    after: '<div id="' + this.table.id + '-options" class="prototools-options"></div>'
                })
            }
            this.createFilter()
        }
        if (this.options.search) {
            if (this.options.search == 'top') {
                this.table.insert({
                    before: '<div id="' + this.table.id + '-search" class="prototools-search"></div>'
                })
            } else {
                this.table.insert({
                    after: '<div id="' + this.table.id + '-search" class="prototools-search"></div>'
                })
            }
            this.createSearch()
        }
        if (this.options.paginate) {
            if (this.options.paginate == 'top') {
                this.table.insert({
                    before: '<div id="' + this.table.id + '-pager" class="prototools-pager"></div>'
                })
            } else {
                this.table.insert({
                    after: '<div id="' + this.table.id + '-pager" class="prototools-pager"></div>'
                })
            }
            this.createPager()
        }
    },
    createRows: function () {
        var e = 1;
        var f, enddisplay, startdisplay, dataView, dat, col, searchStr, row, s;
        this.table.insert({
            top: this.createFirstRow()
        });
        dataView = this.cache;
        if (this.options.filter && !this.isCached && this.tools.filterData !== '') {
            col = this.tools.filterCol;
            dat = this.tools.filterData.toUpperCase();
            dataView = [];
            dataView = this.cache.inject([], function (a, b, c) {
                if (b[col].toString().toUpperCase().include(dat)) {
                    a.push(b)
                }
                return a
            })
        }
        if (this.options.search && !this.isCached && this.tools.searchData !== '') {
            dat = this.tools.searchData.toUpperCase();
            dataView = dataView.inject([], function (b, c, d) {
                searchStr = Object.values(c).inject('', function (a, n) {
                    return a + " " + n
                });
                if (searchStr.toUpperCase().include(dat)) {
                    b.push(c)
                }
                return b
            })
        }
        f = dataView;
        if (this.options.paginate) {
            this.tools.pages = Math.ceil(dataView.size() / this.options.pageCount);
            if (this.tools.page > this.tools.pages) {
                this.tools.page = this.tools.pages
            }
            if (this.tools.page < 1) {
                this.tools.page = 1
            }
            if (this.tools.pages === 0) {
                this.tools.page = 0
            }
            $(this.table.id + '-page-current').update(this.tools.page);
            $(this.table.id + '-page-total').update(this.tools.pages);
            startdisplay = this.options.pageCount * (this.tools.page - 1);
            enddisplay = this.options.pageCount * this.tools.page;
            f = dataView.slice(startdisplay, enddisplay)
        }
        f.each(function (i, a) {
            this.table.insert({
                bottom: this.createRow(i, a)
            });
            e = (e == 1) ? 2 : 1
        }.bind(this));
        if (f.size() === 0) {
            s = this.tableColumnsName.size();
            row = '<tr class="data line0" id="' + this.table.id + '-0">\n';
            row += '\t<td class="' + this.table.id + '-column" colspan="' + s + '">' + this.msgs.emptyResults + '</td>\n';
            row += '\n</tr>';
            this.table.insert({
                bottom: row
            })
        }
        if (this.orderField) {
            $(this.table.id + '-' + this.orderField).addClassName(this.order)
        }
        if (!this.isCached) {
            this.isCached = true;
            this.cache = dataView
        }
		
		//dealLink();
		replaceText();
    }
};