var num = 0;
var tabid = null;
var border = '';
var __flag = 0;

function checkField(formname, fieldname, expressions)
{
    num = 0;
//    obj = document.getElementById(fieldname);
    obj = eval('document.'+formname+'.'+fieldname);
//    alert(obj.name);
//temp = (obj[0] != 'undefined')?1:0;
//    alert(temp);
    params = expressions.split(':');
    
    tabid = params[1];
    exps = params[0].split('|');
    
    for (i in exps) {
        switch (exps[i]) {
            case 'l' : // not empty and les then zero (for select id controls)
                if (isEmpty(obj, true)) {
                    alert("Can't be empty");
                    highlightInput(obj);
                    return false;
                }
//                alert('1');
                break;
            case 'r' : // not empty
                if (isEmpty(obj)) {
                    alert("Can't be empty");
                    highlightInput(obj);
                    return false;
                }
                break;
                
            case 'n' : // numeric
                if (!isNumeric(obj)) {
                    alert("Should be numeric");
                    highlightInput(obj);
                    return false;
                }
                break;
                
            default : 
                alert("Internal Error: Unknown Expression");
                return false;
            
        }
    }
    
    return true;
}
// VALIDATE LOGIC
function isEmpty(obj, notnull)
{
    if (notnull != null && obj.value == '0') return true;
    return (obj.value.replace(/^\s+/g, '').replace(/\s+$/g, '').length == 0);
}

function isNumeric(obj) {
    return true;
}
// GUI PART
function highlightInput(obj) {
    if (tabid != null) {
        showTab(tabid);
        tabid = null;
    }
    num++;
    obj.focus();
    border = obj.style.border;
    obj.className = 'borderRed';
    time = (num == 3) ? 600 : 200;
    setTimeout("resetBorder(obj)", time);
} 

function resetBorder(obj) {
    obj.className = 'borderGrey';
    obj.focus();
    if (num < 3) setTimeout("highlightInput(obj)", 200);
    else {
        num = 0;
    }
}


// PRICE CONTROL
function parseIntVal(val)
{
    val = val.replace(/\$/g, "");
    val = val.replace(/[a-z;]/gi, "");
    val = val.replace(/,/g, "");
    val = val.replace(/^0/g, "");
    
    if (val.length  == 0) return 0;
    
    intVal = parseInt(val);
    
    if (isNaN(val)) {
        return 0;
    }
    
    var str = "";

    while (diviser = parseInt(intVal / 1000)) {
        reminder = parseInt(intVal - diviser*1000);
        if (reminder < 100) {
            reminder = "0" + reminder;
            if (reminder == 0) {
                reminder = "0" + reminder;
            }
        }
        str = "," + reminder + str;
        intVal = parseInt(intVal / 1000);
    } 
    
    str =  parseInt(intVal) + str;
    return str;
}

function parseFloatVal(val, currentValue)
{
//    alert(val);
    var tempVal = "0."+val;
    tempVal = Math.round(tempVal*100)/100; 
//    alert(tempVal);
    if (tempVal > 0) { 
        tempVal *= 100;
        if (tempVal == 1) {
            return "01";
        }
        return tempVal;
    } else {
        return "00";
    }
    //alert(tempVal); 
//    while(val.length > 2){
////        alert(val.length);
//        val = val/10;
//    }
////    alert(val);
//    return (val<10) ? "0"+parseInt(val) : parseInt(val);
}

function priceOnChange(control)
{
    
    filterNumericValues(control);
    
//    str = control.value;
//    if (str == null) return;
//    
//    
//    
//    comp = str.split('.');
//    intValue = (comp[0] == null) ? '0' : parseIntVal(comp[0]);
//    floatValue = (comp[1] == null) ? '00' : parseFloatVal(comp[1]);
//    
////    alert(floatValue);
//    finValue = "$"+intValue + "." + floatValue;
//    control.value = finValue.replace("$-", "-$");
    
}

function priceOnBlur(control)
{
        
    filterNumericValues(control);
    
    str = control.value;
    if (str == null) return;
    
    
    
    comp = str.split('.');
    intValue = (comp[0] == null) ? '0' : parseIntVal(comp[0]);
    floatValue = (comp[1] == null) ? '00' : parseFloatVal(comp[1]);
    
//    alert(floatValue);
    finValue = "$"+intValue + "." + floatValue;
    control.value = finValue.replace("$-", "-$");
}

function priceOnKeyDown(objTextBox)
{
    var iKeyCode        = window.event.keyCode;
    var iCaretPosition  = getCaretPosition(objTextBox);

    if (window.event.srcElement.readOnly) return;
    
    // Allow key presses of <cursor arrow> or <Home> or <End>
    if ((iKeyCode > 36 && iKeyCode < 41) || (iKeyCode > 34 && iKeyCode <37)) return 1;
    
    // Allow <Ctrl+C>, <Ctrl+V>, <Ctrl+X> and <Ctrl+Z>
    if (window.event.ctrlKey && (iKeyCode == 67 || iKeyCode == 86 || iKeyCode == 88 || iKeyCode == 90)) return 1;
    
    //Forbid NumLock keys
    
    if (iKeyCode == 8 || iKeyCode == 46){
        pos = (iKeyCode==8) ? iCaretPosition-1:iCaretPosition;
        objTextBox.value = replaceNotCorrectSymbol(objTextBox.value, pos, '');
        objTextBox.value = getPriceValueEx(objTextBox.value);
        putCursor(objTextBox, pos-1);
    }    
    // If key pressed is <0-9>
    if ((iKeyCode > 47 && iKeyCode < 58) || (iKeyCode > 95 && iKeyCode < 106)) {
        if (iKeyCode > 95) iKeyCode -= (95-47);

            var currentValue = String.fromCharCode(iKeyCode);
            var text         = InsertSymbol(objTextBox.value, iCaretPosition, currentValue);
            
            objTextBox.value = getPriceValueEx(text);
            putCursor(objTextBox, iCaretPosition);
    }
    // If key pressed is <Tab>
    if (iKeyCode != 9) {
        window.event.returnValue = false;
    }
}

function getPriceValueEx(text){
    comp = text.split('.');
    intValue = (comp[0] == null) ? '0' : parseIntVal(comp[0]);
    floatValue = (comp[1] == null) ? '00' : parseFloatVal(comp[1]);
    finValue = "$"+intValue + "." + floatValue;

    return finValue.replace("$-", "-$");
}

function getPriceValue(value)
{
    value   = value.replace(/\$/g, "");
    value   = value.replace(/[a-z;]/gi, "");
    value   = value.replace(/,/g, "");
    value   = value.replace(/^0/g, "");     
    
    return parseFloat(value);
}

function saveChanges()
{
    
    if (document.adminForm.reload != "undefined") {
        if ( document.adminForm.reload.value > 0 ) 
            return true;
    }
    
    if ( document.adminForm.submitted.value > 0 || document.adminForm.cancelled.value > 0 ) {    
        return true;
    }
    if (confirm('Do you want to save changes?')) { 

        document.adminForm.target = "adminForm_iframe";
        document.adminForm.onsubmit(); 
        document.adminForm.submit(); 
        
        //setTimeout("SubmitAdminForm()", 3000);

//        alert("test1");        
        
        sleep(3000);
        
//        alert("test2");
        
//        counter = 0;
//        while (__flag < 1 && counter < 1000000) {
//            counter++;
//        }
        //alert(counter);
        return true;
    } 
    
    return false;
}

function SubmitAdminForm()
{
    __flag = 1;
    alert("afadfadf"); 
}

function dateOnKeyDown() {
    var DATE_DIVIDER = "/";
    var SPACE_CHARACTER = "_";
    
    var objTextBox = window.event.srcElement;
    var iKeyCode = window.event.keyCode;
    var bSelectedText = false;
//    alert(dateFormat);
    // Exit if field is read-only
    if (window.event.srcElement.readOnly) return;

    // Allow key presses of <cursor arrow> or <Home> or <End>
    if ((iKeyCode > 36 && iKeyCode < 41) || (iKeyCode > 34 && iKeyCode <37)) return 1;

    // Allow <Ctrl+C>, <Ctrl+V>, <Ctrl+X> and <Ctrl+Z>
    if (window.event.ctrlKey && (iKeyCode == 67 || iKeyCode == 86 || iKeyCode == 88 || iKeyCode == 90)) return 1;

    // Get the position of the cursor
    var iCaretPosition = getCaretPosition(objTextBox);
    if (iCaretPosition > 10 || objTextBox.value.length>=10) window.event.returnValue=false;
    // Get the selected text
    var objSelectedText = document.selection.createRange();

    // Determine if some text has been selected
    if (objSelectedText.parentElement() == objTextBox && objSelectedText.text.length > 0)   bSelectedText = true;    

    // Get the element next to the cursor (to be used later)
    var sFirstElement = objTextBox.value.substring(iCaretPosition,iCaretPosition-1);

    // Do not enter number if there's no space for it
    if ((sFirstElement != SPACE_CHARACTER) && !(iKeyCode == 8 || iKeyCode== 46) && objSelectedText.text == 0) return 0;

    // If key pressed is <0-9>
    if ((iKeyCode > 47 && iKeyCode < 58) || (iKeyCode > 95 && iKeyCode < 106)) {
        if (iKeyCode > 95) iKeyCode -= (95-47);
            
        date = deleteUnderlineSymbols(objTextBox.value);
        date = date.split("/");
        var currentElement = String.fromCharCode(iKeyCode);
        if (iCaretPosition <= 10) {
            // Only write the character if it's filling an empty gap
            // ie don't overwrite existing number or '/' characters
            var sNextElement = objTextBox.value.substring(iCaretPosition-1,iCaretPosition);
            
            if (!bSelectedText && sNextElement == SPACE_CHARACTER) {
                // Get the text before the cursor
                var sElement1 = objTextBox.value.substring(0, iCaretPosition-1);
                // Get the text after the cursor
                var sElement2 = objTextBox.value.substring(iCaretPosition + objSelectedText.text.length, objTextBox.value.length);
                // Append the new character
                sElement1 += String.fromCharCode(iKeyCode);
                // Append the text from after the cursor
                sElement1 += sElement2;
                objTextBox.value = sElement1;                          
                // Move the cursor position on one for "/" charcters
                switch (iCaretPosition) {
                    case 2:
                    case 5:
                    iCaretPosition = iCaretPosition+1;
                    default:
                    }
                }
                // Handle selected text
                if (bSelectedText) {
                    // Get the text before the selected text
                    var sElement1 = objTextBox.value.substring(0, iCaretPosition-1);
                    // We need to keep "/" characters
                    if (sFirstElement == DATE_DIVIDER) sElement1 += DATE_DIVIDER;
    
                    // Append the new character
                    sElement1 += String.fromCharCode(iKeyCode);
    
                    // Replace the remaining selected text with blank spaces
                    for (var i=1; i<objSelectedText.text.length; i++) {
                        var sDeletedChar = objSelectedText.text.substring(i, i+1);
                        if (sDeletedChar == DATE_DIVIDER) {
                            // Keep the slash characters
                            sElement1 += DATE_DIVIDER;
                        } else {
                            // Do not insert extra space if the first selected character isa "/"
                            if (!(i==1 && sFirstElement == DATE_DIVIDER)) {
                                // Replace numbers with a space
                                sElement1 += SPACE_CHARACTER;
                            }
                        }
                    }
    
                    // Get the text after the selected text and append
                    var sElement2 = objTextBox.value.substring(iCaretPosition + objSelectedText.text.length-1, objTextBox.value.length);
                    sElement1 += sElement2;
                    objTextBox.value = sElement1;
                }
                // Put the cursor in the correct position
                objSelectedRange = objTextBox.createTextRange();
                // Move cursor on 1 if the first selected character is a "/"
                if (bSelectedText && sFirstElement == DATE_DIVIDER) iCaretPosition= iCaretPosition+1;
                objSelectedRange.move("character", iCaretPosition)
                objSelectedRange.select();
            } else {
                window.event.returnValue = false;
            }
        } // End if key pressed is <0-9>

        // If key pressed is <Del>
        if (iKeyCode == 8 || iKeyCode == 46) {
            // Handle selected text
            if (bSelectedText) {
                // Get the text before the selected text
                var sElement1 = objTextBox.value.substring(0, iCaretPosition-1);
                // We need to keep "/" characters
                if (sFirstElement == DATE_DIVIDER) {
                    sElement1 += DATE_DIVIDER;
                }

                // Append the new character
                sElement1 += SPACE_CHARACTER;

                // Replace the remaining selected text with blank spaces
                for (var i=1; i<objSelectedText.text.length; i++) {
                    var sDeletedChar = objSelectedText.text.substring(i, i+1);
                        if (sDeletedChar == DATE_DIVIDER) {
                            // Keep the slash characters
                            sElement1 += DATE_DIVIDER;
                        } else {
                            // Do not insert extra space if the first selected character is a "/"
                            if (!(i==1 && sFirstElement == DATE_DIVIDER)) {
                                // Replace numbers with a space
                                sElement1 += SPACE_CHARACTER;
                            }
                        }
                }

                // Get the text after the selected text and append
                var sElement2 = objTextBox.value.substring(iCaretPosition + objSelectedText.text.length-1, objTextBox.value.length);
                    sElement1 += sElement2;
                    objTextBox.value = sElement1;
                    iCaretPosition = iCaretPosition+1;
                } else {
                    // We need to delete character by character
                    if (iCaretPosition != 11 || iKeyCode != 46) {
                        if (iKeyCode == 46) iCaretPosition = iCaretPosition+1;
                            if (iCaretPosition != 1 && iCaretPosition != 4 && iCaretPosition!= 7){
                                var sElement1 = objTextBox.value.substring(0, iCaretPosition-2);
                                var sElement2 = objTextBox.value.substring(iCaretPosition-1,objTextBox.value.length);
                                sElement1 += SPACE_CHARACTER;
                                sElement1 += sElement2;
                                objTextBox.value = sElement1;
                        }
                    }
                }
                // Put the cursor in the correct position
                // Move cursor on 1 if the first selected character is a "/"
                if (bSelectedText && sFirstElement == DATE_DIVIDER) iCaretPosition = iCaretPosition+1;
                putCursor(objTextBox, iCaretPosition-2);

        } // End if key pressed is <Del>

        if (dateFormat==1){
            if(iCaretPosition>=4 && iCaretPosition<=6) {
                if(checkMonth(date[1], currentElement)){
                    objTextBox.value = replaceNotCorrectSymbol(objTextBox.value, iCaretPosition-1, "_");
                    putCursor(objTextBox, iCaretPosition-2);
                }
            }
            if(iCaretPosition<=3) {
                if(checkDay(date[0], currentElement)){
                    objTextBox.value = replaceNotCorrectSymbol(objTextBox.value, iCaretPosition-1, "_");
                    putCursor(objTextBox, iCaretPosition-2);
                }
            }
        } else {
            if(iCaretPosition<=3) {
                if(checkMonth(date[0], currentElement)){
                    objTextBox.value = replaceNotCorrectSymbol(objTextBox.value, iCaretPosition-1, "_");
                    putCursor(objTextBox, iCaretPosition-2);
                }
            }
            if(iCaretPosition>=4 && iCaretPosition<=6) {
                if(checkDay(date[1], currentElement)){
                    objTextBox.value = replaceNotCorrectSymbol(objTextBox.value, iCaretPosition-1, "_");
                    putCursor(objTextBox, iCaretPosition-2);
                }
            }
        }
        if(iCaretPosition>=7 && iCaretPosition<=10) {
            if(checkYear(date[2], currentElement, iCaretPosition)){
                objTextBox.value = replaceNotCorrectSymbol(objTextBox.value, iCaretPosition, "_");
                putCursor(objTextBox, iCaretPosition-1);
            }    
        }

        // If key pressed is <Tab>
        if (iKeyCode != 9) {
            window.event.returnValue = false;
        }
}

function deleteUnderlineSymbols(str) {
    return str.replace(/_/g, "");
}

function  putCursor(objTextBox, iCaretPosition) {
    // Put the cursor in the correct position
    objRange = objTextBox.createTextRange();
    objRange.move("character", iCaretPosition)
    objRange.select();
}

function replaceNotCorrectSymbol(str, currentPos, symbol){
    var temp = '';
    for(i=0; i<str.length; i++){
        temp += (i==(currentPos-1)) ? symbol : str.charAt(i);
    }

    return temp;
}

function InsertSymbol(str, currentPos, symbol){
    var temp = '';
    for(i=0; i<str.length; i++){
        temp += (i==(currentPos-1)) ? symbol+str.charAt(i) : str.charAt(i);
    }

    return temp;
}

function checkMonth(month, currentElement){
    month = (month=='') ? currentElement : month+currentElement;
    return (month>12 && month.length<=2) ? true : false;        
}

function checkDay(day, currentElement){
    day = (day=='') ? currentElement : day+currentElement;
    return (day>31 && day.length<=2) ? true : false;
}

function checkYear(year, currentElement, currentPos){
    year = (year=='') ? currentElement : year+currentElement;
    return (currentElement=="0" && currentPos==7) ? true : false;
}

function getCaretPosition(objTextBox){
    var i = objTextBox.value.length+1;
    if (objTextBox.createTextRange){
        objCaret = document.selection.createRange().duplicate();
        while (objCaret.parentElement()==objTextBox &&
            objCaret.move("character",1)==1) --i;
        }

    return i;
}

function dateOnPaste(objTextBox) {
    var sClipboard = window.clipboardData.getData('Text');
    // Validate that the pasted text is in nn/nn/nnnn format
    if (sClipboard.match(/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/)) {
        objTextBox.value = sClipboard;
    } else {
        // Do not allow paste
        window.event.returnValue = 0;
    }
}

//function setPriceValueForCtrl(ctrl, form)
function setPriceValueForCtrl(ctrl)
{
//    formCtrl = document.getElementById(form);
//    ctrl = document.getElementById(ctrl);
//alert('1');
//alert(getPriceValue(ctrl.value));
    ctrl.value = getPriceValue(ctrl.value);
    return true; 
//    formCtrl.ctrl.value = getPriceValue(ctrl.value);   
//alert(getPriceValue(ctrl.value));
//    ctrl.value = getPriceValue(ctrl.value);   
}

function isAlien(a) {
   return isObject(a) && typeof a.constructor != 'function';
}

function isArray(a) {
    return isObject(a) && a.constructor == Array;
}

function isBoolean(a) {
    return typeof a == 'boolean';
}
//
//function isEmpty(o) {
//    var i, v;
//    if (isObject(o)) {
//        for (i in o) {
//            v = o[i];
//            if (isUndefined(v) && isFunction(v)) {
//                return false;
//            }
//        }
//    }
//    return true;
//}

function isFunction(a) {
    return typeof a == 'function';
}

function isNull(a) {
    return typeof a == 'object' && !a;
}

function isNumber(a) {
    return typeof a == 'number' && isFinite(a);
}

function isObject(a) {
    return (a && typeof a == 'object') || isFunction(a);
}

function isString(a) {
    return typeof a == 'string';
}

function isUndefined(a) {
    return typeof a == 'undefined';
} 

///////////////////////////////////////
// autotype notes field function 
///////////////////////////////////////

function notesFieldKeyDown(e)
{
	if (!e) var e = window.event;
	if (e.keyCode) iKeyCode = e.keyCode;
	else if (e.which) iKeyCode = e.which;
	
	if (e.target) objTextBox = e.target;
	else if (e.srcElement) objTextBox = e.srcElement;
	if (objTextBox.nodeType == 3) // defeat Safari bug
		objTextBox = objTextBox.parentNode;
	    
    autoType        = '';
    autoTypeValue   = '';
    
    if (iKeyCode == 32) 
    {
        autoType        = retrieveAutoType(objTextBox.value);
//        alert(autoType);
        autoTypeValue   = retrieveAutoTypeValue(autoType, objTextBox);
        
    }
    return true;   
}

function retrieveAutoType(str)
{
//    alert(str.lastIndexOf(' '));
    temp_str = str.substring(str.substring(0,str.length-2).lastIndexOf(' '));
    
    return temp_str.replace(/ /g, "");
}

function retrieveAutoTypeValue(autoType, control)
{
    var autoTypeValue = '';
//    var url = "{$this->autoTypeUrl}&autoType="+escape(autoType);
    var url = "?xft=AutoTypeList&xfp=PopupPage&xfa=getDescriptionByAbbreviation&autoType="+escape(autoType);
    
    function handleHttpResponse_autoTypeValue() { 
        if (http.readyState == 4) { // Split the comma delimited response into an array                 
            if (http.responseText != 'NA') {
                  autoTypeValue = http.responseText;
                  if (autoType != '' && autoTypeValue != '') {
//                    alert(autoTypeValue);
                    control.value = control.value.replace(autoType, autoTypeValue);  
                  }
            }
        } 
    }
    
    function sendRequest(autoType) {
//        alert(autoType);
//        alert(url);
        http.open("GET", url, true); 
        http.onreadystatechange = handleHttpResponse_autoTypeValue; 
        http.send(null);
    }
    
    sendRequest(autoType);
    
    return true;
}
///////////////////////////////////////////

function openSOAPWindow(url)
{
    url = '?xft=Injury&xfp=PopupPage&xfa=SOAP';
    open(url, "SOAPPage","width=660,height=500,screenX="+((screen.width / 2) - (660 / 2))+", screenY="+((screen.height / 2) - (420 / 2))+",toolbar=no,menubar=no,resizable=yes,location=no,scrollbars=no,status=no");
    
}
//function filterNumericValues(e) {
function filterNumericValues(obj) {
    
//	if (!e) var e = window.event;
//	
//	if (e.keyCode) iKeyCode = e.keyCode;
//	else if (e.which) iKeyCode = e.which;
//	
//	if (e.target) obj = e.target;
//	else if (e.srcElement) obj = e.srcElement;
//	if (obj.nodeType == 3) // defeat Safari bug
//		obj = obj.parentNode;    
    
    buf = '';
    waserror = false;
        
    // Allow key presses of <cursor arrow> or <Home> or <End>
//    if ((iKeyCode > 36 && iKeyCode < 41) || (iKeyCode > 34 && iKeyCode <37)) return 1;  
      
    str = new String(obj.value);		          
    
    for(i=0;i<str.length;i++) {
    
        if((str.charAt(i) >= '0' && str.charAt(i) <= '9' ) || (str.charAt(i) == '$' && i==0) || str.charAt(i) == '.' || str.charAt(i) == '-' || str.charAt(i) == ','){
          buf = buf + str.charAt(i);
        } else {
          waserror = true;
        }
//        alert(str.charAt(i)+" "+waserror);
    }
    //alert(buf);
    if(waserror) {
      obj.value = buf;
      alert('Numeric Values Only (N.NN)');
    }		          
}

function SelectComboByValue(control, value)
{
    if (control.options != undefined) {
        if (value > -1) {
            for (i = 0; i < control.options.length; i++) 
            {
                if (control.options[i].value == value) 
                {
                    control.options[i].selected = true;
                    break;
                }
            }            
        } else {
            control.selectedIndex = -1;
        }
    }
}
function sleep (m) {
    var then = new Date(new Date().getTime() + m); 
    while (new Date() < then) 
    {
        
    }
}