//******************************************************************************
//* Created By: Jack Liao                       
//* Created On: 7/15/2007                       
//* ---------------------------------------------------------------------------- 
//* Description:                                
//*    This is the main javascript library for  
//*    all Arbor Research web sites.            
//* ---------------------------------------------------------------------------- 
//* HISTORY (MM/DD/YYYY NAME: CHANGE DESCRIPTION)
//*   7/15/2009 Jack: Created initial sets of common functions that
//*                   is based on DOPPSLink application. 
//******************************************************************************


// Recursively find its parent with matching keyword using DOM
function findParentNode(obj, matchPart) {
	var re = new RegExp(matchPart);
	var parent = obj.parentNode;
	if (parent && parent != null) {
		if (!parent.id || parent.id == null)
			parent = findParentNode(parent, matchPart);
		else if (!re.test(parent.id))
			parent = findParentNode(parent, matchPart);
	}
	else 
		parent = obj;
	
	return parent;
}

// Put the cursor at the end of text in a textbox
function setCursorToEndOfText(tbid) {
    var textbox = document.getElementById(tbid);
    if(textbox != null && textbox.value.length > 0) {
        var fieldRange = textbox.createTextRange();
        fieldRange.moveStart('character', textbox.value.length);
        fieldRange.collapse();
        fieldRange.select();
    } else if(textbox != null) {
        // when textbox is empty, then just focus inside it
        textbox.focus();
    }
}

// gets the browser screen view area total width
function getBrowserScreenWidth() {
   if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    return window.innerWidth;
   } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    return document.documentElement.clientWidth;
   } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    return document.body.clientWidth;
   } else {
    return 0;
   }
}

// gets the browser screen view area total height
function getBrowserScreenHeight() {
   if( typeof(window.innerHeight) == 'number' ) {
    //Non-IE
    return window.innerHeight;
   } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    return document.documentElement.clientHeight;
   } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    return document.body.clientHeight;
   } else {
    return 0;
   }
}

// test if passed-in "obj" is an Array
function is_array(obj){
	return obj instanceof Array;
}

function is_in_array(arr, obj) {
    if(is_array(arr) && arr.length > 0) {
        for(var i=0; i<arr.length; i++) {
            if(arr[i] == obj) return true;
        }
    }
    return false;
}

// converts a boolean value to integer 1 or 0
// true --> 1, false --> 0
function ConvertBoolTo01(tf) {
    if(tf) {
        return 1;
    }
    return 0;
}

// clears all input elements inside a div
function clearDivContent(div_id) {
    var div = document.getElementById(div_id);
    if(div != null) {
        var inputs = div.getElementsByTagName("input");
        for(var i=0; i<inputs.length; i++) {
            if(inputs[i].type == "text") {
                inputs[i].value = "";
            }
            else if(inputs[i].type == "hidden") {
                inputs[i].value = "";
            }
        }
        var ddls = div.getElementsByTagName("select");
        for (var i = 0; i < ddls.length; i++) {
            set_dropdown(ddls[i], "-1");
        }
    }
}

// Show a popup on top of a gray layer
// the gray layer covers the whole page, so the user can't interact with the form until the popup is closed.
// the popup is at the center of the page
function showModalPopup(popup_id) {
    var div1 = document.getElementById("modalPtDiv");
    if(div1 == null) {
        div1 = document.createElement("DIV");
        div1.id = "modalPtDiv";
        div1.className = "transparentLayer";
        document.body.appendChild(div1);
    }
    
    var div2 = document.getElementById(popup_id);
    if(div2 != null) {
        div1.style.zIndex = 1000;
        div1.style.display = "block";
        div1.style.visibility = "visible";
        if(document.body.scrollHeight ) {
           div1.style.height = document.body.scrollHeight + "px";
        }
        div2.style.zIndex = div1.style.zIndex + 1;
        div2.style.position = "absolute";
        div2.style.display = "block";
        div2.style.visibility = "visible";
        // IMPORTANT: we always display div first, so that we can get its offsetWidth and offsetHeight
        var x = Math.floor((getBrowserScreenWidth() - div2.offsetWidth)/2);
        var y = Math.floor((getBrowserScreenHeight() - div2.offsetHeight)/2);
        if(x < 0) x = 0;
        if (y < 0) y = 0;
        if (document.body.scrollTop != null && document.body.scrollTop > 0) {
            y = y + document.body.scrollTop;
        } else if (document.documentElement.scrollTop != null && document.documentElement.scrollTop > 0) {
            y = y + document.documentElement.scrollTop;
        }
        div2.style.left = x + "px";
        div2.style.top = y + "px";   
    }
}

// Hide the popup and the gray layer.
function hideModalPopup(popup_id) {
    var div1 = document.getElementById("modalPtDiv");
    var div2 = document.getElementById(popup_id);
    if(div1 != null) {
      div1.style.display = "none";
      div1.style.visibility = "hidden";
    }
    if(div2 != null) {
      div2.style.display = "none";
      div2.style.visibility = "hidden";
    }	
}

// trim the leading and trailing character specified
 function trim(string, ch) {
    // leading
    while(string.charAt(0) == ch) {
        string = string.substring(1);
    }
    // trailing
    while(string.charAt(string.length-1) == ch) {
        string = string.substring(0, string.length - 1);
    }
    return string;
 }
 
 // test if a character is a digit
 function isDigit(c) {
    return ((c >= "0") && (c <= "9"))
 }

 // test if a string is integer
 function isInteger(s) {
    var i;
    for (i = 0; i < s.length; i++) {
	     var c = s.charAt(i);
         if (!isDigit(c)) return false;
    }
    return true;
 }
 
 // test if a string only contains alphabet [a-z]
 function isAlphabet(s) {
    var pattern = /^[A-Za-z]$/;
    for(var i=0; i<s.length; i++) {
        if(!s.charAt(i).match(pattern)) return false;
    }
    return true;
 }
 
 function IsValidDayForMonth(month, day, year) {
   var leapYear = new Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
   var regularYear = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
 
   var maxDays;
   if (IsLeapYear(year))
      maxDays = leapYear[month - 1];
   else
      maxDays = regularYear[month - 1];
    
   if(day > maxDays || day < 1)
      return false;
 
   return true;
 }
 
 function IsLeapYear(year)
 {
   return new Date(year,2-1,29).getDate() == 29;
 }
 
 
 // define an iframe for fixing the bug of select box appearing above the message div
 var popupIFrame = null;
   
 function createIFrame(iFrame_id) {
   var new_iframe = document.createElement("IFRAME");
   new_iframe.id = iFrame_id;
   new_iframe.style.filter = "alpha(opacity=0)";
   document.body.appendChild(new_iframe);
   return new_iframe;
 }

 function hideIFrame() {
   // destroy the iframe when hiding the div
   if(popupIFrame != null)
     document.body.removeChild(popupIFrame);
   popupIFrame = null;
 }
 
function showIFrame(div) {
  // create an iframe that has the same position and size as div, so that the 
  // div will be above the select box
  if(popupIFrame == null) {
  //		popupIFrame = document.createElement("IFRAME");
  //		popupIFrame.id = "floatIFrame";
    popupIFrame = createIFrame("floatIFrame");
    popupIFrame.style.zIndex=div.style.zIndex - 1;
    popupIFrame.style.position="absolute";
    popupIFrame.style.left = div.offsetLeft + "px";
    popupIFrame.style.top = div.offsetTop + "px";
    popupIFrame.style.width = div.offsetWidth + "px";
    popupIFrame.style.height = div.offsetHeight + "px";
  //		popupIFrame.style.filter = "alpha(opacity=0)";
  //		document.body.appendChild(popupIFrame);
  }
}

function convertStringToType(value, data_type) {
	if(value != null && value.length > 0) {
	  switch(data_type.toLowerCase()) {
			case "float":
				return parseFloat(localizeNumberToENUS(value));
				
			case "int":
				return parseInt(value);
				
			case "datetime":
				return new Date(value);
	  }
  }
  return null;
}

function localizeNumberToENUS(val) {
  // convert 1,43 to 1.43
  // since client side doesn't allow number group seperator, it is safe to just 
  // change "," to "."
  return val.replace(",", ".");
}

function set_dropdown(dropdown, value) {
    if (dropdown != null && dropdown.options.length > 0) {
        dropdown.options[0].selected = true; // init the 1st option to be selected, which should always be -1 "--"
        for (var i = 0; i < dropdown.options.length; i++) {
            if (dropdown.options[i].value == value) {
                dropdown.options[i].selected = true;
                break;
            }
        }
    }
}

function set_dropdown_options(option_str, ddl) {
    if(ddl != null && option_str.length > 0) {
        //if(ddl.options.length > 0) {
            RemoveAllOptionsInDropDown(ddl);
        //}
                
        var options = option_str.split(';');
        for(var i=0; i<options.length; i++) {
            var vals = options[i].split('|');
            var opt = document.createElement("option");
            opt.text = vals[0];
            // vals[2] indicates if it is a N/A option
//            if(vals[2] == "0") {
                opt.value = vals[1];
//                opt.selected = true;
//            } else {
//                opt.value = "NA";
//            }
            ddl.options.add(opt);
        }
        //ddl.click();
//        RecordDropDownSelectedValue(ddl, $get("selectedDdlBatch"));
    }
}

function RemoveAllOptionsInDropDown(ddl) {
    if(ddl != null)
        while(ddl.options.length > 0)
            ddl.options.remove(ddl.options.length - 1);
}

function get_dropdown_value(dropdown) {
    if (dropdown != null && dropdown.options.length > 0) {
        return dropdown.options[dropdown.selectedIndex].value;
    }
    return null;
}

// convert the special chars in vb format to its original ascii format
 function convertSpecialCharsFromVB(str) {
    str = str.replace(/Chr\(34\)/g, '"');
    str = str.replace(/Chr\(44\)/g, ",");
    str = str.replace(/Chr\(58\)/g, ":");
    str = str.replace(/Chr\(13\)/g, "\r");
    str = str.replace(/Chr\(10\)/g, "\n");
    return str
 }
 
 // convert the special chars in its original ascii format to vb format
 function convertSpecialCharsToVB(str) {
    str = str.replace(/\"/g, "Chr(34)");
    str = str.replace(/,/g, "Chr(44)");
    str = str.replace(/:/g, "Chr(58)");
    str = str.replace(/&/g, "Chr(38)");
    str = str.replace(/\|/g, "Chr(124)");
    return str
 }
 
 // Global Enum variable for error types
 var errorTypes = {None:0, Information:1, Warn:2, Error:3};
 
 function MessagePopup(msg, btn_text, error_type) {
    var div = document.getElementById("standard_msg_popup");
    if(div == null) { // if not exist, create one
        div = document.createElement("DIV");
        div.id = "standard_msg_popup";
        document.body.appendChild(div);
    }
    div.style.border = "solid 2px #003366";
    div.style.backgroundColor = "#ffffff";
    div.style.padding = "8px";
    div.style.maxWidth = "300px";
    if(btn_text == null || btn_text.length <= 0) btn_text = "Close";
    
    div.innerHTML = "<table><tr>" + GetImageHTMLString(error_type) + "<td>" + msg + "</td></tr></table>";
    div.innerHTML += "<br/><br/><div style='text-align:center;'><a class='button' style='cursor:default;' onclick=\"hideModalPopup('" + div.id + "');\">&nbsp;&nbsp;" + btn_text + "&nbsp;&nbsp;</a></div><br/>";
    showModalPopup(div.id);
 }
 
 function ConfirmPopup(msg, btn_clicked, ok_btn_text, cancel_btn_text, error_type) {
//    var action = "";
//    if(event) action = event.srcElement.toString().replace("javascript:", "");
  
    var div = document.getElementById("custom_confirm_popup");
    if(div == null) { // if not exist, create one
        div = document.createElement("DIV");
        div.id = "custom_confirm_popup";
        document.body.appendChild(div);
    }
    div.style.border = "solid 2px #003366";
    div.style.backgroundColor = "#ffffff";
    div.style.padding = "8px";
    div.style.maxWidth = "300px";
    if(ok_btn_text == null || ok_btn_text.length <= 0) ok_btn_text = "Continue";
    if(cancel_btn_text == null || cancel_btn_text.length <= 0) cancel_btn_text = "Cancel";
    
    div.innerHTML = "<table><tr>" + GetImageHTMLString(error_type) + "<td>" + msg + "</td></tr></table>";
    div.innerHTML += "<br/><br/><div style='text-align:center;'><a class='button' style='cursor:default;' onclick=\"ClickButton('" + btn_clicked.id + "');\">&nbsp;&nbsp;" + ok_btn_text + "&nbsp;&nbsp;</a>&nbsp;<a class='button' style='cursor:default;' onclick=\"hideModalPopup('" + div.id + "');\">&nbsp;&nbsp;" + cancel_btn_text + "&nbsp;&nbsp;</a></div><br/>";
    showModalPopup(div.id);
    
    return false;  // always return false to block postback. The Continue button click will trigger the postback for the same event.
 }
 
 function ClickButton(id) {
    var button = document.getElementById(id);
    if(button != null) {
//        var str = button.onclick.toString();
        // remove "return ConfirmPopup(...);"
//        str = str.replace(/return ConfirmPopup\(.*\);/i, "");
        button.onclick = "";  //str;
        button.click();
    }
 }
 
 // To use this function, you need to have "images" folder at the root level,
 // and have 3 image files in it: alert.gif, info.gif and error_medium.gif
 function GetImageHTMLString(error_type) {
    var image_indicator = "";
    if(error_type != null) {
        if(error_type == 1) image_indicator = "<td valign='top'><img src='" + GetServerRootPath() + "/images/info.gif' /></td>";
        else if(error_type == 2) image_indicator = "<td valign='top'><img src='" + GetServerRootPath() + "/images/alert.gif' /></td>";
        else if(error_type == 3) image_indicator = "<td valign='top'><img src='" + GetServerRootPath() + "/images/error_medium.gif' /></td>";
    }
    return image_indicator;
 }
 
 // To use this function, create a HTML hidden field in the master page or banner user control
 // with id="hidden_server_path", and use the "Request.ApplicationPath" to set the hidden field value
 function GetServerRootPath() {
    var hidden = document.getElementById("hidden_server_path");
    if(hidden != null) {
        return hidden.value;
    }
    return "";
 }
 
 function getCurrentFocusedElementByEvent(e) {
    if(!e) e=event;
    return (e.target) ? e.target : e.srcElement;
 }
 
 function getTargetActionElementID(current_focused_id) {
    if(element_action_mapping != null && element_action_mapping.length>0 && current_focused_id != null) {
        for(var i=0; i<element_action_mapping.length; i++) {
            var map = element_action_mapping[i].split('|');
            var source = map[0];
            var target = map[1];
            if(source.toLowerCase() == current_focused_id.toLowerCase()) {
                return target;
            }
        }
    }
    return "";
}

function enable_disable_dropdown(ctl_id, enabled) {
    var dropdown = $get(ctl_id);
    if (dropdown != null) {
        //if(!enabled) set_dropdown(dropdown, "-1");
        dropdown.disabled = !enabled;
    }
}

function enable_disable_textbox(txtbox, enabled) {
    if (!enabled) {
        txtbox.style.backgroundColor = "#d4d0c8";
    } else {
        txtbox.style.backgroundColor = "#ffffff";
    }
    txtbox.disabled = !enabled;
}
