var winHelpHNDL = null;
var winUtilityHNDL = null;
var winDebug = null;
var new_fieldname = "";

var _mousePosX;
var _mousePosY;

//Used for color changes in forms
var highlightcolor="lightYellow";
var ns6 = document.getElementById&&!document.all;
var previous='';
var eventobj;
var intended=/INPUT|TEXTAREA/;

var isIE = false;
var isIE7 = false;
var isOther = false;
var isNS4 = false;
var isNS6 = false;
var isSafari = false;
var isOpera = false;

var submitted = false;

var onLoadFunctions = [];

if(document.getElementById)
{
    if(!document.all)
    {
        isNS6=true;
    }
    if(document.all)
    {
        isIE=true;
    }
}
else
{
    if(document.layers)
    {
        isNS4=true;
    }
    else
    {
        isOther=true;
    }
}

isSafari = (document.childNodes && !document.all && !navigator.taintEnabled && !navigator.accentColorName)? true : false;
isOpera = navigator.userAgent.toLowerCase().indexOf("opera") != -1;
isIE7 = isIE && document.documentElement && typeof document.documentElement.style.maxHeight!="undefined";

function rmbr(string){
    var regexp = /(<br>)|(<br\/>)/gi;
     // IE needs the newlines explicitly
    if (isIE === true) {
        string = string.replace(regexp, '\n');
    } else {
        string = string.replace(regexp, '');
    }

    return string;
}

function nl2br(string){
    var regexp = /\n/g;
    string = string.replace(regexp, '<br>\n');
    return string;
}

//calls a method to change the records per page in pagination
function alterRecsPerPage(fileName,tableid,limit,extraPars){
    var pars =  extraPars+'&updatelimit='+ limit;
    new Ajax.Updater(tableid, fileName,{onLoading:function(request){resetStatus(lang('Loading'))}, onComplete:function(request){unsetStatus(lang('Loaded'),1000)}, method: 'get', parameters:pars, asynchronous:true});
}


//calls a method to change the page in pagination
function pageBarAction(tableid,file,pars){
    new Ajax.Updater(tableid, file,{onLoading:function(request){resetStatus(lang('Loading'))}, onComplete:function(request){unsetStatus(lang('Loaded'),1000)}, method: 'get', parameters:pars, asynchronous:true});
}

/**
 * Function : dump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
 */
function dump(arr,level) {
	var dumped_text = "";
	if(!level) {
            level = 0;
        }

	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) {
            level_padding += "    ";
        }

	if(typeof(arr) == 'object') { //Array/Hashes/Objects
		for(var item in arr) {
			var value = arr[item];

			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}


/**
* Returns the value of the selected radio button in the radio group, null if
* none are selected, and false if the button group doesn't exist
*
* @param {radio Object} or {radio id} el
* OR
* @param {form Object} or {form id} el
* @param {radio group name} radioGroup
*/
function $RF(el, radioGroup) {
      if($(el).type && $(el).type.toLowerCase() == 'radio') {
          var radioGroup = $(el).name;
          var el = $(el).form;
      } else if ($(el).tagName.toLowerCase() != 'form') {
          return false;
      }

      var checked = $(el).getInputs('radio', radioGroup).find(
          function(re) {return re.checked;}
      );
      return (checked) ? $F(checked) : null;
}
//function used to make sure clicking enter on text box will not force form submit
//use the following in the textbox input section
// onkeypress="return noenter()"
function noenter(e) {
    if(window.event) {
        return !(window.event.keyCode == 13);
    }else{
        return !(e.which == 13);
    }
}

function InArray(tarray,value)
// Returns true if the passed value is found in the
// array.  Returns false if it is not.
{
    var i;
    for (i=0; i < tarray.length; i++) {
        // Matches identical (===), not just similar (==).
        if (tarray[i] === value) {
            return true;
        }
    }
    return false;
}

// Returns the selected value of a select input field.
function selectedValue(id)
{
    return $(id).options[$(id).selectedIndex].value
}

function MakeVisable(cur,which){
    strength = (which==0) ? 1 : 0.4;
    if (cur.style.MozOpacity){
        cur.style.MozOpacity=strength;
    }else if(cur.filters){
        cur.filters.alpha.opacity = strength * 100;
    }
}

//function used to ensure that at least one checkbox has been clicked
//to perform the action on
function ItemSelected(form,warningmsg, onlyCb){
    intCount = form.elements.length;
    bolShowMessage=true;
    for(x=1;x<=intCount;x++) {
            if(form.elements[x-1].checked && (!onlyCb || form.elements[x-1].id.substring(0, 3) == 'cb_')) {
                    bolShowMessage=false;
                    continue;
            }
    }

    if (bolShowMessage){
            if(warningmsg!="") alert(warningmsg);
            return false;
    }else{
            return true;
    }
}


function ltrim(inputString){
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   return retValue;
}

function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function

<!--hide from old browsers
//Regular expression to highlight only form elements
//Function to check whether element clicked is form element
function submitonce(theform){
    if (document.all||document.getElementById){
        for (i=0;i<theform.length;i++){
            var tempobj=theform.elements[i]
            if(tempobj.type.toLowerCase()=="submit"||tempobj.type.toLowerCase()=="button")
            tempobj.disabled=true
        }
    }
}


function openWindow(theURL,winName,features)
{
  window.open(theURL,winName,features);
}

function closeHelpWindow(){
  if (winHelpHNDL != null && winHelpHNDL.open) winHelpHNDL.close();
  if (winUtilityHNDL != null && winUtilityHNDL.open) winUtilityHNDL.close();
}

function openHelpWindow(module, className, settingName, features)
{
  var strURL = "index.php?fuse=newedge&view=HelpWindow&module=" + module + "&className=" + className + "&settingName=" + settingName;
  if (winHelpHNDL != null && winHelpHNDL.open) winHelpHNDL.close();
  winHelpHNDL =  window.open(strURL,'winHelp', features);
}

function oldOpenHelpWindow(intHelpID)
{
  var strURL = "index.php?fuse=newedge&view=HelpWindow&helpID="+intHelpID;
  if (winHelpHNDL != null && winHelpHNDL.open) winHelpHNDL.close();
  winHelpHNDL =  window.open(strURL,'winHelp', 'menubar=no,scrollbars=yes,width=240,height=420');
}

function newOpenHelpWindow(intHelpID)
{
    var helpInfo = new Ext.data.JsonStore({
        id:             "helpInfo",
        root:           'helpinfo',
        totalProperty:  'totalcount',
        idProperty:     'id',
        remoteSort:     true,
        baseParams:     {
            helpID: intHelpID
        },
        fields:         [
                            'title',
                            'detail'
                        ],
        proxy:          new Ext.data.HttpProxy({
                            url: 'index.php?fuse=newedge&action=HelpWindow'
                        })
    });
    
    helpInfo.on('load',function(){
        recordHelpInfo = helpInfo.getAt(0);
        
        var htmlString = "<style type=\"text/css\"><!--"
                       + "    .body8          {"
                       + "        font-family:      Verdana, Arial, Helvetica, sans-serif;"
                       + "        font-size:        7pt;"
                       + "        line-height:      8pt;"
                       + "        text-decoration:  none"
                       + "    }"
                       + "    "
                       + "    .bodyhighlight  {"
                       + "        font-size:        7pt;"
                       + "        line-height:      8pt;"
                       + "        color:            navy;"
                       + "    }"
                       + "    "
                       + "    TD.tight        {"
                       + "        padding:          10px 5px 5px 10px;"
                       + "    }"
                       + "    "
                       + "    TD.heading      {"
                       + "        padding:          0px 0px 5px 9px;"
                       + "    }"
                       + "    "
                       + "    A               {"
                       + "        text-decoration:  none"
                       + "    }"
                       + "//--></style>"
                       + ""
                       + "<table id=help cellSpacing=0 cellPadding=0 width=\"100%\" border=0 bgcolor='#cccccc'>"
                       + "    <tbody>"
                       + "        <tr>"
                       + "            <td vAlign=top>"
                       + "                <div align=center>"
                       + "                    <table cellSpacing=0 cellPadding=0 width=200 border=0>"
                       + "                        <tbody>"
                       + "                            <tr>"
                       + "                                <td colSpan=2>"
                       + "                                    <img height=30 src=\"../templates/admin/images/help_top.jpg\" width=200 border=0>"
                       + "                                </td>"
                       + "                            </tr>"
                       + "                            <tr>"
                       + "                                <td colSpan=2 class=heading height=25 width=200 background=\"../templates/admin/images/help_midtop_background.gif\">"
                       + "                                    <font class=body8><b>" + lang('Topic') + ":</b><br>" + recordHelpInfo.get('title') + "</font>"
                       + "                                </td>"
                       + "                            </tr>"
                       + "                            <tr>"
                       + "                                <td colspan=2>"
                       + "                                    <table width=100% cellpadding=0 cellspacing=0 border=0>"
                       + "                                        <tr>"
                       + "                                            <td class=tight bgcolor=white>"
                       + "                                                <font class=body8>" + recordHelpInfo.get('detail') + "</font>"
                       + "                                            </td>"
                       + "                                        </tr>"
                       + "                                    </table>"
                       + "                                </td>"
                       + "                            </tr>"
                       + "                        </tbody>"
                       + "                    </table>"
                       + "                </div>"
                       + "            </td>"
                       + "        </tr>"
                       + "    </tbody>"
                       + "</table>";
        
        // Window
        var helpWin = new Ext.Window({
            id:           "helpWindow",
            y:            100,
            layout:       'fit',
            resizable:    false,
            autoHeight:   true,
            modal:        true,
            closable:     false,
            title:        recordHelpInfo.get('title'),
            header:       true,
            plain:        true,
            shadow:       false,
            html:         htmlString,
            buttons:      [
                {
                    text:     'Close',
                    handler:  function(){
                        helpWin.hide();
                        helpWin.destroy();
                    }
                }
            ]
        });
        
        helpWin.enable();
        helpWin.show();
    });
    
    helpInfo.load();
}

function jumpMenu(targ,selObj,restore)
{
    s = new String(selObj.options[selObj.selectedIndex].value);
    s.replace("&amp;","&");
    if (selObj.selectedIndex==0) return false;
    eval(targ+".location='"+s+"'");
    if (restore) selObj.selectedIndex=0;
}

function jumpMenu2(targ,selObj,restore)
{
    s = new String(selObj.options[selObj.selectedIndex].value);
    s.replace("&amp;","&");
    eval(targ+".location='"+s+"'");
    if (restore) selObj.selectedIndex=0;
}

function hideshow(which,imgid){
    if (!document.getElementById)  return
    if (which.style.display=="none"){
        which.style.display="";
        if(document.images[imgid] != null){
                document.images[imgid].src= relativePath + "images/collapse.gif";
        }
    }else{
        which.style.display="none";
        if(document.images[imgid] != null){
                document.images[imgid].src= relativePath + "images/expand.gif";
        }
    }
}

// *** TABLE CHECKBOX OPERATIONS *****
var checkCount = 0;

function makevisible(cur,which)
{
    strength=(which==0)? 1 : 0.2

    if (cur.style.MozOpacity)
        cur.style.MozOpacity=strength
    else if (cur.filters)
        cur.filters.alpha.opacity=strength*100
}

function updateButtons(form)
{
    if (checkCount > 0) {
        for (i = 0; i < form.length; i++) {
            element = form.elements[i];
            if (element.type == "button" || element.type == "submit") {
                element.disabled = false;
                makevisible(element, 0);
            }
        }
    } else {
        for (i = 0; i < form.length; i++) {
            element = form.elements[i];
            if (element.type == "button" || element.type == "submit") {
                element.disabled = true;
                makevisible(element, 1);
            }
        }
    }
}

function checkCheckBox(checkBox)
{
    if (checkBox.checked) checkCount++;
    else checkCount--;
    updateButtons(checkBox.form);
}

function toggleAll(form)
{
    check = form.toggleAllChk.checked;
    for (i = 0; i < form.length; i++) {
        element = form.elements[i];
        if (element.type == 'checkbox' && element.name != 'toggleAll' && element.checked != check && element.disabled != true) {
            element.checked = check;
            if (check) checkCount++;
            else checkCount = 0;
        }
    }
    updateButtons(form);
}
// *** END TABLE CHECKBOX OPERATIONS *****

function debug(str)
{
    if (!winDebug) {
        winDebug = window.open('', 'debugging', 'width=400, height=500, scrollbars=yes, resizable=yes');
        winDebug.document.write('<pre>\n');
    }
    winDebug.document.write(str + '\n');
}

function strrpos( haystack, needle, offset){
    var i = (haystack+'').lastIndexOf( needle, offset ); // returns -1
    return i >= 0 ? i : false;
}

function substr( f_string, f_start, f_length ) {
    // http://kevin.vanzonneveld.net
    // +     original by: Martijn Wieringa
    // +     bugfixed by: T.Wild
    // +      tweaked by: Onno Marsman
    // *       example 1: substr('abcdef', 0, -1);
    // *       returns 1: 'abcde'
    // *       example 2: substr(2, 0, -6);
    // *       returns 2: ''

    f_string += '';

    if(f_start < 0) {
        f_start += f_string.length;
    }

    if(f_length == undefined) {
        f_length = f_string.length;
    } else if(f_length < 0){
        f_length += f_string.length;
    } else {
        f_length += f_start;
    }

    if(f_length < f_start) {
        f_length = f_start;
    }

    return f_string.substring(f_start, f_length);
}

/* Used for snapshot menu */
function addClassName(el, sClassName)
{
    var s = el.className;
    var p = s.split(" ");
    var l = p.length;
    for (var i = 0; i < l; i++) {
        if (p[i] == sClassName)
            return;
    }
    p[p.length] = sClassName;
    el.className = p.join(" ");

}

function removeClassName(el, sClassName)
{
    var s = el.className;
    var p = s.split(" ");
    var np = [];
    var l = p.length;
    var j = 0;
    for (var i = 0; i < l; i++) {
        if (p[i] != sClassName)
            np[j++] = p[i];
    }
    el.className = np.join(" ");
}

function getAbsoluteTop(objectId) {
        // Get an object top position from the upper left viewport corner
        // Tested with relative and nested objects
        o = $(objectId)
        oTop = o.offsetTop            // Get top position from the parent object
        while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
                oParent = o.offsetParent  // Get parent object reference
                oTop += oParent.offsetTop // Add parent top position
                o = oParent
        }
        // Return top position
        return oTop
}
/* End dynamic menu */

function lang(phrase)
{
    if ((typeof language != "undefined") && (typeof language[phrase] != "undefined") && (language[phrase] != '')) {
        switch (lang.arguments.length) {
            case 1:
                return language[phrase];
            case 2:
                return _sprintf(language[phrase], lang.arguments[1]);
            case 3:
                return _sprintf(language[phrase], lang.arguments[1], lang.arguments[2]);
        }

        return language[phrase];
    }

    switch (lang.arguments.length) {
        case 1:
            return phrase;
        case 2:
            return _sprintf(phrase, lang.arguments[1]);
        case 3:
            return _sprintf(phrase, lang.arguments[1], lang.arguments[2]);
    }

    return phrase;
}

// Same as lang() but only used for dynamically generated strings, like varLang(foo).
// Doesn't get parsed by update_languages.php script
function varLang(phrase)
{
    return lang(phrase);
}

function processOnLoadFunctions()
{
    for (var i = 0; i < onLoadFunctions.length; i++) {
        onLoadFunctions[i]();
    }
}

// *** AUXILIARY FUNCTIONS *****
function getURLVar(varName)
{
    var input = unescape(location.search.substr(1));
    if (input) {
        var srchArray = input.split('&');
        var tempArray = new Array();
        for (var i = 0; i < srchArray.length; i++) {
            tempArray = srchArray[i].split('=');
            if (tempArray[0] == varName) {
                return tempArray[1];
            }
        }
    }

    return false;
}

// taken from the javascript bible
function isNumber(inputVal)
{
    var oneDecimal = false;
    inputStr = inputVal.toString();
    for (var i = 0; i < inputStr.length; i++) {
        var oneChar = inputStr.charAt(i);
        if (i == 0 && oneChar == '.') {
            continue;
        }
        if (oneChar == '.' && !oneDecimal) {
            oneDecimal = true;
            continue;
        }
        if (oneChar < '0' || oneChar > '9') {
            return false;
        }

        return true;
    }
}

function getElementsByName_iefix(tag, name) {
     var elem = document.getElementsByTagName(tag);
     var arr = new Array();
     for(i = 0,iarr = 0; i < elem.length; i++) {
          att = elem[i].getAttribute("name");
          if(att == name) {
               arr[iarr] = elem[i];
               iarr++;
          }
     }
     return arr;
}

// Functions to escape strings.
// Can't use encodeURIComponent if document is not UTF-8.
// escape() works fine with ISO-8859-1 but will most likely break under other charsets,
// but this is the best we can do...
function _escapeString(str)
{
    var isUTF = (isIE && document.charset == 'utf-8') || (!isIE && document.characterSet == 'UTF-8');
    if (isUTF) {
        return encodeURIComponent(str);
    }

    return escape(str);
}

function _sprintf(s)
{
    var re = /%/;
    var i = 0;
    while (re.test(s))
    {
       s = s.replace(re, _sprintf.arguments[++i]);
    }

    return s;
}

function passwordRequest(inputMail)
{
    var newElement = $(inputMail);

    var newEmail = newElement.value;

    var opt = {
     	 onSuccess	: messageEmailSent,
     	 onLoading  : function() {resetStatus(lang('Loading'));}
    }

    new Ajax.Request('index.php?fuse=admin&action=RequestPassword&ajaxRequest=1&emailToSend='+newEmail, opt);

}

function messageEmailSent(t)
{
    unsetStatus(false);
    var response = t.responseText;
    $('message').innerHTML = '<font class="redtext"><b>'+response+'</b></font>';
}



function deletePermissions()
{
    if (confirm(lang('By disabling this permission you will disable all permissions that depend on it. \n \n Are you sure you want to do this?'))) {
        return true;
    }
    return false;
}

function check(form,x)
{
    script_name = "Form Validator ver 2.0";
    action =  "Checks Required, Integer and Date";
    cpyrght = "(c) 1998 - Art Lubin / Artswork";
    email = "perflunk@aol.com";
    var set_up_var = doall(script_name, cpyrght, email);
    var message = "";
    var more_message = "";
    if (set_up_var == 5872){
        x = x - 1;

        for (var i = 0; i <= x; i++) {

            if (typeof form.elements[i].name == 'undefined') {
                continue;
            }

            var messenger = form.elements[i].name;
            messenger = messenger.substring(0, 2);
            var fieldname = form.elements[i].name;
            fieldname = fieldname.substring(2);
            if((form.elements[i].name == "ccnumber" || form.elements[i].name == "ccmonth" || form.elements[i].name == "ccyear") && document.getElementById("creditcardinfo").style.display == "none")
            {
                form.elements[i].value = "";
            }

            var cctypes = null;
            if (messenger == "r_"){
                if (form.elements[i].value!=""){
                    more_message = r_check(form,x,fieldname,i);
                }
            }else if (messenger == "c_"){
                if (form.elements[i].value!=""){
                    //more_message = c_check(form,x,fieldname,i,false);
                    more_message = c_check(form,x,fieldname,i,true);        //blanks are allowed with this line
                    cctypes = form.elements['validcc'].value
                    if (more_message==""){  more_message = CheckWithAllowedCardTypes(cctypes,form,x,fieldname,i);   }
                }
            }else if (messenger == "C_"){
                //same as case above but blanks are allowed
                if (form.elements[i].value!=""){
                    more_message = c_check(form,x,fieldname,i,true);
                    cctypes = form.elements['validcc'].value
                    if (more_message==""){  more_message = CheckWithAllowedCardTypes(cctypes,form,x,fieldname,i); }
                }
            }else if (messenger == "D_"){
                if (form.elements[i].value!=""){
                    more_message = D_check(form,x,fieldname,i);
                }
            }else if (messenger == "i_"){
                more_message = i_check(form,x,fieldname,i);
            }else if (messenger == "d_"){
                more_message = d_check(form,x,fieldname,i);
            }else if (messenger == "e_"){
                more_message = e_check(form,x,fieldname,i);
            }else if (messenger == "n_"){
                more_message = n_check(form, x, fieldname, i);
            }
            if (more_message != ""){
                if (more_message){
                    if (message == ""){
                        message = more_message;
                        more_message="";
                    }else{
                        message = message + "\n" + more_message;
                        more_message="";
                    }
                }
            }
        }

        if (message != ""){
            alert(lang("The following form field(s) were incomplete or incorrect")+":\n\n" + message + "\n\n"+lang("Please complete or correct the form and submit again."));
        }else{
            submitonce(form);

            // call form onsubmit event, if it exists
            try {
                form.onsubmit();
            } catch(e) {
            }

            if (!submitted) {
                form.submit();
                submitted = true;
            }
        }
    }else{
        alert ("The copyright information has been changed. \n In order to use this javascript please keep the copyright information intact. \n\n Script Name: Form Validator ver 2.0 \n Copyright: (c) 1998 - Art Lubin / Artswork \n Email: perflunk@aol.com");
    }
}

// When completed, this function will replace the check() function, that doesn't work with fieldset tags
function getFormErrors(form)
{
    var strAlertMessageArr = new Array();

    var elements = form.getElementsByTagName("input");
    for (var i = 0; i < elements.length; i++) {
        if (elements[i].name.substr(0, 2) == "r_") {
            var requiredElementName = elements[i].name.substr(2);
            for (var j = 0; j < elements.length; j++) {
                if (elements[j].name == requiredElementName && elements[j].value == "") {
                    strAlertMessageArr.push(lang('The field % can\'t be empty.', elements[i].value));
                    break;
                }
            }
        }
        if (elements[i].name.substr(0, 2) == "e_") {
            regexp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,6})+$/;
            var elementName = elements[i].name.substr(2);
            for (var j = 0; j < elements.length; j++) {
                if (elements[j].name == elementName && !regexp.test(elements[j].value)) {
                    strAlertMessageArr.push(lang('Invalid E-mail format for field %.', elements[i].value));
                    break;
                }
            }
        }
    }

    return strAlertMessageArr;
}

function isNum(str)
{
    // 0.234, .234, 234, 234.234
    regexp = /(^\d+\.?\d*)|(^\d*\.?\d+)/;
    if (regexp.test(str)) return true;
    else return false;
}

function n_check(form, x, fieldname, i)
{
    var msg_addition = "";
    error=0;
    for (var y = 0; y <= x; y++) {
        if (form.elements[y].name == fieldname) break;
    }
    numberField = form.elements[y].value;
    if(!isNum(numberField)) { error = 1;} else {
        if (numberField.indexOf ('.3') > 1)  error = 1;
    }
    if (error == 1) msg_addition = form.elements[i].value;
    return(msg_addition);
}
function c_check(form,x,fieldname,i,blankallowed)
{
       /*************************************************************************\
       luhn check
       \*************************************************************************/
        var msg_addition = "";
        error=0;
        for (var y = 0; y <= x; y++){   if (form.elements[y].name == fieldname) break;  }
        CardNumber = form.elements[y].value;
        if (CardNumber != ""){
            if (! isNum(CardNumber)) {      error=1;      }
            var  no_digit = CardNumber.length;
            var oddoeven = no_digit & 1;
            var sum = 0;
            if (error==0){
                for (var count = 0; count < no_digit; count++) {
                    var digit = parseInt(CardNumber.charAt(count));
                    if (!((count & 1) ^ oddoeven)) {
                        digit *= 2;
                        if (digit > 9) digit -= 9;
                    }
                    sum += digit;
                }
                if (sum % 10 == 0)  error=0;
                else error=1;
            }
            if (error == 1) msg_addition = form.elements[i].value;
        }else if (!blankallowed) msg_addition = form.elements[i].value;
        return(msg_addition);
}

function D_check(form,x,fieldname,i)
{
    for (var y = 0; y <= x; y++)
    {
            if (form.elements[y].name == fieldname) break;
    }
    var msg_addition = "";

    regexp = /^\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    if (regexp.test(form.elements[y].value))  error = 0;
    else{
         error=1;
    }

    if (error == 1) msg_addition = form.elements[i].value;
    return(msg_addition);
}

function r_check(form,x,fieldname,i)
{
        var msg_addition = "";
        new_fieldname = fieldname;
        for (var y = 0; y <= x; y++)
            {

                if ((form.elements[y].type == "radio" || form.elements[y].type == "checkbox") && form.elements[y].name == new_fieldname && form.elements[y].checked == true)
                    {
                            msg_addition = "";
                            break;
                    }
                else if ((form.elements[y].type == "radio" || form.elements[y].type == "checkbox") && form.elements[y].name == new_fieldname && form.elements[y].checked == false)
                    {
                        msg_addition = form.elements[i].value;
                    }

            else if (form.elements[y].type == "select-one")
                            {
                                var l = form.elements[y].selectedIndex;
                                if (form.elements[y].name == fieldname && form.elements[y].options[l].value != "")
                                    {
                                        msg_addition = "";
                                        break;
                                    }
                                else if (form.elements[y].name == fieldname && form.elements[y].options[l].value == "")
                                    {

                                        msg_addition = form.elements[i].value;

                                    }
                                }
         else if (form.elements[y].name == fieldname && form.elements[y].value == "" && form.elements[y].type != "radio" && form.elements[y].type != "checkbox" && form.elements[y].type != "select-one")
                            {

                                if(form.elements[y].name == 'UserName' || form.elements[y].name == 'Password'){
                                    msg_addition = "";
                                }else{
                                    msg_addition = form.elements[i].value;
                                    break;
                                }
                            }
                else if (form.elements[y].name == fieldname && form.elements[y].value != "" && form.elements[y].type != "radio" && form.elements[y].type != "checkbox" && form.elements[y].type != "select-one")
                            {
                                msg_addition = "";
                            }
                }
            return(msg_addition);
}


function i_check(form,x,fieldname,i)
{
        for (var y = 0; y <= x; y++)
            {
                if (form.elements[y].name == fieldname) break;
            }

    var msg_addition = "";
    var decimal = "";
    inputStr = form.elements[y].value.toString();

    if (inputStr == "")
        {
        }
    else
        {
            for (var c = 0; c < inputStr.length; c++)
                {
                    var oneChar = inputStr.charAt(c);
                    if (c == 0 && oneChar == "-" || oneChar == "."  && decimal == "")
                            {
                                if (oneChar == ".");
                                    {
                                        decimal = "yes";
                                    }
                                continue;

                            }
                                if (oneChar < "0" || oneChar > "9")
                                    {
                                        msg_addition = form.elements[i].value;
                                    }
                }
        }
        return(msg_addition);
}



function e_check(form,x,fieldname,i)
{
            for (var y = 0; y <= x; y++){   if (form.elements[y].name == fieldname) break;  }
            var msg_addition = "";
            regexp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,6})+$/;

            if (!regexp.test(form.elements[y].value)){
                msg_addition = form.elements[i].value;
            }

            return(msg_addition);
}

function d_check(form,x,fieldname,i)
{
        for (var y = 0; y <= x; y++)
            {
                if (form.elements[y].name == fieldname) break;
            }

        var msg_addition = "";
        var sDate = form.elements[y].value;
        var int_or_not = isInteger(form.elements[y].value);
        if (int_or_not == "true")
        {
                if ((!(form.elements[y].value.length >= 6)) || (!(form.elements[y].value.length <= 10)))
                {
                        msg_addition = form.elements[i].value;
                }
                else
                {
                     var SlashlPos = form.elements[y].value.indexOf("/",0);
                        if (SlashlPos > 0 && SlashlPos <= 2)
                            {
                                if (SlashlPos == 1)
                                    {
                                        if (form.elements[y].value.charAt(0) < 1 || form.elements[y].value.charAt(0) > 9)
                                            {
                                                msg_addition = form.elements[i].value;
                                            }
                                        else
                                            {
                                                if ((form.elements[y].value.charAt(0) == 1 || form.elements[y].value.charAt(0) == 3 || form.elements[y].value.charAt(0) == 5 || form.elements[y].value.charAt(0) == 7 || form.elements[y].value.charAt(0) == 8) && ((form.elements[y].value.charAt(2) == 0 && form.elements[y].value.charAt(3) == "/") || (form.elements[y].value.charAt(3) == "/" && form.elements[y].value.length >= 7) || (form.elements[y].value.charAt(1) == "/" && form.elements[y].value.charAt(2) == "/")))
                                                    {
                                                        msg_addition = form.elements[i].value;
                                                    }
                                                else if ((form.elements[y].value.charAt(0) == 1 || form.elements[y].value.charAt(0) == 3 || form.elements[y].value.charAt(0) == 5 || form.elements[y].value.charAt(0) == 7 || form.elements[y].value.charAt(0) == 8) && ((form.elements[y].value.charAt(2) >= 3 && form.elements[y].value.charAt(3) > 1) || (form.elements[y].value.charAt(2) == 0 && form.elements[y].value.charAt(3) == 0) || (form.elements[y].value.charAt(1) == "/" && (form.elements[y].value.charAt(3) != "/" && form.elements[y].value.charAt(4) != "/" && form.elements[y].value.charAt(5) != "/" && form.elements[y].value.charAt(6) != "/"))))
                                                    {
                                                        msg_addition = form.elements[i].value + "hi";
                                                    }
                                                else if ((form.elements[y].value.charAt(0) == 1 || form.elements[y].value.charAt(0) == 3 || form.elements[y].value.charAt(0) == 5 || form.elements[y].value.charAt(0) == 7 || form.elements[y].value.charAt(0) == 8) && (((form.elements[y].value.charAt(2) > 3 && form.elements[y].value.charAt(3) != "/") || (((form.elements[y].value.charAt(1) == "/" && form.elements[y].value.charAt(4) == "/")) && ((form.elements[y].value.length == 6 || form.elements[y].value.length == 8)))) || form.elements[y].value.charAt(5) == "/"))
                                                    {
                                                        msg_addition = form.elements[i].value;
                                                    }
                                                else
                                                    {
                                                        if ((form.elements[y].value.charAt(0) == 2 && ((form.elements[y].value.charAt(2) == 0 && form.elements[y].value.charAt(3) == "/") || (form.elements[y].value.charAt(3) == "/" && form.elements[y].value.length >= 7) || (form.elements[y].value.charAt(1) == "/" && form.elements[y].value.charAt(2) == "/") || (form.elements[y].value.charAt(2) == 0 && form.elements[y].value.charAt(3) == 0) || (form.elements[y].value.charAt(1) == "/" && (form.elements[y].value.charAt(3) != "/" && form.elements[y].value.charAt(4) != "/" && form.elements[y].value.charAt(5) != "/" && form.elements[y].value.charAt(6) != "/")))))
                                                            {
                                                                msg_addition = form.elements[i].value;
                                                            }
                                                        else if (form.elements[y].value.charAt(0) == 2 && ((form.elements[y].value.charAt(2) > 2 && form.elements[y].value.charAt(3) != "/") || (((form.elements[y].value.charAt(1) == "/" && form.elements[y].value.charAt(4) == "/") && ((form.elements[y].value.length == 6 || form.elements[y].value.length == 8)))) || form.elements[y].value.charAt(5) == "/"))
                                                            {
                                                                msg_addition = form.elements[i].value;
                                                            }
                                                        else
                                                            {
                                                                if ((form.elements[y].value.charAt(0) == 4 || form.elements[y].value.charAt(0) == 6 || form.elements[y].value.charAt(0) == 9) && ((form.elements[y].value.charAt(2) == 0 && form.elements[y].value.charAt(3) == "/") || (form.elements[y].value.charAt(3) == "/" && form.elements[y].value.length >= 7) || (form.elements[y].value.charAt(1) == "/" && form.elements[y].value.charAt(2) == "/")))
                                                                    {
                                                                        msg_addition = form.elements[i].value;
                                                                    }
                                                                else if ((form.elements[y].value.charAt(0) == 4 || form.elements[y].value.charAt(0) == 6 || form.elements[y].value.charAt(0) == 9) && ((form.elements[y].value.charAt(2) >= 3 && form.elements[y].value.charAt(3) > 0) || (form.elements[y].value.charAt(2) == 0 && form.elements[y].value.charAt(3) == 0) || (form.elements[y].value.charAt(1) == "/" && (form.elements[y].value.charAt(3) != "/" && form.elements[y].value.charAt(4) != "/" && form.elements[y].value.charAt(5) != "/" && form.elements[y].value.charAt(6) != "/"))))
                                                                    {
                                                                        msg_addition = form.elements[i].value;
                                                                    }
                                                                else if ((form.elements[y].value.charAt(0) == 4 || form.elements[y].value.charAt(0) == 6 || form.elements[y].value.charAt(0) == 9) && (((form.elements[y].value.charAt(2) > 3 && form.elements[y].value.charAt(3) != "/") || ((form.elements[y].value.charAt(1) == "/" && form.elements[y].value.charAt(4) == "/") && ((form.elements[y].value.length == 6 || form.elements[y].value.length == 8)))) || form.elements[y].value.charAt(5) == "/"))
                                                                    {
                                                                        msg_addition = form.elements[i].value;
                                                                    }
                                                            }
                                                    }
                                            }
                                    }
                                else
                                    {
                                        if (form.elements[y].value.charAt(0) > 1 || (form.elements[y].value.charAt(0) == 1 && form.elements[y].value.charAt(1) > 2) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 0))
                                            {
                                                msg_addition = form.elements[i].value;
                                            }
                                        else
                                            {
                                                if (((form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 1) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 3) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 5) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 7) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 8) || (form.elements[y].value.charAt(0) == 1 && form.elements[y].value.charAt(1) == 0) || (form.elements[y].value.charAt(0) == 1 && form.elements[y].value.charAt(1) == 2)) && ((form.elements[y].value.charAt(3) == 0 && form.elements[y].value.charAt(4) == "/") || (form.elements[y].value.charAt(2) == "/" && form.elements[y].value.charAt(3) == "/") || (form.elements[y].value.charAt(2) == "/" && (form.elements[y].value.charAt(4) != "/" && form.elements[y].value.charAt(5) != "/" && form.elements[y].value.charAt(6) != "/" && form.elements[y].value.charAt(7) != "/"))))
                                                    {
                                                        msg_addition = form.elements[i].value;
                                                    }
                                                else if (((form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 1) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 3) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 5) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 7) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 8) || (form.elements[y].value.charAt(0) == 1 && form.elements[y].value.charAt(1) == 0) || (form.elements[y].value.charAt(0) == 1 && form.elements[y].value.charAt(1) == 2)) && ((form.elements[y].value.charAt(3) >= 3 && form.elements[y].value.charAt(4) > 1) || (form.elements[y].value.charAt(3) == 0 && form.elements[y].value.charAt(4) == 0) || form.elements[y].value.length < 7))
                                                    {
                                                        msg_addition = form.elements[i].value;
                                                    }
                                                else if (((form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 1) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 3) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 5) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 7) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 8) || (form.elements[y].value.charAt(0) == 1 && form.elements[y].value.charAt(1) == 0) || (form.elements[y].value.charAt(0) == 1 && form.elements[y].value.charAt(1) == 2)) && ((form.elements[y].value.charAt(3) > 3 && form.elements[y].value.charAt(4) != "/")   || ((form.elements[y].value.charAt(2) == "/" && form.elements[y].value.charAt(5) == "/" && form.elements[y].value.length == 7 || form.elements[y].value.charAt(6) == "/") || (form.elements[y].value.charAt(2) == "/" && form.elements[y].value.charAt(4) == "/" && (form.elements[y].value.length == 6 || form.elements[y].value.length == 8)))))
                                                    {
                                                        msg_addition = form.elements[i].value;
                                                    }
                                                else
                                                    {
                                                        if (((form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 2) && ((form.elements[y].value.charAt(3) == 0 && form.elements[y].value.charAt(4) == "/") || (form.elements[y].value.charAt(3) == 0 && form.elements[y].value.charAt(4) == 0)) || form.elements[y].value.length < 7) || (form.elements[y].value.charAt(2) == "/" && (form.elements[y].value.charAt(4) != "/" && form.elements[y].value.charAt(5) != "/" && form.elements[y].value.charAt(6) != "/" && form.elements[y].value.charAt(7) != "/")))
                                                            {
                                                                msg_addition = form.elements[i].value;
                                                            }
                                                        else if ((form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 2) && ((form.elements[y].value.charAt(3) > 2 && form.elements[y].value.charAt(4) != "/") || ((form.elements[y].value.charAt(2) == "/" && form.elements[y].value.charAt(5) == "/" && form.elements[y].value.length == 7 || form.elements[y].value.charAt(6) == "/") || (form.elements[y].value.charAt(2) == "/" && form.elements[y].value.charAt(4) == "/" && (form.elements[y].value.length == 6 || form.elements[y].value.length == 8)))))
                                                            {
                                                                msg_addition = form.elements[i].value;
                                                            }
                                                        else
                                                            {
                                                                if (((form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 4) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 6) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 9) || (form.elements[y].value.charAt(0) == 1 && form.elements[y].value.charAt(1) == 1)) && ((form.elements[y].value.charAt(3) == 0 && form.elements[y].value.charAt(4) == "/") || (form.elements[y].value.charAt(2) == "/" && form.elements[y].value.charAt(3) == "/") || (form.elements[y].value.charAt(2) == "/" && (form.elements[y].value.charAt(4) != "/" && form.elements[y].value.charAt(5) != "/" && form.elements[y].value.charAt(6) != "/" && form.elements[y].value.charAt(7) != "/"))))
                                                                    {
                                                                        msg_addition = form.elements[i].value;
                                                                    }
                                                                else if (((form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 4) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 6) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 9) || (form.elements[y].value.charAt(0) == 1 && form.elements[y].value.charAt(1) == 1)) && ((form.elements[y].value.charAt(3) >= 3 && form.elements[y].value.charAt(4) > 0) || (form.elements[y].value.charAt(3) == 0 && form.elements[y].value.charAt(4) == 0) || form.elements[y].value.length < 7))
                                                                    {
                                                                        msg_addition = form.elements[i].value;
                                                                    }
                                                                else if (((form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 4) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 6) || (form.elements[y].value.charAt(0) == 0 && form.elements[y].value.charAt(1) == 9) || (form.elements[y].value.charAt(0) == 1 && form.elements[y].value.charAt(1) == 1)) && ((form.elements[y].value.charAt(3) > 3 && form.elements[y].value.charAt(4) != "/") || ((form.elements[y].value.charAt(2) == "/" && form.elements[y].value.charAt(5) == "/" && form.elements[y].value.length == 7 || form.elements[y].value.charAt(6) == "/") || (form.elements[y].value.charAt(2) == "/" && form.elements[y].value.charAt(4) == "/" && (form.elements[y].value.length == 6 || form.elements[y].value.length == 8)))))
                                                                    {
                                                                        msg_addition = form.elements[i].value;
                                                                    }
                                                            }
                                                    }
                                            }
                                    }
                            }
            else
                            {
                                msg_addition = form.elements[i].value;
                            }
                    }
            }
        else
            {
                msg_addition = form.elements[i].value;
            }
        return(msg_addition);
}

function isInteger(sDate)
{
    var new_msg = "true";
    inputStr = sDate.toString();
    for (var i = 0; i < inputStr.length; i++)
        {
        var oneChar = inputStr.charAt(i);
        if ((oneChar < "0" || oneChar > "9") && oneChar != "/")
                {
                    new_msg = "false";
                }
        }
    return (new_msg);
}

function doall(script_name, copyright, email)
{
    var code = 0;
    var test = script_name + copyright + email;
    for (var a = 0; a < test.length; a++)
        {
        var each_char = test.charAt(a);
        var x = asc(each_char);
        code += x;
        }
    return (code);
}

function asc(each_char)
{
    var n = 0;
        var char_str = charSetStr();
        for (i = 0; i < char_str.length; i++)
            {
                if (each_char == char_str.substring(i, i+1))
                    {
                        break;
                    }
            }
        return i + 32;
}

function charSetStr()
{
        var str;
    str = ' !"#$%&' + "'" + '()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~';
        return str;
}


function CheckWithAllowedCardTypes(cctypes,form,x,fieldname,i)
{
        var msg_addition = "";
        error=0;
        for (var y = 0; y <= x; y++){if (form.elements[y].name == fieldname) break;}
        var msg_addition = "";
        CardNumber = form.elements[y].value;
        typeVisa   = checkCreditCard(CardNumber, 'Visa');
        typeMc     = checkCreditCard(CardNumber, 'MasterCard');
        typeAmex   = checkCreditCard(CardNumber, 'AmEx');
        typeDisc   = checkCreditCard(CardNumber, 'Discover');
        
        typeLaser  = checkCreditCard(CardNumber, 'LaserCard');
        typeDiners = checkCreditCard(CardNumber, 'DinersClub');
        typeSwitch = checkCreditCard(CardNumber, 'Switch');
        
        //c_1000000_ = visa
        //c_0100000_ = mastercard
        //c_0010000_ = americanexpress
        //c_0001000_ = discover
        
        //c_0000100_ = lasercard
        //c_0000010_ = dinersclub
        //c_0000001_ = switch
        
        if (typeVisa){
            if (cctypes.substr(0,1)=="0") return lang("Visa is not accepted at this time");
        }else if (typeMc){
            if (cctypes.substr(1,1)=="0") return lang("MasterCard is not accepted at this time");
        }else if (typeAmex){
            if (cctypes.substr(2,1)=="0") return lang("American Express is not accepted at this time");
        }else if (typeDisc){
            if (cctypes.substr(3,1)=="0") return lang("Discover is not accepted at this time");
        }else if (typeLaser){
            if (cctypes.substr(4,1)=="0") return lang("LaserCard is not accepted at this time");
        }else if (typeDiners){
            if (cctypes.substr(5,1)=="0") return lang("Diners Club is not accepted at this time");
        }else if (typeSwitch){
            if (cctypes.substr(6,1)=="0") return lang("Switch is not accepted at this time");
        }
}


/*================================================================================================*/

/*

This routine checks the credit card number. The following checks are made:

1. A number has been provided
2. The number is a right length for the card
3. The number has an appropriate prefix for the card
4. The number has a valid modulus 10 number check digit if required

If the validation fails an error is reported.

The structure of credit card formats was gleaned from a variety of sources on the web, although the 
best is probably on Wikepedia ("Credit card number"):

  http://en.wikipedia.org/wiki/Credit_card_number

Parameters:
            cardnumber           number on the card
            cardname             name of card as defined in the card list below

Author:     John Gardner
Date:       1st November 2003
Updated:    26th Feb. 2005      Additional cards added by request
Updated:    27th Nov. 2006      Additional cards added from Wikipedia
Updated:    18th Jan. 2008      Additional cards added from Wikipedia
Updated:    26th Nov. 2008      Maestro cards extended
Updated:    19th Jun. 2009      Laser cards extended from Wikipedia
Updated:    11th Sep. 2010      Typos removed from Diners and Solo definitions (thanks to Noe Leon)

*/

/*
   If a credit card number is invalid, an error reason is loaded into the global ccErrorNo variable. 
   This can be be used to index into the global error  string array to report the reason to the user 
   if required:
   
   e.g. if (!checkCreditCard (number, name) alert (ccErrors(ccErrorNo);
*/

var ccErrorNo = 0;
var ccErrors = new Array ()

ccErrors [0] = "Unknown card type";
ccErrors [1] = "No card number provided";
ccErrors [2] = "Credit card number is in invalid format";
ccErrors [3] = "Credit card number is invalid";
ccErrors [4] = "Credit card number has an inappropriate number of digits";

function checkCreditCard (cardnumber, cardname) {
     
  // Array to hold the permitted card characteristics
  var cards = new Array();

  // Define the cards we support. You may add addtional card types as follows.
  
  //  Name:         As in the selection box of the form - must be same as user's
  //  Length:       List of possible valid lengths of the card number for the card
  //  prefixes:     List of possible prefixes for the card
  //  checkdigit:   Boolean to say whether there is a check digit
  
  cards [0] = {name: "Visa", 
               length: "13,16", 
               prefixes: "4",
               checkdigit: true};
  cards [1] = {name: "MasterCard", 
               length: "16", 
               prefixes: "51,52,53,54,55",
               checkdigit: true};
  cards [2] = {name: "DinersClub", 
               length: "14,16", 
               prefixes: "305,36,38,54,55",
               checkdigit: true};
  cards [3] = {name: "CarteBlanche", 
               length: "14", 
               prefixes: "300,301,302,303,304,305",
               checkdigit: true};
  cards [4] = {name: "AmEx", 
               length: "15", 
               prefixes: "34,37",
               checkdigit: true};
  cards [5] = {name: "Discover", 
               length: "16", 
               prefixes: "6011,622,64,65",
               checkdigit: true};
  cards [6] = {name: "JCB", 
               length: "16", 
               prefixes: "35",
               checkdigit: true};
  cards [7] = {name: "enRoute", 
               length: "15", 
               prefixes: "2014,2149",
               checkdigit: true};
  cards [8] = {name: "Solo", 
               length: "16,18,19", 
               prefixes: "6334,6767",
               checkdigit: true};
  cards [9] = {name: "Switch", 
               length: "16,18,19", 
               prefixes: "4903,4905,4911,4936,564182,633110,6333,6759",
               checkdigit: true};
  cards [10] = {name: "Maestro", 
               length: "12,13,14,15,16,18,19", 
               prefixes: "5018,5020,5038,6304,6759,6761",
               checkdigit: true};
  cards [11] = {name: "VisaElectron", 
               length: "16", 
               prefixes: "417500,4917,4913,4508,4844",
               checkdigit: true};
  cards [12] = {name: "LaserCard", 
               length: "16,17,18,19", 
               prefixes: "6304,6706,6771,6709",
               checkdigit: true};
               
  // Establish card type
  var cardType = -1;
  for (var i=0; i<cards.length; i++) {

    // See if it is this card (ignoring the case of the string)
    if (cardname.toLowerCase () == cards[i].name.toLowerCase()) {
      cardType = i;
      break;
    }
  }
  
  // If card type not found, report an error
  if (cardType == -1) {
     ccErrorNo = 0;
     return false; 
  }
   
  // Ensure that the user has provided a credit card number
  if (cardnumber.length == 0)  {
     ccErrorNo = 1;
     return false; 
  }
    
  // Now remove any spaces from the credit card number
  cardnumber = cardnumber.replace (/\s/g, "");
  
  // Check that the number is numeric
  var cardNo = cardnumber
  var cardexp = /^[0-9]{13,19}$/;
  if (!cardexp.exec(cardNo))  {
     ccErrorNo = 2;
     return false; 
  }
       
  // Now check the modulus 10 check digit - if required
  if (cards[cardType].checkdigit) {
    var checksum = 0;                                  // running checksum total
    var mychar = "";                                   // next char to process
    var j = 1;                                         // takes value of 1 or 2
  
    // Process each digit one by one starting at the right
    var calc;
    for (i = cardNo.length - 1; i >= 0; i--) {
    
      // Extract the next digit and multiply by 1 or 2 on alternative digits.
      calc = Number(cardNo.charAt(i)) * j;
    
      // If the result is in two digits add 1 to the checksum total
      if (calc > 9) {
        checksum = checksum + 1;
        calc = calc - 10;
      }
    
      // Add the units element to the checksum total
      checksum = checksum + calc;
    
      // Switch the value of j
      if (j ==1) {j = 2} else {j = 1};
    } 
  
    // All done - if checksum is divisible by 10, it is a valid modulus 10.
    // If not, report an error.
    if (checksum % 10 != 0)  {
     ccErrorNo = 3;
     return false; 
    }
  }  

  // The following are the card-specific checks we undertake.
  var LengthValid = false;
  var PrefixValid = false; 
  var undefined; 

  // We use these for holding the valid lengths and prefixes of a card type
  var prefix = new Array ();
  var lengths = new Array ();
    
  // Load an array with the valid prefixes for this card
  prefix = cards[cardType].prefixes.split(",");
      
  // Now see if any of them match what we have in the card number
  for (i=0; i<prefix.length; i++) {
    var exp = new RegExp ("^" + prefix[i]);
    if (exp.test (cardNo)) PrefixValid = true;
  }
      
  // If it isn't a valid prefix there's no point at looking at the length
  if (!PrefixValid) {
     ccErrorNo = 3;
     return false; 
  }
    
  // See if the length is valid for this card
  lengths = cards[cardType].length.split(",");
  for (j=0; j<lengths.length; j++) {
    if (cardNo.length == lengths[j]) LengthValid = true;
  }
  
  // See if all is OK by seeing if the length was valid. We only check the length if all else was 
  // hunky dory.
  if (!LengthValid) {
     ccErrorNo = 4;
     return false; 
  };   
  
  // The credit card is in the required format.
  return true;
}

/*================================================================================================*/


function move(moveaction,movefrom,moveto)
{
    var moveto = $(moveto);
    if(moveaction == 'remove') {
        for(x = 0;x<($(movefrom).length);x++) {
            if($(movefrom).options[x].selected) {
                with(moveto) {
                    options[options.length] = new Option($(movefrom).options[x].text,$(movefrom).options[x].value);
                }
                $(movefrom).options[x] = null;
                x = -1;
            }
        }
    }
    if(moveaction == 'add') {
        for(x = 0;x<(moveto.length);x++) {
            if(moveto.options[x].selected) {
                with($(movefrom)) {
                    options[options.length] = new Option(moveto.options[x].text,moveto.options[x].value);
                }
                moveto.options[x] = null;
                x = -1;
            }
        }
    }
    return true;
}

// *************************************
// RICH TEXT EDITOR FUNCTIONS
// *************************************
function showRichTextEditor(objName, width, height, buttonArr, textareaId, mode)
{

    if (typeof mode == "undefined") {
        mode = "XHTMLBody";
    }

    eval(objName + " = new InnovaEditor('" + objName + "')");
    var tempEditorObj = eval(objName);
    tempEditorObj.useTab = false;
    tempEditorObj.useTagSelector = false;
    tempEditorObj.width = width;
    tempEditorObj.height = height;
    //tempEditorObj.CustomTags.add(new Param("First Name","{%first_name%}"));

    /***************************************************
        RECONFIGURE TOOLBAR BUTTONS
    ***************************************************/
    tempEditorObj.features = buttonArr; // => Custom Button Placement

    /***************************************************
        OTHER SETTINGS
    ***************************************************/
    tempEditorObj.mode = mode; //Editing mode. Possible values: "HTMLBody" (default), "XHTMLBody", "HTML", "XHTML"

    tempEditorObj.REPLACE(textareaId);
}

function selectPlainTextTab(hrefObj, areaId)
{
    var ulChildren = hrefObj.parentNode.parentNode.getElementsByTagName("li");
    ulChildren[0].className = '';
    ulChildren[1].className = 'selected';
    $('richTextWrapper_' + areaId).style.display = 'none';
    $(areaId + '[1]').style.display = 'block';
}

function selectHTMLTab(hrefObj, areaId)
{
    var ulChildren = hrefObj.parentNode.parentNode.getElementsByTagName("li");
    ulChildren[0].className = 'selected';
    ulChildren[1].className = '';
    $(areaId + '[1]').style.display = 'none';
    $('richTextWrapper_' + areaId).style.display = 'block';
}


// *************************************
// JAVASCRIPT POPUPS FUNCTIONS
// Based on Chris Campbell's lightbox script  -- still used in support.. need to replace to extjs window in the support view
// found at http://particletree.com
// *************************************
var lightbox;
function jsPopup(content, isURL)
{
	bod                 = document.getElementsByTagName('body')[0];
	overlay             = document.createElement('div');
	overlay.id          = 'overlay';
	lb                  = document.createElement('div');
	lb.id               = 'lightbox';
	lb.className        = 'loading';
	lb.innerHTML        = '<div id="lbLoadMessage">' +
						  '<p>Loading</p>' +
						  '</div>';
	bod.appendChild(overlay);
	bod.appendChild(lb);

    lightbox = Class.create();

    lightbox.prototype = {

        yPos : 0,
        xPos : 0,

        initialize: function(content, isURL) {
            this.content = content;
            if (typeof isURL == 'undefined') {
                isURL = true;
            }
            this.isURL = isURL;
            this.activate();
        },

        // Turn everything on - mainly the IE fixes
        activate: function(){
            if (isIE){
                this.getScroll();
                this.prepareIE('100%', 'hidden');
                this.setScroll(0,0);
                if (!isIE7) {
                    this.hideSelects('hidden');
                }
            }
            this.displayLightbox("block");
        },

        // Ie requires height to 100% and overflow hidden or else you can scroll down past the lightbox
        prepareIE: function(height, overflow){
            bod = document.getElementsByTagName('body')[0];
            bod.style.height = height;
            bod.style.overflow = overflow;

            htm = document.getElementsByTagName('html')[0];
            htm.style.height = height;
            htm.style.overflow = overflow;
        },

        // In IE, select elements hover on top of the lightbox
        hideSelects: function(visibility){
            selects = document.getElementsByTagName('select');
            for(i = 0; i < selects.length; i++) {
                selects[i].style.visibility = visibility;
            }
        },

        // Taken from lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
        getScroll: function(){
            if (self.pageYOffset) {
                this.yPos = self.pageYOffset;
            } else if (document.documentElement && document.documentElement.scrollTop){
                this.yPos = document.documentElement.scrollTop;
            } else if (document.body) {
                this.yPos = document.body.scrollTop;
            }
        },

        setScroll: function(x, y){
            window.scrollTo(x, y);
        },

        displayLightbox: function(display){
            $('overlay').style.display = display;
            $('lightbox').style.display = display;
            if(display != 'none') this.loadInfo();
        },

        loadInfo: function() {
            if (this.isURL) {
                var myAjax = new Ajax.Request(  this.content,
                                                {
                                                    method: 'get', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)
                                                }
                            );
            } else {
                this.showPopup(this.content);
            }

        },

        // Display Ajax response
        processInfo: function(response){
            this.showPopup(response.responseText);
        },

        showPopup: function(strContent){
            info = "<div id='lbContent'>" + strContent + "</div>";
            new Insertion.Before($('lbLoadMessage'), info)
            $('lightbox').className = "done";
            this.actions();
        },

        // Search through new links within the lightbox, and attach click event
        actions: function(){
            lbActions = document.getElementsByClassName('lbAction');

            for(i = 0; i < lbActions.length; i++) {
                Event.observe(lbActions[i], 'click', this[lbActions[i].rel].bindAsEventListener(this), false);
                lbActions[i].onclick = function(){return false;};
            }

        },

        save: function(e){
           link = Event.element(e).parentNode;
           Element.remove($('lbContent'));

           var myAjax = new Ajax.Request(   link.href,
                                            {
                                                    method      : 'post',
                                                    parameters  : "",
                                                    onComplete  : this.processInfo.bindAsEventListener(this)
                                            }
                        );

        },

        deactivate: function(){
            Element.remove($('lbContent'));

            if (isIE){
                this.setScroll(0,this.yPos);
                this.prepareIE("auto", "auto");
                if (!isIE7) {
                    this.hideSelects("visible");
                }
            }

            this.displayLightbox("none");
        }
    }

    valid = new lightbox(content, isURL);
}

// *************************************
// CUSTOMER NOTES FUNCTIONS
// *************************************
function loadClientNotes(customerGroup, includeArchived)
{
    if (!customerGroup) {
        customerGroup = 0;
    }

    new Ajax.Updater(   'clientNotes',
                        'index.php?fuse=clients&view=GetClientNotes&customerGroup='+customerGroup+'&includeArchived=' + (includeArchived? 1 : 0),
                        {
                            onLoading   : function(request) {resetStatus(lang('Loading Notes'))},
                            onComplete  : function(request) {unsetStatus(false)}
                        }
    );
}

function deleteNote(noteId,calledfromfuse,selectedId)
{
    if (!confirm(lang('Are you sure you wish to delete this note?\nBe aware that if the note is linked to a ticket type, all tickets of that type won\'t show this note anymore.'))) {
        return;
    }

    if(selectedId==null) selectedId = 0;

    new Ajax.Request(   'index.php?fuse=clients&action=deleteClientNote',
                        {
                            method      : 'post',
                            parameters  : 'noteId=' + noteId + '&calledfromfuse=' + calledfromfuse + '&selectedId=' + selectedId,
                            onLoading   : function(request) {resetStatus(lang('Deleting Note'))},
                            onComplete  : completedDeleteNote
                        }
    );
}

function completedDeleteNote(responseObj)
{
    unsetStatus(false)

    var responseArr = responseObj.responseText.split('|');

    if (typeof responseArr[1] == 'undefined' || responseArr[0] != 'OK') {
        alert(responseObj.responseText);
    }

	//need to check where I deleted from
    if(responseArr[2] == "client"){
	    //if from client profile
    	loadClientNotes(responseArr[1]);
    }else{
    	//if from support module
    	loadStaffNotesInSupport(responseArr[3]);
    }
}

//General function to shoot out the async function performed on invoices
function PerformAsyncAction(bolShowStatus,items,fuse,action,successfunc,extraargs,ignoreErrors)
{
    if (bolShowStatus){
        setStatus('Working ...');
    }

    var args = 'items='+items;
    if(extraargs!="") args = args+"&"+extraargs;

    var opt = {
         method: 'post',
         postBody: args,
         onSuccess: eval(successfunc)
    }
    new Ajax.Request('index.php?fuse='+fuse+'&action='+action, opt);
}

//only used by switching tab function cSelectTab
function PerformAsyncUpdater(bolShowStatus,items,fuse,view,extraargs,mydiv)
{
   mydiv = mydiv || 'activesnapshot';

   if (bolShowStatus){
        setStatus(lang('Working ...'));
   }

   var args = 'items='+items+'&mydiv='+mydiv;
   if(extraargs!="") {
       args = args+"&"+extraargs;
   }

   var opt = {
         method: 'post',
         postBody: args,
         onComplete:function(){
             if($('message')) { $('message').focus(); }
             if($('initialsnapshot')) { $('initialsnapshot').innerHTML="" }
             unsetStatus('', 1);
         },
         evalScripts:true,
         asynchronous:true
    }
    new Ajax.Updater(mydiv, 'index.php?fuse='+fuse+'&view='+view, opt);
}

function cSelectTab(fuse,view,tabid,grouptabname,div,args,selectclassname)
{
	if(args==null){
		args="snapshot="+tabid
	}else{
		args+="&snapshot="+tabid
	}

    cToggleTabs(tabid,grouptabname,selectclassname);
    PerformAsyncUpdater(true,"",fuse,view,args,div);
    return false;
}

function cToggleTabs(tabid,grouptabname,selectclassname)
{
    //unselect tab
    items = getElementsByName_iefix("li",grouptabname);
    for(x=0;x<items.length;x++){
        items[x].className = "";
    }
    if(selectclassname != undefined){
        $(tabid+"_tab").className = selectclassname;
    }else{
        $(tabid+"_tab").className = "selected";
    }
}



// *************************************
// KNOWLEDGE BASE FUNCTIONS
// USED IN DIFFERENT PLACES
// *************************************
var lastsent="";
var request=0;

function setKBRequest(t)
{
    if (document.getElementById('ajaxLoader')) {
        $('ajaxLoader').style.display = 'none';
    } else {
        unsetStatus('', 1);
    }

    var newcontent = "";

	if(t.responseText!=""){
    	var responseArr = t.responseText.split('|');
    	if (typeof responseArr[1] == 'undefined' || responseArr[0] != 'OK') {
        	alert(t.responseText.stripTags());
        	return;
    	}
        if (responseArr[1] == "") {
            return;
        }

        newcontent = responseArr[1];
	}

    $('kb_wrap').innerHTML = newcontent;
    if (document.getElementById('kb_wrap_wrap')) {
        $('kb_wrap_wrap').style.display = "block";
    }
}

function sendKBRequest(str, ispublic, path)
{
	if(str=="")return;
	lastsent=str;
	request++;

    var timeStamp = new Date();

    if (document.getElementById('ajaxLoader')) {
        $('ajaxLoader').style.display = 'block';
    } else {
        resetStatus(lang('Loading'));
    }

    if (document.getElementById('latestArticles')) {
        $('latestArticles').style.display = 'none';
    }

    new Ajax.Request(path + 'index.php?request='+request+'&fuse=knowledgebase&subject='+encodeURIComponent(str)+'&view=KB_AutoSuggestion'+(ispublic? '&public=1' : '')+'&path='+encodeURIComponent(path),
        {
            onSuccess   : setKBRequest
        });
}

function loadKBArticles(e, inputField, ispublic, path)
{
	var str = ltrim(inputField.value);

    if(str == lastsent || str == "") {
        return;
    }

    var lastChar = str.substr(str.length -1);
    if (lastChar != " ") {
        setTimeout("checkIfTypingStopped('"+inputField.id+"','"+str+"',"+ ispublic+",'"+path+"')", 500);
    } else {
        sendKBRequest(str, ispublic, path);
    }
}

function checkIfTypingStopped(fieldName, str, ispublic, path)
{
    if ($(fieldName).value != str) {
        return;
    }

    sendKBRequest(str, ispublic, path);
}

function showRichTextEditorForSettings(areaId, isDual)
{
    var fieldId = isDual? areaId + '[0]' : areaId;
    showRichTextEditor("oEdit" + areaId, 650, '250px',
                        [
                            'Undo','Redo','|','Hyperlink','|','JustifyLeft','JustifyCenter','JustifyRight','JustifyFull','|','Numbering','Bullets','|','LTR','RTL','|','XHTMLFullSource','StyleAndFormatting','TextFormatting','ListFormatting','BoxFormatting','ParagraphFormatting','CssText','|','FontName','FontSize','|','Bold','Italic','Underline','|','ForeColor','BackColor'
                        ],
                        "value_" + fieldId);
}
