function updateSelect(element, transport, noChangeEvent) {
	var element = $(element);
	var value = $F(element);
	var select = transport.responseXML.getElementsByTagName("select")[0];
	var optionArray = $A(select.getElementsByTagName("option"));
	element.options.length = 0;
	element.selectedIndex = -1;
	if ( optionArray.length > 0 ) {		
	    optionArray.each( function(option) {
	        var optionText = Try.these(
                function() { return option.childNodes[0].nodeValue },
                function() { return option.nodeValue }
            ) || '';
		var optionValue = option.getAttribute("value") || optionText;

		    element.options[element.options.length] = new Option(optionText,optionValue);
		    if (optionText == value) {
			element.selectedIndex = element.options.length - 1;
		    }
	    });
        }

    if (noChangeEvent) return;
	
	if ( element.onchange ) {
		element.onchange();
	}
}

function setSelectedIndex(element,value) {
	element = $(element);
	for ( var i = 0; i < element.options.length; i++ ) {
		if (element.options[i].value == value || element.options[i].text == value) {
			element.selectedIndex = i;
			break;
		}
	}
}

function validate(element,hash) {
	var messages = $A([]);
	hash.each( function( pair ) {
		var field = $(pair.key);
		var validator = pair.value;
        var error = false;
		if (validator.required) {
            if ($(field).type == 'select-one') { 
               if ($(field).selectedIndex == -1) {
				  messages.push(validator.required);	
                  error = true;
               }
            } else if ( $(field).type == 'checkbox' || $(field).type == 'radio' ) { 
               if (!$(field).checked) {
                  messages.push(validator.required);
                  error = true;
               }
            } else if ( !Field.present(field)) {
				messages.push(validator.required);	
                error = true;
            }
        }
        if ( !error ) {
           if ( validator.callback ) {
              validator.message = validator.callback();
              if (validator.message.length>0) {
                  messages.push(validator.message);
                  error = true;
              }
		   } else if ( validator.re && $F(field).search(validator.re) == -1 ) {
		  	  messages.push(validator.message);
              error = true;
           }
		}
        if (validator.indicator) {
            $(validator.indicator).className = (error)?'required':'';
        }
	});
	element = $(element);
	if (element) {
		var message = messages.map(function(msg) {
				return "<p>"+msg+"</p>";
				}).join("\n");
		element.update(message);
		if (message.length>0) {
			element.show();
			var errorFields = $$('.required');
			if (errorFields && errorFields.length > 0) {
			  $(errorFields[0]).focus();
			}
			logJsError(message);
		} else {
			element.hide();
		}
	}
	return (messages.length == 0);
}

function showError( message, callback ) {
	if (message.length>0) {
		if (message.search(/<p>/) == -1) {
			message = "<p>"+message+"</p>";
		}
		$('errors').update(message);
		$('errors').show();
		var errorFields = $$('.required');
		if (errorFields && errorFields.length > 0) {
		  $(errorFields[0]).focus();
		}

		logJsError(message);
		
		if (callback) {
		  callback();
		}
	} else {
		$('errors').hide();
	}
}

function logJsError(jsErrMsg) {
	var postBack = document.location.href;
	var index = postBack.search(/.aspx/);
	if ( index == -1) {
		postBack = postBack+"/default.aspx/postback/jsError";
	} else {
		// add the current controller to the url
		index += 5;
		postBack = postBack.substr(0,index)+"/postback/jsError";
	}
    	new Ajax.Request(postBack+"?sid="+$F('sid')+"&errMsg="+encodeURIComponent(jsErrMsg),{method: 'get'});
}

Object.extend(String.prototype, {
  evalJSON: function() {
    try {
      return this ? eval('(' + this + ')') : null;
    } catch (e) { return null }
  },
  mask: function(format,reverse) {
	var result = '';
	var source = this;
	if (reverse) {
	    source = source.reverse();
	    format = format.reverse();
	}
	var si = 0;
	for (var fi = 0; fi < format.length; fi++) {
		var fc = format.charAt(fi);
		var re = null;
		switch (fc) {
		case '#':
			re = /\d| /; break;
		case '9':
			re = /\d/; break;
		case 'X':
			re = /\w/; break;
		case 'A':
			re = /[A-Za-z]/; break;
		default:
			result += fc;
			continue;
		}
	
		var source = source.substr(si);
		var si = source.search(re);
		if (si == -1) {
			break;
		} else {
			var sc = source.charAt(si);
			if (fc == '#' && sc == '0') {
				sc = ' ';
			}
			result += sc;
			si++;
			if (si >= source.length) {
				break;
			}
		}
	}
	if (reverse) {
	    return result.reverse();
	}
	return result;
  },
  reverse: function() {
    var r = '';
    var i = this.length-1;
    while (i>-1) {
        r += this.charAt(i--);
    }
    return r;
  },
  trim: function() {
	return this.ltrim().rtrim();
  },
  ltrim: function() {
	return this.replace(/^\s+/,"");
  },
  rtrim: function() {
	return this.replace(/\s+$/,"");
  }

});
function updateCodeValue(fieldId, optionArray) {
		var element = $(fieldId);
		var value = $F(element);
		element.options.length = 0;
		element.selectedIndex = -1;
        
        for (var i = 0; i < optionArray.length; i++) {		
            var option = optionArray[i];
			element.options[i] = new Option(option.value,option.code,(option.value == value));
	    }
}
function getWindowHeight() { 
    var windowheight = 0; 
    if (typeof(window.innerHeight) == 'number') { 
        windowheight = window.innerHeight; 
    } else if (document.documentElement && 
               document.documentElement.clientHeight) { 
        windowheight = document.documentElement.clientHeight; 
    } else if (document.body && document.body.clientHeight) { 
        windowheight = document.body.clientHeight; 
    } else if (document.body && document.body.clientHeight) { 
        windowheight = document.body.clientHeight; 
    } 
    return Math.max(windowheight,document.body.offsetHeight);
    return windowheight;
} 

function luhn (cc) {
   cc = cc.replace(/[^\d]/g,"");
   var sum = 0;
   var i;

   for (i = cc.length - 2; i >= 0; i -= 2) {
      sum += Array (0, 2, 4, 6, 8, 1, 3, 5, 7, 9) [parseInt (cc.charAt (i), 10)];
   }
   for (i = cc.length - 1; i >= 0; i -= 2) {
      sum += parseInt (cc.charAt (i), 10);
   }
   return (sum % 10) == 0;
}

function is_valid_aba(aba) {
  // Run through each digit and calculate the total.

  var n = 0;
  for (var i = 0; i < aba.length; i += 3) {
    n += parseInt(aba.charAt(i),     10) * 3
      +  parseInt(aba.charAt(i + 1), 10) * 7
      +  parseInt(aba.charAt(i + 2), 10);
  }

  // If the resulting sum is an even multiple of ten (but not zero),
  // the aba routing number is good.

  if (n != 0 && n % 10 == 0)
    return true;
  else
    return false;
}
	

function is_valid_vin(vin)
{
    /* From http://www.fastcustom.biz/content/blogcategory/71/44/ */
    // bpm -- source from above url did not work, digits evaluated to NaN. 
    // Replaced strings with JSON objects, arrays.
	var check_digit='', check_digit_value=0, sum=0;
	var has_invalid_characters=0;
	var check_digit_position=8;
	var letters = {
	    _0:0,_1:1,_2:2,_3:3,_4:4,_5:5,_6:6,_7:7,_8:8,_9:9,_A:1,_B:2,
	    _C:3,_D:4,_E:5,_F:6,_G:7,_H:8,_J:1,_K:2,_L:3,_M:4,_N:5,_O:6,
	    _P:7,_R:9,_S:2,_T:3,_U:4,_V:5,_W:6,_X:7,_Y:8,_Z:9
    }
	var weights = [8,7,6,5,4,3,2,10,0,9,8,7,6,5,4,3,2];
	if(vin.length !=17 ){
		return false;
	} 
	for(i=0 ; i<= 16 ; i++){	
		digit=vin.substring(i,i+1).toUpperCase();
		if (i==check_digit_position){
			check_digit=digit;
		} else {
            var digit_value = letters['_'+digit] * weights[i];
			sum+= digit_value;			
		}
	}
	if(check_digit=='X'){
		check_digit_value=10
	} else {
		check_digit_value=parseInt(check_digit) ;
	}
	if((sum % 11) != check_digit_value){
		return false;
	}
	return true;
}

Element.addMethods({
    updatePartial: function(element,regExp,replacement) {
        element = $(element);
        var newHtml = element.innerHTML.replace(regExp,replacement);
        element.update(newHtml);
        return element;
    },
    trigger: function(element,event) {
		element = $(element);
		if ( element['on'+event] ) {
		  return element['on'+event]();
	    }
    	Event.observers.findAll(function(observer){
		  return observer[0] == element && observer[1] == event;
	    }).each(function(handler) {
	      handler[2].bind(handler[0])();
	    });
    }
});

Ajax.Submit = function( element, form, fragment ) {
	element = $(element);
	form = $(form);
	new Ajax.Request(form.action, {
		parameters: form.serialize(),
		method: 'post',
		onComplete: function(transport) {
			Effect.Fade(element, {
			    afterFinish: function() {
				    element.update(transport.responseText);
				    Effect.Appear(element);
					var backtrack = document.location;
					backtrack = backtrack.replace(/#.*/,'#'+fragment);
					document.location = backtrack;
			    }
			});
		}
	});
}
