// Copyright 2008, eCare Software LLC, Roswell GA.  All Rights Reserved.


// ================================== utility ==================================

// strip leading and trailing whitespace of all types (spaces, tabs, newlines)
function stripSpaces(x) {
     return  (x.replace(/^\W+/,'')).replace(/\W+$/,'');
}


// don't advance focus - set focus back to the current element, and select its content (cookbook)
function focusElement( formName, elemName) {
    var elem = document.forms[formName].elements[elemName];
    elem.focus();
    elem.select();
}


function focusElem( elem) {
    elem.focus();
    elem.select();
}

// provides support for auto_complete on associations (used on diagnosis codes)
function auto_complete_on_select(element, selectedElement) {
		var entityParts = selectedElement.id.split('::');
		var entityType = entityParts[0];
		var entityId = entityParts[1];
		$(entityType).value = entityId;
}

function setupPrevNextLinks(param){
	var idx;
	var prevNext = '';
	
	if (_2ndTabId != undefined)
		_2ndTabId = param;
		
	for (var i = 0; i < tabArray.length; i++){
		if (tabArray[i] == _2ndTabId){
			idx = i;
		}
	}
	
	prevNext += '<span id="prvNxt">';
	if (idx == 0){
		prevNext += '&lt;&lt;&nbsp;Previous';
	}else{
		prevNext += '<a href="#" onclick="tabOn(\'' + tabArray[idx - 1] + '\');">&lt;&lt;&nbsp;Previous</a>';
	}
	prevNext += '</span>';

	prevNext += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
	prevNext += '<input type="image" src="/images/btn-save_info.jpg" name="save" class="fbutton"/>';
	prevNext += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
	
	prevNext += '<span id="prvNxt">';
	if (idx + 1 == tabArray.length){
		prevNext += 'Next&nbsp;&gt;&gt;';
	}else{
		prevNext += '<a href="#" onclick="tabOn(\'' + tabArray[idx + 1] + '\');">Next&nbsp;&gt;&gt;</a>';
	}
	prevNext += '</span>';

	$('prevNextLinks').innerHTML = prevNext;
	
}


// =================================== cookie ==================================

// Set expiration date with 3 ints: the number of days, hours, and minutes
// from now that the cookie will expire.  All 3 args required, so use zeros.
function getExpDate(days, hours, minutes) {
    var expDate = new Date();
    if (typeof days == "number" && typeof hours == "number" && typeof hours == "number") {
        expDate.setDate(expDate.getDate() + parseInt(days));
        expDate.setHours(expDate.getHours() + parseInt(hours));
        expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
        return expDate.toGMTString();
    }
    return 0;
}


// getCooke() and getCookieVal() have been moved to application.rhtml


// Set cookie.  Name and value are required, other args are optional.
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape (value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

// remove the cookie by setting ancient expiration date
function deleteCookie(name,path,domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

// - - - - - - - - Firebug print wrappers - - - - - -


function isFireFox() {
    return (navigator.userAgent.search(/FireFox/i) != -1);
}


function ferror(arg) {
    // if (isFireFox()) {
    //     console.error(arg);
    // }
}


function fdebug(arg) {
    // if (isFireFox()) {
    //     console.debug(arg);
    // }
}

function fassert(arg) {
    // if (isFireFox()) {
    //     console.assert(arg);
    // }
}


// =================================== tablib ==================================


// - - - - -       Parametric Tabs        - - - - -
// - - - - - (param specifies Pri or Sec) - - - - -

function clear_Tabs(ttype) {
    var elements = YAHOO.util.Dom.getElementsByClassName(ttype, "li");
    YAHOO.util.Dom.removeClass(elements, "on");
}


function hideTabSections() {
    var elements = YAHOO.util.Dom.getElementsByClassName("tabsect", "div");
    for (var i=0; i < elements.length; i++) {
        elements[i].style.display = 'none';
    }
    fdebug("hideTabSections called");
}


function setTabCookie(name) {
    var expDate = getExpDate(0, 12, 0);      // 0 days, 12 hrs, 0 min
    setCookie("selectedTab", name, expDate);
}



// TODO - consolidate this as a parametric func with the 'ptabOn()' above.
// TODO - check that actual operation still requires 'strong'.
// TODO - can tab selection be derived from Controller.name ?

// Set both the Secondary Tabs themselves (class 'stab'), and the Tab Sections (class 'tabsect')
var _2ndTabId;
function tabOn(bare_id) {
	_2ndTabId = bare_id;
    clear_Tabs('stab');
    fdebug("clear_Tabs(stab) called");
    hideTabSections();

    // First, turn on the Tab
    var id = "tli" + bare_id;
    var sel = document.getElementById(id);
    if (sel == null)
    {
        fdebug("Busted Secondary Tab: missing stab: " +  id + " in tabOn");
        return;
    }
    var strong = document.createElement("strong"); 
    var txt = sel.firstChild;

    var removed  = sel.removeChild(txt);
    sel.appendChild(strong);
    strong.appendChild(removed);

    YAHOO.util.Dom.addClass(sel, "on");

    // Now make the corresponding Tab Section visible
    id = "adm" + bare_id;
    sel = document.getElementById(id);
    if (sel == null)
    {
        fdebug("Busted Secondary Tab: missing tabsect: " +  id + " in tabOn");
        return;
    }
    sel.style.display = 'block';
}


function getSelectedTab() {
    if (RenderCount == 0)
    {
        fdebug('getSelectedTab using initial value of General because RenderCount = 0');
        RenderCount++;
        return 'General';
    }

    var stabArray = YAHOO.util.Dom.getElementsByClassName('stab');   // works for 'stab' only!!

    if (stabArray.length == 0)
    {
            fdebug('getSelectedTab is unable to find any stab elements');
            return '';
    }

    for (tab in stabArray)
    {
        if (YAHOO.util.Dom.hasClass(tab, 'on'))
        {
            return tab;
        }
        else
        {
            fdebug('getSelectedTab is unable to find any tab that has been selected');
            return '';
        }
    }
    fdebug('getSelectedTab has no Tabs in stabArray but len != 0. Impossible case! ');
    return '';
}


// ==================================== dates ==================================

//function makeArray()    {
//    this[0] = makeArray.arguments.length;
//    this[0] = makeArray.arguments.length;
//    for (var i = 0; i<makeArray.arguments.length; i++)
//        this[i+1] = makeArray.arguments[i];
//}

// TODO lo: namespace
//var accumulate    = new makeArray( 0, 31, 59, 90,120,151,181,212,243,273,304,334);
//var accumulateLY  = new makeArray( 0, 31, 60, 91,121,152,182,213,244,274,305,335);
var accumulate   = new Array(0,31,59,90,120,151,181,212,243,273,304,334);
var accumulateLY = new Array(0,31,60,91,121,152,182,213,244,274,305,335);


function LeapYear(year) {
    if ((year/4)   != Math.floor(year/4))   return false;
    if ((year/100) != Math.floor(year/100)) return true;
    if ((year/400) != Math.floor(year/400)) return false;
    return true;
}


function getJulian(day,month,year) {
    if (LeapYear(year))
        return (day + accumulateLY[month]);
    else
        return (day + accumulate[month]);
}


function chk_date(elem, b_need4, b_future) {
  // map boolean args to integers
  var need4  = (b_need4)  ? 1 : 0;
  var future = (b_future) ? 1 : 0;
  check_date(elem, need4, future);
}

/* A general-purpose date parsing routine. This routine depends on the date.js and prototype.js libraries. */
function parseDate(control) {
  var date = $F(control);
  if ( date == '' || date == null ) {
    return;
  }  
  var parsedDate;    
  if ( date.match(/^[01][0-9][0-3][0-9][0-9][0-9]$/) ) {
    parsedDate = Date.parseExact(date, "MMddyy");
  } else if ( date.match(/^[01][0-9][0-3][0-9](19|20)[0-9][0-9]$/) ) {
    parsedDate = Date.parseExact(date, "MMddyyyy");      
  } else {
    parsedDate = Date.parse(date);
  }
  if ( parsedDate == null ) {
    alert('Invalid date format.');
    $(control).focus();
  } else {
    control.value = parsedDate.toString("MM/dd/yyyy");       
  }
}


function check_date(elem, need4, allowFuture) {
    var str = stripSpaces(elem.value);
    // valid entries: m/d/yy   mm/dd/yy   mm/dd/yyyy   m-d-yy   mm-dd-yy   mm-dd-yyyy
    var date_rgx = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;

    // this regex requires yyyy:
    if (check_date.arguments.length == 1) {
        need4 = 0;
    }

    // if need4 flag is set, change regex to require yyyy.
    if (parseInt(need4) != 0) {
        date_rgx = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
    }

    var matchArray = str.match(date_rgx); // check format regex
    if (!matchArray) {
        if (parseInt(need4) != 0) {
            alert("Valid format: mm/dd/yyyy or mm-dd-yyyy.");
        } else {
            alert("Valid format: mm/dd/yy or mm-dd-yy (use 4-digit years for prior centuries).");
        }
        fdebug("elem.form.name = " + elem.form.name);
        setTimeout("focusElement('" + elem.form.name + "','" + elem.name + "')", 0);
        return false;
    }
    month = matchArray[1]; // parse date
    day = matchArray[3];
    year = matchArray[4];
    if (month < 1 || month > 12) {
        alert("Month must be between 1 and 12.");
        setTimeout("focusElement('" + elem.form.name + "','" + elem.name + "')", 0);
        return false;
    }
    if (day < 1 || day > 31) {
        alert("Day must be between 1 and 31.");
        setTimeout("focusElement('" + elem.form.name + "','" + elem.name + "')", 0);
        return false;
    }
    if ((month==4 || month==6 || month==9 || month==11) && day==31) {
        alert("Month "+month+" doesn't have 31 days!");
        return false;
    }
    if (month == 2) { // feb check
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day>29 || (day==29 && !isleap)) {
            alert("February " + year + " doesn't have " + day + " days!");
            setTimeout("focusElement('" + elem.form.name + "','" + elem.name + "')", 0);
            return false;
        }
    }
    var now = new Date();
    var fdate = new Date();

    iyear = parseInt(year);

    if (iyear < 100)
    {
        var iyear = 2000 + iyear;
    }

    fdate.setFullYear(iyear, month - 1, day);

    if (iyear < parseInt(now.getFullYear()) - 125)
    {
        alert("Can not enter dates more than 125 years ago.");
        setTimeout("focusElement('" + elem.form.name + "','" + elem.name + "')", 0);
        return false;
    }

    if (parseInt(allowFuture) == 0)
    {
        if (fdate > now )
        {
            alert("Future dates can not be entered here.");
            setTimeout("focusElement('" + elem.form.name + "','" + elem.name + "')", 0);
            return false;
        }
    }
    return true;
}


// =================================== init ====================================
// Create the variable 'jsInit' and give it some value.
// 'application.rhtml' will not build the page until this variable has been created.
// Each controller that can be invoked from the first page displayed after login will
// also have to poll for this initialization variable.
var JsInit = 1;
var RenderCount = 0;

// ============================= table row lighting ============================
var arrayOfRolloverClasses = new Array();
var arrayOfClickClasses    = new Array();
var activeRowClickArray    = new Array();
var activeRow  = false;

function highlightTableRow() {
  var tableObj = this.parentNode;
  if (tableObj.tagName!='TABLE') tableObj = tableObj.parentNode;

  if (this!=activeRow){
    this.setAttribute('origCl',this.className);
    this.origCl = this.className;
  }
  this.className = arrayOfRolloverClasses[tableObj.id];
  activeRow = this;
}


function clickOnTableRow() {
  var tableObj = this.parentNode;
  if (tableObj.tagName!='TABLE') tableObj = tableObj.parentNode;    
  
  if (activeRowClickArray[tableObj.id] && this!=activeRowClickArray[tableObj.id]) {
    activeRowClickArray[tableObj.id].className ='';
  }
  this.className = arrayOfClickClasses[tableObj.id];
  activeRowClickArray[tableObj.id] = this;
}


function resetRowStyle() {
  var tableObj = this.parentNode;
  if (tableObj.tagName!='TABLE') tableObj = tableObj.parentNode;

  if (activeRowClickArray[tableObj.id]  &&  this == activeRowClickArray[tableObj.id]) {
    this.className = arrayOfClickClasses[tableObj.id];
    return; 
  }
  var origCl = this.getAttribute('origCl');
  if (!origCl) origCl = this.origCl;
  this.className=origCl;
}
  

function addTableRolloverEffect( tableId, whichClass, whichClassOnClick) {
  arrayOfRolloverClasses[tableId] = whichClass;
  arrayOfClickClasses[tableId] = whichClassOnClick;
  
  var tableObj = document.getElementById(tableId);

  if (!tableObj) { return; }

  var tBody = tableObj.getElementsByTagName('TBODY');
  if (tBody) {
    var rows = tBody[0].getElementsByTagName('TR');
  }else{
    var rows = tableObj.getElementsByTagName('TR');
  }
  for (var no=0;no<rows.length;no++) {
    rows[no].onmouseover = highlightTableRow;
    rows[no].onmouseout  = resetRowStyle;
    if (whichClassOnClick) {
      rows[no].onclick = clickOnTableRow; 
    }
  }
}

// ========================== search box autocomplete ==========================

function auto_log_id(str) {
  fdebug("auto_log_id: " + str);
}

