//------------------------------------------------------------------------------------
// Show OR hide funtion depends on if element is shown or hidden
//------------------------------------------------------------------------------------
var imgout=new Image(9,9);
var imgin=new Image(9,9);
imgout.src="images/up.gif";
imgin.src="images/right.gif";
function showOrHide(id, img_up, img_down) { 

	imgout.src=img_up;
	imgin.src=img_down;
	
	if (document.getElementById) { // DOM3 = IE5, NS6
		if (document.getElementById(id).style.display == "none"){
			document.getElementById(id).style.display = 'block';
			filter(id+'img','imgin');			
		} else {
			filter(id+'img','imgout');
			document.getElementById(id).style.display = 'none';			
		}	
	} else { 
		if (document.layers) {	
			if (document.id.display == "none"){
				document.id.display = 'block';
				filter(id,'imgin');
			} else {
				filter(id,'imgout');	
				document.id.display = 'none';
			}
		} else {
			if (document.all.id.style.visibility == "none"){
				document.all.id.style.display = 'block';
			} else {
				filter(id,'imgout');
				document.all.id.style.display = 'none';
			}
		}
	}
}

//------------------------------------------------------------------------------------
// This switches expand collapse icons
//------------------------------------------------------------------------------------
function filter(imagename,objectsrc){
	if (document.images){
		document.images[imagename].src=eval(objectsrc+".src");
	}
}

//------------------------------------------------------------------------------------
// Replaces text with by in string
//------------------------------------------------------------------------------------
function replace(fullString,text,by) {
    var strLength = fullString.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return fullString;

    var i = fullString.indexOf(text);
    if ((!i) && (text != fullString.substring(0,txtLength))) return fullString;
    if (i == -1) return fullString;

    var newstr = fullString.substring(0,i) + by;

    if (i+txtLength < strLength)
        newstr += replace(fullString.substring(i+txtLength,strLength),text,by);

    return newstr;
}

//------------------------------------------------------------------------------------
// Validates email address
//------------------------------------------------------------------------------------
function checkEmail(myForm) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.emailAddr.value)){
		return (true)
	}
	alert("Invalid E-mail Address! Please re-enter.")
	return (false)
}

//------------------------------------------------------------------------------------
// Places focus on specific form element
//------------------------------------------------------------------------------------
function putFocus(formInst, elementInst) {
	if (document.forms.length > 0) {
		document.forms[formInst].elements[elementInst].focus();
	}
}

//------------------------------------------------------------------------------------
// Places forcus on first text, textarea or password input on the current form
//------------------------------------------------------------------------------------
function firstFocus()
{
   if (document.forms.length > 0)
   {
      var TForm = document.forms[0];
      for (i=0;i<TForm.length;i++)
      {
         if ((TForm.elements[i].type=="text")||
           (TForm.elements[i].type=="textarea")||
           (TForm.elements[i].type=="password"))
         {
            document.forms[0].elements[i].focus();
            break;
         }
      }
   }
}

//------------------------------------------------------------------------------------
// Locks all inputs and submits the form
//------------------------------------------------------------------------------------
function lockFormAndSubmit(form, fieldName, source) 
{
	lockFormAndSubmit(form, fieldName, source, 'Please wait...');
}

//------------------------------------------------------------------------------------
// Locks all inputs and submits the form with custom msg on locked inputs
//------------------------------------------------------------------------------------
function lockFormAndSubmit(form, fieldName, source, msg) 
{
		if (msg == null) msg = 'Please wait...';
		
		source.value = msg;
    	for (i = 0; i < form.length; i++) 
    	{
     		var tempobj = form.elements[i];
     		if (tempobj.type.toLowerCase() == 'submit' || 
				tempobj.type.toLowerCase() == 'button' || 
				tempobj.type.toLowerCase() == 'reset')
			{
       			tempobj.disabled = true;
       		}
		}

  if (document.getElementById) {
    var input = document.createElement('input');
    if (document.all) 
    { // what follows should work with NN6 but doesn't in M14
        input.type = 'hidden';
        input.name = fieldName;
        input.value = 'true';
    }
    else if (document.getElementById) { // so here is the
                                        // NN6 workaround
        input.setAttribute('type', 'hidden');
        input.setAttribute('name', fieldName);
        input.setAttribute('value', 'true');
    }
    form.appendChild(input);
  }
  
  form.submit();
}

//------------------------------------------------------------------------------------
// Validates credit card number
//------------------------------------------------------------------------------------
function isValidCreditCardNumber(formField, ccType, fieldLabel)
{
	var result = true;
 	var ccNum = formField.value;
 
  	if (result && (formField.value.length>0))
 	{ 
 		if (!allDigits(ccNum))
 		{
 			alert('Please enter only numbers (no dashes or spaces) for the "' + fieldLabel +'" field.');
			formField.focus();
			result = false;
		}

		if (result)
 		{ 
 			
 			if (!LuhnCheck(ccNum) || !validateCCNum(ccType,ccNum))
 			{
 				alert('Please enter a valid ' + ccType + ' card number');
				formField.focus();
				result = false;
			}	
		} 

	} 
	
	return result;
}

//------------------------------------------------------------------------------------
// Verifies if the string is all numeric
//------------------------------------------------------------------------------------
function allDigits(str)
{
	return inValidCharSet(str,"0123456789");
}

//------------------------------------------------------------------------------------
// Verifies that string only contains characters from specific set
//------------------------------------------------------------------------------------
function inValidCharSet(str,charset)
{
	var result = true;
	
	for (var i=0;i<str.length;i++)
		if (charset.indexOf(str.substr(i,1))<0)
		{
			result = false;
			break;
		}
	
	return result;
}

//------------------------------------------------------------------------------------
// Performs Luhn check on the string
//------------------------------------------------------------------------------------
function LuhnCheck(str) 
{
  var result = true;

  var sum = 0; 
  var mul = 1; 
  var strLen = str.length;
  
  for (i = 0; i < strLen; i++) 
  {
    var digit = str.substring(strLen-i-1,strLen-i);
    var tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }
  
  if ((sum % 10) != 0)
    result = false;
    
  return result;
}

//------------------------------------------------------------------------------------
// Validates credit card number
//------------------------------------------------------------------------------------
function validateCCNum(cardType,cardNum)
{
	var result = false;
	cardType = cardType.toUpperCase();
	
	var cardLen = cardNum.length;
	var firstdig = cardNum.substring(0,1);
	var seconddig = cardNum.substring(1,2);
	var first4digs = cardNum.substring(0,4);

	switch (cardType)
	{
		case "VISA":
			result = ((cardLen == 16) || (cardLen == 13)) && (firstdig == "4");
			break;
		case "AMERICAN EXPRESS":
			var validNums = "47";
			result = (cardLen == 15) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;
		case "MASTER CARD":
			var validNums = "12345";
			result = (cardLen == 16) && (firstdig == "5") && (validNums.indexOf(seconddig)>=0);
			break;
		case "DISCOVER":
			result = (cardLen == 16) && (first4digs == "6011");
			break;
		case "DINERS":
			var validNums = "068";
			result = (cardLen == 14) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;
	}
	return result;
}

//------------------------------------------------------------------------------------
// Checks specific radio button based on its id
//------------------------------------------------------------------------------------
function selectRadioButton(id)
{ 
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).checked = true;
	} else { 
		if (document.layers) {	
			document.id.checked = true;
		} else {
			document.all.id.checked = true;
		}
	}
}

//------------------------------------------------------------------------------------
// Escapes out forward slashes
//------------------------------------------------------------------------------------
function simpleEscape(text) {
    return text.replace(/\//g, "%2F");
}

//------------------------------------------------------------------------------------
// simple encoding of a given URL.
// Any "/" character in the parameters of the given URL will be replaced by "%2F".
//------------------------------------------------------------------------------------
function encodeUrl(url) {
    encodedurl = url
    asteriskIdx = url.indexOf("?");
    if(asteriskIdx > -1 && asteriskIdx < (url.length-1)) {
        encodedurl = url.substring(0, asteriskIdx) + "?" + simpleEscape(url.substring(asteriskIdx + 1));
    }
    return encodedurl;
}

//------------------------------------------------------------------------------------
// Opens a new window with parameter URL, Windowname, width and height
//------------------------------------------------------------------------------------
var smallwindow;
function opensmallwin(url, name, w, h)
{
    encodedurl = encodeUrl(url);
    smallwindow = window.open(encodedurl, name, 'toolbar=no,location=no,directories=no,status=no,menubar=0,scrollbars=yes,resizable=yes,top=150,left=660,width='+w+',height='+h);
    if(smallwindow != null)
       {
          if (smallwindow.opener == null)
          {
             smallwindow.opener = self;
          }
        }
    //smallwindow.focus();
    return smallwindow;
}

//------------------------------------------------------------------------------------
// Dynamically adds form element
//------------------------------------------------------------------------------------
function addelementtoform(field,fieldType,fieldName,fieldValue)
{
	var input = document.createElement(field);
	input.type = fieldType;
	input.name = fieldName;
	input.value = fieldValue;
	document.resourceForm.appendChild(input);
}

function openExtWindow(url) 
{
	alert('You are about to open a link that is outside of our website in a new window. Once done, to return to our website, close the new window.');
	var load = window.open(url,'','scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
	load.focus();
}
