//modal popup window
var popWin = '';
function popWindow(file, height, width){
	if(popWin.closed != undefined){if(!popWin.closed){popWin.close();};}
	popWin = window.open(file, 'popwin', 'height=' + height + ', width=' + width + ', resizable, scrollbars=yes, modal=yes, dialog=yes, menubar=no');
	popWin.moveTo(20,20);
	popWin.focus();
}


function insRow(){
  var x=document.getElementById('myTable').insertRow(0)
  var y=x.insertCell(0)
  var z=x.insertCell(1)
  y.innerHTML="NEW CELL1"
  z.innerHTML="NEW CELL2"
}


//column sorting function
	//col is the name of the db column
	//orderby is the mysql 'order by' caluse string
	//reloads page with new orderby parameter
function resort(col,orderby){
	var newsort1 = ''; newsort2 = '';
	var orderby = orderby.split(',');
	for(i=0; i<orderby.length; i++){
		if(orderby[i].split(' ')[0] == col){
			if(orderby[i].split(' ')[1] == 'asc'){newsort1 = col + ' desc,';}
			else{newsort1 = col + ' asc,';}
		}
		else{newsort2 += orderby[i] + ',';}
	}
	var newsort = newsort1 + newsort2;
	newsort = newsort.substr(0, newsort.length-1);
	document.location = location.protocol + '//' + location.hostname + location.pathname + '?orderby=' + newsort;
}


//div toggle
function shDetails(divid){
	with (document.getElementById(divid)) {
		if(style.display == ''){style.display = 'none';}
		else{style.display = '';}
	}
}



/////////////////begin form validation code/////////////////////

//form validation - multiple form inputs
/*
	uses validateInput() for each input
	returns true or false
	displays any failure message
	form is the name of the form
	validate format: input_name=friendly_name=test=required
		leave the 'test' parameter blank or 'nada' to allow field to be required only - no test
		input_name may specify an element in a field array as in quantity[1] where input elements named like quantity[] ala php
			* array is zero indexed
			* there must be two or more such input objects
			* the input tags must include an id value = to the base name of the element as in name='quantity[]' id='quantity'
		example: validateForm('Form1', 'per_email=Email Address=email=true,cas_uid=Case Number=integer=false,fromdate=From Date=date=false,todate=To Date=date=true')
	errors are caught and immediatly output
*/
function validateForm(form, validate){
	var oInput, sName, sTest, bReq, msg = "", index = "";
	var pairs = validate.split(",");
	for(i in pairs){
		index = '';
		try{
			oInput = pairs[i].split("=")[0];	//name of field
			var re = /\[(\d+)\]$/;				//determine if array element syntax
			var oMatches = oInput.match(re);
			if(oMatches != null){
				if(oMatches.length >  1){
					index = oMatches[1];
					oInput = oInput.substr(0, oInput.length - oMatches[0].length);	//trim off array index characters
					t1 = oInput;	//testing
				}
			}
			//get actual field object from field name
			if(index != ''){oInput = eval("document." + form + ".elements['" + oInput + "'][" + index + "]");}
			else{oInput = eval("document." + form + ".elements['" + oInput + "']");}
			//other parameters from validation string
			sName = pairs[i].split("=")[1];
			sTest = pairs[i].split("=")[2];
			bReq = eval(pairs[i].split("=")[3]);
			//run validation routine
			msg += validateInput(oInput, sName, sTest, bReq);
		}catch(e){msg += e /*+ '\n' + i + '\n' + oInput + '\n' + t1 + '\n' + index + '\n' + sName + '\n' + sTest + '\n' + bReq + '\n\n'*/;}
	}
	if(msg != ""){
		alert(msg);
		return false;
	}
	return true;
}

//form validation - single form input
	//returns empty string '' upon success
	//rerturns error message upon failure
	//oInput is form input object, sName is friendly name of input, sTest is the test to perfom, bReq is true if input is required
		//example: validateInput(per_email, 'Email Address', 'email', true)
function validateInput(oInput, sName, sTest, bReq){
    var rTest = "";
    var sVal = oInput.value;
//    try {var sVal = oInput.value;}
//    catch(e) {alert(sName)}
    if(sVal == "" && !bReq){return rTest;}
    if(sVal == "" && bReq){return sName + ": This field is required.\n";}
    if(sTest == "date"){rTest = validateDate(oInput.value);}
    if(sTest == "money"){rTest = validateMoney(oInput.value);}
    if(sTest == "email"){rTest = validateEmail(oInput.value);}
    if(sTest == "zip"){rTest = validateZipCode(oInput.value);}
    if(sTest == "integer"){rTest = validateInteger(oInput.value);}
    if(sTest == "numeric"){rTest = validateNumeric(oInput.value);}
    if(sTest == "ssn"){rTest = validateSSN(oInput.value);}
    if(sTest == "group"){rTest = validateGroup(oInput);}
    if(rTest != ""){rTest = sName + ": " + rTest + "\n"}
    return rTest;
}


// validation functions used by validateInput() above

//validate us date
function validateDate(sVal){
    var reDatePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
    var OmatchArray = sVal.match(reDatePat);
    if (OmatchArray == null) {
        return "all dates require a valid mm/dd/yyyy or mm-dd-yyyy date format.";
    }
    else{
        var strError = "";
        var strMonth = OmatchArray[1]; // parse date into variables
        var strDay = OmatchArray[3];
        var strYear = OmatchArray[5];
        if(strMonth < 1 || strMonth > 12) { // check month range
            strError="Month must be between 1 and 12.";
        }
        if(strDay < 1 || strDay > 31) {
			if(strError != ""){strError += ", ";}
            strError += "Day must be between 1 and 31.";
        }
        if((strMonth==4 || strMonth==6 || strMonth==9 || strMonth==11) && strDay==31) {
			if(strError != ""){strError += ", ";}
            strError += "Month "+strMonth+" doesn't have 31 days.";
        }
        if(strMonth == 2) { // check for february 29th
            var blnIsleap = (strYear % 4 == 0 && (strYear % 100 != 0 || strYear % 400 == 0));
            if (strDay>29 || (strDay==29 && !blnIsleap)) {
				if(strError != ""){strError += ", ";}
                strError += "February " + strYear + " doesn't have " + strDay + " days.";
            }
        }
        if(strYear < 1900 || strYear > 9999) {	//restrict year (mostly for sql)
			if(strError != ""){strError += ", ";}
            strError += "Year must be within a valid range.";
        }
        if(strError != ""){
            return strError;
        }
    }
    return "";
}

//validate us money
function validateMoney(sVal){
    reMoneyPat = /^\$|,/g;
    sVal=sVal.replace(reMoneyPat, "");
    if(isNaN(sVal)){return "A valid US monitary format is required.";}
    return "";
}

//validate email
function validateEmail(sVal){
    var rePat = /[a-zA-Z0-9_\.\-\+]+@[a-zA-Z0-9_\.\-\+]+\.[a-zA-Z]+$/;
    var bln = rePat.test(sVal);
    if(!bln){return "A valid email address is required.";}
    return "";
}

//validate us zip format
function validateZipCode(sVal){
    var rePat1 = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
    var OmatchArray1 = sVal.match(rePat1);
    if (OmatchArray1 == null) {
        return "A valid zipcode is required.";
    }
    return "";
}

//validate integer
function validateInteger(sVal){
	var re = /^-?\d+$/;
	if(sVal.match(re) == null){
		return "This field accepts Integers only.";
	}
	return "";
}

//validate decimal
function validateNumeric(sVal){
	if(isNaN(sVal)){return "This field accepts numbers only.";}
	return "";
}

//validate ssn
function validateSSN(sVal){
	var rePat1 = /^(\d{3})-(\d{2})-(\d{4})$/;
	var OmatchArray1 = sVal.match(rePat1);
	if (OmatchArray1 == null) {
		return "This field requires a number of the format NNN-NN-NNNN.";
	}
	return "";
}

//validate group
function validateGroup(oIn){
	for(i=0; i<oIn.length; i++){
		if(oIn[i].checked){return "";}
	}
	return "Please make a selection.";
}


//validate a password as being strong
function strongPass(password){
	var msg = "";
	if(!(password.length >= 7)){msg += "passwords must be at least 7 characters long.\n";}
	if(!(password.match(/\d/))){msg += "passwords must include at least one number.\n";}
	if(!(password.match(/[A-Z]/))){msg += "passwords must include at least one uppercase letter.\n";}
	if(!(password.match(/[a-z]/))){msg += "passwords must include one or more lowercase letters.\n";}
	if(!(password.match(/\W+/))){msg += "passwords must include at least one special character - #,@,%,!\n";}
	if(msg != ""){
		alert(msg);
		return false;
	}
	return true;
}


//check file upload extentions
function safeUpload(fvalue){
	if(fvalue == ''){return true;}
	var re = /\w+\.bmp|gif|tif|jpg|jpeg|doc|pdf|xls|ppt|txt$/i;
	if(!re.test(fvalue)){return false;}
	return true;
}
/////////////////end form validation code/////////////////////


// rounding function: n is number to round; p is precision
function JSround(n, p){return Math.round(n * Math.pow(10, p)) / Math.pow(10, p)}


//number formatting function  --  http://javascript.about.com/library/blnumfmt.htm
/*
num			the number
dec			the precision
thou		thousands separator symbol
pnt			decimal point symbol
curr1		currancy symbol - left
curr2		currancy symbol - right
n1			negetive symbol - right
n2			negetive symbol - left
*/
function formatNumber(num,dec,thou,pnt,curr1,curr2,n1,n2) {
	var x = Math.round(num * Math.pow(10,dec));
	if (x >= 0) n1=n2='';
	var y = (''+Math.abs(x)).split('');
	var z = y.length - dec; if (z<0) z--;
	for(var i = z; i < 0; i++) y.unshift('0');
	y.splice(z, 0, pnt);
	if(y[0] == pnt) y.unshift('0');
	while (z > 3) {z-=3; y.splice(z,0,thou);}
	var r = curr1+n1+y.join('')+n2+curr2;
	return r;
}


//fill the contents of a form with test data
function fillFormTest(form){
	var choice = "1234567890abcdefghiklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXTZ";
	var rndword; var rnd;
	for(i = 0; i < form.elements.length - 1; i++){
		rndword = '';
		for (var r = 0; r < Math.floor(Math.random() * 13) + 3; r++) {
		  rnd = Math.floor(Math.random() * choice.length);
		  rndword += choice.substring(rnd,rnd+1);
		}
		etype = form.elements[i].type;
		if(etype == 'text' || etype == 'textarea'){form.elements[i].value = rndword}
		if(etype == 'checkbox' || etype == 'radio'){form.elements[i].checked = true;}
	}
}


var xmlHttp
function GetXmlHttpObject(){
	var xmlHttp=null;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}

function checkLoginForm(form){
	var bPass = true;
	var validate = 'lgn_username=Username=nada=true,';
		validate += 'lgn_password=Password=nada=true,';
		validate += 'lgn_fname=First Name=nada=true,';
		validate += 'lgn_lname=Last Name=nada=true,';
		validate += 'lgn_email=E-Mail Address=email=true';
		//validate += 'lgn_phone=Phone=nada=true';

	bPass = validateForm('loginForm', validate);
	if(bPass){
		//fix any default values here
		return confirm('Are you sure?');
	} else { return false; }

	return true;
}

function showInstructions(name) {
	if(document.getElementById("incTrades")) document.getElementById("incTrades").style.display = "none";
	if(document.getElementById("insAccount")) document.getElementById("insAccount").style.display = "none";
	if(document.getElementById("insAdmin")) document.getElementById("insAdmin").style.display = "none";
	if(document.getElementById("insCRM")) document.getElementById("insCRM").style.display = "none";
	if(document.getElementById("insInventory")) document.getElementById("insInventory").style.display = "none";

	if(document.getElementById("incHome")) document.getElementById("incHome").style.display = "none";
	if(document.getElementById("incTrade")) document.getElementById("incTrade").style.display = "none";
	if(document.getElementById("insAccount")) document.getElementById("insAccount").style.display = "none";
	if(document.getElementById("insLearn")) document.getElementById("insLearn").style.display = "none";
	if(document.getElementById("insContact")) document.getElementById("insContact").style.display = "none";

	if(name != "") document.getElementById(name).style.display = "block";
}


function makeRollover() {
	var evenList = getElementsByClassName(document,'*','even');
	var oddList = getElementsByClassName(document,'*','odd');

	for(var i=0; i<evenList.length; i++) {
		evenList[i].onmouseover = function() { this.className="even_over"; }
		evenList[i].onmouseout = function() { this.className="even"; }
	}

	for(var i=0; i<oddList.length; i++) {
		oddList[i].onmouseover = function() { this.className="odd_over"; }
		oddList[i].onmouseout = function() { this.className="odd"; }
	}
}
window.onload = makeRollover;


function getElementsByClassName(oElm, strTagName, oClassNames){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	var arrRegExpClassNames = new Array();
	if(typeof oClassNames == "object"){
		for(var i=0; i<oClassNames.length; i++){
			arrRegExpClassNames.push(new RegExp("(^|\s)" + oClassNames[i].replace(/-/g, "\-") + "(\s|$)"));
		}
	}
	else{
		arrRegExpClassNames.push(new RegExp("(^|\s)" + oClassNames.replace(/-/g, "\-") + "(\s|$)"));
	}
	var oElement;
	var bMatchesAll;
	for(var j=0; j<arrElements.length; j++){
		oElement = arrElements[j];
		bMatchesAll = true;
		for(var k=0; k<arrRegExpClassNames.length; k++){
			if(!arrRegExpClassNames[k].test(oElement.className)){
				bMatchesAll = false;
				break;
			}
		}
		if(bMatchesAll){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}


function getContent(){
	var source = document.getElementById("areaSource");
	var target = document.getElementById("areaTarget");

	try{target.innerHTML = source.innerHTML;} catch(e){}
}


function CheckOther(data,target) {
	if(data == 'Other' || data == '_Other/Please specify') {
		document.getElementById(target).readOnly = false;
		document.getElementById(target).className = 'text';
	} else {
		document.getElementById(target).readOnly = true;
		document.getElementById(target).value='';
		document.getElementById(target).className = 'text disabled';
	}
}

