/*********************************************************************
Form Functions
/********************************************************************/

function getDateTime(TargetID,Format){
    Target = MM_findObj(TargetID);
    curDate = new Date();
    switch(Format){
        case "Short":
            Month = curDate.getMonth()+1;if(Month < 10){Month = "0"+ Month;}
            Day = curDate.getDate();if(Day < 10){Day = "0"+ Day;}
            Year = curDate.getFullYear();
            Hour = curDate.getHours();if(Hour < 10){Hour = "0"+ Hour;}
            Min = curDate.getMinutes();if(Min < 10){Min = "0"+ Min;}
            Sec = curDate.getSeconds();if(Sec < 10){Sec = "0"+ Sec;}
            Target.value = Month+"/"+Day+"/"+Year+" "+Hour+":"+Min+":"+Sec;
            break;
        
        case "mysql":
            Month = curDate.getMonth()+1;if(Month < 10){Month = "0"+ Month;}
            Day = curDate.getDate();if(Day < 10){Day = "0"+ Day;}
            Year = curDate.getFullYear();
            Hour = curDate.getHours();if(Hour < 10){Hour = "0"+ Hour;}
            Min = curDate.getMinutes();if(Min < 10){Min = "0"+ Min;}
            Sec = curDate.getSeconds();if(Sec < 10){Sec = "0"+ Sec;}
            Target.value = Year+"-"+Month+"-"+Day+" "+Hour+":"+Min+":"+Sec;
            break;
        default:
            Target.value = curDate.toLocaleString();
            break;
    } 

}

function mysql_datetime_to_timestamp($dt){
    $yr=strval(substr($dt,0,4));
    $mo=strval(substr($dt,5,2));
    $da=strval(substr($dt,8,2));
    $hr=strval(substr($dt,11,2));
    $mi=strval(substr($dt,14,2));
    $se=strval(substr($dt,17,2));

    return mktime($hr,$mi,$se,$mo,$da,$yr);
} // End  mysql_datetime_to_timestamp Fun

function doPageAction(PageAct){
    if(CheckForm(document.frm,true)){
        document.frm.PageAction.value = PageAct;
        document.frm.submit();
    } // End If
} // End Page Action 

/*********************************************************************
Interface Functions
/********************************************************************/
function CollapseTabels(Tabel){
    if(Tabel == undefined){
        var tbls = document.getElementsByTagName("table");
        for (cur in tbls){
            //Hide or show tabs
            if(tbls[cur].id != undefined){
                if(tbls[cur].getAttribute('collapserows') != null){ 
                    var rows = tbls[cur].getElementsByTagName('tr');
                    for (eachRow=0;eachRow<rows.length;eachRow++) {
                        if(eachRow == 0){
                            var cell = rows[eachRow].cells[0];
                            if(cell.innerHTML != "&nbsp;" && cell.innerHTML.substring(0,2) != "<a" && cell.innerHTML.substring(0,2) != "<A"){
                                cell.innerHTML = '<a href="#" style="text-decoration:none" '+ 
                                'onclick="CollapseTabels(\''+tbls[cur].id+'\')"> <font size="4"> + </font>' + cell.innerHTML + '</a>';
                            }
                            tbls[cur].setAttribute('collapsed','true')
                        }else{
                            rows[eachRow].style.display = 'none';
                        }
                    } // End For Each Row
                } // End If CollapseAttrib 
            } // End ID validation IF
        } // End For Each Tabel
    }else{
        Tabel = document.getElementById(Tabel);
        if(Tabel != undefined){
                if(Tabel.getAttribute('collapserows') != null){ 
                    var rows = Tabel.getElementsByTagName('tr');
                    for (eachRow=0;eachRow<rows.length;eachRow++) {
                        if(eachRow == 0){
                            cell = rows[eachRow].cells[0];
                            if(cell.innerHTML.substring(0,2) == "<a" || cell.innerHTML.substring(0,2) == "<A"){
                                if(Tabel.attributes.collapsed.value == 'true'){
                                    cell.innerHTML = cell.innerHTML.replace(' + ',' - ');
                                    Tabel.attributes.collapsed.value = 'false';
                                }else{
                                    cell.innerHTML = cell.innerHTML.replace(' - ',' + ');
                                    Tabel.attributes.collapsed.value = 'true';
                                }
                            }
                        }else{
                            if(Tabel.attributes.collapsed.value == 'false'){
                                rows[eachRow].style.display = '';
                            }else{
                                rows[eachRow].style.display = 'none';
                            }
                        }
                    } // End For Each Row
                } // End If CollapseAttrib 
            } // End ID validation IF
    }
} // End setupCollapseTabels

function Tabs(getTab){
    var tbls = document.getElementsByTagName("table");
    for (cur in tbls){
        //Hide or show tabs
        if(tbls[cur].id != undefined){
        //Setup TabMasters if needed
            if(tbls[cur].getAttribute('tabmaster') != null){
                if(getTab != 'default'){tbls[cur].setAttribute('curtab',getTab);}
                var firstRow = tbls[cur].rows[0];
                for (var i=0;i<firstRow.cells.length;i++) {
                    var cell = firstRow.cells[i];
                    if(cell.id == tbls[cur].getAttribute('curtab')){
                        cell.bgColor = tbls[cur].getAttribute('selectedcolor');
                    }else{
                        cell.bgColor = "";
                    }
                    if(cell.innerHTML != "&nbsp;" && cell.innerHTML.substring(0,2) != "<a"){
                        cell.innerHTML = '<a href="#" style="text-decoration:none " '+ 
                        'onclick="Tabs(\''+cell.id+'\')">' + cell.innerHTML + '</a>';
                    }
                }
            } //End If Master Tab
            if(tbls[cur].getAttribute('tabset') != null){               
                if(getTab == 'default'){
                    TabMaster = tbls[cur].getAttribute('tabset'); 
                    if(TabMaster != null){ 
                        TabMaster = document.getElementById(TabMaster);
                        if(TabMaster.getAttribute("curtab") == tbls[cur].id){ 
                            tbls[cur].style.display="";
                            addAttribToKids(tbls[cur],'isHidden','false');
                        }else{
                            tbls[cur].style.display="none";
                            addAttribToKids(tbls[cur],'isHidden','true');
                        }
                    } // End TabMaster not Defined IF
                }else{
                    if(tbls[cur].id == getTab){
                        tbls[cur].style.display="";
                        addAttribToKids(tbls[cur],'isHidden','false');
                    }else{
                        tbls[cur].style.display="none";
                        addAttribToKids(tbls[cur],'isHidden','true');
                    }
                }
            } // End If in TabSet
        } // End Table ID if
    } // End For Each in Document
} // End Tabs Fun

function addAttribToKids(PTag,attribName,attribValue){
    if(PTag.hasChildNodes != undefined){
        if(PTag.hasChildNodes()){
            for(each in PTag.childNodes){
                if(PTag.childNodes[each].setAttribute != undefined){
                    if(PTag.childNodes[each].id !=undefined || PTag.childNodes[each].id != ''){
                        PTag.childNodes[each].setAttribute(attribName,attribValue);
                    }
                }
                if(PTag.childNodes[each].hasChildNodes != undefined){
                    if(PTag.childNodes[each].hasChildNodes()){
                        //recurse
                        addAttribToKids(PTag.childNodes[each],attribName,attribValue);
                    } // End Child has Children IF
                }
            } // ENd For each Kid
        } // End if Tag has Children
    }
} // End Add attrib to tag Fun

function ShowDiv(strDivID){
    var DivID = document.getElementById(strDivID);
    if(DivID.style.display == "none"){
        DivID.style.display = "";
    }else{
        DivID.style.display = "none";
    }
}

function UnhideDiv(strDivID){
    var DivID = document.getElementById(strDivID);
    if(DivID.style.display == "none"){
        DivID.style.display = "";
    }
}

function EditDiv(ID){
    // Rplaces the contents of a Div with a text box
    DIV = document.getElementById(ID);
    if(DIV != undefined){
        if(DIV.getAttribute('Editing') == undefined){
            DIV.setAttribute('Editing','true');
            DIV.innerHTML = '<input name="frm'+ID+'" id="frm'+ID+'" type="text" size="35" value="'+ts_getInnerText(DIV)+'" onblur="SaveDiv(\''+DIV.id+'\',this)" maxlength="50">'
            frmObj = document.getElementById('frm'+ID);
            frmObj.focus();
        } // End Currently editing IF
    } //End Not Found IF
} // End Edit Div

function SaveDiv(ID,frmElm){
    // Rplaces the contents of a Div with a text box
    DIV = document.getElementById(ID);
    if(DIV != undefined){
        if(DIV.getAttribute('Editing') != undefined){
            DIV.removeAttribute('Editing');

            if(frmElm != undefined || frmElm != null){
                if(frmElm.value.replace( /^\s+/g, "" ) == ""){
                    DIVValue = "No Value Set";
                    frmElm.value = "";
                }else{
                    DIVValue = frmElm.value;
                }
                DIV.innerHTML = DIVValue+'<input name="frm'+ID+'" type="hidden" value="'+frmElm.value+'">';
            } // End Found Frm Elm OF       
        } // End Currently editing IF
    } //End Not Found IF
} // End Edit Div

/*********************************************************************
Sort Functions
/********************************************************************/
addEvent(window, "load", sortables_init);

var SORT_COLUMN_INDEX;

function sortables_init() {
    // Find all tables with class sortable and make them sortable
    if (!document.getElementsByTagName) return;
    tbls = document.getElementsByTagName("table");
    for (ti=0;ti<tbls.length;ti++) {
        thisTbl = tbls[ti];
        if (((' '+thisTbl.className+' ').indexOf("sortable") != -1) && (thisTbl.id)) {
            //initTable(thisTbl.id);
            ts_makeSortable(thisTbl);
        }
    }
}

function ts_makeSortable(table) {
    if (table.rows && table.rows.length > 0) {
        var firstRow = table.rows[0];
    }
    if (!firstRow) return;
    
    // We have a first row: assume it's the header, and make its contents clickable links
    for (var i=0;i<firstRow.cells.length;i++) {
        var cell = firstRow.cells[i];
        var txt = ts_getInnerText(cell);
        cell.innerHTML = '<a href="#" class="sortheader" '+ 
        'onclick="ts_resortTable(this, '+i+');return false;"><strong>' + 
        txt+'</strong><span class="sortarrow"><strong>&nbsp;</strong></span></a>';
    }
}

function ts_getInnerText(el) {
    if (typeof el == "string") return el;
    if (typeof el == "undefined") { return el };
    if (el.innerText) return el.innerText;  //Not needed but it is faster
    var str = "";
    
    var cs = el.childNodes;
    var l = cs.length;
    for (var i = 0; i < l; i++) {
        switch (cs[i].nodeType) {
            case 1: //ELEMENT_NODE
                str += ts_getInnerText(cs[i]);
                break;
            case 3: //TEXT_NODE
                str += cs[i].nodeValue;
                break;
        }
    }
    return str;
}

function ts_resortTable(lnk,clid) {
    // get the span
    var span;
    for (var ci=0;ci<lnk.childNodes.length;ci++) {
        if (lnk.childNodes[ci].tagName && lnk.childNodes[ci].tagName.toLowerCase() == 'span') span = lnk.childNodes[ci];
    }
    var spantext = ts_getInnerText(span);
    var td = lnk.parentNode;
    var column = clid || td.cellIndex;
    var table = getParent(td,'TABLE');
    
    // Work out a type for the column
    if (table.rows.length <= 1) return;
    var itm = ts_getInnerText(table.rows[1].cells[column]);
    sortfn = ts_sort_caseinsensitive;
    if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d\d\d$/)) sortfn = ts_sort_date;
    if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/)) sortfn = ts_sort_date;
    if (itm.match(/^[£$]/)) sortfn = ts_sort_currency;
    if (itm.match(/^[\d\.]+$/)) sortfn = ts_sort_numeric;
    SORT_COLUMN_INDEX = column;
    var firstRow = new Array();
    var newRows = new Array();
    for (i=0;i<table.rows[0].length;i++) { firstRow[i] = table.rows[0][i]; }
    for (j=1;j<table.rows.length;j++) { newRows[j-1] = table.rows[j]; }

    newRows.sort(sortfn);

    if (span.getAttribute("sortdir") == 'down') {
        ARROW = '<strong>&nbsp;&or;</strong>';
        newRows.reverse();
        span.setAttribute('sortdir','up');
    } else {
        ARROW = '<strong>&nbsp;&and;</strong>';
        span.setAttribute('sortdir','down');
    }
    
    // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
    // don't do sortbottom rows
    for (i=0;i<newRows.length;i++) { if (!newRows[i].className || (newRows[i].className && (newRows[i].className.indexOf('sortbottom') == -1))) table.tBodies[0].appendChild(newRows[i]);}
    // do sortbottom rows only
    for (i=0;i<newRows.length;i++) { if (newRows[i].className && (newRows[i].className.indexOf('sortbottom') != -1)) table.tBodies[0].appendChild(newRows[i]);}
    
    // Delete any other arrows there may be showing
    var allspans = document.getElementsByTagName("span");
    for (var ci=0;ci<allspans.length;ci++) {
        if (allspans[ci].className == 'sortarrow') {
            if (getParent(allspans[ci],"table") == getParent(lnk,"table")) { // in the same table as us?
                allspans[ci].innerHTML = '<strong>&nbsp;</strong>';
            }
        }
    }
        
    span.innerHTML = ARROW;
}

function getParent(el, pTagName) {
    if (el == null) return null;
    else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase())    // Gecko bug, supposed to be uppercase
        return el;
    else
        return getParent(el.parentNode, pTagName);
}
function ts_sort_date(a,b) {
    // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
    if (aa.length == 10) {
        dt1 = aa.substr(6,4)+aa.substr(3,2)+aa.substr(0,2);
    } else {
        yr = aa.substr(6,2);
        if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
        dt1 = yr+aa.substr(3,2)+aa.substr(0,2);
    }
    if (bb.length == 10) {
        dt2 = bb.substr(6,4)+bb.substr(3,2)+bb.substr(0,2);
    } else {
        yr = bb.substr(6,2);
        if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
        dt2 = yr+bb.substr(3,2)+bb.substr(0,2);
    }
    if (dt1==dt2) return 0;
    if (dt1<dt2) return -1;
    return 1;
}

function ts_sort_currency(a,b) { 
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
    return parseFloat(aa) - parseFloat(bb);
}

function ts_sort_numeric(a,b) { 
    aa = parseFloat(ts_getInnerText(a.cells[SORT_COLUMN_INDEX]));
    if (isNaN(aa)) aa = 0;
    bb = parseFloat(ts_getInnerText(b.cells[SORT_COLUMN_INDEX])); 
    if (isNaN(bb)) bb = 0;
    return aa-bb;
}

function ts_sort_caseinsensitive(a,b) {
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).toLowerCase();
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).toLowerCase();
    if (aa==bb) return 0;
    if (aa<bb) return -1;
    return 1;
}

function ts_sort_default(a,b) {
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
    if (aa==bb) return 0;
    if (aa<bb) return -1;
    return 1;
}


function addEvent(elm, evType, fn, useCapture){
// addEvent and removeEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
// By Scott Andrew
  if (elm.addEventListener){
    elm.addEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.attachEvent){
    var r = elm.attachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be removed");
  }
} 



/*********************************************************************
Support Functions
/********************************************************************/
function ReqSLL(){
    if (document.location.protocol != "https:"){
        document.location.href = "https://"+document.location.hostname+ document.location.pathname;
    };
} // ENd Req SSL

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}