﻿var LastRec = '';
function HttpClient() { }
HttpClient.prototype = {
    // type GET,POST passed to open
    requestType: 'GET',
    // when set to true, async calls are made
    isAsync: false,

    // where an XMLHttpRequest instance is stored
    xmlhttp: false,

    // what is called when a successful async call is made
    callback: false,

    // what is called when send is called on XMLHttpRequest
    // set your own function to onSend to have a custom loading
    // effect
    onSend: function() {
        //document.getElementById('HttpClientStatus').style.display = 'block';
    },

    // what is called when readyState 4 is reached, this is
    // called before your callback
    onload: function() {
        //document.getElementById('HttpClientStatus').style.display = 'none';
    },

    // what is called when an http error happens
    onError: function(error) {
        alert(error);
    },

    // method to initialize an xmlhttpclient
    init: function() {
        try {
            // Mozilla / Safari
            this.xmlhttp = new XMLHttpRequest();
        } catch (e) {
            // IE
            var XMLHTTP_IDS = new Array('MSXML2.XMLHTTP.5.0',
                                       'MSXML2.XMLHTTP.4.0',
                                       'MSXML2.XMLHTTP.3.0',
                                       'MSXML2.XMLHTTP',
                                       'Microsoft.XMLHTTP');
            var success = false;
            for (var i = 0; i < XMLHTTP_IDS.length && !success; i++) {
                try {
                    this.xmlhttp = new ActiveXObject(XMLHTTP_IDS[i]);
                    success = true;
                } catch (e) { }
            }
            if (!success) {
                this.onError('Unable to create XMLHttpRequest.');
            }
        }
    },

    // method to make a page request
    // @param string url  The page to make the request to
    // @param string payload  What you're sending if this is a POST
    //                        request
    makeRequest: function(url, payload) {
        if (!this.xmlhttp) {
            this.init();
        }
        this.xmlhttp.open(this.requestType, url, this.isAsync);

        // set onreadystatechange here since it will be reset after a
        //completed call in Mozilla
        var self = this;
        this.xmlhttp.onreadystatechange = function() {
            self._readyStateChangeCallback();
        }
        this.xmlhttp.send(payload);

        if (!this.isAsync) {
            return this.xmlhttp.responseText;
        }
    },

    // internal method used to handle ready state changes
    _readyStateChangeCallback: function() {
        switch (this.xmlhttp.readyState) {
            case 2:
                this.onSend();
                break;
            case 4:
                this.onload();
                if (this.xmlhttp.status == 200) {
                    if (this.callback) {
                        this.callback(this.xmlhttp.responseText);
                    }
                } else {
                    this.onError('HTTP Error Making Request: ' + '[' + this.xmlhttp.status + ']' + this.xmlhttp.statusText);
                }
                break;
        }
    }
}

/*function LoadSubUrbAjax()
{
var stateId = document.getElementById('SubUrbControl1_dlStates').value;
var searchText = document.getElementById('SubUrbControl1_txtSubUrb').value;
var httpClient = new HttpClient();
httpClient.isAsync=true;
document.getElementById('SubUrbControl1_txtSubUrb').value='Loading Suburbs...';
//document.getElementById('SubUrbControl1_txtSubUrb').disabled='disabled';
httpClient.callback = function (response)
{
var parts_ = response.split('@@@@@');
data = null;
$(document).ready(function(){
document.getElementById('SubUrbControl1_txtSubUrb').value='';
//document.getElementById('SubUrbControl1_txtSubUrb').disabled='';
data = parts_[0].split(";");
$("#SubUrbControl1_txtSubUrb").autocomplete(data);
});
document.getElementById('hidSuburbid').value=parts_[1];
}
httpClient.makeRequest('SubUrbAjax.aspx?StateId='+stateId+'&SearchText='+searchText);
}*/

if (!Array.indexOf) {
    Array.prototype.indexOf = function(obj) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
        return -1;
    }
}

function processSelectedRecord(_rid, _act, _type) {
    var httpClient = new HttpClient();
    httpClient.isAsync = true;
    httpClient.callback = function(response) { ; }
    var url = "RecordSelect.aspx?recid=" + _rid + "&act=" + ((_act) ? "add" : "remove") + "&type=" + _type + "&u=" + Math.random();
    httpClient.makeRequest(url);
}

function processCheck(aspCheckBoxID, elm, direction) {
    var checkVal = elm.checked;
    if (checkVal) {
        document.getElementById('hidChkSel').value = parseInt(document.getElementById('hidChkSel').value) + 1;
    }
    else {
        document.getElementById('hidChkSel').value = parseInt(document.getElementById('hidChkSel').value) - 1;
    }

    var chkValId = document.getElementById(elm.id.replace(aspCheckBoxID, 'hidchkItem')).value;
    processSelectedRecord(chkValId, checkVal, direction)
}
function CheckAllCheckBoxes(aspCheckBoxID, checkVal, direction) {
    re = new RegExp('\\\$' + aspCheckBoxID + '$')  //generated control name starts with a colon
    for (i = 0; i < document.forms[0].elements.length; i++) {
        elm = document.forms[0].elements[i]
        if (elm.type == 'checkbox') {
            if (re.test(elm.name)) {
                elm.checked = checkVal;
                processCheck(aspCheckBoxID, elm, direction);
            }
        }
    }
}

//Raj 03-December-2011 Start
function processSelectedRecord_New(_rid, _act, _type,RecordName) {
    var httpClient = new HttpClient();
    httpClient.isAsync = true;
    httpClient.callback = function(response) { ; }
    var url = "RecordSelect.aspx?recid=" + _rid + "&act=" + ((_act) ? "add" : "remove") + "&type=" + _type + "&RecordName=" + RecordName + "&u=" + Math.random();
    httpClient.makeRequest(url);
}

function processCheck_New(aspCheckBoxID, elm, direction, RecordName) {
    var checkVal = elm.checked;    
    if (checkVal) {
        document.getElementById('hidChkSel').value = parseInt(document.getElementById('hidChkSel').value) + 1;
    }
    else {
        document.getElementById('hidChkSel').value = parseInt(document.getElementById('hidChkSel').value) - 1;
    }

    var chkValId = document.getElementById(elm.id.replace(aspCheckBoxID, 'hidchkItem')).value;
    processSelectedRecord_New(chkValId, checkVal, direction,RecordName)
}

function CheckAllCheckBoxes_New(aspCheckBoxID, checkVal, direction,rgdData) {
    re = new RegExp('\\\$' + aspCheckBoxID + '$')  //generated control name starts with a colon
    var RecID = null;
    var RecordName = '';
    var chkHeaderVal = false;

    $('#' + rgdData + ' > table > thead > tr > th').each(function(index) {
        if ($(this).find("input:checkbox[id$=chkHeader]").attr('checked') != undefined) {
            chkHeaderVal = $(this).find("input:checkbox[id$=chkHeader]").attr('checked');
        }
    });

    $('#' + rgdData + ' > table > tbody > tr').each(function(index) {
        //alert($(this).find("[id$=chkItem]").attr('checked'));
        if (chkHeaderVal) {
            $(this).find("[id$=chkItem]").attr('checked', true);
        }
        else {
            $(this).find("[id$=chkItem]").removeAttr('checked');
        }
        RecID = $(this).find("[id$=hidchkItem]").val();
        RecordName = RecID + ";" + $(this).find("[id$=name" + RecID + "]").val();
        var elm = document.getElementById($(this).find("[id$=chkItem]").attr('id'));
        processCheck_New(aspCheckBoxID, elm, direction, RecordName);
    });
//    for (i = 0; i < document.forms[0].elements.length; i++) {
//        elm = document.forms[0].elements[i]
//        if (elm.type == 'checkbox') {
//            if (re.test(elm.name)) {
//                elm.checked = checkVal;
//                //processCheck_New(aspCheckBoxID, elm, direction,SiteName,TypeOfRecord,Date);
//            }
//        }
//    }    
}
//Raj 03-December-2011 End

function GetSelectedRecords() {
    var httpClient = new HttpClient();
    httpClient.isAsync = false;
    var url = "RecordSelect.aspx?getcount=true&u=" + Math.random();
    return httpClient.makeRequest(url);
}

function GetSelectedRecordsMessage() {
    var httpClient = new HttpClient();
    httpClient.isAsync = false;
    var url = "RecordSelect.aspx?getmessage=true&u=" + Math.random();
    return httpClient.makeRequest(url);
}

function GetSelectedRecordMessage(RecordID) {
    var httpClient = new HttpClient();
    httpClient.isAsync = false;
    var url = "RecordSelect.aspx?getmessageforRecord=" + RecordID + "&u=" + Math.random();
    return httpClient.makeRequest(url);
}


function GetSelectedRecordsArray() {
    var httpClient = new HttpClient();
    httpClient.isAsync = false;
    var url = "RecordSelect.aspx?getarray=true&u=" + Math.random();
    var p = httpClient.makeRequest(url);
    return p;
}

var recid = null;
var cindex = 0;
var recids = new Array();
var delRecords = new Array();
var currRecId = null;

function StartDeletion(rcid) {
    recid = null;    
    var selectedChecks = rcid != 'undefined' ? 1 : parseInt(GetSelectedRecords());

    //Raj 16-August-2011    
    var Msg = rcid != 'undefined' ? GetSelectedRecordMessage(rcid).toString() : GetSelectedRecordsMessage().toString();

    if (rcid == null && selectedChecks == 0) {
        Message.ShowMessage("Delete Record", "Select atleast one record to delete!");
        return false;
    }

    //Raj 16-August-2011
    if (rcid == 'undefined' && selectedChecks == 0) {
        Message.ShowMessage("Delete Record", "Select atleast one record to delete!");
        return false;
    }

    recid = rcid;
    if ('<%= Request["mode"]%>' != 'rb')
        ExtConfirm.ShowDialog('Please confirm...!!', Msg, firstPass);
    else
        ExtConfirm.ShowDialog('Please confirm...!!', "You are about to permanently delete " + (selectedChecks > 1 ? "(" + selectedChecks + ")" : "") + " Record" + (selectedChecks > 1 ? "s" : "") + "?", firstPass);
    return false;

}
function DeleteSequence(rcid) {
    window.setTimeout("StartDeletion('" + rcid + "')", rcid != undefined ? 100 : 200);
    return false;
}

function firstPass() {
    var Msg = ""; 
    if (recid != 'undefined') {
        recids.push(recid);
    }
    else {
        recids = GetSelectedRecordsArray().toString().split(";");
        if (recids.length == 0) return;
    }
    //alert(recids.length);
    var recnames = '';
    for (cindex = 0; cindex < recids.length; cindex++) {
        currRecId = recids[cindex];
        
        var faults = document.getElementById('fault' + currRecId) == null ? parseInt(getFaultCount(currRecId)) : parseInt(document.getElementById('fault' + currRecId).value);
        var recname = document.getElementById('name' + currRecId) == null ? getRecordName(currRecId) : document.getElementById('name' + currRecId).value;
        
        //return;
        recid = currRecId;
        if (faults > 0) {
            //if(confirm("Warning - there are one or more open faults which are associated with record " + recname + " - deleting the record will also delete the fault(s). Do you wish to proceed?")) {
            //    DeleteCurrentRecord(cindex+1==recids.length ? 'last':'');
            //}
            if (confirm("This record with name " + recname + " is associated with one or more open faults, deleting this record will remove this association.")) {
                DeleteCurrentRecord(cindex + 1 == recids.length ? 'last' : '');
            }
            //Msg = "This record with name " + recname + " is associated with one or more open faults, deleting this record will remove this association.";
            //LastRec = cindex + 1 == recids.length ? 'last' : '';
            //ExtConfirm.ShowDialog('Please confirm...!!', Msg, RecDelNew);
        }
        else {            
            DeleteCurrentRecord(cindex + 1 == recids.length ? 'last' : '');
        }
    }
    return false;
}

function RecDelNew() {    
    DeleteCurrentRecord(LastRec);
}

function getFaultCount(recordId) {
    var httpClient = new HttpClient();
    httpClient.isAsync = false;
    var url = "RecordSelect.aspx?action=gfc&RecordId=" + recordId + "&u=" + Math.random();
    var p = httpClient.makeRequest(url);
    return p;
}

function getRecordName(recordId) {
    var httpClient = new HttpClient();
    httpClient.isAsync = false;
    var url = "RecordSelect.aspx?action=grn&RecordId=" + recordId + "&u=" + Math.random();
    var p = httpClient.makeRequest(url);
    return p;
}
function ClearSiteName(recordId) {
    var httpClient = new HttpClient();
    httpClient.isAsync = false;
    var url = "RecordSelect.aspx?action=cls&RecordId=" + recordId + "&u=" + Math.random();
    httpClient.makeRequest(url);
}
function getUploadCount() {
    var httpClient = new HttpClient();
    httpClient.isAsync = false;
    var url = "RecordSelect.aspx?action=uplcnt&u=" + Math.random();
    var p = httpClient.makeRequest(url);
    return p;
}
function getProgress() {
    var hClient = new HttpClient();
    hClient.isAsync = false;
    var url = "RecordSelect.aspx?action=getstatus&u=" + Math.random();
    var p = hClient.makeRequest(url);
    return p;
}
