if( !tick ) {
    var tick = function(){};
}
function windowOpen (earl){
    window.open(earl, 'jsWindow',"height=650,width=800,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes");
}
function getPostcode (postcode, addressField){
    windowOpen('/popups/postcode.inc.php?postcode='+ postcode +'&addressField='+addressField);
}
function getFNOLPostcode (clickedID){
    windowOpen('/popups/fnolPostcode.inc.php?clickedID='+ clickedID);
}
function copyFrom (from, to){
    if (from) from = from + '_';
    else from = '';
    if (to) to = to + '_';
    else to = '';
    $('#' + to + 'address1').val($('#' + from + 'address1').val());
    $('#' + to + 'address2').val($('#' + from + 'address2').val());
    $('#' + to + 'address3').val($('#' + from + 'address3').val());
    $('#' + to + 'address4').val($('#' + from + 'address4').val());
    $('#' + to + 'postcode').val($('#' + from + 'postcode').val());
    $('#' + to + 'phone').val($('#' + from + 'phone').val());
    $('#' + to + 'name').val($('#' + from + 'name').val());
}

function saveComplaintNote (){
    $('.complaintText').each(function(){
        $complaint_note = $(this).val();
        $complaint_log_id = $(this).attr('complaint_id');
        if ($complaint_note != ''){
            $.ajax({
                url: '/ajax/claimSaveComplaintNote',
                data : {
                    status : $complaint_note,
                    complaint_log_id : $complaint_log_id
                },
                type: 'POST',
                async:   false
            });
        }
    });
    
}
function saveStatus(incident_id){
    var latestStatus = $('#statusText').val();
    var statusCode = $('#status_code').val();
    var assigned_user = $('#assigned_user').val();
    var chaseDate = $('#chase_date').val();
    var chaseTime = $('#chase_time').val();
    if (latestStatus != ''){
        $.ajax({
            type: 'POST',
            url: '/ajax/claimSaveStatusUpdate',
            async: false,
            data: {
                status : latestStatus,
                status_code : statusCode,
                chase_date : chaseDate,
                chase_time : chaseTime,
                assigned_user : assigned_user,
                incident_id : incident_id
            },
            success: function (jsonData){
                $('#statusUpdates tr.header').after('<tr><td>'+ jsonData.updateDate +'</td><td>'+ jsonData.updateTime +'</td><td>'+ jsonData.name +'</td><td>'+ jsonData.status_code +'</td><td>'+ jsonData.chase_date +'</td><td>'+ jsonData.status +'</td></tr>');
                $('#statusText').val('');
            },
            dataType: "json"
        });

    }
}
function deleteStatus (status_id){
    if (confirm('Are you sure you want to delete this status update?')){
        $.post('/ajax/claimDeleteStatusUpdate', {
            id : status_id
        }, function (jsonData){
            $('#status_' + status_id).hide('slow');
        }, 'json');
    }
}
function ajaxFileUpload(incident_id, comment){
    $("#loadingIcon").ajaxStart(function(){
        $(this).show();
    })
    $.ajaxFileUpload({
        url:'/ajax/claimSaveFile/incident_id='+ incident_id + '&comment='+comment,
        secureuri:false,
        fileElementId:'fileToUpload',
        dataType: 'json',
        success: function (){},
        error: function (data, status, e){
        }
    }
)
    return false;
}

var bounds;
var map

function createMap (){
    var map = new GMap2(document.getElementById('map1'));
    map.setCenter(new GLatLng(53.448193, -2.331419), 13);
    map.addControl(new GSmallMapControl());
    map.setMapType(G_NORMAL_MAP);
    bounds = new GLatLngBounds();
    return map;
};
function createIcon (iconName, size) {
    if (!iconName) iconName = "map_car";
    var icon = new GIcon();
    icon.image = "/images/map_icons/" + iconName + ".gif";
    icon.shadow = "/images/map_icons/" + iconName + ".gif";
    icon.iconSize = new GSize(size, size);
    icon.shadowSize = new GSize(1, 1);
    icon.iconAnchor = new GPoint(7, 7);
    icon.infoWindowAnchor = new GPoint(22, 10);
    return icon;
}
function createMarker(point, infoTabs, iconName, final) {
    bounds.extend(point);
    var marker = new GMarker(point, iconName);
    map.addOverlay(marker);
    GEvent.addListener(marker, "click", function(){
        marker.openInfoWindowTabsHtml(infoTabs);
        //map.setCenter(marker.getPoint());
    });
}
function setRepairer (repairerName, repairerID){
    //alert('repairer id: ' + repairerID);
    window.opener.document.getElementById('repairerName').innerHTML = repairerName;
    window.opener.document.getElementById('repairer_id').value = repairerID;
    window.close();
}
function checkdocspelling2() {
    try {
        var tmpis = new ActiveXObject("ieSpell.ieSpellExtension");
        return tmpis.CheckAllLinkedDocuments2(document, true);
    } catch(exception) {
        if (is_ie&&is_win) {
            window.open("http://www.iespell.com/download.php","Download");
        }
    }
}

var myAgent = navigator.userAgent.toLowerCase();
var myVersion = parseInt(navigator.appVersion);

var is_ie = ((myAgent.indexOf("msie") != -1) 
    && (myAgent.indexOf("opera") == -1));
var is_nav = ((myAgent.indexOf('mozilla')!=-1) 
    && (myAgent.indexOf('spoofer')==-1)
    && (myAgent.indexOf('compatible') == -1)
    && (myAgent.indexOf('opera')==-1)
    && (myAgent.indexOf('webtv') ==-1)
    && (myAgent.indexOf('hotjava')==-1));

var is_win = ((myAgent.indexOf("win")!=-1) 
    || (myAgent.indexOf("16bit")!=-1));

var is_mac = (myAgent.indexOf("mac")!=-1);

//this function uses the more advanced node spell check method that does not
//prompts the user with the "Spell Check Completed" message as well as returning a
//FALSE if the user cancels the spell check.
function checknodespelling2(node) {
    try {
        var tmpis = new ActiveXObject("ieSpell.ieSpellExtension");
        return tmpis.CheckDocumentNode2(node, true);
    } catch(exception) {
        if (is_ie&&is_win) {
            window.open("http://www.iespell.com/download.php","Download");
        }
    }
}

function checknodespelling(node) {
    try {
        var tmpis = new ActiveXObject("ieSpell.ieSpellExtension");
        tmpis.CheckDocumentNode(node);
    } catch(exception) {
        if (is_ie&&is_win) {
            window.open("http://www.iespell.com/download.php","Download");
        }
    }
}

function spellcheck (objName){
    oEditor = FCKeditorAPI.GetInstance(objName);
    oEditor.Commands.GetCommand('SpellCheck').Execute();
}

/*
        TableSort revisited v5.0 by frequency-decoder.com

        Released under a creative commons Attribution-ShareAlike 2.5 license (http://creativecommons.org/licenses/by-sa/2.5/)

        Please credit frequency decoder in any derivative work - thanks

        You are free:

        * to copy, distribute, display, and perform the work
        * to make derivative works
        * to make commercial use of the work

        Under the following conditions:

                by Attribution.
                --------------
                You must attribute the work in the manner specified by the author or licensor.

                sa
                --
                Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under a license identical to this one.

        * For any reuse or distribution, you must make clear to others the license terms of this work.
        * Any of these conditions can be waived if you get permission from the copyright holder.
*/

(function() {
fdTableSort = {
        regExp_Currency:        /^[£$€¥¤]/,
        regExp_Number:          /^(\-)?[0-9]+(\.[0-9]*)?$/,
        pos:                    -1,
        uniqueHash:             1,
        thNode:                 null,
        tableId:                null,
        tableCache:             {},
        tmpCache:               {},
        sortActiveClass:        "sort-active",
        /*@cc_on
        /*@if (@_win32)
        colspan:                "colSpan",
        rowspan:                "rowSpan",
        @else @*/
        colspan:                "colspan",
        rowspan:                "rowspan",
        /*@end
        @*/
        
        addEvent: function(obj, type, fn, tmp) {
                tmp || (tmp = true);
                if( obj.attachEvent ) {
                        obj["e"+type+fn] = fn;
                        obj[type+fn] = function(){obj["e"+type+fn]( window.event );};
                        obj.attachEvent( "on"+type, obj[type+fn] );
                } else {
                        obj.addEventListener( type, fn, true );
                };
        },
        removeEvent: function(obj, type, fn, tmp) {
                tmp || (tmp = true);
                try {
                        if( obj.detachEvent ) {
                                obj.detachEvent( "on"+type, obj[type+fn] );
                                obj[type+fn] = null;
                        } else {
                                obj.removeEventListener( type, fn, true );
                        };
                } catch(err) {};
        },
        stopEvent: function(e) {
                e = e || window.event;

                if(e.stopPropagation) {
                        e.stopPropagation();
                        e.preventDefault();
                };
                
                /*@cc_on@*/
                /*@if(@_win32)
                e.cancelBubble = true;
                e.returnValue  = false;
                /*@end@*/
                return false;
        },
        parseClassName: function(head, tbl) {
                var colMatch = tbl.className.match(new RegExp(head + "((-[\\d]+([r]){0,1})+)"));
                return colMatch && colMatch.length ? colMatch[0].replace(head, "").split("-") : [];
        },
        disableSelection: function(element) {
                element.onselectstart = function() {
                        return false;
                };
                element.unselectable = "on";
                element.style.MozUserSelect = "none";
        },
        removeTableCache: function(tableId) {
                if(!(tableId in fdTableSort.tableCache)) return;

                fdTableSort.tableCache[tableId] = null;
                delete fdTableSort.tableCache[tableId];

                var tbl = document.getElementById(tableId);
                if(!tbl) return;
                var ths = tbl.getElementsByTagName("th");
                var a;
                for(var i = 0, th; th = ths[i]; i++) {
                        a = th.getElementsByTagName("a");
                        if(a.length) a[0].onkeydown = a[0].onclick = null;
                        th.onclick = th.onselectstart = th = a = null;
                };
        },
        removeTmpCache: function(tableId) {
                if(!(tableId in fdTableSort.tmpCache)) return;
                var headers = fdTableSort.tmpCache[tableId].headers;
                var a;
                for(var i = 0, row; row = headers[i]; i++) {
                        for(var j = 0, th; th = row[j]; j++) {
                                a = th.getElementsByTagName("a");
                                if(a.length) a[0].onkeydown = a[0].onclick = null;
                                th.onclick = th.onselectstart = th = a = null;
                        };
                };
                fdTableSort.tmpCache[tableId] = null;
                delete fdTableSort.tmpCache[tableId];
        },
        initEvt: function(e) {
                fdTableSort.init(false);
        },
        init: function(tableId) {
                if (!document.getElementsByTagName || !document.createElement || !document.getElementById) return;

                var tables = tableId && document.getElementById(tableId) ? [document.getElementById(tableId)] : document.getElementsByTagName("table");
                var c, ii, len, colMatch, showOnly, match, showArrow, columnNumSortObj, obj, workArr, headers, thtext, aclone, multi, colCnt, cel, allRowArr, rowArr, sortableTable, celCount, colspan, rowspan, rowLength;

                var a          = document.createElement("a");
                a.href         = "#";
                a.className    = "fdTableSortTrigger";

                var span       = document.createElement("span");

                for(var k = 0, tbl; tbl = tables[k]; k++) {

                        if(tbl.id) {
                                fdTableSort.removeTableCache(tbl.id);
                                fdTableSort.removeTmpCache(tbl.id);
                        };

                        allRowArr     = tbl.getElementsByTagName('thead').length ? tbl.getElementsByTagName('thead')[0].getElementsByTagName('tr') : tbl.getElementsByTagName('tr');
                        rowArr        = [];
                        sortableTable = false;

                        for(var i = 0, tr; tr = allRowArr[i]; i++) {
                                if(tr.getElementsByTagName('td').length || !tr.getElementsByTagName('th').length) { continue; };
                                rowArr[rowArr.length] = tr.getElementsByTagName('th');
                                for(var j = 0, th; th = rowArr[rowArr.length - 1][j]; j++) {
                                        if(th.className.search(/sortable/) != -1) { sortableTable = true; };
                                };
                        };

                        if(!sortableTable) continue;

                        if(!tbl.id) { tbl.id = "fd-table-" + fdTableSort.uniqueHash++; };

                        showArrow   = tbl.className.search("no-arrow") == -1;
                        showOnly    = tbl.className.search("sortable-onload-show") != -1;

                        columnNumSortObj = {};
                        colMatch         = fdTableSort.parseClassName(showOnly ? "sortable-onload-show" : "sortable-onload", tbl);
                        for(match = 1; match < colMatch.length; match++) {
                                columnNumSortObj[parseInt(colMatch[match], 10)] = { "reverse":colMatch[match].search("r") != -1 };
                        };

                        rowLength = rowArr[0].length;

                        for(c = 0;c < rowArr[0].length;c++){
                                if(rowArr[0][c].getAttribute(fdTableSort.colspan) && rowArr[0][c].getAttribute(fdTableSort.colspan) > 1){
                                        rowLength = rowLength + (rowArr[0][c].getAttribute(fdTableSort.colspan) - 1);
                                };
                        };

                        workArr = new Array(rowArr.length);
                        for(c = rowArr.length;c--;){ workArr[c]= new Array(rowLength); };

                        for(c = 0;c < workArr.length;c++){
                                celCount = 0;
                                for(i = 0;i < rowLength;i++){
                                        if(!workArr[c][i]){
                                                cel = rowArr[c][celCount];
                                                colspan = (cel.getAttribute(fdTableSort.colspan) > 1) ? cel.getAttribute(fdTableSort.colspan):1;
                                                rowspan = (cel.getAttribute(fdTableSort.rowspan) > 1) ? cel.getAttribute(fdTableSort.rowspan):1;
                                                for(var t = 0;((t < colspan)&&((i+t) < rowLength));t++){
                                                        for(var n = 0;((n < rowspan)&&((c+n) < workArr.length));n++) {
                                                                workArr[(c+n)][(i+t)] = cel;
                                                        };
                                                };
                                                if(++celCount == rowArr[c].length) break;
                                        };
                                };
                        };

                        for(c = 0;c < workArr.length;c++) {
                                for(i = 0;i < workArr[c].length;i++){

                                        if(workArr[c][i].className.search("fd-column-") == -1 && workArr[c][i].className.search("sortable") != -1) workArr[c][i].className = workArr[c][i].className + " fd-column-" + i;

                                        if(workArr[c][i].className.match('sortable')) {
                                                workArr[c][i].className = workArr[c][i].className.replace(/forwardSort|reverseSort/, "");

                                                if(i in columnNumSortObj) {
                                                        columnNumSortObj[i]["thNode"] = workArr[c][i];
                                                        columnNumSortObj["active"] = true;
                                                };

                                                thtext = fdTableSort.getInnerText(workArr[c][i], true);
                                                
                                                for(var cn = workArr[c][i].childNodes.length; cn--;) {
                                                        // Skip image nodes and links created by the filter script.
                                                        if(workArr[c][i].childNodes[cn].nodeType == 1 && (workArr[c][i].childNodes[cn].className == "fdFilterTrigger" || /img/i.test(workArr[c][i].childNodes[cn].nodeName))) {
                                                                continue;
                                                        };
                                                        if(workArr[c][i].childNodes[cn].nodeType == 1 && /^a$/i.test(workArr[c][i].childNodes[cn].nodeName)) {
                                                                workArr[c][i].childNodes[cn].onclick = workArr[c][i].childNodes[cn].onkeydown = null;
                                                        };
                                                        workArr[c][i].removeChild(workArr[c][i].childNodes[cn]);
                                                };

                                                aclone = a.cloneNode(true);
                                                //aclone.appendChild(document.createTextNode(thtext));
                                                aclone.innerHTML = thtext;
                                                aclone.title = "Sort on \u201c" + thtext.replace('<br />', '') + "\u201d";
                                                aclone.onclick = aclone.onkeydown = workArr[c][i].onclick = fdTableSort.initWrapper;
                                                workArr[c][i].appendChild(aclone);
                                                if(showArrow) workArr[c][i].appendChild(span.cloneNode(false));
                                                workArr[c][i].className = workArr[c][i].className.replace(/fd-identical|fd-not-identical/, "");
                                                fdTableSort.disableSelection(workArr[c][i]);
                                                aclone = null;
                                        };
                                };
                        };

                        fdTableSort.tmpCache[tbl.id] = {cols:rowLength, headers:workArr};

                        workArr = null;
                        multi   = 0;

                        if("active" in columnNumSortObj) {
                                fdTableSort.tableId = tbl.id;
                                fdTableSort.prepareTableData(document.getElementById(fdTableSort.tableId));

                                delete columnNumSortObj["active"];

                                for(col in columnNumSortObj) {
                                        obj = columnNumSortObj[col];
                                        if(!("thNode" in obj)) { continue; };
                                        fdTableSort.multi = true;

                                        len = obj.reverse ? 2 : 1;

                                        for(ii = 0; ii < len; ii++) {
                                                fdTableSort.thNode = obj.thNode;
                                                if(!showOnly) {
                                                        fdTableSort.initSort(false, true);
                                                } else {
                                                        fdTableSort.addThNode();
                                                };
                                        };

                                        if(showOnly) {
                                                fdTableSort.removeClass(obj.thNode, "(forwardSort|reverseSort)");
                                                fdTableSort.addClass(obj.thNode, obj.reverse ? "reverseSort" : "forwardSort");
                                                if(showArrow) {
                                                        span = fdTableSort.thNode.getElementsByTagName('span')[0];
                                                        if(span.firstChild) { span.removeChild(span.firstChild); };
                                                        span.appendChild(document.createTextNode(len == 1 ? " \u2193" : " \u2191"));
                                                };
                                        };
                                };
                                if(showOnly && (fdTableSort.tableCache[tbl.id].colStyle || fdTableSort.tableCache[tbl.id].rowStyle)) {
                                        fdTableSort.redraw(tbl.id, false);
                                };
                        } else if(tbl.className.search(/onload-zebra/) != -1) {
                                fdTableSort.tableId = tbl.id;
                                fdTableSort.prepareTableData(tbl);
                                if(fdTableSort.tableCache[tbl.id].rowStyle) { fdTableSort.redraw(tbl.id, false); };
                        };
                };

                fdTableSort.thNode = aclone = a = span = columnNumSortObj = thNode = tbl = allRowArr = rowArr = null;
        },
        initWrapper: function(e) {
                e = e || window.event;
                var kc = e.type == "keydown" ? e.keyCode != null ? e.keyCode : e.charCode : -1;
                if(fdTableSort.thNode == null && (e.type == "click" || kc == 13)) {
                        var targ = this;
                        while(targ.tagName.toLowerCase() != "th") { targ = targ.parentNode; };
                        fdTableSort.thNode = targ;
                        while(targ.tagName.toLowerCase() != "table") { targ = targ.parentNode; };
                        fdTableSort.tableId = targ.id;
                        fdTableSort.multi = e.shiftKey;
                        fdTableSort.addSortActiveClass();
                        setTimeout(fdTableSort.initSort,5,false);
                        return fdTableSort.stopEvent(e);
                };
                return kc != -1 ? true : fdTableSort.stopEvent(e);
        },
        jsWrapper: function(tableid, colNums) {
                if(!(tableid in fdTableSort.tmpCache)) { return false; };
                if(!(tableid in fdTableSort.tableCache)) { fdTableSort.prepareTableData(document.getElementById(tableid)); };
                if(!(colNums instanceof Array)) { colNums = [colNums]; };

                fdTableSort.tableId = tableid;
                var len = colNums.length, colNum;

                if(fdTableSort.tableCache[tableid].thList.length == colNums.length) {
                        var identical = true;
                        var th;
                        for(var i = 0; i < len; i++) {
                                colNum = colNums[i];
                                th = fdTableSort.tmpCache[tableid].headers[0][colNum];
                                if(th != fdTableSort.tableCache[tableid].thList[i]) {
                                        identical = false;
                                        break;
                                };
                        };
                        if(identical) {
                                fdTableSort.thNode = th;
                                fdTableSort.initSort(true);
                                return;
                        };
                };

                fdTableSort.addSortActiveClass();

                for(var i = 0; i < len; i++) {
                        fdTableSort.multi = i;
                        colNum = colNums[i];
                        fdTableSort.thNode = fdTableSort.tmpCache[tableid].headers[0][colNum];
                        fdTableSort.initSort(true);
                };
        },
        addSortActiveClass: function() {
                if(fdTableSort.thNode == null) { return; };
                fdTableSort.addClass(fdTableSort.thNode, fdTableSort.sortActiveClass);
                fdTableSort.addClass(document.getElementsByTagName('body')[0], fdTableSort.sortActiveClass);
        },
        removeSortActiveClass: function() {
                if(fdTableSort.thNode == null) return;
                fdTableSort.removeClass(fdTableSort.thNode, fdTableSort.sortActiveClass);
                fdTableSort.removeClass(document.getElementsByTagName('body')[0], fdTableSort.sortActiveClass);
        },
        doCallback: function(init) {
                if(!fdTableSort.tableId || !(fdTableSort.tableId in fdTableSort.tableCache)) { return; };
                fdTableSort.callback(fdTableSort.tableId, init ? fdTableSort.tableCache[fdTableSort.tableId].initiatedCallback : fdTableSort.tableCache[fdTableSort.tableId].completeCallback);
        },
        addClass: function(e,c) {
                if(new RegExp("(^|\\s)" + c + "(\\s|$)").test(e.className)) { return; };
                e.className += ( e.className ? " " : "" ) + c;
        },
        /*@cc_on
        /*@if (@_win32)
        removeClass: function(e,c) {
                e.className = !c ? "" : e.className.replace(new RegExp("(^|\\s)" + c + "(\\s|$)"), " ").replace(/^\s*((?:[\S\s]*\S)?)\s*$/, '$1');
        },
        @else @*/
        removeClass: function(e,c) {
                e.className = !c ? "" : e.className.replace(new RegExp("(^|\\s)" + c + "(\\s|$)"), " ").replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        },
        /*@end
        @*/
        callback: function(tblId, cb) {
                var func, parts;
                try {
                        if(cb.indexOf(".") != -1) {                              
                                parts = cb.split('.');
                                obj   = window;
                                for (var x = 0, part; part = obj[parts[x]]; x++) {
                                        if(part instanceof Function) {
                                                (function() {
                                                        var method = part;
                                                        func = function (data) { method.apply(obj, [data]) };
                                                })();
                                        } else {
                                                obj = part;
                                        };
                                };
                        } else if(cb + tblId in window) {
                                func = window[cb + tblId];
                        } else if(cb in window) {
                                func = window[cb];
                        } else {
                                func = null;
                        };
                 } catch(err) {};
                           
                if(!(func instanceof Function)) return;
                func(tblId, fdTableSort.tableCache[tblId].thList);                               
        },
        prepareTableData: function(table) {
                var data = [];

                var start = table.getElementsByTagName('tbody');
                start = start.length ? start[0] : table;

                var trs = start.rows;
                var ths = table.getElementsByTagName('th');

                var numberOfRows = trs.length;
                var numberOfCols = fdTableSort.tmpCache[table.id].cols;

                var data = [];
                var identical = new Array(numberOfCols);
                var identVal  = new Array(numberOfCols);

                for(var tmp = 0; tmp < numberOfCols; tmp++) identical[tmp] = true;

                var tr, td, th, txt, tds, col, row;

                var re = new RegExp(/fd-column-([0-9]+)/);
                var rowCnt = 0;

                var sortableColumnNumbers = [];

                for(var tmp = 0, th; th = ths[tmp]; tmp++) {
                        if(th.className.search(re) == -1) continue;
                        sortableColumnNumbers[sortableColumnNumbers.length] = th;
                };

                for(row = 0; row < numberOfRows; row++) {

                        tr              = trs[row];
                        if(tr.parentNode != start || tr.getElementsByTagName("th").length || (tr.parentNode && tr.parentNode.tagName.toLowerCase().search(/thead|tfoot/) != -1)) continue;
                        data[rowCnt]    = [];
                        tds             = tr.cells;

                        for(var tmp = 0, th; th = sortableColumnNumbers[tmp]; tmp++) {
                                col = th.className.match(re)[1];

                                td  = tds[col];
                                txt = fdTableSort.getInnerText(td) + " ";
                                txt = txt.replace(/^\s+/,'').replace(/\s+$/,'');

                                if(th.className.search(/sortable-date/) != -1) {
                                        txt = fdTableSort.dateFormat(txt, th.className.search(/sortable-date-dmy/) != -1);
                                } else if(th.className.search(/sortable-numeric|sortable-currency/) != -1) {
                                        txt = parseFloat(txt.replace(/[^0-9\.\-]/g,''));
                                        if(isNaN(txt)) txt = "";
                                } else if(th.className.search(/sortable-text/) != -1) {
                                        txt = txt.toLowerCase();
                                } else if (th.className.search(/sortable-keep/) != -1) {
                                        txt = rowCnt;
                                } else if(th.className.search(/sortable-([a-zA-Z\_]+)/) != -1) {
                                        if((th.className.match(/sortable-([a-zA-Z\_]+)/)[1] + "PrepareData") in window) {
                                                txt = window[th.className.match(/sortable-([a-zA-Z\_]+)/)[1] + "PrepareData"](td, txt);
                                        };
                                } else if(txt != "") {
                                        fdTableSort.removeClass(th, "sortable");
                                        if(fdTableSort.dateFormat(txt) != 0) {
                                                fdTableSort.addClass(th, "sortable-date");
                                                txt = fdTableSort.dateFormat(txt);
                                        } else if(txt.search(fdTableSort.regExp_Number) != -1 || txt.search(fdTableSort.regExp_Currency) != -1) {
                                                fdTableSort.addClass(th, "sortable-numeric");
                                                txt = parseFloat(txt.replace(/[^0-9\.\-]/g,''));
                                                if(isNaN(txt)) txt = "";
                                        } else {
                                                fdTableSort.addClass(th, "sortable-text");
                                                txt = txt.toLowerCase();
                                        };
                                };

                                if(rowCnt > 0 && identical[col] && identVal[col] != txt) { identical[col] = false; };

                                identVal[col]     = txt;
                                data[rowCnt][col] = txt;
                        };
                        data[rowCnt][numberOfCols] = tr;
                        rowCnt++;
                };

                var colStyle = table.className.search(/colstyle-([\S]+)/) != -1 ? table.className.match(/colstyle-([\S]+)/)[1] : false;
                var rowStyle = table.className.search(/rowstyle-([\S]+)/) != -1 ? table.className.match(/rowstyle-([\S]+)/)[1] : false;
                var iCBack   = table.className.search(/sortinitiatedcallback-([\S-]+)/) == -1 ? "sortInitiatedCallback" : table.className.match(/sortinitiatedcallback-([\S]+)/)[1];
                var cCBack   = table.className.search(/sortcompletecallback-([\S-]+)/) == -1 ? "sortCompleteCallback" : table.className.match(/sortcompletecallback-([\S]+)/)[1];
                iCBack = iCBack.replace("-", ".");
                cCBack = cCBack.replace("-", ".");
                fdTableSort.tableCache[table.id] = { hook:start, initiatedCallback:iCBack, completeCallback:cCBack, thList:[], colOrder:{}, data:data, identical:identical, colStyle:colStyle, rowStyle:rowStyle, noArrow:table.className.search(/no-arrow/) != -1 };
                sortableColumnNumbers = data = tr = td = th = trs = identical = identVal = null;
        },
        onUnload: function() {
                for(tbl in fdTableSort.tableCache) { fdTableSort.removeTableCache(tbl); };
                for(tbl in fdTableSort.tmpCache) { fdTableSort.removeTmpCache(tbl); };
                fdTableSort.removeEvent(window, "load", fdTableSort.initEvt);
                fdTableSort.removeEvent(window, "unload", fdTableSort.onUnload);
                fdTableSort.tmpCache = fdTableSort.tableCache = null;
        },
        addThNode: function() {
                var dataObj = fdTableSort.tableCache[fdTableSort.tableId];
                var pos     = fdTableSort.thNode.className.match(/fd-column-([0-9]+)/)[1];
                var alt     = false;

                if(!fdTableSort.multi) {
                        if(dataObj.colStyle) {
                                var len = dataObj.thList.length;
                                for(var i = 0; i < len; i++) {
                                        dataObj.colOrder[dataObj.thList[i].className.match(/fd-column-([0-9]+)/)[1]] = false;
                                };
                        };
                        if(dataObj.thList.length && dataObj.thList[0] == fdTableSort.thNode) alt = true;
                        dataObj.thList = [];
                };

                var found = false;
                var l = dataObj.thList.length;

                for(var i = 0, n; n = dataObj.thList[i]; i++) {
                        if(n == fdTableSort.thNode) {
                                found = true;
                                break;
                        };
                };

                if(!found) {
                        dataObj.thList.push(fdTableSort.thNode);
                        if(dataObj.colStyle) { dataObj.colOrder[pos] = true; };
                };

                var ths = document.getElementById(fdTableSort.tableId).getElementsByTagName("th");
                for(var i = 0, th; th = ths[i]; i++) {
                        found = false;
                        for(var z = 0, n; n = dataObj.thList[z]; z++) {
                                if(n == th) {
                                        found = true;
                                        break;
                                };
                        };
                        if(!found) {
                                fdTableSort.removeClass(th, "(forwardSort|reverseSort)");
                                if(!dataObj.noArrow) {
                                        span = th.getElementsByTagName('span');
                                        if(span.length) {
                                                span = span[0];
                                                while(span.firstChild) span.removeChild(span.firstChild);
                                        };
                                };
                        };
                };

                if(dataObj.thList.length > 1) {
                        classToAdd = fdTableSort.thNode.className.search(/forwardSort/) != -1 ? "reverseSort" : "forwardSort";
                        fdTableSort.removeClass(fdTableSort.thNode, "(forwardSort|reverseSort)");
                        fdTableSort.addClass(fdTableSort.thNode, classToAdd);
                        dataObj.pos = -1
                } else if(alt) { dataObj.pos = fdTableSort.thNode };
        },
        initSort: function(noCallback, ident) {
                var thNode      = fdTableSort.thNode;
                var tableElem   = document.getElementById(fdTableSort.tableId);

                if(!(fdTableSort.tableId in fdTableSort.tableCache)) { fdTableSort.prepareTableData(document.getElementById(fdTableSort.tableId)); };

                fdTableSort.addThNode();

                if(!noCallback) { fdTableSort.doCallback(true); };

                fdTableSort.pos = thNode.className.match(/fd-column-([0-9]+)/)[1];
                var dataObj     = fdTableSort.tableCache[tableElem.id];
                var lastPos     = dataObj.pos && dataObj.pos.className ? dataObj.pos.className.match(/fd-column-([0-9]+)/)[1] : -1;
                var len1        = dataObj.data.length;
                var len2        = dataObj.data.length > 0 ? dataObj.data[0].length - 1 : 0;
                var identical   = dataObj.identical[fdTableSort.pos];
                var classToAdd  = "forwardSort";

                if(dataObj.thList.length > 1) {
                        var js  = "var sortWrapper = function(a,b) {\n";
                        var l   = dataObj.thList.length;
                        var cnt = 0;
                        var e,d,th,p,f;

                        for(var i=0; i < l; i++) {
                                th = dataObj.thList[i];
                                p  = th.className.match(/fd-column-([0-9]+)/)[1];
                                if(dataObj.identical[p]) { continue; };
                                cnt++;

                                if(th.className.match(/sortable-(numeric|currency|date|keep)/)) {
                                        f = "fdTableSort.sortNumeric";
                                } else if(th.className.match('sortable-text')) {
                                        f = "fdTableSort.sortText";
                                } else if(th.className.search(/sortable-([a-zA-Z\_]+)/) != -1 && th.className.match(/sortable-([a-zA-Z\_]+)/)[1] in window) {
                                        f = "window['" + th.className.match(/sortable-([a-zA-Z\_]+)/)[1] + "']";
                                } else  f = "fdTableSort.sortText";

                                e = "e" + i;
                                d = th.className.search('forwardSort') != -1 ? "a,b" : "b,a";
                                js += "fdTableSort.pos   = " + p + ";\n";
                                js += "var " + e + " = "+f+"(" + d +");\n";
                                js += "if(" + e + ") return " + e + ";\n";
                                js += "else { \n";
                        };

                        js += "return 0;\n";

                        for(var i=0; i < cnt; i++) {
                                js += "};\n";
                        };

                        if(cnt) js += "return 0;\n";
                        js += "};\n";

                        eval(js);
                        dataObj.data.sort(sortWrapper);
                        identical = false;
                } else if((lastPos == fdTableSort.pos && !identical) || (thNode.className.search(/sortable-keep/) != -1 && lastPos == -1)) {
                        dataObj.data.reverse();
                        classToAdd = thNode.className.search(/reverseSort/) != -1 ? "forwardSort" : "reverseSort";
                        if(thNode.className.search(/sortable-keep/) != -1 && lastPos == -1) fdTableSort.tableCache[tableElem.id].pos = thNode;
                } else {
                        fdTableSort.tableCache[tableElem.id].pos = thNode;
                        classToAdd = thNode.className.search(/forwardSort/) != -1 ? "reverseSort" : "forwardSort";
                        if(!identical) {
                                if(thNode.className.match(/sortable-(numeric|currency|date|keep)/)) {
                                        dataObj.data.sort(fdTableSort.sortNumeric);
                                } else if(thNode.className.match('sortable-text')) {
                                        dataObj.data.sort(fdTableSort.sortText);
                                } else if(thNode.className.search(/sortable-([a-zA-Z\_]+)/) != -1 && thNode.className.match(/sortable-([a-zA-Z\_]+)/)[1] in window) {
                                        dataObj.data.sort(window[thNode.className.match(/sortable-([a-zA-Z\_]+)/)[1]]);
                                };

                                if(thNode.className.search(/(^|\s)favour-reverse($|\s)/) != -1) {
                                        classToAdd = classToAdd == "forwardSort" ? "reverseSort" : "forwardSort";
                                        dataObj.data.reverse();
                                };
                        };
                };
                if(ident) { identical = false; };
                if(dataObj.thList.length == 1) {
                        fdTableSort.removeClass(thNode, "(forwardSort|reverseSort)");
                        fdTableSort.addClass(thNode, classToAdd);
                };
                if(!dataObj.noArrow) {
                        var span = fdTableSort.thNode.getElementsByTagName('span')[0];
                        if(span.firstChild) span.removeChild(span.firstChild);
                        span.appendChild(document.createTextNode(fdTableSort.thNode.className.search(/forwardSort/) != -1 ? " \u2193" : " \u2191"));
                };
                if(!dataObj.rowStyle && !dataObj.colStyle && identical) {
                        fdTableSort.removeSortActiveClass();
                        if(!noCallback) { fdTableSort.doCallback(false); };
                        fdTableSort.thNode = null;
                        return;
                };
                if("tablePaginater" in window && tablePaginater.tableIsPaginated(fdTableSort.tableId)) {
                        tablePaginater.redraw(fdTableSort.tableId, identical);
                } else {
                        fdTableSort.redraw(fdTableSort.tableId, identical);
                };
                fdTableSort.removeSortActiveClass();
                if(!noCallback) { fdTableSort.doCallback(false); };
                fdTableSort.thNode = null;
        },
        redraw: function(tableid, identical) {
                if(!tableid || !(tableid in fdTableSort.tableCache)) { return; };
                var dataObj     = fdTableSort.tableCache[tableid];
                var data        = dataObj.data;
                var len1        = data.length;
                var len2        = len1 ? data[0].length - 1 : 0;
                var hook        = dataObj.hook;
                var colStyle    = dataObj.colStyle;
                var rowStyle    = dataObj.rowStyle;
                var colOrder    = dataObj.colOrder;
                var highLight   = 0;
                var reg         = /(^|\s)invisibleRow(\s|$)/;
                var tr, tds;

                for(var i = 0; i < len1; i++) {
                        tr = data[i][len2];
                        if(colStyle) {
                                tds = tr.cells;
                                for(thPos in colOrder) {
                                        if(!colOrder[thPos]) fdTableSort.removeClass(tds[thPos], colStyle);
                                        else fdTableSort.addClass(tds[thPos], colStyle);
                                };
                        };
                        if(!identical) {
                                if(rowStyle && tr.className.search(reg) == -1) {
                                        if(highLight++ & 1) fdTableSort.addClass(tr, rowStyle);
                                        else fdTableSort.removeClass(tr, rowStyle);
                                };

                                // Netscape 8.1.2 requires the removeChild call or it freaks out, so add the line if you want to support this browser
                                // hook.removeChild(tr);
                                hook.appendChild(tr);
                        };
                };
                tr = tds = hook = null;
        },
        getInnerText: function(el, allowBrTags) {
                if (typeof el == "string" || typeof el == "undefined") return el;
                if(el.innerText) return el.innerText;
                var txt = '', i;
                for(i = el.firstChild; i; i = i.nextSibling) {
                        if(allowBrTags && i.nodeName && i.nodeName == "BR") txt += "<br />";
                        else if(i.nodeType == 3)       txt += i.nodeValue;
                        else if(i.nodeType == 1)       txt += fdTableSort.getInnerText(i);
                };
                return txt;
        },
        dateFormat: function(dateIn, favourDMY) {
                var dateTest = [
                        { regExp:/^(0?[1-9]|1[012])([- \/.])(0?[1-9]|[12][0-9]|3[01])([- \/.])((\d\d)?\d\d)$/, d:3, m:1, y:5 },  // mdy
                        { regExp:/^(0?[1-9]|[12][0-9]|3[01])([- \/.])(0?[1-9]|1[012])([- \/.])((\d\d)?\d\d)$/, d:1, m:3, y:5 },  // dmy
                        { regExp:/^(\d\d\d\d)([- \/.])(0?[1-9]|1[012])([- \/.])(0?[1-9]|[12][0-9]|3[01])$/, d:5, m:3, y:1 }      // ymd
                        ];
                var start, cnt = 0, numFormats = dateTest.length;
                while(cnt < numFormats) {
                        start = (cnt + (favourDMY ? numFormats + 1 : numFormats)) % numFormats;
                        if(dateIn.match(dateTest[start].regExp)) {
                                res = dateIn.match(dateTest[start].regExp);
                                y = res[dateTest[start].y];
                                m = res[dateTest[start].m];
                                d = res[dateTest[start].d];
                                if(m.length == 1) m = "0" + String(m);
                                if(d.length == 1) d = "0" + String(d);
                                if(y.length != 4) y = (parseInt(y) < 50) ? "20" + String(y) : "19" + String(y);

                                return y+String(m)+d;
                        };
                        cnt++;
                };
                return 0;
        },
        sortNumeric:function(a,b) {
                var aa = a[fdTableSort.pos];
                var bb = b[fdTableSort.pos];
                if(aa == bb) return 0;
                if(aa === "" && !isNaN(bb)) return -1;
                if(bb === "" && !isNaN(aa)) return 1;
                return aa - bb;
        },
        sortText:function(a,b) {
                var aa = a[fdTableSort.pos];
                var bb = b[fdTableSort.pos];
                if(aa == bb) return 0;
                if(aa < bb)  return -1;
                return 1;
        }
};
})();
fdTableSort.addEvent(window, "load",   fdTableSort.initEvt);
fdTableSort.addEvent(window, "unload", fdTableSort.onUnload);

/*
    sortEnglishDateTime
    -------------------

    This function sorts English dateTime vaues such as:

    1st January 2003, 23:32:01
    23/03/1972 à 10:22:22
    1970/13/03 at 23:22:01
    
    The function is "safe" i.e. non-dateTime data (like the word "Unknown") can be passed in and is sorted properly.
    
    UPDATE 08/01/2009: 1. Full or Short-hand english month names (e.g. "March" or "Mar") now require a space
                       or a comma after them to be properly parsed.
                       2. If no timestamp is given, a fake timestamp "00:00:00" is added to the string this enables
                       the function to parse both date and datetime data.
*/
var sortEnglishDateTime = fdTableSort.sortNumeric;

function sortEnglishDateTimePrepareData(tdNode, innerText) {
        // You can localise the function here
        var months = ['january','february','march','april','may','june','july','august','september','october','november','december','jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'];

        // Lowercase the text
        var aa = innerText.toLowerCase();         
        
        // Replace the longhand and shorthand months with an integer equivalent
        for(var i = 0; i < months.length; i++) {                 
                aa = aa.replace(new RegExp(months[i] + '([\\s|,]{1})'), (i+13)%12 + " ");
        };

        // Replace multiple spaces and anything that is not valid in the parsing of the date, then trim
        aa = aa.replace(/\s+/g, " ").replace(/([^\d\s\/-:.])/g, "").replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        
        // REMOVED: No timestamp at the end, then return -1
        //if(aa.search(/(\d){2}:(\d){2}(:(\d){2})?$/) == -1) { return -1; };

        // No timestamp at the end, then create a false one         
        if(aa.search(/(\d){2}:(\d){2}(:(\d){2})?$/) == -1) { aa += " 00:00:00"; };
        
        
        // Grab the timestamp
        var timestamp = aa.match(/(\d){2}:(\d){2}(:(\d){2})?$/)[0].replace(/:/g, "");

        // Make the timestamp 6 characters by default
        if(timestamp.length == 4) { timestamp += "00"; };

        // Remove it from the string to assist the date parser, then trim
        aa = aa.replace(/(\d){2}:(\d){2}(:(\d){2})?$/, "").replace(/\s\s*$/, '');

        // If you want the parser to favour the parsing of European dd/mm/yyyy dates then leave this set to "true"
        // If you want the parser to favour the parsing of American mm/dd/yyyy dates then set to "false"
        var favourDMY = true;

        // If you have a regular expression you wish to add, add the Object to the end of the array
        var dateTest = [
                       { regExp:/^(0?[1-9]|1[012])([- \/.])(0?[1-9]|[12][0-9]|3[01])([- \/.])((\d\d)?\d\d)$/, d:3, m:1, y:5 },  // mdy
                       { regExp:/^(0?[1-9]|[12][0-9]|3[01])([- \/.])(0?[1-9]|1[012])([- \/.])((\d\d)?\d\d)$/, d:1, m:3, y:5 },  // dmy
                       { regExp:/^(\d\d\d\d)([- \/.])(0?[1-9]|1[012])([- \/.])(0?[1-9]|[12][0-9]|3[01])$/, d:5, m:3, y:1 }      // ymd
                       ];

        var start,y,m,d;
        var cnt = 0;
        var numFormats = dateTest.length;
        while(cnt < numFormats) {
               start = (cnt + (favourDMY ? numFormats + 1 : numFormats)) % numFormats;
               if(aa.match(dateTest[start].regExp)) {
                       res = aa.match(dateTest[start].regExp);
                       y = res[dateTest[start].y];
                       m = res[dateTest[start].m];
                       d = res[dateTest[start].d];
                       if(m.length == 1) m = "0" + String(m);
                       if(d.length == 1) d = "0" + String(d);
                       if(y.length != 4) y = (parseInt(y) < 50) ? "20" + String(y) : "19" + String(y);

                       return y+String(m)+d+String(timestamp);
               };
               cnt++;
        };
        return -1;
};

/*
        paginate table object v2.0 by frequency-decoder.com

        Released under a creative commons Attribution-ShareAlike 2.5 license (http://creativecommons.org/licenses/by-sa/2.5/)

        Please credit frequency decoder in any derivative work - thanks

        You are free:

        * to copy, distribute, display, and perform the work
        * to make derivative works
        * to make commercial use of the work

        Under the following conditions:

                by Attribution.
                --------------
                You must attribute the work in the manner specified by the author or licensor.

                sa
                --
                Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under a license identical to this one.

        * For any reuse or distribution, you must make clear to others the license terms of this work.
        * Any of these conditions can be waived if you get permission from the copyright holder.
*/

var tablePaginater = (function() {
        /*

        Localise the button titles here...

        %p is replaced with the appropriate page number
        %t is replaced with the total number of pages
        
        */
        var tableInfo = {},
            uniqueID  = 0,
            text      = ["First Page","Previous Page (Page %p)","Next Page (Page %p)","Last Page (Page %t)","Page %p of %t"];
            
        var addClass = function(e,c) {
                if(new RegExp("(^|\\s)" + c + "(\\s|$)").test(e.className)) return;
                e.className += ( e.className ? " " : "" ) + c;
        }; 
        
        /*@cc_on
        /*@if (@_win32)
        var removeClass = function(e,c) {
                e.className = !c ? "" : e.className.replace(new RegExp("(^|\\s)" + c + "(\\s|$)"), " ").replace(/^\s*((?:[\S\s]*\S)?)\s*$/, '$1');
        };
        @else @*/
        var removeClass = function(e,c) {                 
                e.className = !c ? "" : (e.className || "").replace(new RegExp("(^|\\s)" + c + "(\\s|$)"), " ").replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        };
        /*@end
        @*/  
        
        var addEvent = function(obj, type, fn) {
                if( obj.attachEvent ) {
                        obj["e"+type+fn] = fn;
                        obj[type+fn] = function(){obj["e"+type+fn]( window.event );};
                        obj.attachEvent( "on"+type, obj[type+fn] );
                } else {
                        obj.addEventListener( type, fn, true );
                };
        };
        var removeEvent = function(obj, type, fn) {
                try {
                        if( obj.detachEvent ) {
                                obj.detachEvent( "on"+type, obj[type+fn] );
                                obj[type+fn] = null;
                        } else {
                                obj.removeEventListener( type, fn, true );
                        };
                } catch(err) {};
        };
        var stopEvent = function(e) {
                e = e || window.event;
                if(e.stopPropagation) {
                        e.stopPropagation();
                        e.preventDefault();
                };
                
                /*@cc_on@*/
                /*@if(@_win32)
                e.cancelBubble = true;
                e.returnValue  = false;
                /*@end@*/
                return false;
        }; 
        
        var init = function(tableId) {
                var tables = tableId && typeof(tableId) == "string" ? [document.getElementById(tableId)] : document.getElementsByTagName('table'),
                    hook, maxPages, visibleRows, numPages, cp, cb, rowList;
                
                for(var t = 0, tbl; tbl = tables[t]; t++) {
                        if(tbl.className.search(/paginate-([0-9]+)/) == -1) { continue; };

                        if(!tbl.id) { tbl.id = "fdUniqueTableId_" + uniqueID++; };

                        maxPages = tbl.className.search(/max-pages-([0-9]+)/) == -1 ? null : Number(tbl.className.match(/max-pages-([0-9]+)/)[1]);
                        if(maxPages % 2 == 0 && maxPages > 1) { maxPages--; };
                        
                        hook = tbl.getElementsByTagName('tbody');
                        hook = (hook.length) ? hook[0] : tbl;

                        visibleRows = calculateVisibleRows(hook);
                        
                        if(maxPages > (visibleRows / Number(tbl.className.match(/paginate-([0-9]+)/)[1]))) {
                                maxPages = null;
                        };
                        
                        numPages = Math.ceil(visibleRows / Number(tbl.className.match(/paginate-([0-9]+)/)[1]));
                        
                        if(numPages < 2 && !(tbl.id in tableInfo)) {
                                continue;
                        };
                        
                        cp = (tbl.id in tableInfo) ? Math.min(tableInfo[tbl.id].currentPage, numPages) : 1;
                        
                        tableInfo[tbl.id] = {
                                rowsPerPage:Number(tbl.className.match(/paginate-([0-9]+)/)[1]),
                                currentPage:cp,
                                totalRows:hook.getElementsByTagName('tr').length,
                                hook:hook,
                                maxPages:maxPages,
                                numPages:numPages,
                                rowStyle:tbl.className.search(/rowstyle-([\S]+)/) != -1 ? tbl.className.match(/rowstyle-([\S]+)/)[1] : false,
                                callbacks:parseCallback(/^paginationcallback-/i, /paginationcallback-([\S-]+)/ig, tbl.className)
                        };
                        
                        showPage(tbl.id);
                        hook = null;
                };
        };
        
        var parseCallback = function(head, regExp, cname) {
                var cbs    = [],
                    matchs = cname.match(regExp),
                    parts, obj, func;
                
                if(!matchs) { return []; };
                  
                for(var i = 0, mtch; mtch = matchs[i]; i++) {                         
                        mtch = mtch.replace(head, "").replace(/-/g, ".");
                         
                        try {
                                if(mtch.indexOf(".") != -1) {
                                        parts = mtch.split('.');
                                        obj   = window;
                                        for (var x = 0, part; part = obj[parts[x]]; x++) {
                                                if(part instanceof Function) {
                                                        (function() {
                                                                var method = part;
                                                                func = function (data) { method.apply(obj, [data]) };
                                                        })();
                                                } else {
                                                        obj = part;
                                                };
                                        };
                                } else {
                                        func = window[mtch];
                                };
                            
                                if(!(func instanceof Function)) continue;
                                cbs[cbs.length] = func;                              
                        } catch(err) {};
                };
                
                return cbs;                      
        };
                
        var callback = function(tblId, opts) {                
                if(!(tblId in tableInfo) || !(tableInfo[tblId]["callbacks"].length)) return;                
                for(var i = 0, func; func = tableInfo[tblId]["callbacks"][i]; i++) {
                        func(opts || {});
                };
        };
        
        var calculateVisibleRows = function(hook) {
                var trs = hook.rows,
                    cnt = 0,
                    reg = /(^|\s)invisibleRow(\s|$)/;
                
                for(var i = 0, tr; tr = trs[i]; i++) {
                        if(tr.parentNode != hook || tr.getElementsByTagName("th").length || (tr.parentNode && tr.parentNode.tagName.toLowerCase().search(/thead|tfoot/) != -1)) continue;
                        if(tr.className.search(reg) == -1) { cnt++; };
                };
                
                return cnt;
        };
        
        var createButton = function(details, ul, pseudo) {
                var li   = document.createElement("li"),
                    but  = document.createElement(pseudo ? "div" : "a"),
                    span = document.createElement("span");

                if(!pseudo) { 
                        but.href = "#"; 
                        but.title = details.title; 
                };
                
                but.className = details.className;

                ul.appendChild(li);
                li.appendChild(but);
                but.appendChild(span);
                span.appendChild(document.createTextNode(details.text));

                if(!pseudo) { 
                        li.onclick = but.onclick = buttonClick; 
                        if(details.id) { but.id = details.id; };
                };                 
                
                li = but = span = null;
        };
        var removePagination = function(tableId) {
                var wrapT = document.getElementById(tableId + "-fdtablePaginaterWrapTop"),
                    wrapB = document.getElementById(tableId + "-fdtablePaginaterWrapBottom");
                if(wrapT) { wrapT.parentNode.removeChild(wrapT); };
                if(wrapB) { wrapB.parentNode.removeChild(wrapB); };
        };
        var buildPagination = function(tblId) {
                if(!(tblId in tableInfo)) { return; };

                removePagination(tblId);

                var details = tableInfo[tblId];
                
                if(details.numPages < 2) return;
                
                function resolveText(txt, curr) {
                        curr = curr || details.currentPage;
                        return txt.replace("%p", curr).replace("%t", details.numPages);
                };

                if(details.maxPages) {
                        findex = Math.max(0, Math.floor(Number(details.currentPage - 1) - (Number(details.maxPages - 1) / 2)));
                        lindex = findex + Number(details.maxPages);
                        if(lindex > details.numPages) {
                                lindex = details.numPages;
                                findex = Math.max(0, details.numPages - Number(details.maxPages));
                        };
                } else {
                        findex = 0;
                        lindex = details.numPages;
                };
                

                var wrapT = document.createElement("div");
                wrapT.className = "fdtablePaginaterWrap";
                wrapT.id = tblId + "-fdtablePaginaterWrapTop";

                var wrapB = document.createElement("div");
                wrapB.className = "fdtablePaginaterWrap";
                wrapB.id = tblId + "-fdtablePaginaterWrapBottom";

                // Create list scaffold
                var ulT = document.createElement("ul");
                ulT.id  = tblId + "-tablePaginater";

                var ulB = document.createElement("ul");
                ulB.id  = tblId + "-tablePaginaterClone";
                ulT.className = ulB.className = "fdtablePaginater";

                // Add to the wrapper DIVs
                wrapT.appendChild(ulT);
                wrapB.appendChild(ulB);

                // FIRST (only created if maxPages set)
                if(details.maxPages) {
                        createButton({title:text[0], className:"first-page", text:"\u00ab"}, ulT, !findex);
                        createButton({title:text[0], className:"first-page", text:"\u00ab"}, ulB, !findex);
                };
                
                // PREVIOUS (only created if there are more than two pages)
                if(details.numPages > 2) {
                        createButton({title:resolveText(text[1], details.currentPage-1), className:"previous-page", text:"\u2039", id:tblId+"-previousPage"}, ulT, details.currentPage == 1);
                        createButton({title:resolveText(text[1], details.currentPage-1), className:"previous-page", text:"\u2039", id:tblId+"-previousPageC"}, ulB, details.currentPage == 1);
                };
                
                // NUMBERED
                for(var i = findex; i < lindex; i++) {
                        createButton({title:resolveText(text[4], i+1), className:i != (details.currentPage-1) ? "page-"+(i+1) : "currentPage page-"+(i+1), text:(i+1), id:i == (details.currentPage-1) ? tblId + "-currentPage" : ""}, ulT);
                        createButton({title:resolveText(text[4], i+1), className:i != (details.currentPage-1) ? "page-"+(i+1) : "currentPage page-"+(i+1), text:(i+1), id:i == (details.currentPage-1) ? tblId + "-currentPageC" : ""}, ulB);
                };

                // NEXT (only created if there are more than two pages)
                if(details.numPages > 2) {
                        createButton({title:resolveText(text[2], details.currentPage + 1), className:"next-page", text:"\u203a", id:tblId+"-nextPage"}, ulT, details.currentPage == details.numPages);
                        createButton({title:resolveText(text[2], details.currentPage + 1), className:"next-page", text:"\u203a", id:tblId+"-nextPageC"}, ulB, details.currentPage == details.numPages);
                };
                
                // LAST (only created if maxPages set)
                if(details.maxPages) {
                        createButton({title:resolveText(text[3], details.numPages), className:"last-page", text:"\u00bb"}, ulT, lindex == details.numPages);
                        createButton({title:resolveText(text[3], details.numPages), className:"last-page", text:"\u00bb"}, ulB, lindex == details.numPages);
                };
                
                // DOM inject wrapper DIVs (FireFox 2.x Bug: this has to be done here if you use display:table)
                if(document.getElementById(tblId+"-paginationListWrapTop")) {
                        document.getElementById(tblId+"-paginationListWrapTop").appendChild(wrapT);
                } else {
                        document.getElementById(tblId).parentNode.insertBefore(wrapT, document.getElementById(tblId));
                };

                if(document.getElementById(tblId+"-paginationListWrapBottom")) {
                        document.getElementById(tblId+"-paginationListWrapBottom").appendChild(wrapB);
                } else {
                        document.getElementById(tblId).parentNode.insertBefore(wrapB, document.getElementById(tblId).nextSibling);
                };
        };
        
        // The tableSort script uses this function to redraw.
        var tableSortRedraw = function(tableid, identical) {
                if(!tableid || !(tableid in fdTableSort.tableCache) || !(tableid in tableInfo)) { return; };
                
                var dataObj     = fdTableSort.tableCache[tableid],
                    data        = dataObj.data,
                    len1        = data.length,
                    len2        = len1 ? data[0].length - 1 : 0,
                    hook        = dataObj.hook,
                    colStyle    = dataObj.colStyle,
                    rowStyle    = dataObj.rowStyle,
                    colOrder    = dataObj.colOrder,                 
                    page        = tableInfo[tableid].currentPage - 1,
                    d1          = tableInfo[tableid].rowsPerPage * page,
                    d2          = Math.min(tableInfo[tableid].totalRows, d1 + tableInfo[tableid].rowsPerPage), 
                    cnt         = 0,
                    rs          = 0,
                    reg         = /(^|\s)invisibleRow(\s|$)/,                
                    tr, tds, cell, pos;
                
                for(var i = 0; i < len1; i++) {
                        tr = data[i][len2];
                        
                        if(colStyle) {
                                tds = tr.cells;
                                for(thPos in colOrder) {
                                        if(!colOrder[thPos]) removeClass(tds[thPos], colStyle);
                                        else addClass(tds[thPos], colStyle);
                                };
                        };
                        
                        if(tr.className.search(reg) != -1) { continue; };
                        
                        if(!identical) {
                                cnt++;

                                if(cnt > d1 && cnt <= d2) {
                                        if(rowStyle) {
                                                if(rs++ & 1) addClass(tr, rowStyle);
                                                else removeClass(tr, rowStyle);
                                        };
                                        tr.style.display = "";
                                } else {
                                        tr.style.display = "none";
                                };

                                // Netscape 8.1.2 requires the removeChild call or it freaks out, so add the line if you want to support this browser
                                // hook.removeChild(tr);
                                hook.appendChild(tr);
                        };
                };

                tr = tds = hook = null;
        };
        
        var showPage = function(tblId, pageNum) {
                if(!(tblId in tableInfo)) { return; };

                var page = Math.max(0, !pageNum ? tableInfo[tblId].currentPage - 1 : pageNum - 1),
                    d1  = tableInfo[tblId].rowsPerPage * page,
                    d2  = Math.min(tableInfo[tblId].totalRows, d1 + tableInfo[tblId].rowsPerPage),
                    trs = tableInfo[tblId].hook.rows,
                    cnt = 0,
                    rc  = 0,
                    len = trs.length,
                    rs  = tableInfo[tblId].rowStyle,
                    reg = /(^|\s)invisibleRow(\s|$)/,
                    row = [];
                
                for(var i = 0; i < len; i++) {
                        if(trs[i].className.search(reg) != -1 || trs[i].getElementsByTagName("th").length || (trs[i].parentNode && trs[i].parentNode.tagName.toLowerCase().search(/thead|tfoot/) != -1)) { continue; };
                        
                        cnt++;
                        
                        if(cnt > d1 && cnt <= d2) {
                                if(rs) {
                                        if(rc++ & 1) {
                                                addClass(trs[i], rs);
                                        } else {
                                                removeClass(trs[i], rs);
                                        }
                                };
                                trs[i].style.display = "";
                                row[row.length] = trs[i];
                        } else {
                                trs[i].style.display = "none";
                        };
                };

                buildPagination(tblId);
                callback(tblId, {"totalRows":len, "currentPage":(page+1), "rowsPerPage":tableInfo[tblId].rowsPerPage, "visibleRows":row});
        };
        
        var buttonClick = function(e) {
                e = e || window.event;

                var a = this.tagName.toLowerCase() == "a" ? this : this.getElementsByTagName("a")[0];

                if(a.className.search("currentPage") != -1) return false;

                var ul = this;
                while(ul.tagName.toLowerCase() != "ul") ul = ul.parentNode;

                var tblId = ul.id.replace("-tablePaginaterClone","").replace("-tablePaginater", "");

                tableInfo[tblId].lastPage = tableInfo[tblId].currentPage;
                
                var showPrevNext = 0;
                
                if(a.className.search("previous-page") != -1) {
                        tableInfo[tblId].currentPage = tableInfo[tblId].currentPage > 1 ? tableInfo[tblId].currentPage - 1 : tableInfo[tblId].numPages;
                        showPrevNext = 1;
                } else if(a.className.search("next-page") != -1) {
                        tableInfo[tblId].currentPage = tableInfo[tblId].currentPage < tableInfo[tblId].numPages ? tableInfo[tblId].currentPage + 1 : 1;
                        showPrevNext = 2;
                } else if(a.className.search("first-page") != -1) {
                        tableInfo[tblId].currentPage = 1;
                } else if(a.className.search("last-page") != -1) {
                        tableInfo[tblId].currentPage = tableInfo[tblId].numPages;
                } else {
                        tableInfo[tblId].currentPage = parseInt(a.className.match(/page-([0-9]+)/)[1]) || 1;
                };

                showPage(tblId);

                // Focus on the appropriate button (previous, next or the current page)
                // I'm hoping screen readers are savvy enough to indicate the focus event to the user
                if(showPrevNext == 1) {
                        var elem = document.getElementById(ul.id.search("-tablePaginaterClone") != -1 ? tblId + "-previousPageC" : tblId + "-previousPage");
                } else if(showPrevNext == 2) {
                        var elem = document.getElementById(ul.id.search("-tablePaginaterClone") != -1 ? tblId + "-nextPageC" : tblId + "-nextPage");
                } else {
                        var elem = document.getElementById(ul.id.search("-tablePaginaterClone") != -1 ? tblId + "-currentPageC" : tblId + "-currentPage");
                };
                
                if(elem && elem.tagName.toLowerCase() == "a") { elem.focus(); };   
                
                return stopEvent(e);
        };
        
        var onUnLoad = function(e) {
                var tbl, lis, pagination, uls;
                for(tblId in tableInfo) {
                        uls = [tblId + "-tablePaginater", tblId + "-tablePaginaterClone"];
                        for(var z = 0; z < 2; z++) {
                                pagination = document.getElementById(uls[z]);
                                if(!pagination) { continue; };
                                lis = pagination.getElementsByTagName("li");
                                for(var i = 0, li; li = lis[i]; i++) {
                                        li.onclick = null;
                                        if(li.getElementsByTagName("a").length) { li.getElementsByTagName("a")[0].onclick = null; };
                                };
                        };
                };
        };
        
        addEvent(window, "load",   init);
        addEvent(window, "unload", onUnLoad); 
        
        return {                  
                init:                   function(tableId) { init(tableId); },                 
                redraw:                 function(tableid, identical) { tableSortRedraw(tableid, identical); },
                tableIsPaginated:       function(tableId) { return (tableId in tableInfo); },
                changeTranslations:     function(translations) { text = translations; }
        };        
})();
/**
 * Ajax Queue Plugin
 * 
 * Homepage: http://jquery.com/plugins/project/ajaxqueue
 * Documentation: http://docs.jquery.com/AjaxQueue
 */

/**

<script>
$(function(){
	jQuery.ajaxQueue({
		url: "test.php",
		success: function(html){ jQuery("ul").append(html); }
	});
	jQuery.ajaxQueue({
		url: "test.php",
		success: function(html){ jQuery("ul").append(html); }
	});
	jQuery.ajaxSync({
		url: "test.php",
		success: function(html){ jQuery("ul").append("<b>"+html+"</b>"); }
	});
	jQuery.ajaxSync({
		url: "test.php",
		success: function(html){ jQuery("ul").append("<b>"+html+"</b>"); }
	});
});
</script>
<ul style="position: absolute; top: 5px; right: 5px;"></ul>

 */
/*
 * Queued Ajax requests.
 * A new Ajax request won't be started until the previous queued 
 * request has finished.
 */

/*
 * Synced Ajax requests.
 * The Ajax request will happen as soon as you call this method, but
 * the callbacks (success/error/complete) won't fire until all previous
 * synced requests have been completed.
 */


(function($) {
	
	var ajax = $.ajax;
	
	var pendingRequests = {};
	
	var synced = [];
	var syncedData = [];
	
	$.ajax = function(settings) {
		// create settings for compatibility with ajaxSetup
		settings = jQuery.extend(settings, jQuery.extend({}, jQuery.ajaxSettings, settings));
		
		var port = settings.port;
		
		switch(settings.mode) {
		case "abort": 
			if ( pendingRequests[port] ) {
				pendingRequests[port].abort();
			}
			return pendingRequests[port] = ajax.apply(this, arguments);
		case "queue": 
			var _old = settings.complete;
			settings.complete = function(){
				if ( _old )
					_old.apply( this, arguments );
				jQuery([ajax]).dequeue("ajax" + port );;
			};
		
			jQuery([ ajax ]).queue("ajax" + port, function(){
				ajax( settings );
			});
			return;
		case "sync":
			var pos = synced.length;
	
			synced[ pos ] = {
				error: settings.error,
				success: settings.success,
				complete: settings.complete,
				done: false
			};
		
			syncedData[ pos ] = {
				error: [],
				success: [],
				complete: []
			};
		
			settings.error = function(){ syncedData[ pos ].error = arguments; };
			settings.success = function(){ syncedData[ pos ].success = arguments; };
			settings.complete = function(){
				syncedData[ pos ].complete = arguments;
				synced[ pos ].done = true;
		
				if ( pos == 0 || !synced[ pos-1 ] )
					for ( var i = pos; i < synced.length && synced[i].done; i++ ) {
						if ( synced[i].error ) synced[i].error.apply( jQuery, syncedData[i].error );
						if ( synced[i].success ) synced[i].success.apply( jQuery, syncedData[i].success );
						if ( synced[i].complete ) synced[i].complete.apply( jQuery, syncedData[i].complete );
		
						synced[i] = null;
						syncedData[i] = null;
					}
			};
		}
		return ajax.apply(this, arguments);
	};
	
})(jQuery);
/*jslint browser: true */ /*global jQuery: true */

/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

// TODO JsDoc

/**
 * Create a cookie with the given key and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String key The key of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given key.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String key The key of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function (key, value, options) {

    // key and value given, set cookie...
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = jQuery.extend({}, options);

        if (value === null) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? String(value) : encodeURIComponent(String(value)),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
/*
 * uiLock 1.0 - UI locker plugin for jQuery
 *
 * Copyright (c) 2009 jQuery Howto
 *
 * Licensed under the GPL license:
 *   http://www.gnu.org/licenses/gpl.html
 *
 * URL:
 *   http://jquery-howto.blogspot.com
 *
 * Author URL:
 *   http://me.boo.uz
 *
 */
(function($) {
    $.extend({
        uiLock: function(content){
            if(content == 'undefined') content = '';
            $('#uiLockId').attr('id', 'uiLockId').css({
                'position': 'absolute',
                'top': 0,
                'left': 0,
                'z-index': 1000,
                'opacity': 0.6,
                'width':'100%',
                'height':'100%',
                'color':'white',
                'background-color':'black'
            }).html(content);

            $('#uiLockId').show();
        },
        uiUnlock: function(){
            $('#uiLockId').hide();
        }
    });
})(jQuery);

