function formatCurrency(num) {
	num = num.toString().replace(/[^\d]+/g,'');
	if(isNaN(num) || (num.toString().length==0)) return '';
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return '$' + num;
}

function validate_date(date_field, desc) {

        if (!date_field.value) return false;
        var in_date = stripCharString(date_field.value," ");
        in_date = in_date.toUpperCase();
        var date_is_bad = 0;  
        if (!allowInString(in_date,"/0123456789T+-"))
                date_is_bad = 1; // invalid characters in date
        if (!date_is_bad) { 
                var has_rdi = 0;
                if (in_date.indexOf("T") >= 0){ 
                        has_rdi = 1;
                }
                if (!date_is_bad && has_rdi && (in_date.indexOf("T") != 0)) { 
                        date_is_bad = 2; // relative date index character is not in first position
                }
                if (!date_is_bad && has_rdi && (in_date.length == 1)) { 
                        var d = new Date();
						var return_month = parseInt(d.getMonth() + 1).toString();
						return_month = (return_month.length==1 ? "0" : "") + return_month; 
						var return_date =  parseInt(d.getDate()).toString();
						return_date = (return_date.length==1 ? "0" : "") + return_date; 
				        in_date = return_month + "/" + return_date + "/" + get_full_year(d);		
                        has_rdi = 0; // date doesn't have rdi char anymore (will also cause failure of add'l rdi checks, which is a good thing)
                }
                if (!date_is_bad && has_rdi && (in_date.length > 1) && !(in_date.charAt(1) == "+" || in_date.charAt(1) == "-")) {
                        date_is_bad = 3; // length of rdi string is greater than 1 but second char is not "+" or "-"
                }
                if (!date_is_bad && has_rdi && isNaN(parseInt(in_date.substring(2,in_date.length),10))) {
                        date_is_bad = 4; // rdi value is not a number
                }
                if (!date_is_bad && has_rdi && (parseInt(in_date.substring(2,in_date.length),10) < 0)) {
                        date_is_bad = 5; // rdi value is not a positive integer
                }
                if (!date_is_bad && has_rdi) {
                        var d = new Date();
                        ms = d.getTime();
                        offset = parseInt(in_date.substring(2,in_date.length),10);
                        if(in_date.charAt(1) == "+") {
                                ms += (86400000 * offset);
                        } else {
                                ms -= (86400000 * offset);
                        }
                        d.setTime(ms);
						var return_month = parseInt(d.getMonth() + 1).toString();
						return_month = (return_month.length==1 ? "0" : "") + return_month; 
						var return_date =  parseInt(d.getDate()).toString();
						return_date = (return_date.length==1 ? "0" : "") + return_date; 
				        in_date = return_month + "/" + return_date + "/" + get_full_year(d);	
                        has_rdi = 0;
                }
        } 
        if (!date_is_bad) {
                var date_pieces = new Array();
                date_pieces = in_date.split("/");
                if (date_pieces.length == 2) {
                        var d = new Date();
                        in_date = in_date + "/" + get_full_year(d);
                        date_pieces = in_date.split("/");
                }
                if (date_pieces.length != 3 || parseInt(date_pieces[0],10) < 1 || parseInt(date_pieces[0],10) > 12 
                                || parseInt(date_pieces[1],10) < 1 || parseInt(date_pieces[1],10) > 31 
                                || (date_pieces[2].length != 2 && date_pieces[2].length != 4)) {
                        date_is_bad = 6;  // date is not in format of m[m]/d[d]/yy[yy]
                }
        }
        if (date_is_bad) {
                alert(desc + " must be in the format of mm/dd/yy, mm/dd/yyyy");
                date_field.focus();
                return (false);
        }
        
        var ms = Date.parse(in_date);
        var d = new Date();
        d.setTime(ms);
		var return_date = d.toLocaleString();
		var return_month = parseInt(d.getMonth() + 1).toString();
		return_month = (return_month.length==1 ? "0" : "") + return_month; 
		var return_date =  parseInt(d.getDate()).toString();
		return_date = (return_date.length==1 ? "0" : "") + return_date; 
        return_date = return_month + "/" + return_date + "/" + get_full_year(d);
        date_field.value = return_date;
        return true;
}       

// normalize the year to yyyy
function get_full_year(d) {
		var y = ""
		if (d.getFullYear() != null)
		{
			y = d.getFullYear();
			if (y < 1970) y+= 100;		
		} else
		{	
	        y = d.getYear();
	        if (y > 69  && y < 100) y += 1900;
	        if (y < 1000) y += 2000;
		}
        return y;
}

// The following functions were written by Gordon McComb
// More information can be found here: http://www.javaworld.com/javaworld/jw-02-1997/jw-02-javascript.html
function stripCharString (InString, CharString)  {
        var OutString="";
   for (var Count=0; Count < InString.length; Count++)  {
        var TempChar=InString.substring (Count, Count+1);
      var Strip = false;
      for (var Countx = 0; Countx < CharString.length; Countx++) {
        var StripThis = CharString.substring(Countx, Countx+1)
         if (TempChar == StripThis) {
                Strip = true;
            break;
         }
      }
      if (!Strip)
        OutString=OutString+TempChar;
   }
        return (OutString);
}
function allowInString (InString, RefString)  {
        if(InString.length==0) return (false);
        for (var Count=0; Count < InString.length; Count++)  {
        var TempChar= InString.substring (Count, Count+1);
      if (RefString.indexOf (TempChar, 0)==-1)  
        return (false);
   }
   return (true);
}


function checkAmount(amount)
{
	return amount.toString().match(/^\s*\$?(\d{1,3}[\.\,]?)*\d{1,3}\s*$/) ? true : false;
}

function isEmpty(value)
{
	return (value != null ) && value.toString().match(/^\s*$/) ? true : false;
}

function checkIntInRange(m, left, right)
{
	i =  parseInt(m);
	if (isNaN(i)) return 0;
	return (i>=left && i<=right) ? 1 : 0;
}

function checkPurchaseDate(date_str)
{
	return date_str.toString().match(/^\s*\d{2}\/\d{2}\/\d{4}\s*$/);
}

function checkYear(year)
{
	if (isNaN(year)) return 0;
	return (year>=1900 && year<=2099) ? 1 : 0;
}

function checkMiles(miles)
{
	return miles.toString().match(/^\s*(\d+[\.\,]?)*\d+\s*$/) ? true : false;

//	if (isNaN(miles)) return 0;
//	return miles>1 ? miles : 0;
}

function checkEmail(email)
{
	return email.toString().match(/^\s*(\w+[\.\-])*\w+\@(\w+[\.\-])*\w*\.\w+\s*$/);
}

function toggleArea(area,flag)
{
	ac = document.getElementById(area);
	display = document.getElementById(flag).value;
	ac.style.display = display=='0' ? 'none' : 'block';
}

function checkMultiForm(form)
{
	var suffixes = new Array();
	var els = form.elements;

	var els_cnt = (typeof(els.length) != 'undefined') ? els.length : 0;
	
	for (var i = 0; i < els_cnt; i++)
	{
	//	alert(els[i].name.toString());
		var res = els[i].name.toString().match(/^year_(\d+)$/);
	//	alert(res);
		if (res)
		{
			suffixes.push(res[1]);
		}
	}

	for (var i = 0; i< suffixes.length; i++)
	{
		if (!checkForm(form,suffixes[i].toString()))
		{
			return false;
		}
	}

	return true;
}


function checkForm(form,ctrl_suffix)
{
	var suffix = (ctrl_suffix == null) ? '' : '_'+ctrl_suffix;

	// Checking vehicle parameters
	vp = ['year', 'make', 'model', 'trim'];

	for (i = 0; i < vp.length; i++)
	{
		select = form[vp[i]+suffix];
		if (select && select.value==0)
		{
			alert('Please select vehicle '+vp[i]);
			select.focus();
			return false;
		}
	}

	// Checking msrp, invoice, final transaction prices
	vp = [
		['msrp', 1, 'MSRP Price'],
		['invoice', 0, 'Invoice price'],
		['final', 1, 'Final Transaction Price'],
		['cash_rebate', 0, 'Cache Rebate']
	];
	
	for (i = 0; i < vp.length; i++)
	{
		input = form[vp[i][0]+suffix];
		value = input.value;

		if (vp[i][1])
		{
			if (!checkAmount(value))
			{
				alert('Please provide correct '+vp[i][2]);
				input.focus();
				return false;
			}
		}
		else
		{
			if (!isEmpty(value) && !checkAmount(value))
			{
				alert('Please provide correct '+vp[i][2]+', or leave it empty');
				input.focus();
				return false;
			}
			
		}
	}

	// Checking loan rebate
	lr_perc = form['lr_perc'+suffix];
	lr_mon = form['lr_mon'+suffix];

	perc = lr_perc.value; perc_empty = isEmpty(perc);
	mon = lr_mon.value; mon_empty = isEmpty(mon);

	if (!perc_empty || !mon_empty)
	{
		if (perc_empty || !checkIntInRange(perc,0,10))
		{
			alert('Please provide correct loan rebate percents (between 0 and 10)');
			lr_perc.focus();
			return false;
		}	
		if (mon_empty || !checkIntInRange(mon,0,90))
		{
			alert('Please provide correct loan rebate months (between 0 and 90)');
			lr_mon.focus();
			return false;
		}
	}

	// Checking dealer and city
	vp = [['dealer','Dealership'],['city','city']];

	for (i = 0; i<vp.length; i++)
	{
		input = form[vp[i][0]+suffix];
		if (isEmpty(input.value))
		{
			alert('Please provide correct '+vp[i][1]);
			input.focus();
			return false;	
		}
	}

	// Checking state
	state = form['state'+suffix];
	if (state.value == 0)
	{		
		alert('Please select state');
		state.focus();
		return false;
	}

	// Checking purchase date


	date = form['purch_date'+suffix];

	if (!validate_date(date,'Purchase date'))
	{
		alert('Please provide purchase date');
		date.focus();
		return false;
	}


	// Checking trade in values
	if (form['tin_option'+suffix].value==1)
	{
		tin_year = form['tin_year'+suffix];
		tin_make = form['tin_make'+suffix];
		tin_model = form['tin_model'+suffix];
		tin_miles = form['tin_miles'+suffix];
		tin_dealer_paid = form['tin_dealer_paid'+suffix];
		tin_bbook_value = form['tin_bbook_value'+suffix];

		if (!checkYear(tin_year.value))
		{
			alert('Please specify correct Trade In Year');
			tin_year.focus(); return false;
		}

		if (isEmpty(tin_make.value))
		{
			alert('Please specify correct Trade In Make');
			tin_make.focus(); return false;
		}

		if (isEmpty(tin_model.value))
		{
			alert('Please specify correct Trade In Model');
			tin_model.focus();
			return false;
		}

		if (!isEmpty(tin_miles.value) && !checkMiles(tin_miles.value))
		{
			alert('Please specify correct Trade In Miles');
			tin_miles.focus();
			return false;
		}

		if (!isEmpty(tin_dealer_paid.value) && !checkAmount(tin_dealer_paid.value))
		{
			alert('Please specify correct Trade In Dealer Paid');
			tin_dealer_paid.focus();
			return false;
		}

		if (!isEmpty(tin_bbook_value.value) && !checkAmount(tin_bbook_value.value))
		{
			alert('Please specify correct Trade In Blue Book Value');
			tin_bbook_value.focus();
			return false;
		}
	}			

	// Checking text fields
	text_fields = ['comments', 'pros', 'cons'];
	for (i=0; i<text_fields.length; i++)
	{
		field_name = text_fields[i];
		field = form[field_name+suffix];
		if (field.value.toString().length>1500)
		{
			alert('Max '+field_name+' size allowed is 1500 characters, but you have entered '+field.value.toString().length);
			field.focus();
			return false;
		}
	}
	

	// Checking satisfaction
	satisfaction = form['satisfaction'+suffix];
	if (satisfaction.value == 0)
	{		
		alert('Please select satisfaction level');
		satisfaction.focus();
		return false;
	}

	// Checking email
	email = form['email'+suffix];
	if (!checkEmail(email.value))
	{
		alert('Please provide valid email address');
		email.focus();
		return false;		
	}

	return true;
}

