// var editmode = true;	// caller must set if required
var MAXSIZE=16;
var MAX_SIZES_NEW = 21;

newWin = null;

String.prototype.strip = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

// Stupid IE STILL has no array search!!!!
if (!Array.indexOf) {
	Array.prototype.indexOf = function(obj) {
		for (i=0; i<this.length; i++) {
			if (this[i] == obj) return i;
		}
		return -1;
	}
}

// document.onkeypress = keyHandler

// helpers to void typing document.getElementsByName all the time
function getval(name) {
	var x = document.getElementsByName(name);
	if (x.length) return x[0].value;
	alert("Getval: no variable "+name);
	return '';
}

function getID(id) {
	 var x = document.getElementById(id);
	 if (!x)
	 	alert("getID: no variable "+id);
	 return x;
}

function setval(name, val) {
	 var x = document.getElementsByName(name);
	 if (x.length) {
		try {
	 		x[0].value = val;
			x[0].onchange();
		} catch (e) {}
	 }
	 else alert("No variable <"+name+">");
	 
}

function setvalID(id, value) {
	 var x = document.getElementById(id);
	 if (!x)
	 	alert("No variable "+id);
	else
		x.value = value;
}

function setinnerID(id, value) {
	 var x = document.getElementById(id);
	 if (!x)
	 	alert("No variable "+id);
	else
		x.innerHTML = value;
}

function innerToId(valId, innerId)
{
	getID(valId).value = getID(innerId).innerHTML.replace(/&amp;/g,"&");
}

function setselect(idIn, valueIn)
{
	var x = getID(idIn);
	for (var i = 0; i < x.options.length; i++)
		if (x.options[i].value == valueIn)
			x.selectedIndex = i;
}


// Conversion Routines
function dateobjToStr(d) {
	// Convert Date object to "01-01-2001"
	out = '';
	day = d.getDate();
	if (day < 10) out += '0';
	out += day + "-";
	m = d.getMonth() + 1;
	if (m < 10) out += '0';
	out += m + "-";
	out += d.getFullYear();
	return out;
}

function dateobjToEuroStr(d) {
	// Convert Date object to "2001-01-01"
	out = d.getFullYear() + "-";
	m = d.getMonth() + 1;
	if (m < 10) out += '0';
	out += m + "-";
	day = d.getDate();
	if (day < 10) out += '0';
	out += day + "-";
	return out;
}




// allow field editing by removing readonly unless noinput is set
function setEditMode(form) {
	editmode = true;

	var f = getID(form);
	l = f.getElementsByTagName('input');
	for (i=0; i<l.length; i++)
		if (l[i].type == 'text' && (l[i].getAttribute('noinput') == null)) {
			l[i].readOnly = false;
		}

	l = f.getElementsByTagName('textarea');
	for (i=0; i<l.length; i++)
		if (l[i].getAttribute('noinput') == null) {
			l[i].readOnly = false;
		}

	l = f.getElementsByTagName('select');
	for (i=0; i<l.length; i++)
		if (l[i].getAttribute('noinput') == null) {
			l[i].disabled = false;
		}
}

// check that char typed is in the allowed list
function checkValidchar(evt, allowed) {
	var key=(evt.charCode)?evt.charCode: ((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
	ret = false;
	for (var i=0; i<allowed.length; i++)
		if (key == allowed[i]) {
			ret = true; break;
		}

	if (!ret) {
		evt.cancel = true;
		evt.returnValue = false;
		return false;
	}
	return true;
}

function checkNumeric(e) {
	// allow: digits, BS, DEL, LEFT, RIGHT
	var evt = (e) ? e : window.event;
	return checkValidchar(evt, [8,37,39,46,48,49,50,51,52,53,,54,55,56,57]);
}

// find prompt field text for this entry to use in error popup
function getPrompt(obj) {
	prompt = document.getElementById('t_' + obj.name);
	if (prompt) return prompt.innerHTML;
	else return obj.name;
}

// nasty, horrid javascript date check
function check_date(obj) {
	// check for validity. return [valid, d, m, y]
	var s = obj.value.strip();
	var monthdays = [31,28,31,30,31,30,31,31,30,31,30,31];
	if ((s[2] != '-' || s[5] != '-') && (s[2] != '/' || s[5] != '/')) return [0,0];
	if (s.length == 8) s = s.substring(0, 5) + "20" + s.substring(6,7);
	d = parseInt(s.substr(0,2),10);
	m = parseInt(s.substr(3,2),10);
	y = parseInt(s.substr(6,4),10);
	leap = ((y % 4) == 0) ? true : false;
	if (m >= 1 && m < 13) {
		md = monthdays[m-1];
		if (leap && (m == 2)) md = 29;
		if (d >= 1 && d <= md) {
			if (y > 2004 && y < 2015) {
				vres = true;
				return [1, new Date(y,m-1,d)];
			}
		}
	}
	// alert("invalid date")
	return [0, 0];
}

// 2-digit numbers for dates
function twoDigits(x) {
	return (x < 10) ? '0'+x : ''+x;
}

function twoDP(x) {
	x = Math.floor(x * 100 + 0.049) + '';
	if (x.length < 2) x = '0' + x;
	if (x.length < 3) x = '0' + x;
	var pos = x.length - 2;
	return x.substr(0,pos)+'.'+x.substr(pos);
}

// validate every field and post form if OK, else alert error message
function validateAndPost() {
 	var l = document.getElementsByTagName("input");
	errs = '';
 	for (var i = 0; i<l.length; i++) {
		name = l[i].name;
		if (validates[name]) {
			vtype = validates[name][0];
			res = validate_types[vtype](l[i], validates[name]);
			pr = document.getElementById('t_'+name);
			if (pr)	pr.style.color = (res == '') ? 'black' : 'red';
			if (res != '') errs += res+"\n";
		}
 	}
	if (errs != '') {
		alert(errs);
		return false;
	}
	else return true;
}

validate_types = {
	// field not empty
	'ne': function validate_empty(obj, limits) {
		if (obj.value.strip() == '') {
			// alert(obj.name+" must not be empty");
			return(getPrompt(obj)+" must not be empty");
		}
		return '';
	},

	// not empty if some other field not empty
	'emptyif': function validate_empty_if(obj, limits) {
		if (document.getElementById(limits[1]).value.strip() != '')
			if (obj.value.strip() == '') {
				return (getPrompt(obj)+" must not be empty");
			}
		return '';
	},

	// <= value
	'le': function validate_max(obj, limits) {
		maxval = limits[1];
		v = parseInt(obj.value);
		if (v > maxval) {
			return (getPrompt(obj)+" cannot be over "+maxval);
		}
		return '';
	},

	// value must be in range
	'range': function validate_range(obj, limits) {
		minval = limits[1]; maxval = limits[2]
		v = parseInt(obj.value);
		if (v < minval || v > maxval) {
			return (getPrompt(obj)+" ("+obj.value+") must be in range "+minval+" to "+maxval);
		}
		return '';
	},

	// value must be in list, e.g. Y, N
	'in': function validate_inlist(obj, list) {
		for (item in list)
		{
				if (obj.value == item) return '';
		}
		//if (obj.value in list) return '';
		return (getPrompt(obj)+ "must be in " + list.join(","));
	},

	// value must be in the given table/column
	'lu': function validate_inlookup(obj, list) {
		// list[1]=table, list[2]=column
		// will queue and combine later to speed it up...
		x = loadURL("/cgi-bin/python/lookups.py/ci/find?filename="+list[1]+"&column="+list[2]+"&value="+obj.value);
		if (x == "OK") return '';
		return (getPrompt(obj)+ " must be a value from table "+list[1]);
	},

	// must be valid date
	'date': function validate_date(obj) {
		if (obj.value == "dd-mm-yyyy" || obj.value=='') return '';
		res = check_date(obj);
		if (!res[0]) return (getPrompt(obj)+" is not a valid date");
		return '';
	},

	// must be valid date at least n days hence
	'dateafter': function validate_date_after(obj, limits) {
		// check that date is after today - mdays
		if (obj.value == "dd-mm-yyyy" || obj.value=='') return '';
		ndays = limits[1];
		res = check_date(obj);
		if (!res[0]) return (getPrompt(obj)+" is not a valid date");
		var today = new Date();
		var ms = today.getTime() - 86400 * 1000 * ndays;
		if (res[1].getTime() < ms) {
			return("date must be within last "+ndays+" days");
		}
		return '';
	},

	// must be valid date at least n days prior
	'datebefore': function validate_date_before(obj, ndays) {
		// check that date is before today + mdays
		if (obj.value == "dd-mm-yyyy" || obj.value=='') return '';
		ndays = limits[1];
		res = check_date(obj);
		if (!res[0]) return (obj.name+" is not a valid date");

		var today = new Date();
		var ms = today.getTime() + 86400 * 1000 * ndays;
		if (res[1].getTime() > ms) {
			return(getPrompt(obj)+" must be within next "+ndays+" days");
		}
		return ''
	}
	// add your own validates here to confuse others....
}

function openLookup(filename, retvar) {
	// open a lookup window. When it closes it copies selected value to retvar
	// window sizes
	try {
		if (!editmode) {
			alert("Not in Edit mode");
			return;
		}
	}
	catch (e) {}

	newwin = window.open("/cgi-bin/python/lookups.py/ci/lookup?filename="+filename+"&retvar="+retvar+"&dummy="+(new Date()).getTime(), "w_"+filename, 'top=100,left=200,width=500,height=400,resizable=yes,toolbar=no,location=no');
	newwin.focus();
}

function openwin(url, name) {
	newwin = window.open(url, name, 'top=200, left=200, width=600, height=400, scrollbars=yes');
	newwin.focus();
}

function resizeWindow(width, height) {
	// if we pass only the width, should still work OK
	try {
		document.body.clientWidth = width;
		document.body.clientHeight = height;
	}
	catch (e) {
		window.outerWidth = width;
		window.outerHeight = height;
	}
}

function noPropagation(e) {
	if (window.event) window.event.cancelBubble = true;
	else if (e.stopPropagation) e.stopPropagation();
}

function show(name) {
	document.getElementById(name).style.display = "";
}

function inline(name) {
	document.getElementById(name).style.display = "inline";
}

function block(name) {
	document.getElementById(name).style.display = "block";
}

function hide(name) {
	document.getElementById(name).style.display = "none";
}

//If value is in the array, return the index; else return -1.
//function findInArray(arrayIn, valueIn)
//{
//		returnVar = -1;
//		for (var i = 0; i < arrayIn.length; i++)
//		{
//				if (arrayIn[i] == valueIn)
//				{
//						returnVar = i;
//				}
//		}
//		return returnVar;
//}

//Decodes any &amp; , &lt; etc. combinations.
function htmlDecode(stringIn)
{
	try 
	{
		return stringIn.replace("\&amp;","\&").replace("\&lt;","\<").replace("\&gt;","\>").replace("\&quot;",'"').replace("\&apos;","'");
	} catch(e)
	{
		alert("DEBUG in htmlDecode, error: "+e);
	}
}

//If value is in the select, return the index; else return -1.
function findInSelect(selIn, valueIn)
{
	returnVar = -1;
	for (var i = 0; i < selIn.options.length; i++)
	{
		if (selIn.options[i].value == valueIn)
		{
			returnVar = i;
		}
	}
	return returnVar;
}

function setSelect(name, value) {
	sel = document.getElementsByName(name)[0];
	for (var i=0; i < sel.options.length; i++)
	{
		if (sel.options[i].value == value) {
			sel.selectedIndex = i;
			return;
		}
	}
}

//Returns today's date as YYYY-MM-DD
function getDateAsISO()
{
	theDate = (new Date());
	d = theDate.getDate().toString();
	if (d.length < 2) d = "0"+d;
	m = (theDate.getMonth() + 1).toString();
	if (m.length < 2) m = "0"+m;
	y = theDate.getFullYear().toString();
	return y+"-"+m+"-"+d;
}

function printInner(container)
{
	newWin = window.open("","_blank","location=no,menubar=yes,scrollbars=yes");
	newWin.resizeTo(screen.width-200, screen.height-200);
	newWin.moveTo(100,100);

	newWin.document.open();
	newWin.document.write("<html><head><link href='/css/stylesheet.css' rel=stylesheet type='text/css' ><head><body>")
	newWin.document.write(container.innerHTML);
	newWin.document.write("</body></html>");
	newWin.document.close();
	setTimeout("_printInner2();",200);
}

function _printInner2()
{
	heads = newWin.document.getElementsByTagName("th");
	for (var i = 0; i < heads.length; i++)
	{
			heads[i].style.backgroundColor = "#ffffff";
	}
	cells = newWin.document.getElementsByTagName("td");
	for (var i = 0; i < cells.length; i++)
	{
			if (cells[i].leavecolour == 'Y')
					cells[i].style.backgroundColor = "#ffffff";
	}
	rows = newWin.document.getElementsByTagName("tr");
	for (var i = 0; i < rows.length; i++)
			rows[i].style.backgroundColor = "#ffffff";

	//hide all buttons...
	buttons = newWin.document.getElementsByTagName("input");
	for (var i = 0; i < buttons.length; i++)
	{
		if (buttons[i].type == 'button')
			buttons[i].style.display='none';
	}
	
	setTimeout("newWin.print();",300);
}

function hasClass(obj, name) {
	var classes = obj.className.split(' ');
	var pos = classes.indexOf(name);
	if (pos >= 0) return 1;
	return 0;
}

function addClass(obj, name) {
	if (!obj.className) {
		obj.className = name; return;
	}
	var classes = obj.className.split(' ');
	var pos = classes.indexOf(name);
	if (pos >= 0) return;
	classes.push(name)
	obj.className = classes.join(' ');
	
}

function removeClass(obj, name) {
	if (!obj.className) {
		obj.className = ''; return;
	}
	var classes = obj.className.split(' ');
	var pos = classes.indexOf(name);
	if (pos < 0) return;
	classes.splice(pos, 1);
	obj.className = classes.join(' ');
}

function showPanel(myid)
{
	if (typeof(myid) == 'string') num = myid;
	else num = myid.id.slice(3);		// "tabxx"
	document.getElementById("tab"+lastTab).className = 'tab';
	document.getElementById("panel"+lastTab).style.display="none";
	tab = document.getElementById("tab"+num);
	tab.className = 'tab sel';
	document.getElementById("panel"+num).style.display = "block";
	lastTab = num;

	var action = 'onTab' + num;
	var t = eval('typeof('+action+')');
	if (t == 'function') {eval(action+'()')}
}

function plainButton(obj, list) {
	// Multistate button which displays the variable's value
	if (!editmode) {
		alert("Not in edit mode");
		return;
	}

	var id = obj.id;
	var varname = id.substr(4);		// button id is btn_xxxxx
	var val = getval(varname);		// name of hidden var is xxxx
	var pos = -1;
	for (var i=0; i < list.length; i++)
		if (val == list[i]) {
		pos = i; break;
	}
	pos += 1;
	if (pos >= list.length) pos = 0;
	val = list[pos];
	setval(varname, val);
	obj.value = val;
	obj.blur();
}

//  ------------------ experimental and style sheet includes -------------
//Let's have functional programming like in Python.
//Somewhat like Google's famed MapReduce() function:
//take all array elements that includeFn returns true, and
//map them to new array using mapFn.
function reduceMap(arrayIn, includeIfFn, mapFn)
{
	var returnVar = [];
	for (var i = 0; i < arrayIn.length; i++)
	{
		if (includeIfFn(arrayIn[i]))
		{
			returnVar[returnVar.length] = mapFn(arrayIn[i]);
		}
	}
	return returnVar;
}

function forEach(fn, arrayIn)
{
	return reduceMap(arrayIn, function (x){return true;}, fn);
}

//function inArray(arrayIn, val)
//{
//	res = reduceMap(arrayIn, 
//			function(x){return val == x;},
//			function(x){return 1;});
//	return res.length > 0;
//}

function nonindent_from_percent(indentIn, percentIn)
{
	return indentIn / (1 - (percentIn/100.0));
}


function _popupStyle(styleIn, initialiseCodeIn) {
	if (styleIn!= "")
	{
		var wid = screen.width - 1024;
		if (wid < 0) wid = 0;
		wid += 900;
		var x = window.open(STYLES_URLBASE+"start?dummy="+(new Date()).getTime()+
				"&initialisecode="+encodeURIComponent(initialiseCodeIn)+
				"&ste_code="+encodeURIComponent(styleIn)+
				"&nomenu=Y","stylepopup","scrollbars=yes,width="+wid+",height=665,top=95,left=110");
		x.focus();
	}
}
function popupStyle(styleIn) {
	_popupStyle(styleIn,"");
}
function PS(obj) {
	popupStyle(obj.parentNode.cells[2].innerHTML);
}
function PSS(styleIn) {
	//PopupStyle with a String
	popupStyle(styleIn);
}
function popupStyleFabrics(styleIn) {
	_popupStyle(styleIn, 'showPanel(document.getElementById(\'tab1\'));');
}
function PSF(styleIn){
	popupStyleFabrics(styleIn);
}

function popupStyleLogos(styleIn) {
	_popupStyle(styleIn, 'showPanel(document.getElementById(\'tab4\'));');
}
function PSL(styleIn){
	popupStyleLogos(styleIn);
}

function popupStyleSamples(styleIn) {
	_popupStyle(styleIn, 'showPanel(document.getElementById(\'tab8\'));');
}
function PSA(styleIn){
	popupStyleSamples(styleIn);
}

function popupLogoRequest(idIn)
{
	if (idIn != "")
	{
		//var wid = screen.width - 1024;
		//if (wid < 0) wid = 0;
		//wid += 900;
		window.open(REQUESTS_URLBASE+"logoRequestEdit?dummy="+(new Date()).getTime()+ 
				"&requestid="+encodeURIComponent(idIn)+ 
				"&ispopup="+encodeURIComponent("Y") , 
				"_blank","menubar=yes,status=yes,scrollbars=yes,width=950,height=665,left=80,top=30");
		//"_blank","menubar=yes,status=yes,scrollbars=yes,width="+wid+",height=665,left=80,top=30");
	}
}
function popupStyleRequest(idIn)
{
	if (idIn != "")
	{
		var wid = screen.width - 1024;
		if (wid < 0) wid = 0;
		wid += 900;
		window.open(REQUESTS_URLBASE+"styleRequestEdit?dummy="+(new Date()).getTime()+ 
				"&requestid="+encodeURIComponent(idIn)+ 
				"&ispopup="+encodeURIComponent("Y") , 
				"_blank","menubar=yes,status=yes,scrollbars=yes,width="+wid+",height=665,left=80,top=30");

	}
}

function reqShowLogoInfo(rowIn)
{
	logoCellStr = rowIn.cells[12].innerHTML;
	logoIDStr = rowIn.cells[18].innerHTML;
	if (logoCellStr != "")
	{
		window.open(REQUESTS_URLBASE+"logoRequestQuotePopup?dummy="+(new Date()).getTime()+
					"&requestid="+encodeURIComponent(logoIDStr), "_blank", 
					"top=200,left=200");
	}
}


function showStyleTaskPopup(styleIn, taskIn)
{
	w = window.open(STYLES_URLBASE+"showTaskPopup?dummy="+(new Date()).getTime()+
			"&style="+encodeURIComponent(styleIn)+
			"&task="+encodeURIComponent(taskIn)+
			"&successruncode="+encodeURIComponent(
				'window.opener.criteriaChanged();window.close();'),
			"_blank","menubar=no,status=no,scrollbars=no,left=200,top=150");
	w.focus();
}
function STP(obj, which) {
	showStyleTaskPopup(obj.parentNode.cells[2].innerHTML, which);
}

function showStyleTasksPopup(styleIn )
{
	w = window.open(STYLES_URLBASE+"showTasksPopup?dummy="+(new Date()).getTime()+
			"&style="+encodeURIComponent(styleIn)+
			"&successruncode="+encodeURIComponent(
				'window.opener.criteriaChanged();window.close();'),
			"_blank","menubar=no,status=no,scrollbars=no,left=200,top=150");
	w.focus();
}

//Called when a Cost cell is clicked in dev report.
function showStyleCostTaskPopup(styleIn)
{
	w = window.open(STYLES_URLBASE+"showCostTaskPopup?dummy="+(new Date()).getTime()+
			"&style="+encodeURIComponent(styleIn)+
			"&successruncode="+encodeURIComponent(
				'window.opener.criteriaChanged();window.close();'),
			"_blank","menubar=no,status=no,scrollbars=no,left=200,top=150");
	w.focus();
}

function stylePopupSelect(idIn, custIn)
{
	custnum = '';
	if (custIn != null && custIn != '0' && custIn!= '')
	{
		custnum = custIn;
	}


	w = window.open(STYLES_URLBASE+"styleSelectPopup?dummy="+(new Date()).getTime()+
			"&ste_custnum="+encodeURIComponent(custnum)+
		"&returnid="+encodeURIComponent(idIn) ,"_blank");

	w.focus();
}

//Called when a due date is clicked in prep report.
function showSampleTaskPopup(styleIn, sampleIDIn, taskIn)
{
	w = window.open(SAMPLES_URLBASE+"showTaskPopup?dummy="+(new Date()).getTime()+
			"&style="+encodeURIComponent(styleIn)+
			"&sampleid="+encodeURIComponent(sampleIDIn)+
			"&task="+encodeURIComponent(taskIn)+
			"&successruncode="+encodeURIComponent(
				'window.opener.doSampReport(\''+PREVIOUS_SORT_COLUMN+'\');window.close();'),
			"_blank","menubar=no,status=yes,scrollbars=yes,left=200,top=150");
	w.focus();
}

//Called when a due date is clicked in prep report.
function showSampleTasksPopup(styleIn, sampleIDIn)
{
	window.open(SAMPLES_URLBASE+"showTasksPopup?dummy="+(new Date()).getTime()+
			"&style="+encodeURIComponent(styleIn)+
			"&sampleid="+encodeURIComponent(sampleIDIn)+
			"&successruncode="+encodeURIComponent(
				'window.opener.doSampReport(\''+PREVIOUS_SORT_COLUMN+'\');window.close();'),
			"_blank","menubar=no,status=no,scrollbars=no,left=100,top=50");
}

function fullSizePicture(picURL, caption, details)
{
	extn = picURL.substr(-3).toUpperCase();
	if (extn == 'DST')
	{
		//Hmm, it's an embroidery file.  Be a bit smarter.
		newWin = window.open("","_blank","location=no,menubar=yes,scrollbars=yes");
		newWin.resizeTo(screen.width-200, screen.height-200);
		newWin.moveTo(100,100);
	
		newWin.document.open();
		newWin.document.write("<html><head><title>Embroidery data file</title></head>\n");
		newWin.document.write("<body >\n");
		newWin.document.write("<center><div style='display:inline;' id='topdiv'>\n");
		if (caption != "")
		{
			newWin.document.write(caption+"<br>\n");
		}
		if (details != "")
		{
			newWin.document.write(details+"<br>\n");
		}
		newWin.document.write('</div><br><br><a href="'+picURL+"?dummy="+(new Date()).getTime()+'" title="Click to download">Download file...</a><br>\n');
		newWin.document.write("</center>\n");
		newWin.document.write("</body></html>\n");
		newWin.document.close();
	}
	else if (['GIF', 'JPG', 'PNG', 'PEG', 'BMP'].indexOf(extn) >= 0)
	{
		//Hmm, it's a picture.  Be a bit smarter.
		newWin = window.open("","_blank","location=no,menubar=yes,scrollbars=yes");
		newWin.resizeTo(screen.width-200, screen.height-200);
		newWin.moveTo(100,100);
	
		newWin.document.open();
		newWin.document.write("<html><head><title>Full-size picture</title></head>\n");
		newWin.document.write("<body >\n");
		newWin.document.write("<center><div style='display:inline;' id='topdiv'>\n");
		if (caption != "")
		{
			newWin.document.write(caption+"<br>\n");
		}
		if (details != "")
		{
			newWin.document.write(details+"<br>\n");
		}
		newWin.document.write("<br><input type=button value='Original Size' id='fullbutton' onclick='document.getElementById(\"thepic\").style.height=\"auto\";this.style.display=\"none\";document.getElementById(\"normalbutton\").style.display=\"inline\";'>\n");
		newWin.document.write("<input type=button value='Fit to Screen' id='normalbutton' style='display:none;' onclick='document.getElementById(\"thepic\").style.height=\"80%\";this.style.display=\"none\";document.getElementById(\"fullbutton\").style.display=\"inline\";'>\n");
		newWin.document.write("<input type=button value='Print' onclick='document.getElementById(\"thepic\").style.height=\"auto\";document.getElementById(\"thepic\").style.width=\"100%\";document.getElementById(\"topdiv\").style.display=\"none\";window.print();'>\n");
		newWin.document.write("<input type=button value='Close' onclick='window.close();'><br>\n");
		newWin.document.write('</div><img id="thepic" title="'+caption+'" src="'+picURL+"?dummy="+(new Date()).getTime()+'" style="height:80%;"><br>\n');
		newWin.document.write("</center>\n");
		newWin.document.write("</body></html>\n");
		newWin.document.close();
	}
	else {
		// Let the browser handle it
		newWin = window.open(picURL,"_blank","location=no,menubar=yes,scrollbars=yes");
	}
}

//Convert a tab-delimited csv text (with heading in first row) to array of hashes.
function csvToArray(resultsIn)
{
	return _csvToArray(resultsIn, "\t");
}

//Convert a delimited csv text (with heading in first row) to array of hashes.
function csvToArrayDelim(resultsIn, delim)
{
	return _csvToArray(resultsIn, delim);
}

//Convert a delimited csv text (with heading in first row) to array of hashes.
function _csvToArray(resultsIn, delim)
{
	rows = resultsIn.split("\n");
	returnVar = [];
	numadded=0;
	if (rows.length > 0)
	{
		cols = rows[0].split(delim);
		//For each row...
		for (var i = 1; i < rows.length; i++)
		{
			newRow = [];
			dataCols = rows[i].split(delim);
			//...For each column in the row...
			for (var k = 0; k < cols.length; k++)
			{
				//...insert that column into the hash...
				newRow[cols[k]] = dataCols[k];
			}
			//...and add it to the return values.
			returnVar[returnVar.length] = newRow;
			numadded++;
		}
	}
	return returnVar;
}

function popupOrder(ordernum,checkorder)
{
	w = window.open(CUSTOMERS_URLBASE+"viewfromorder?dummy="+(new Date()).getTime()+
			"&ordernum="+encodeURIComponent(ordernum)+
			"&checkorder="+encodeURIComponent(checkorder), '_blank');
}

