// +------------------------------------------------------------------------+
// |                  Copyright (c) 2003 ACTIVESEND.COM                     |
// |                         All Rights Reserved.                           |
// |      CONFIDENTIAL MATERIAL - UNAUTHORIZED ACCESS PROHIBITED.           |
// |------------------------------------------------------------------------|
// |  Module:   $RCSfile: util.js,v $                                       |
// |  Author:   Christopher Go                                              |
// |  Rev Date: $Date: 2007-02-03 00:50:32 $                                |
// |  Revision: $Revision: 1.38 $ $Author: chris $                          |
// +------------------------------------------------------------------------+

// ================================================== WINDOW

function setWindowLocation(aURL, aWindow, aProperties ) {
    if( aProperties==null ) {
        aProperties = "height=300,width=400,menubar=no,scrollbars=yes,status=no,titlebar=no,toolbar=no";
    }
    if(aWindow!=null) {
        var win = open( aURL, aWindow, aProperties);
        win.focus();
    } else {
        window.location = aURL;
        //window.focus();
    }
}

function openHelperWindow( aURL, aHeight, aWidth ) {
    if( aHeight==null ) aHeight=300;
    if( aWidth==null ) aWidth=400;
    var windowName  = 'helperWin';
    var windowProps = 'height=' + aHeight + ',width=' + aWidth + ',menubar=no,scrollbars=yes,status=no,titlebar=no,toolbar=no';
    var win = open(aURL, windowName, windowProps);
    win.focus();
}

function reloadSelf() {
    self.location.reload();
}

function reloadParent() {
    opener.location.reload();
}

function resizeWindow( _minWidth, _minHeight ) {
    var currWidth   = document.body.offsetWidth;
    var currHeight  = document.body.offsetHeight;
    if( currWidth<_minWidth || currHeight<_minHeight ) {    
        var targetWidth     = currWidth<=_minWidth?_minWidth:currWidth;
        var targetHeight    = currHeight<=_minHeight?_minHeight:currHeight;
        window.resizeTo( targetWidth, targetHeight );
    }
}

// Updates the image on a page using a select box
function updateImage(aFormField, aImageName, aImagePath) {   
    document.images[aImageName].src = aImagePath + "/" + aFormField.value;
}

// Opens an HTML editor with a predefined size and width and sends the 
// information back to the form field that called it
function openHTMLEditor(aForm, aField) {
    var properties = "toolbar=no,location=no,directories=no,menubar=no,scrollbars=no,width=550px,height=320px,modal=yes";
	var url = "../admin/popupHTMLEditor.php?form=" + aForm + "&field=" + aField;
	win = window.open(url, 'htmlEditor', properties);
}

// Generic open window command that all other functions use
function openWindow(aURL, aProperties) {
    var properties = "toolbar=no,location=no,directories=no,menubar=no,scrollbars=no,width=200px,height=200px,modal=yes";
    if( aProperties!=null ) {
        properties = aProperties;
    }
	win = window.open(aURL, "crossing", aProperties);
}

// ================================================== FORMS

function getCalendarField(aFormName, aFieldName) {
    var obj = document.getElementById(aFormName);
    var field = obj.elements[aFieldName];
    return field;
}

function setFormAction( _form, _action ) {
    var action = path + "/" + _action;
    document.forms[_form].submit();
}

function highlightButton(s) {
    if ("INPUT"==event.srcElement.tagName) {
        event.srcElement.className=s;
    }
}

function processCommand(aSelectBox) {
    var command = aSelectBox.options[aSelectBox.selectedIndex].value;
    if( trimstr(command)!='' ) {
        aSelectBox.form.elements['command'].value = command;
        // alert(document.forms['newsForm'].elements['command'].value);
        //document.forms['newsForm'].submit();
    }
}


/**
 * MAIN check form function (DEPRECATE THIS !!!!)
 * Will not work for XAJAX generated forms
 * 
 * [0] is the name
 * [1] is the label
 * [2] is the required
 * [3] is the type
 * [4] is the reg exp (optional)
 */
function processCheckForm(aFormName, aFieldArr) {
    // Make sure form exists
    if( !document.forms[aFormName] ) {
        return false;
    }
    var errorArr = new Array();
    var formObj = document.forms[aFormName];
    // Loop through each of the fields and so some validation
    for(ii=0; ii<aFieldArr.length; ii++) {
        var fieldObj    = formObj.elements[aFieldArr[ii][0]];
        var label       = aFieldArr[ii][1];
        var req         = aFieldArr[ii][2];
        var type        = aFieldArr[ii][3];
        var regExp      = aFieldArr[ii][4];
        // Check to see if field exists in form
        if( !fieldObj ) {
            errorArr.push('Form element name="' + aFieldArr[ii][0] + '" [' + label + '] does not exist!');
            continue;
        }
        // Check required
        if( req && trimstr(fieldObj.value)=='' ) {
            errorArr.push(label + ' is a required field');
            continue;
        }
        // Check type
        if( trimstr(fieldObj.value)!='' ) {
            var value = trimstr(fieldObj.value);
            switch( type ) {
                case FIELD_TYPE_TEXT:
                    break;
                case FIELD_TYPE_NUMBER:
                    if( !isInteger(value) ) {
                        errorArr.push(label + ' needs to be a number');
                    }
                    break;
                case FIELD_TYPE_INTEGER:
                    if( !isInteger(value) ) {
                        errorArr.push(label + ' needs to be a number');
                    }
                    break;
                case FIELD_TYPE_DATE:
                    if( !isDateString(value) ) {
                        errorArr.push(label + ' needs to be a valid date (MM/DD/YYYY format)');
                    }
                    break;
                case FIELD_TYPE_EMAIL:
                    if( !isEmail(value) ) {
                        errorArr.push(label + ' needs to be a valid email address');
                    }
                    break;
                case FIELD_TYPE_URL:
                    if( !isURL(value) ) {
                        errorArr.push(label + ' needs to be a valid URL (starts with http://)');
                    }
                    break;
                case FIELD_TYPE_PHONE:
                    if( !isPhoneNumber(value) ) {
                        errorArr.push(label + ' needs to be a valid US phone number');
                    }
                    break;
                case FIELD_TYPE_FLOAT:
                	value = str_replace('-','',value);
                    if( !isFloat(value) ) {
                        errorArr.push(label + ' needs to be a number (decimals ok)');
                    }
                    break;
                case FIELD_TYPE_DATETIME:
                    if( !isDateTimeString(value) ) {
                        errorArr.push(label + ' needs to be a valid date/time (MM/DD/YYYY HH:MM AM format)');
                    }
                    break;
                case FIELD_TYPE_CCNUM:
                    if ( value.length<15 || value.length>16 || !isInteger(value) ) {
                        errorArr.push(label + ' needs to be a 15 (Amex) or 16 digit number');
                    }
                    if( !validateCreditCardNumber(value) ) {
                        errorArr.push(label + ' does not appear to be a valid credit card number.');
                    }
                    break;
                case FIELD_TYPE_CCEXP:
                    if( !isInteger(value) || value.length!=4 || !validateCreditCardExpiration(value) ) {
                        errorArr.push(label + ' needs to be a 4 numbers (MMYY format)');
                    }
                    break;
                case FIELD_TYPE_ZIP:
                    if ( !isInteger(value) || value.length!=5 ) {
                        errorArr.push(label + ' needs to be a 5 digit number');
                    }
                    break;
                case FIELD_TYPE_ROUTING:
                    if ( !isInteger(value) || value.length!=9 ) {
                        errorArr.push(label + ' needs to be a 9 digit number');
                    }
                    break;
                case FIELD_TYPE_AMOUNT:
                    if ( !isAmount(value) ) {
                        errorArr.push(label + ' needs to be a valid amount');
                    }
                    break;
            }
        }
    }
    if( errorArr.length>0 ) {
        errorStr = '';
        for( ii=0; ii<errorArr.length; ii++ ) {
            errorStr += errorArr[ii] + "\n";
        }
        alert('Please correct the following errors to continue.\n\n' + errorStr);
        return false;
    } else {
        return true;
    }
}

// ================================================== FORMS

function toggleCheckboxes(aCheckbox) {
    var form = aCheckbox.form;
    var check = aCheckbox.ch;
    if( document.forms[aCheckbox.form.name] ) {
        for (i=0;i<form.length;i++) {
            if (form.elements[i].type=='checkbox'&&
                form.elements[i].name.indexOf(aCheckbox.name)==0) {
                form.elements[i].checked=aCheckbox.checked;
            }
        }
    }
}

function focusField(aForm, aField) {
    if( document.forms[aForm] && document.forms[aForm].elements[aField] ) {
        document.forms[aForm].elements[aField].focus();
    }
}


function getNumberChecked(aFormName, aCheckboxName) {
    var ii;
    var counter = 0;
    //alert( getNumberCheckboxes(aForm, aCheckboxElement) );
    if( getNumberCheckboxes(aFormName, aCheckboxName) > 1 ) {
        for(ii=0; ii<getNumberCheckboxes(aFormName, aCheckboxName); ii++) {
            if( document.forms[aFormName].elements[aCheckboxName][ii].checked ) {
                counter++;
            }
        }
    } else if( getNumberCheckboxes(aFormName, aCheckboxName) == 1 ) {
        if( document.forms[aFormName].elements[aCheckboxName].checked ) {
            counter = 1;
        }
    }
    return counter;
}

function getNumberCheckboxes(aFormName, aCheckboxName) {
    if( document.forms[aFormName].elements[aCheckboxName].length ) {
        return document.forms[aFormName].elements[aCheckboxName].length;
    } else if( document.forms[aFormName].elements[aCheckboxName] ) {
        return 1;
    } else {
        return 0;
    }
}

function getCheckboxValuesAsString(aFormName, aCheckboxName) {
    if( document.forms[aFormName].elements[aCheckboxName] ) {
        var checkboxObj = document.forms[aFormName].elements[aCheckboxName];
        if( checkboxObj.length ) {
            var checkValueArr = new Array();
            for( var ii=0; ii<checkboxObj.length; ii++ ) {
                if( checkboxObj[ii].checked ) {
                    checkValueArr.push(checkboxObj[ii].value);
                }
            }
            if( checkValueArr.length>0 ) {
                return checkValueArr.toString();
            }
        } else {
            if( checkboxObj.checked ) {
                return checkboxObj.value;
            }
        }
    }
    return null;
}

function getSelectedRadioValue(aFormName, aRadioName) {
    if( document.forms[aFormName] && 
        document.forms[aFormName].elements[aRadioName] ) 
    {
        var radioObj = document.forms[aFormName].elements[aRadioName];
        if( radioObj.length ) {
            for( ii=0; ii<radioObj.length; ii++ ) {
                // alert(radioObj[ii].checked);
                if( radioObj[ii].checked ) {
                    return radioObj[ii].value;
                }
            }
            return false;
        } else {
            if( radioObj.checked ) {
                return radioObj.value;
            }
        }
    } else {
        return false;
    }
}

function getSelectedRadioValueWithFrame(aFormName, aRadioName, aFrameName) {
    if( window.frames[aFrameName].document.forms[aFormName] && 
        window.frames[aFrameName].document.forms[aFormName].elements[aRadioName] ) 
    {
        var radioObj = window.frames[aFrameName].document.forms[aFormName].elements[aRadioName];
        if( radioObj.length ) {
            for( ii=0; ii<radioObj.length; ii++ ) {
                // alert(radioObj[ii].checked);
                if( radioObj[ii].checked ) {
                    return radioObj[ii].value;
                }
            }
            return false;
        } else {
            if( radioObj.checked ) {
                return radioObj.value;
            }
        }
    } else {
        return false;
    }
}

// ================================================== DATES

function writeCurrentDate() {
    var months          = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
    var monthAbbrevs	= new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
    var days            = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
    var dayAbbrevs      = new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
    var time            = new Date();
    var day             = time.getDay();
    var month           = time.getMonth();
    var date            = time.getDate();
    var year            = time.getYear();
    if (year < 2000)    // Y2K Fix, Isaac Powell
    	year = year + 1900; // http://onyx.idbsu.edu/~ipowell
    document.write(dayAbbrevs[day] + ", " + date + " " + monthAbbrevs[month] + " " + year);
}

/**
 * Function to populate the due date based on convenient time conventions
 */
function populateDateFieldUsingConventions(aSelectBox, aFormField) {
    var value = aSelectBox.options[aSelectBox.selectedIndex].value;
    if( value ) {
        var currDate    = new Date();
        var currDay     = currDate.getDate();
        var currMonth   = currDate.getMonth();
        var currYear    = currDate.getYear();
        var currHour    = currDate.getHours();
        var currMinute  = currDate.getMinutes();
        switch (value) {
            case '0.5':
                currMinute += 30;
                if( currMinute>60 ) {
                    currHour++;
                    currMinute = currMinute-60;
                }
                break;
            case '1':
                currHour++;
                if( currHour>24 ) {
                    currDay++;
                    currHour = currHour-24;
                }
                break;
            case '2':
                currHour += 2;
                if( currHour>24 ) {
                    currDay++;
                    currHour = currHour-24;
                }
                break;
            case '4':
                currHour += 6;
                if( currHour>24 ) {
                    currDay++;
                    currHour = currHour-24;
                }
                break;
            case '24':
                currDay++;
                break;
            case 'todayCOB':
                currHour = 18;
                currMinute = 0;
                break;
            case 'tomorrowNoon':
                currDay++;
                currHour = 12;
                currMinute = 0;
                break;
            case 'tomorrowCOB':
                currDay++;
                currHour = 18;
                currMinute = 0;
                break;
        }
        var dateStr  = '';
        if( currMonth+1<10 ) dateStr += '0'+(currMonth+1) + '/'
        else dateStr += (currMonth+1) + '/';
        if( currDay<10 ) dateStr += '0'+(currDay)
        else dateStr += (currDay);
        dateStr += '/'+ currYear + ' ';
        if( currHour>12 ) {
            currHour = currHour-12;
            meridiem = ' PM';
        } else {
            meridiem = ' AM';
        }
        if( currHour<10 ) dateStr += '0'+currHour + ':'
        else dateStr += currHour + ':';
        if( currMinute<10 ) dateStr += '0'+currMinute
        else dateStr += currMinute;
        dateStr += meridiem;
        aSelectBox.form.elements[aFormField].value = dateStr;
    }
}

// ================================================== PAYMENT FORMS


// ================================================== ARRAY

function in_array(_needle, _haystack) {
    var exists = false;
    for (var ii=0;ii<_haystack.length;ii++) {
        if( _needle.toUpperCase() == _haystack[ii].toUpperCase() ) {
            exists = true;
            break;
        }
    }
    return exists;
}

// ================================================== STRING

function str_replace(aSearch, aReplace, aString) {
    return aString.replace(aSearch,aReplace);
}

function ltrim ( s )
{
	return s.replace( /^\s*/, "" );
}
function rtrim ( s )
{
	return s.replace( /\s*$/, "" );
}
function trimstr ( s )
{
    return rtrim(ltrim(s));
}

/************************************************************
 *                       DEPRECATED
 ************************************************************/

function toggleDivDisplayWithSwitch(aDivName, aDisplay) {
	if( document.getElementById(aDivName) ) {
		if( aDisplay ) document.getElementById(aDivName).style.display = '';
		else document.getElementById(aDivName).style.display = 'none';
	}
}

/**
 * Toggle the visibility of a DIV (toggles from the current state)
 */
function toggleDivDisplay( aDivName ) {
    if( document.getElementById(aDivName) ) {
        var divElement = document.getElementById(aDivName);
        if( divElement.style.display=='' ) {
            divElement.style.display = 'none';
        } else {
            divElement.style.display = '';
        }
    }
}

//Function to use one checkbox to check a bunch of other checkboxes
function globalCheck(aCheckboxObj, aFormName, aFieldName) {
    var status = true;
    if( !aCheckboxObj.checked ) {
        status = false;
    }
    for(ii=0; ii<document.forms[aFormName].elements.length; ii++) {
        if( document.forms[aFormName].elements[ii].name == aFieldName ) {
            document.forms[aFormName].elements[ii].checked = status;
        }
    }
}

var MESSAGE_STATUS_SUCCESS  = 0;
var MESSAGE_STATUS_WAIT     = 1;
var MESSAGE_STATUS_ERROR    = 2;

function showStatus(aMessage,aStatus) {
    switch(aStatus) {
        case MESSAGE_STATUS_ERROR: messageColor='#cc0000'; break;
        case MESSAGE_STATUS_SUCCESS: messageColor='#009933'; break;
        case MESSAGE_STATUS_WAIT: messageColor='#ffcc00'; break;
        default: messageColor = '#808080'; break;
    }
    overlib("<b>"+aMessage+" &nbsp; </b>", FOLLOWSCROLL, STICKY, NOCLOSE, RELX, -8, RELY, 0, FGCOLOR, messageColor, BORDER, 0, TEXTSIZE, '10pt', TEXTCOLOR, '#ffffff', WRAP, 1, CELLPAD, 4, 4, 4, 4, WRAP);
}
function closeStatus() {
    nd();nd();
}

function loadDivWithURL(aDivName, aURL) {
    if( document.getElementById(aDivName) ) {
        document.getElementById(aDivName).innerHTML = "<div class='loadingBox'><b>Please wait. Loading...</b> <img src='../images/tabs/indicator.gif' /></div>";
    	//var form = document.getElementById('form');
    	//ajax.setVar("myTextBox", form.mytext.value); // recomended method of setting data to be parsed.
        ajax.requestFile = aURL;
    	//ajax.method = form.method.value;
    	ajax.element = aDivName;
    	//ajax.onLoading = whenLoading;
    	//ajax.onLoaded = whenLoaded; 
    	//ajax.onInteractive = whenInteractive;
    	//ajax.onCompletion = whenCompleted;
    	ajax.runAJAX();
    }
}


