﻿var regexZip = /^\d{5}$/;
var regexPhone = /\W?\d\d\d\W?\d\d\d\W?\d\d\d\d/;
var regexEmail = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
var regexText = /^\s*[a-zA-Z,\s]+\s*$/;
var regexNumber = /^[-+]?\d*\.?\d*$/;
var regexPositiveNumber = /^\d*\.?\d*$/;
var regexInteger = /^\d+$/;
var regexUrl = /^[a-zA-Z0-9\-\.]+\.(com|org|net|mil|edu|gov|COM|ORG|NET|MIL|EDU|GOV)$/
var regexTxtNum = /^([1-zA-Z0-1@.\s]{1,255})$/;  // validates against non-keyboard characters
var regexTime = /^([0-1][0-9]):([0-5][0-9])$/;
var regexDate = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;

var selIndex;

function ShowElement(elemId, objId, x, y) {

    if (objId != undefined && objId != '') {
        var j = Sys.UI.DomElement.getLocation($get(objId));
        var y = j.y + y;
        var x = j.x + x;
        $get(elemId).style.top = y + 'px';
        $get(elemId).style.left = x + 'px';
    };
    
    $get(elemId).style.display = 'inline';
};


function StartYMap() {

   
//    var map = new YMap(document.getElementById('map'));
//    var cPT = new YGeoPoint(34.018863,-117.721994);
//    map.addZoomLong();
//    map.addTypeControl();
//   
//    map.disableKeyControls();
//    map.drawZoomAndCenter(cPT, 6);
//    map.addMarker(cPT);

//    document.getElementById('map').style.height = '300px';
//    document.getElementById('map').style.width = '400px';

//    var map = new YMap(document.getElementById('mapAltadena'));
//    var cPT = new YGeoPoint(34.180430, -118.131612);
//    map.addZoomLong();
//    map.addTypeControl();

//    map.disableKeyControls();
//    map.drawZoomAndCenter(cPT, 6);
//    map.addMarker(cPT);

//    document.getElementById('mapAltadena').style.height = '300px';
//    document.getElementById('mapAltadena').style.width = '400px';

//    var map = new YMap(document.getElementById('mapSandiego'));
//    var cPT = new YGeoPoint(32.744943, -117.211909);
//    map.addZoomLong();
//    map.addTypeControl();

//    map.disableKeyControls();
//    map.drawZoomAndCenter(cPT, 6);
//    map.addMarker(cPT);

//    document.getElementById('mapSandiego').style.height = '300px';
//    document.getElementById('mapSandiego').style.width = '400px';

//    var map = new YMap(document.getElementById('mapLaHabra'));
//    var cPT = new YGeoPoint(33.939713, -117.971310);
//    map.addZoomLong();
//    map.addTypeControl();

//    map.disableKeyControls();
//    map.drawZoomAndCenter(cPT, 6);
//    map.addMarker(cPT);

//    document.getElementById('mapLaHabra').style.height = '300px';
//    document.getElementById('mapLaHabra').style.width = '400px';

//    var map = new YMap(document.getElementById('mapUpland'));
//    var cPT = new YGeoPoint(34.093511, -117.636315);
//    map.addZoomLong();
//    map.addTypeControl();

//    map.disableKeyControls();
//    map.drawZoomAndCenter(cPT, 6);
//    map.addMarker(cPT);

//    document.getElementById('mapUpland').style.height = '300px';
//    document.getElementById('mapUpland').style.width = '400px';

//    var map = new YMap(document.getElementById('mapAppleValley'));
//    var cPT = new YGeoPoint(34.544698, -117.268605);
//    map.addZoomLong();
//    map.addTypeControl();

//    map.disableKeyControls();
//    map.drawZoomAndCenter(cPT, 6);
//    map.addMarker(cPT);

//    document.getElementById('mapAppleValley').style.height = '300px';
//    document.getElementById('mapAppleValley').style.width = '400px';


//    var map = new YMap(document.getElementById('mapRialto'));
//    var cPT = new YGeoPoint(34.10677, -117.352409);
//    map.addZoomLong();
//    map.addTypeControl();

//    map.disableKeyControls();
//    map.drawZoomAndCenter(cPT, 6);
//    map.addMarker(cPT);

//    document.getElementById('mapRialto').style.height = '300px';
//    document.getElementById('mapRialto').style.width = '400px';

//    var map = new YMap(document.getElementById('mapLA'));
//    var cPT = new YGeoPoint(34.076735, -118.286454);
//    map.addZoomLong();
//    map.addTypeControl();

//    map.disableKeyControls();
//    map.drawZoomAndCenter(cPT, 6);
//    map.addMarker(cPT);

//    document.getElementById('mapLA').style.height = '300px';
//    document.getElementById('mapLA').style.width = '400px';

//    var map = new YMap(document.getElementById('mapRiverside'));
//    var cPT = new YGeoPoint(33.990382, -117.343754);
//    map.addZoomLong();
//    map.addTypeControl();

//    map.disableKeyControls();
//    map.drawZoomAndCenter(cPT, 6);
//    map.addMarker(cPT);

//    document.getElementById('mapRiverside').style.height = '300px';
//    document.getElementById('mapRiverside').style.width = '400px';

//    var map = new YMap(document.getElementById('mapMurieta'));
//    var cPT = new YGeoPoint(33.551141, -117.127799);
//    map.addZoomLong();
//    map.addTypeControl();

//    map.disableKeyControls();
//    map.drawZoomAndCenter(cPT, 6);
//    map.addMarker(cPT);

//    document.getElementById('mapMurieta').style.height = '300px';
//    document.getElementById('mapMurieta').style.width = '400px';
//    
//    
//    var setupMarker = function(p, d) {
//        var m = new YMarker(p);
//        m.addAutoExpand(d);
//        return m;
//    };
};

function isEnterKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode == 13) {
        return true;
    };
    return false;
};
function validateSubmit(exToValidate, errHolder, exType, exInvalid, exValid) {

    if (exValid != '' && exValid == exToValidate) {
        return true;
    };
    if (exToValidate == exInvalid && exInvalid != '') {
        if (errHolder != '') {
            $get(errHolder).style.display = 'inline';
        };
        return false;
    };

    var regex;
    switch (exType) {
        case 'zip':
            regex = regexZip;
            break;
        case 'phone':
            regex = regexPhone;
            break;
        case 'email':
            regex = regexEmail;
            break;
        case 'text':
            regex = regexText;
            break;
        case 'number':
            if (exToValidate.length == 0) {
                exToValidate = ' ';
            };
            regex = regexNumber;
            break;
        case 'time':
            if (exToValidate.length == 0) {
                exToValidate = ' ';
            };
            regex = regexTime;
            break;
        case 'date':
            if (exToValidate.length == 0) {
                exToValidate = ' ';
            };
            regex = regexDate;
            break;
        case 'url':
            regex = regexUrl;
            break;
        case 'txtNum':
            regex = regexTxtNum;
            break;
        case 'any':
            return true;
            break;
    }

    if (regex.test(exToValidate) == false) {
        if (errHolder != '') {
            $get(errHolder).style.display = 'inline';
        }
        return false;
    }
    return true;
};

function checkNum(field) {
    if (field.value.length > 0) {
        var lastChar = field.value.substring(field.value.length - 1, field.value.length);
        if (regexNumber.test(lastChar) == false) {
            field.value = field.value.substring(0, field.value.length - 1);
        }
    }
};

function shortDate(date) {
    if (date == '') {
        return '';
    };
    var d = new Date(date);
    return (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();
};

//=======TRIM=====
function LTrim(value) {
    var re = /\s*((\S+\s*)*)/;
    return value.replace(re, "$1");
}

function RTrim(value) {
    var re = /((\s*\S+)*)\s*/;
    return value.replace(re, "$1");
}

function trim(value) {
    return LTrim(RTrim(value));
}
//================
//====================COOKIES=========================

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=")
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1
            c_end = document.cookie.indexOf(";", c_start)
            if (c_end == -1) c_end = document.cookie.length
            return unescape(document.cookie.substring(c_start, c_end))
        }
    }
    return ""
};

function setCookie(c_name, value, expiredays) {
    var exdate = new Date()
    exdate.setDate(exdate.getDate() + expiredays)
    document.cookie = c_name + "=" + escape(value) +
       ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString())
};

//====================COOKIES_END=====================
function Watermark(txtField, bFocus, sWatermarkText, errHolder) {

    $get(txtField).value = trim($get(txtField).value);
    ClearErrorHolder(errHolder)
    if (bFocus) {
        if ($get(txtField).value == sWatermarkText) {
            $get(txtField).value = '';
        };
    }
    else {
        if ($get(txtField).value == '') {
            $get(txtField).value = sWatermarkText;
        };
    };
};

function ClearErrorHolder(errHolder) {
    if (errHolder != '') {
        $get(errHolder).style.display = 'none';
    };
};

function HideElement(elemId) {
    $get(elemId).style.display = 'none';
};

function CheckUncheckAll(chk, objName) {
    var obj = document.getElementsByName(objName);
    for (var i = 0; i < obj.length; i++) {
        obj[i].checked = chk.checked;
    };
};

var params = '';
var vals = '';
var strId = '';

function ClearForm() {
   
    strId = '';
    //document.getElementById('ifUploadFile').contentDocument.getElementById('lblUploadError').innerHTML = '';
    setCookie("selectedCustomerId", 0, 1);
    $get('divCustId').innerHTML = '';
    $get('hfSelectedCustomerId').value = 0;
    $get('txtCustSearch').value = '';
    $get('txtCustFirstName').value = '';
    $get('txtCustLastName').value = '';
    $get('txtCustAddress').value = '';
    $get('txtCustCity').value = '';
    $get('txtCustState').value = '';
    $get('txtCustZip').value = '';
    $get('txtCustPhone').value = '';
    $get('txtCustEmail').value = '';
    $get('txtCustNotes').value = '';
    $get('txtCustRecomendation').value = '';
        
    $get('txtCustID').value = '';
    $get('ddlCustSource').selectedIndex = 0;
    $get('ddlDoctor').selectedIndex = 0;
    $get('spEnrollmentDate').innerHTML = '';

    var d = new Date();
    d.setYear(d.getFullYear() + 1);
    $get('txtRecomExp').value = d.format("M/dd/yyyy");
    //$get('btnDeleteCustomer').style.display = 'none';
   
    $get('hfReferralId').value = 0;
    $get('hfReferrals').value = 0;
    $get('spCustReferredBy').style.display = 'inline';
    //$get('divRecomendationExpiration').innerHTML = '';
    
    $get('txtDiscount').value = 0;
    $get('txtCustSearch').focus();

    $get('txtCaregiverName').value = '';
    $get('txtCaregiverId').value = '';
    $get('txtCaregiverIdExp').value = '';
};

function LoadCustomerInfo(i) {
    
    strId = '';
    setCookie("selectedCustomerId", oCust[i].ID, 1);
    $get('divCustId').innerHTML = 'ID: ' + oCust[i].ID;
    $get('spSearchResult').style.display = 'none';
    $get('spCustReferredBy').style.display = 'none';
    $get('txtCustSearch').value = '';
    $get('hfSelectedCustomerId').value = oCust[i].ID;
    $get('txtCustFirstName').value = oCust[i].FirstName;
    $get('txtCustLastName').value = oCust[i].LastName;
    $get('txtCustAddress').value = oCust[i].Address;
    $get('txtCustCity').value = oCust[i].City;
    $get('txtCustState').value = oCust[i].State;
    $get('txtCustZip').value = oCust[i].Zip;
    $get('txtCustPhone').value = oCust[i].Phone;
    $get('txtCustEmail').value = oCust[i].Email;
    $get('txtCustNotes').value = oCust[i].Notes;
    $get('txtCustID').value = oCust[i].Identification;
    
    $get('txtCustRecomendation').value = oCust[i].Recomendation;
    $get('ddlCustSource').value = oCust[i].SourceId;
    
    $get('ddlDoctor').value = oCust[i].DoctorId;

    if (shortDate(oCust[i].RecomendationExpiration) != '1/1/1900') {
        $get('divRecomendation').innerHTML = 'Recommendation Expiration: ' +
                                             '<span style=font-weight:bold id=divRecomendationExpiration></span>' +
                                             ', Last Payment: ' + oCust[i].LastPayment +
                                             ', Discount: ' + oCust[i].Discount +
                                             ' <input type="button" class="ButtonPrint" title="Print Recommendation" id = "btnPrintRecom" onclick="printRecommendation()" />' + 
                                             ' <input onclick=deleteLastPayment(' + oCust[i].ID + ') type=button class=ButtonDelete value="" />'

        $get('divRecomendationExpiration').innerHTML = shortDate(oCust[i].RecomendationExpiration);
        //$get('ddlPayment').selectedIndex = 1;       
    } else {
        $get('divRecomendation').innerHTML = '';
        //$get('ddlPayment').selectedIndex = 0;
    };

    var sEnrollReferred = 'Enr. date: ' + oCust[i].EnrollmentDate
    if (oCust[i].ReferredByName != '') {
        sEnrollReferred += ', Ref: ' + oCust[i].ReferredByName
    };
    $get('spEnrollmentDate').innerHTML = sEnrollReferred;
    $get('hfReferralId').value = oCust[i].ReferredById;
    $get('hfReferrals').value = oCust[i].Referrals;

    $get('txtCaregiverName').value = oCust[i].CaregiverName;
    $get('txtCaregiverId').value = oCust[i].CaregiverId;
    $get('txtCaregiverIdExp').value = oCust[i].CaregiverIdExp;
   
};


var key13 = 0;
function CustomerSearchKeyDown(evt) {
    
    if (isEnterKey(evt)) {
        key13 += 1;
    };

    if (key13 == 1 && isEnterKey(evt) && $get('txtCustSearch').value.indexOf('^?') < 1) {
        CustomerSearch($get('txtCustSearch').value)
        key13 = 0;
        return;
    };    
    
    if (key13 == 3) {
        key13 = 0;
        
        CustomerSearch($get('txtCustSearch').value);
        $get('txtCustSearch').value = '';
    };

    if ($get('txtCustSearch').value.indexOf('#!!') > 0 && isEnterKey(evt)) {
        CustomerSearch($get('txtCustSearch').value);
        $get('txtCustSearch').value = '';
    };
};


function CustomerSearch(search) {
   
    if (search != '') {
        if (search.indexOf('^?') > 0) {
            ClearForm();

            strId = search;
            search = search.substring(search.indexOf('^?;') + 3, search.length);
            search = search.substring(0, search.indexOf('='));
            search = search.substring(8, search.length);
        };

       
        var params = '@search|@accountId';
        var vals = search + '|' + $get("hfa").value;
        $get('ProgressIndicator').className = 'ProgressIndicator';
        PageMethods.GetSearchResult(params, vals, OnSuccess, OnError, 'GetSearchResult');
    };
};

function AddUpdateCustomer() {
    var blnAddUpdate = true;

    if (validateSubmit($get('txtCustFirstName').value, 'spReqFirstName', 'txtNum', '') == false) {
        blnAddUpdate = false;
    };

    if (validateSubmit($get('txtCustLastName').value, 'spReqLastName', 'txtNum', '') == false) {
        blnAddUpdate = false;
    };

    if (validateSubmit($get('txtCustID').value, 'spReqCustId', 'txtNum', '') == false) {
        blnAddUpdate = false;
    }; 
    
    if ($get('ddlCustSource').selectedIndex == 0) {
        alert('Source must be selected.');
        $get('ddlCustSource').focus();
        return false;
    };

    if ($get('ddlDoctor').selectedIndex == 0) {
        alert('Please, selecte the doctor from the list.');
        $get('ddlDoctor').focus();
        return false;
    };

    
    
    if (blnAddUpdate == false) {
        alert('Information is not saved. Please, check if all required information (*) is entered.');
        return false;
    };

    $get('ProgressIndicator').className = 'ProgressIndicator';

    params = '@customerId|@firstName|@lastName|@address|@city|@state|@zip|@phone|' +
             '@email|@identification|@recomendation|@notes|@accountId|@sourceId|@referredById|' +
             '@caregiverName|@caregiverId|@caregiverIdExp|@doctorId'

    if (regexNumber.test($get('txtCustID').value.substring(0, 1)) == false) {
        $get('txtCustID').value = $get('txtCustID').value.substr(1, $get('txtCustID').value.length)
    };
    vals = $get('hfSelectedCustomerId').value + '|' +
           $get('txtCustFirstName').value + '|' +
           $get('txtCustLastName').value + '|' +
           $get('txtCustAddress').value + '|' +
           $get('txtCustCity').value + '|' +
           $get('txtCustState').value + '|' +
           $get('txtCustZip').value + '|' +
           $get('txtCustPhone').value + '|' +
           $get('txtCustEmail').value + '|' +
           $get('txtCustID').value + '|' +
           $get('txtCustRecomendation').value + '|' +
           $get('txtCustNotes').value + '|' +
           $get('hfa').value + '|' +
           $get('ddlCustSource').value + '|' +
           $get('hfReferralId').value + '|' +
           $get('txtCaregiverName').value + '|' +
           $get('txtCaregiverId').value + '|' +
           $get('txtCaregiverIdExp').value + '|' +
           $get('ddlDoctor').value; 
    
    PageMethods.AddUpdateData('CustomerAddUpdate', params, vals, '@customerIdOut', 'int', OnSuccess, OnError, 'CustomerAddUpdate')
};

function DeletePatient() {
    if ($get('hfSelectedCustomerId').value == 0) {
        alert('No patient selected.');
        return;
    };
    if (confirm('Are sure you want to delete this patient and all the records associated with this patient?')) {
        $get('ProgressIndicator').className = 'ProgressIndicator';
        params = '@customerId|@delete';
        vals = $get('hfSelectedCustomerId').value + '|1';
        PageMethods.AddUpdateData('CustomerAddUpdate', params, vals, '@customerIdOut', 'int', OnSuccess, OnError, 'CustomerDelete')
    };
};

function GetCustomerSource(context) {
    var params = '@accountId';
    var vals = $get('hfa').value;
    PageMethods.GetCustomerSource(params, vals, OnSuccess, OnError, context)
};

function LoadCustomerSource(oSource) {
    var sClass = 'ItemRow'

    sTable = '<table cellpadding=0 cellspacing=0 width=100%>'
    for (i = 0; i < oSource.length; i++) {

        sClass = i % 2 ? 'AltRow' : 'ItemRow';

        sTable += '<tr style=height:22px class=' + sClass + ' onmouseover=this.className="ItemOver" '
        sTable += 'onmouseout=this.className="' + sClass + '" '
        if ((oSource[i].AccountID - 0) > 0) {
            sTable += ' onclick=SelectSource(' + oSource[i].SourceId + ',"' + oSource[i].SourceName + '",' + oSource[i].AccountID + ') '
        }
        sTable += ' >'
        sTable += '<td>' + oSource[i].SourceName + '</td>'
        sTable += '</tr>'
    };
    sTable += '</table>'
    
    return sTable;
};

function SelectSource(sourceId, sourceName, accountId) {
    
    $get('hfSelectedCustomerSourceId').value = sourceId;
    $get('txtCustSourceName').value = sourceName;
};

function AddUpdateCustomerSource() {
    var params = '@accountId|@sourceId|@sourceName';
    var vals = $get('hfa').value + '|' + $get('hfSelectedCustomerSourceId').value + '|' + $get('txtCustSourceName').value;
    PageMethods.AddUpdateData('CustomerSourceAddUpdate', params, vals, '@idOut', 'int', OnSuccess, OnError, 'CustomerSourceAddUpdate')
};

function ReferralSearch(search) {
    $get('divReferralSearchResult').innerHTML = '';
    if (search.length > 2 && regexText.test(search)) {
        var params = '@search|@accountId';
        var vals = search + '|' + $get("hfa").value;
        PageMethods.GetSearchResult(params, vals, OnSuccess, OnError, 'GetReferralSearchResult');
    };
};

function SelectReferral(id, name) {
    HideElement('divReferralSearchResult');
    $get('hfReferralId').value = id;
    $get('txtCustReferredBy').value = name;
};

function submitPayment() {

    if ($get('ddlDoctor').value == '' || $get('ddlDoctor').value == '0') {
        alert('Please, selecte doctor from the list.');
        return;
    };
    
    if ($get('hfSelectedCustomerId').value == 0) {
        alert('No patient selected.')
        return;
    };

    if ($get('txtPayment').value == '' || $get('txtPayment').value <= 0) {
       alert('Payment must be a positive number.');
       $get('txtPayment').focus();
       return;
    };

    if (regexInteger.test($get('txtRedeemRefs').value) == false) {
        alert('Redeem number must be numeric value');
        return;
    };

    if ($get('txtRedeemRefs').value > $get('hfReferrals').value) {
        alert('Redeem number exceeds referrals number.');
        return;
    };
    
    if (regexDate.test($get('txtRecomExp').value) == false) {
        alert('Please, enter valid recommendation expiration date.')
        $get('txtRecomExp').focus();
        return;
    };
    
    if (confirm('Click OK to finalize payment') == false) {
        return;
    };
    params = '@patientId|@amount|@discount|@redeemReferrals|@recExpDate|@doctorId';
    vals = $get('hfSelectedCustomerId').value + '|' + $get('txtPayment').value + '|' +
           $get('txtDiscount').value + '|' + $get('txtRedeemRefs').value + '|' + $get('txtRecomExp').value + '|' +
           $get('ddlDoctor').value;

    PageMethods.AddUpdateData('CustomerPayment', params, vals, '@recExpOut', 'str', OnSuccess, OnError, 'CustomerPayment')
};

function deleteLastPayment(patientId) {
    if (confirm('Are you sure you want to delete this payment?') == true) {
        params = '@patientId|@delete';
        vals = patientId + '|1';
        PageMethods.AddUpdateData('CustomerPayment', params, vals, '@recExpOut', 'str', OnSuccess, OnError, 'CustomerPayment')
    };
};

function printRecommendation() {
    if ($get('hfSelectedCustomerId').value == 0) {
        alert('No customer selected.');
        return
    };

    if ($get('divRecomendationExpiration').innerHTML == '') {
        alert('Recommendation expiration date is invalid.');
        return;         
    };
    window.open('recommendation.aspx?patientId=' + $get('hfSelectedCustomerId').value, 'RECOM', 'scrollbars=yes,toolbar=yes,top=0,left=0,scrollbars=yes');
};

function getReport(reportId,doctorId) {
    if (reportId > 0) {

        params = '@accountId|@dateFrom|@dateTo'
        vals = $get('hfa').value + '|' + $get('txtDateFrom').value + '|' + $get('txtDateTo').value
        
        params += reportId == '2' ? '|@deleted' : ''
        vals += reportId == '2' ? '|1' : ''
        
        params += doctorId > 0 ? '|@doctorId' : ''
        vals += doctorId > 0 ? '|' + doctorId : ''
        
        PageMethods.ReportSales(params, vals, OnSuccess, OnError, 'ReportSales')
    };
};
//======================================================
//======================================================
function verifyPatient(recom,dlid) {
    

    if (regexNumber.test(dlid.substring(0, 1)) == false) {
        dlid = dlid.substr(1,dlid.length) 
    }

    params = '@accountId|@verify|@identification|@recomendation';
    vals = '1|1|' + dlid + '|' + recom

    $get('ProgressIndicator').className = 'ProgressIndicator';
    PageMethods.GetSearchResult(params, vals, OnSuccess, OnError, 'Verify');
};

function getCaregiver(id) {
    if (id == '') {
        alert('Please, enter caregiver id');
        return;
    };
    params = '@verify|@identification';
    vals = '2|' + id
    
    $get('ProgressIndicator').className = 'ProgressIndicator';
    PageMethods.GetCaregiver(params, vals, OnSuccess, OnError, 'VerifyCaregiver');
};

//====================ONSUCCESS/ONERROR=========================
var cssClassNames = {
    'headerRow': 'hidden-header',
    'tableRow': '',
    'oddTableRow': '',
    'selectedTableRow': '',
    'hoverTableRow': '',
    'headerCell': '',
    'tableCell': '',
    'rowNumberCell': ''
};

function OnError(errorRet, context, method) {
    $get('ProgressIndicator').className = 'ProgressIndicatorHidden';
    alert(errorRet.get_message());
};

function OnSuccess(result, userContext, method) {
    $get('ProgressIndicator').className = 'ProgressIndicatorHidden';
    switch (userContext) {
        case 'GetSearchResult':

            if (result == 0) {
                
                if (strId != '') {
                    $get('txtCustState').value = strId.substr(1, 2);
                    if (strId.indexOf('^') < 13) {
                        $get('txtCustCity').value = strId.substring(3, strId.indexOf('^')).replace(/^/g, '');
                        $get('txtCustLastName').value = strId.substring(strId.indexOf('^') + 1, strId.indexOf('$')).replace(/^/g, '');

                    } else {
                        $get('txtCustCity').value = strId.substring(3, 13).replace(/^/g, '');
                        $get('txtCustLastName').value = strId.substring(14, strId.indexOf('$')).replace(/^/g, '');
                    };

                    strId = strId.substring(strId.indexOf('$') + 1, strId.length);
                    $get('txtCustFirstName').value = strId.substring(0, strId.indexOf('$')).replace(/^/g, '');

                    strId = strId.substring(strId.indexOf('^') + 1, strId.length);
                    $get('txtCustAddress').value = strId.substring(0, strId.indexOf('^'));

                    strId = strId.substring(strId.indexOf('^?;') + 3, strId.length);
                    //strId = strId.substring(0, strId.indexOf('!!') + 7);

                    $get('txtCustZip').value = strId.substring(strId.indexOf('!!') + 2, strId.indexOf('!!') + 7);
                    strId = strId.substring(0, strId.indexOf('='));
                    strId = strId.substring(8, strId.length);
                    $get('txtCustID').value = strId;
                    strId = '';

                }
                else {
                    result = "<table cellpadding=0 cellspacing=0 "
                    result += "style='width:300px;border:solid 3px #cecece;background-color:#ececec;'><tr>"
                    result += "<td colspan=2 "
                    result += "style='padding-right:3px;text-align:right;height:22px;background-image:url(/images/bg_blue_gradient.jpg)'>"
                    result += "<img src='/images/Close.gif' style='cursor:pointer' onclick=HideElement('spSearchResult'); />"
                    result += "</td></tr>"
                    result += "<tr><td class=Error style='height:22px;padding-left:3px'>"
                    result += "No result found!"
                    result += "</td></tr>"
                    result += "</table>"

                    ShowElement('spSearchResult', 'btnNew', 60, 0);
                    $get('spSearchResult').innerHTML = result;
                };
            }
            else {

                oCust = Sys.Serialization.JavaScriptSerializer.deserialize(result);
                switch (oCust.length) {
                    case 1:
                        LoadCustomerInfo(0)
                        break;
                    default:
                        var sTable
                        var sClass = 'ItemRow'
                        sTable = '<table cellpadding=0 cellspacing=0 style="border:solid 3px #cecece;"><tr><td>'
                        sTable += '<table cellpadding=0 cellspacing=0 style="width:300px"><tr>'
                        sTable += '<td style=padding-right:1px;text-align:right;height:22px;background-image:url(/images/bg_blue_gradient.jpg)>'
                        sTable += '<img src="/images/Close.gif" style=cursor:pointer onclick=HideElement("spSearchResult") />'
                        sTable += '</td></tr></table><div style=width:300px;height:147px;overflow-y:scroll;background-color:#ececec>'
                        sTable += '<table cellpadding=0 cellspacing=0 width=283>'

                        for (i = 0; i < oCust.length; i++) {
                            if (i % 2) {
                                sClass = 'AltRow';
                            }
                            else {
                                sClass = 'ItemRow';
                            }
                            sTable += '<tr style=height:22px;cursor:pointer class=' + sClass + ' onmouseover=this.className="ItemOver" '
                            sTable += 'onmouseout=this.className="' + sClass + '" '
                            sTable += ' onclick=HideElement("spSearchResult");LoadCustomerInfo(' + i + ')>'
                            sTable += '<td style=padding:2px>' + oCust[i].FirstName + '</td>'
                            sTable += '<td>' + oCust[i].LastName + '</td>'
                            sTable += '<td>' + oCust[i].Identification + '</td>'
                            sTable += '</tr>'
                        }
                        sTable += '</table></td></tr></table></div>'
                        //$get('spSearchResult').style.display = 'inline';
                        ShowElement('spSearchResult', 'btnNew', 60, 0);
                        $get('spSearchResult').innerHTML = sTable;
                        break;
                }
            };
            break;
        case 'CustomerAddUpdate':
            if ($get('hfSelectedCustomerId').value == 0) {
                var d = new Date();
                $get('txtCustRecomendation').value = d.getFullYear() + '-' + result;
            };
            $get('hfSelectedCustomerId').value = result;
            break;
        case 'CustomerDelete':
            ClearForm();
            break;
        case 'GetCustomerSource':
            obj = Sys.Serialization.JavaScriptSerializer.deserialize(result);
            $get('divCustomerSource').innerHTML = LoadCustomerSource(obj);
            break;
        case 'CustomerSourceAddUpdate':
            HideElement('tblCustomerSource');
            $get('hfSelectedCustomerSourceId').value = 0;
            $get('txtCustSourceName').value = '';
            GetCustomerSource('UpdateCustomerSource');
            break;
        case 'UpdateCustomerSource':
            selIndex = $get('ddlCustSource').selectedIndex;
            $get('ddlCustSource').length = 0;
            $get('ddlCustSource')[0] = new Option('-Select Source-', 0);
            obj = Sys.Serialization.JavaScriptSerializer.deserialize(result);
            for (i = 0; i < obj.length; i++) {
                $get('ddlCustSource')[i + 1] = new Option(obj[i].SourceName.replace(/&nbsp;/g, ' '), obj[i].SourceId);
            };
            $get('ddlCustSource').selectedIndex = selIndex;
            break;
        case 'GetReferralSearchResult':
            var options = { 'allowHtml': true, 'cssClassNames': cssClassNames, 'alternatingRowStyle': true, 'width': 200 };
            var data = new google.visualization.DataTable();
            var table = new google.visualization.Table($get('divReferralSearchResult'));

            if (result != '') {
                ShowElement('divReferralSearchResult', 'txtCustReferredBy', 2, 22);
                oRef = Sys.Serialization.JavaScriptSerializer.deserialize(result);
                data.addColumn('number', 'ID');
                data.addColumn('string', 'Name');
                data.addRows(oRef.length);

                for (var i = 0; i < oRef.length; i++) {
                    data.setCell(i, 0, oRef[i].ID - 0)
                    data.setCell(i, 1, oRef[i].FirstName + ' ' + oRef[i].LastName, null, { 'style': 'height:22px;' });
                };
                var view = new google.visualization.DataView(data);
                view.setColumns([1]);
                table.draw(view, options);

                google.visualization.events.addListener(table, 'select', function(e) {
                    var selection = table.getSelection();
                    var r = selection[0].row;
                    var id = data.getFormattedValue(r, 0);
                    var name = data.getFormattedValue(r, 1);
                    SelectReferral(id, name)
                });
            }
            else {
                data.addColumn('string', '');
                data.addRows(1);
                data.setCell(0, 0, 'No matching referral', null, { 'style': 'height:22px' })
                table.draw(data, options);
            };
            break;
        case 'CustomerPayment':
            var params = '@customerId|@accountId';
            var vals = $get('hfSelectedCustomerId').value + '|' + $get("hfa").value;
            $get('ProgressIndicator').className = 'ProgressIndicator';
            PageMethods.GetSearchResult(params, vals, OnSuccess, OnError, 'GetSearchResult');
            break;
        case 'Verify':

            var verifyResult;
            if (result == '') {
                verifyResult = 'Search produced no result.';
            } else {
                oCust = Sys.Serialization.JavaScriptSerializer.deserialize(result);

                verifyResult = 'Patient Name: ' + oCust[0].FirstName + ' ' + oCust[0].LastName + '<br>' +
                               'Recomendation Expiration: ' + shortDate(oCust[0].RecomendationExpiration);
            };

            $get('divVerifyResult').innerHTML = verifyResult;
            break;

        case 'VerifyCaregiver':
            if (result == '') {
                $get('divVerifyResult').innerHTML = 'No record found.';
                return;
            }

            oRec = Sys.Serialization.JavaScriptSerializer.deserialize('[' + result + ']');

            $get('divVerifyResult').innerHTML = 'Caregiver: <b>' + oRec[0].CaregiverName + '</b>' +
                                                ', ID: <b>' + oRec[0].CaregiverId + '</b>' + 
                                                ', Expires: <b>' + oRec[0].CaregiverIdExp + '</b>';
            break;
        case 'ReportSales':
        
            
            
            if (result == '') {
                $get('divReport').innerHTML = 'No records.<br>';
                
                data = new google.visualization.DataTable();
                data.addColumn('string', '<div style=width:90px;text-align:right;font-weight:bold;>TOTAL</div>');
                data.addColumn('string', '<div style=width:290px;text-align:right;font-weight:bold;>0</div>');
                data.addColumn('string', '<div style=width:90px;text-align:right;>$0.00</div>');
                data.addColumn('string', '<div style=width:90px;text-align:right;>$0.00</div>');
                data.addColumn('string', '<div style=width:190px;text-align:right;>$0.00</div>');

                table = new google.visualization.Table($get('divReportFooter'));
                table.draw(data, { allowHtml: true});
                return;
            };
            
            
            var sGross = 0;
            var sDisc = 0;
           
            oProm = Sys.Serialization.JavaScriptSerializer.deserialize(result);
            var data = new google.visualization.DataTable();

            data.addColumn('string', 'Date');
            data.addColumn('string', 'Patient');
            data.addColumn('number', 'Amount');
            data.addColumn('number', 'Discount');
            data.addColumn('string', 'Source');

            data.addRows(oProm.length);

            for (var i = 0; i < oProm.length; i++) {
                data.setCell(i, 0, oProm[i].PaymentDate, null, { 'style': 'height:22px; width:100px' });
                data.setCell(i, 1, oProm[i].Customer, null, { 'style': 'height:22px; width:300px' });
                data.setCell(i, 2, oProm[i].Amount, null, { 'style': 'height:22px; width:100px' });
                data.setCell(i, 3, oProm[i].Discount, null, { 'style': 'height:22px; width:100px' });
                data.setCell(i, 4, oProm[i].SourceName, null, { 'style': 'height:22px; width:200px; text-align:right' });
                sGross += oProm[i].Amount - 0;
                sDisc += oProm[i].Discount - 0;
            };
            var formatter = new google.visualization.TableNumberFormat({ prefix: "$", negativeColor: 'red', negativeParens: true });
            formatter.format(data, 2);
            formatter.format(data, 3);

            var view = new google.visualization.DataView(data);
            view.setColumns([0, 1, 2, 3, 4]);

            var table = new google.visualization.Table($get('divReport'));
            table.draw(data, { allowHtml: true, showRowNumber: false, alternatingRowStyle: true, page: 'enable', pageSize: 12 });

            data = new google.visualization.DataTable();
            data.addColumn('string', '<div style=width:90px;text-align:right;font-weight:bold;>TOTAL</div>');
            data.addColumn('string', '<div style=width:290px;text-align:right;font-weight:bold;>' + i + '</div>');
            data.addColumn('string', '<div style=width:90px;text-align:right;>' + '$' + sGross + '</div>');
            data.addColumn('string', '<div style=width:90px;text-align:right;>' + '$' + sDisc + '</div>');
            data.addColumn('string', '<div style=width:190px;text-align:right;>' + '$' + (sGross - sDisc) + '</div>');

            table = new google.visualization.Table($get('divReportFooter'));
            table.draw(data, { allowHtml: true});

            break;
    };         
};