﻿
/**************************************
    base.js 
    commonly used script functions
***************************************/

function toggleElement(e)
{
    if ($get(e).style.display == 'block')
        $get(e).style.display = 'none';
    else
        $get(e).style.display = 'block';   
}

function collapseElement(e)
{
    $get(e).style.display = "none";
}

function isCollapsed(e)
{
    return ($get(e).style.display == "none");
}

function expandElement(e)
{
    $get(e).style.display = "block";
}

function isExpanded(e)
{
    return ($get(e).style.display == "block");
}

// get the selected value from a drop down list
function get_selectedValue(listId)
{
     var value = null;
     var index = $get(listId).selectedIndex;
     if (index >= 0)
        value =  $get(listId).options[index].value;
    return value;
}

// get the selected text from a drop down list
function get_selectedText(listId)
{
     var value = null;
     var index = $get(listId).selectedIndex;
     if (index >= 0)
        value = $get(listId).options[$get(listId).selectedIndex].text;
    return value;
}

// Used to swap images during a mouseover
function changeImage(img, newImage) {
    img.src = newImage;
}

// Open url in a new window
function launch(url)
{
    window.open(url);void(0);
}

// Sets the selected item from a drop down list
function setSelectedItem(listId, value)
{
    var bSuccess = false;
    var theSel = $get(listId);
// removed so default selection "Select ..." is selected
//    if (theSel.length > 0) {
//        theSel.selectedIndex =  -1;
//    }
    for(i=theSel.length-1; i>=0; i--)
    {
        if (theSel.options[i].value == value)
        {
           theSel.options[i].selected = true;
            bSuccess = true; 
        }
    }
   
    return bSuccess;  
}

// better name than above but above kept for backward ass compatibility - L
function setSelectedValue(listId, value)
{
    return setSelectedItem(listId, value);
}

// set the selected item from a drop down list by text
function setSelectedText(listId, text)
{
    var bRet = false;
    var theSel = $get(listId);
   
     if (theSel.length > 0) {
        theSel.selectedIndex =  -1;
    }
    for(i=theSel.length-1; i>=0; i--)
    {
        if (theSel.options[i].text == text)
        {
           theSel.options[i].selected = true;
            bRet = true; 
        }
    }
   
    return bRet;  
}

function setSelectedByIndex(listId, index)
{
    var list = $get(listId);
    if (list.options.length - 1 >= index)
        list.options[index].selected = true;  
}

// generate an option element for a select list
function createOptionElement(strValue, strText)
{
    var e = document.createElement("option");
    e.value = strValue;
    if (document.all)
        e.innerText = strText;  //IE
    else
        e.textContent = strText;    //FF,Safari
    return e;   
}

// generic element creation
function createGenericElement(strTagName, strId, strCSSClass, strText, innerHTML)
{
    var e;
    if (strTagName != null)
        e = document.createElement(strTagName);
    if (strId !== null)
        e.setAttribute("id", strId);
    if (strCSSClass !== null)
        e.className = strCSSClass;
    if (strText !== null)
    {
        if (document.all)
            e.innerText = strText; //IE
        else
            e.textContent = strText;  //FF,Safari
    } 
    if (innerHTML !== null)
        e.innerHTML = innerHTML;  
    return e;
} 


// Remove the currently selected item from a Select tag
function removeSelectedOption(theSel)
{
  var selIndex = theSel.selectedIndex;

  if (selIndex != -1) {
        for(i=theSel.length-1; i>=0; i--)
        {
            if(theSel.options[i].selected)
            {
                //theSel.options[i] = null;
                theSel.remove(i);
            }
        }
        if (theSel.length > 0) {
            theSel.selectedIndex = selIndex == 0 ? 0 : selIndex - 1;
        }
    }
}

// Remove all option items for a Select tag
function removeAllSelectOptions(theSel)
{
    if (theSel != null && typeof(theSel) !== 'undefined')
   { 
        for(i=theSel.length-1; i>=0; i--)
        {
            theSel.remove(i);
        }
        if (theSel.length > 0) {
            theSel.selectedIndex = selIndex == 0 ? 0 : selIndex - 1;
        }
   } 
}

// remove an option from a select tag with particular text value
// e is select list object
function removeOption(e, text)
{
    for(var i = e.length - 1;  i >= 0; i--)
    {
        if (e.options[i].text == text)
        {
           e.removeChild(e.options[i]);
            break; 
        }
    }
} 

// trim empty spaces and carriage returns from the beginning and end of a string
function Trim(strText)
{
    // left trim
    while (strText.length > 0 
     && (strText.substring(0,1) == '\r' || strText.substring(0,1) == '\n' || strText.substring(0,1) == ' '))
        strText = strText.substring(1, strText.length);
    // right trim   
    while (strText.length > 0 
     && (strText.substring(strText.length-1, strText.length) == '\r' || strText.substring(strText.length-1, strText.length) == '\n' || strText.substring(strText.length-1, strText.length) == ' '))
        strText = strText.substring(0, strText.length-1);
       
    return strText;  
}

function showControl(ctlName)
{
    $get(ctlName).style.visibility='visible';
}

function hideControl(ctlName)
{
    $get(ctlName).style.visibility='hidden';
}

// returns querystring object
// get querystring value like this
// var q = queryString();
// var value = q.projectkey || "";
function queryString()
{
    var queryString = new Object();
    var query = location.search.substring(1);
    var pairs = query.split("&");
    
    for (var i = 0; i < pairs.length; i++)
    {
        var pos = pairs[i].indexOf("=");     //find a name=value pair
       if (pos == -1) continue;
       
       var argname = pairs[i].substring(0, pos).toLowerCase();    // extract name
       var value = pairs[i].substring(pos+1);          // extract value
       value = decodeURIComponent(value);          //decode
       
       queryString[argname] = value; 
    }    
   
    return queryString;  
}

// create an option element for a select control
function createOptionElement(strValue, strText)
{
    var e = document.createElement("option");
    e.value = strValue;
    if (document.all)
        e.innerText = strText;
    else
        e.textContent = strText;     
       
    return e; 
}

// remove all children from element
function removeChildren(elementId)
{
    var e =  $get(elementId);
    if (e.hasChildNodes())
    {
        while (e.childNodes.length >= 1)
            e.removeChild(e.firstChild); 
    }    
}

//  sets a message that will disappear after n seconds.  If a time out message
// is included the label will be finalized with that value...otherwise an empty string is inserted
// default time for message to show is 5 seconds
function setTimeoutMsg(elementId, message, timeoutMsg, iSeconds)
{
    var mSecs = (iSeconds && iSeconds != undefined) ? iSeconds * 1000 : 5000;
    var toMsg = (timeoutMsg && timeoutMsg != undefined) ? timeoutMsg : "";
    $get(elementId).innerHTML = message;
    setTimeout("$get('" + elementId + "').innerHTML = '" + toMsg + "'", mSecs); 
}

// Converts an value to currency
// if the showParens argument exists, it will display negative numbers as ($4.23)
function formatCurrency(num, showParens) 
{
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num)) num = "0";
    isNegative = (num != (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10) cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+
        num.substring(num.length-(4*i+3));
    var ret = '$' + num + '.' + cents;
    if(isNegative)
    {
        if(showParens != null)
            ret = '(' + ret + ')';
        else
            ret = '-' + ret;
    }
    return ret;
}

// Converts an value to currency
function formatPercent(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num)) num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10) cents = "0" + cents;
    return (((sign)?'':'-') + num + '.' + cents + '%');
}

function dollarToFloat(stringValue)
{
    if(stringValue != null)
        return parseFloat(stringValue.replace(/[$]/g,"").replace(/[,]/g,"").replace(/[(]/g,"-").replace(/[)]/g,""))
    else
        return 0;
}

// Extended Tooltip Javascript
// copyright 9th August 2002, 3rd July 2005
// by Stephen Chapman, Felgall Pty Ltd

// permission is granted to use this javascript provided that the below code is not altered
var DH = 0;var an = 0;var al = 0;var ai = 0;if (document.getElementById) {ai = 1; DH = 1;}else {if (document.all) {al = 1; DH = 1;} else { browserVersion = parseInt(navigator.appVersion); if ((navigator.appName.indexOf('Netscape') != -1) && (browserVersion == 4)) {an = 1; DH = 1;}}} function fd(oi, wS) {if (ai) return wS ? document.getElementById(oi).style:document.getElementById(oi); if (al) return wS ? document.all[oi].style: document.all[oi]; if (an) return document.layers[oi];}
function pw() {return window.innerWidth != null? window.innerWidth: document.body.clientWidth != null? document.body.clientWidth:null;}
function mouseX(evt) {if (evt.pageX) return evt.pageX; else if (evt.clientX)return evt.clientX + (document.documentElement.scrollLeft ?  document.documentElement.scrollLeft : document.body.scrollLeft); else return null;}
function mouseY(evt) {if (evt.pageY) return evt.pageY; else if (evt.clientY)return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); else return null;}
function popUp(evt,oi) {
if (DH) {var wp = pw(); ds = fd(oi,1); dm = fd(oi,0); st = ds.visibility; 
if (dm.offsetWidth) ew = dm.offsetWidth; else if (dm.clip.width) ew = dm.clip.width; 
if (st == "visible" || st == "show") 
{ ds.visibility = "hidden"; } 
else {tv = mouseY(evt) + 20; 
lv = mouseX(evt) - (ew/4); 
if (lv < 2) lv = 2; else if (lv + ew > wp) lv -= ew/2; 
if (!an) {lv += 'px';tv += 'px';} ds.left = lv; ds.top = tv; 
ds.visibility = "visible";
}}}


/* cookie functions */
function readCookie(name)
{
    var value = "";
    var nameEq = name + "=";
    var cArray = document.cookie.split(';');
    for (var i = 0; i < cArray.length; i++)
    {
            var c = cArray[i];
            // move to first position of cookie text
            while (c.charAt(0) == ' ')
                c = c.substring(1, c.length);
            if (c.indexOf(nameEq) == 0) 
            {
                value = c.substring(nameEq.length, c.length)
                break;
            }    
    }
    
    return value;
}

function deleteAllCookies(path)
{
    var name = "";
    var nameEq = "=";
    var cArray = document.cookie.split(';');
    for (var i = 0; i < cArray.length; i++)
    {
        var c = cArray[i];
        while(c.charAt(0) == ' ')
            c = c.substring(1, c.length);
        var name = c.split("=")[0];
        eraseCookie(name, path);
    }
}

// setting the days to 0 deletes the cookie after the session
// setting the days to -1 deletes the cookie immediately
function createCookie(name, value, days, path)
{
    if (days)
    {
        var date = new Date();
        // current time in milliseconds
        date.setTime(date.getTime() + (days*24*60*60*1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else
    {
        var expires = "";
    }
    
    document.cookie = name + "=" + value + expires + "; path=" + path; 
}

function eraseCookie(name, path)
{
    createCookie(name, "", -1, path);
}
/* end cookie functions */


// is the structure of the date string correct?
function validateDateStructure(value)
{
    var bSuccess = true;
    if (value.length > 0 && !checkValidDate(value))
    {
        bSuccess = false;
    }
    return bSuccess;   
}

/* date validation */
function checkValidDate(dateStr) {
    // dateStr must be of format month day year with either slashes
    // or dashes separating the parts. Some minor changes would have
    // to be made to use day month year or another format.
    // This function returns True if the date is valid.
    var slash1 = dateStr.indexOf("/");
    if (slash1 == -1) { slash1 = dateStr.indexOf("-"); }
    // if no slashes or dashes, invalid date
    if (slash1 == -1) { return false; }
    var dateMonth = dateStr.substring(0, slash1)
    var dateMonthAndYear = dateStr.substring(slash1+1, dateStr.length);
    var slash2 = dateMonthAndYear.indexOf("/");
    if (slash2 == -1) { slash2 = dateMonthAndYear.indexOf("-"); }
    // if not a second slash or dash, invalid date
    if (slash2 == -1) { return false; }
    var dateDay = dateMonthAndYear.substring(0, slash2);
    var dateYear = dateMonthAndYear.substring(slash2+1, dateMonthAndYear.length);
    if ( (dateMonth == "") || (dateDay == "") || (dateYear == "") ) { return false; }
    // if any non-digits in the month, invalid date
    for (var x=0; x < dateMonth.length; x++) {
        var digit = dateMonth.substring(x, x+1);
        if ((digit < "0") || (digit > "9")) { return false; }
    }
    // convert the text month to a number
    var numMonth = 0;
    for (var x=0; x < dateMonth.length; x++) {
        digit = dateMonth.substring(x, x+1);
        numMonth *= 10;
        numMonth += parseInt(digit);
    }
    if ((numMonth <= 0) || (numMonth > 12)) { return false; }
    // if any non-digits in the day, invalid date
    for (var x=0; x < dateDay.length; x++) {
        digit = dateDay.substring(x, x+1);
        if ((digit < "0") || (digit > "9")) { return false; }
    }
    // convert the text day to a number
    var numDay = 0;
    for (var x=0; x < dateDay.length; x++) {
        digit = dateDay.substring(x, x+1);
        numDay *= 10;
        numDay += parseInt(digit);
    }
    if ((numDay <= 0) || (numDay > 31)) { return false; }
    // February can't be greater than 29 (leap year calculation comes later)
    if ((numMonth == 2) && (numDay > 29)) { return false; }
    // check for months with only 30 days
    if ((numMonth == 4) || (numMonth == 6) || (numMonth == 9) || (numMonth == 11)) {
        if (numDay > 30) { return false; }
    }
    // if any non-digits in the year, invalid date
    for (var x=0; x < dateYear.length; x++) {
        digit = dateYear.substring(x, x+1);
        if ((digit < "0") || (digit > "9")) { return false; }
    }
    // convert the text year to a number
    var numYear = 0;
    for (var x=0; x < dateYear.length; x++) {
        digit = dateYear.substring(x, x+1);
        numYear *= 10;
        numYear += parseInt(digit);
    }
    // Year must be a 2-digit year or a 4-digit year
    if ( (dateYear.length != 2) && (dateYear.length != 4) ) { return false; }
    // if 2-digit year, use 50 as a pivot date
    if ( (numYear < 50) && (dateYear.length == 2) ) { numYear += 2000; }
    if ( (numYear < 100) && (dateYear.length == 2) ) { numYear += 1900; }
    if ((numYear <= 0) || (numYear > 9999)) { return false; }
    // check for leap year if the month and day is Feb 29
    if ((numMonth == 2) && (numDay == 29)) {
        var div4 = numYear % 4;
        var div100 = numYear % 100;
        var div400 = numYear % 400;
        // if not divisible by 4, then not a leap year so Feb 29 is invalid
        if (div4 != 0) { return false; }
        // at this point, year is divisible by 4. So if year is divisible by
        // 100 and not 400, then it's not a leap year so Feb 29 is invalid
        if ((div100 == 0) && (div400 != 0)) { return false; }
    }
    // date is valid
    return true;
}
