
//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"
}



/////////////////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
			note: if referening input arrays, 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
				}
			}
			//get acualy 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' + 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){
	if(sVal.search(/[^\d]/) != -1){
		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)}


//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("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"; }
	}
}

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");

	target.innerHTML = source.innerHTML;
}

function CheckOther(data,target) {
	if(data == "Other") {
		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';
	}
}


window.onload = makeRollover;

function CheckRequestForms(form,category) {
	var validate = "";
	var items = "";
	var display = "";
	var test = "";

	//setup fields names and labels for validation
	if(category == "Barrels") {
		items = "barrelstyle[],barrelstyle_other[],toastlevel[],toasthead[],woodorigin[],woodorigin_other[],quantity[],inhandsdate[]";
		display = "Barrel Style,Barrel Style Other,Toast Level,Toast Head,Wood Origin,Wood Origin Other,Quantity,Desired Date";
	} else if(category == "Adjuncts") {
		items = "material,quantity,inhandsdate";
		display = "Material,Quantity,Desired Date";
	} else if(category == "Corks") {
		items = "type[],type_other[],length[],length_other[],diameter[],diameter_other[],quantity[],inhandsdate[]";
		display = "Type,Type Other,Length,Length Other,Diameter,Diameter Other,Quantity,Desired Date";
	} else if(category == "Glass") {
		items = "style[],style_other[],color[],color_other[],capacity[],capacity_other[],finish[],finish_other[],features[],features_other[],moldnumber[],quantity[],inhandsdate[]";
		display = "Style,Style Other,Color,Color Other,Capacity,Capacity Other,Finish,Finish Other,Features,Features Other,Mold Number,Quantity,Desired Date";
	} else if(category == "Bulk Wine") {
		items = "appellation,country,varietals,quantity,pricerange,inhandsdate";
		display = "AVA,Country,Varietals,Tons,Price Range,Desired Date";
	} else if(category == "Wine Grapes") {
		items = "appellation,country,varietals,quantity,pricerange,inhandsdate";
		display = "AVA,Country,Varietals,Tons,Price Range,Desired Date";
	} else if(category == "Brochures") {
		items = "quantity,numcolors,finishedsize,paper_type,paper_weight,paper_manufacture,paper_selfcover,coding,secondary,dyecutting,finishing,qtyperwrap,printquality,linestream,inhandsdate";
		display = "Quantity,Number of Colors,Finished Size,Paper Type,Paper Weight,Paper Manufacture,Paper Self Cover?,Coding,Secondary Operations,Die Cutting,Finishing,Quantity per Wrap,Print Quality,Line Stream,Desired Date";
	} else if(category == "Catalogue") {
		items = "quantity,numcolors,finishedsize,paper_type,paper_weight,paper_manufacture,paper_selfcover,coding,secondary,dyecutting,finishing,qtyperwrap,printquality,linestream,inhandsdate";
		display = "Quantity,Number of Colors,Finished Size,Paper Type,Paper Weight,Paper Manufacture,Paper Self Cover?,Coding,Secondary Operations,Die Cutting,Finishing,Quantity per Wrap,Print Quality,Line Stream,Desired Date";
	} else if(category == "Labels") {
		items = "type,customchoice,stockchoice,material,embossed,foil_manufacture,foil_num_back,foil_num_front,process,numcolors_front,numcolors_back,size,shape,quantity,inhandsdate";
		display = "Type,Custom Labels,Stock Labels,Material,Embossed,Foil - Manufacture,# of Foils per Label (Front),# of Foils per Label (Back),Type of Process,Number of Colors (Front),Number of Colors (Back),Size,Shape,Quantity,Desired Date";
	} else if(category == "POS") {
		items = "quantity,numcolors,finishedsize,paper_type,paper_weight,paper_manufacture,paper_selfcover,coding,secondary,dyecutting,finishing,qtyperwrap,printquality,linestream,inhandsdate";
		display = "Quantity,Number of Colors,Finished Size,Paper Type,Paper Weight,Paper Manufacture,Paper Self Cover?,Coding,Secondary Operations,Die Cutting,Finishing,Quantity per Wrap,Print Quality,Line Stream,Desired Date";
	} else if(category == "Wearables - Embroidered") {
		items = "style,numcolors,numcolors_other,logo,logo_other,colors,colors_other,quantity,inhandsdate";
		display = "Style,Number of Colors in Decoration,Number of Colors Other,Logo Decoration Locations,Logo Locations Other,Color of Garment ,Color of Garment Other,Quantity,Desired Date";
	} else if(category == "Wearables - Screen Printed") {
		items = "style,numcolors,numcolors_other,logo,logo_other,colors,colors_other,quantity,inhandsdate";
		display = "Style,Number of Colors in Decoration,Number of Colors Other,Logo Decoration Locations,Logo Locations Other,Color of Garment ,Color of Garment Other,Quantity,Desired Date";
	} else if(category == "Packaging") {
		items = "type,pack_size,pack_size_other,bottle_size,bottle_size_other,quantity,inhandsdate";
		display = "Type,Pack Size,Pack Size Other,Bottle Size,Bottle Size Other,Quantity,Desired Date";
	} else if(category == "Boxes") {
		items = "dimensions,board_stack,board_stack_other,print,print_other,usage,usage_other,quantity,inhandsdate";
		display = "Dimensions,Board Stack,Board Stack Other,Print,Print Other,Usage,Usage Other,Quantity,Desired Date";
	} else if(category == "Internet" || category == "Electronic" || category == "Cross-Market" || category == "Print" || category == "Outdoor") {
		items = "number_adds,adds_date,hist_publications,budget,quantity,inhandsdate";
		display = "# of Add Placements,Date of Ad. Apperances,Historical Publications,Budget,Quantity,Desired Date";
	} else if(category == "Equipment") {
		items = "equipment_type,budget,prefered_vendors,vendor_contacted,quantity,inhandsdate";
		display = "Type Of Equipment,Budget,Preferred Vendors,Vendor has been contacted,Quantity,Desired Date";
	}
	
	//loop filed names  --  where multi-item only check first field in array
	//note: we may want to check all items in multi-item arrays for validation where quantity is numeric  --  this code can be added later
	for(i=0; i<items.split(',').length; i++){
		fld = items.split(',')[i]; //alert(fld);
		if(form.quantity.length !== undefined){oInput = eval("form.elements['" + fld + "'][0]");}
		else{oInput = eval("form.elements['" + fld + "']");}
		if(!oInput.readOnly) {
			test = 'nada'; //default
			if(fld.substr(0, 8) == 'quantity'){test = 'numeric';}
			if(fld.substr(0, 11) == 'inhandsdate'){test = 'date';}
			if(form.quantity.length !== undefined){validate += fld + "[0]=" + display.split(',')[i] + "=" + test + "=true,";}
			else{validate += fld + "=" + display.split(',')[i] + "=" + test + "=true,";}
		}
	}
	validate = validate.substr(0, validate.length - 1);		//trim off last comma
	
	//common validation elements
	validate += ",trq_requested_price=Requested Price=numeric=true";
	validate += ",trq_target_price=Target Price=numeric=true";
	validate += ",trq_benchmark=Benchmark=numeric=false";
	
	//check to make sure any file uploads are safe
	if(!safeUpload(form.elements['dms_name[]'][0].value)){alert('Error: upload file #1 format not supported'); return false;}
	if(!safeUpload(form.elements['dms_name[]'][1].value)){alert('Error: upload file #2 format not supported'); return false;}
	if(!safeUpload(form.elements['dms_name[]'][2].value)){alert('Error: upload file #3 format not supported'); return false;}
	if(!safeUpload(form.elements['dms_name[]'][3].value)){alert('Error: upload file #4 format not supported'); return false;}
	
	//do validation  --  return result to calling form
	return validateForm(form.name, validate);
}

/*  unused at this time
function CheckRequestItems(items,txtAlerts,num) {
	var item = items.split(",");
	var txtAlert = txtAlerts.split(",");
	var validate = "";
	for(i in item){
		oInput = eval("document.getElementById('mainForm').elements['" + item[i]+"']['"+num + "']");
		if(!oInput.readOnly) {
			validate += item[i]+"']['"+num+"="+txtAlert[i]+" #"+(num+1)+"=nada=true,";
		}
	}
	return validate;
}
*/
