﻿// Gondwana JavaScript Library
// Global Functions
// Origine = GoLive Actions

var deBugOn = false;
deBugThis("DEBUG ON");



// get right formatted date

function formatDate (thisdate,format) {
	month = thisdate.getMonth() + 1;
	day = thisdate.getDate();
	year = thisdate.getFullYear();
	if (day < 10) { day = "0" + day; }
	if (month < 10) { month = "0" + month; }
	if (format == 'DMY') {
		newDate = day + "-" + month + "-" + year;
	} else {
		newDate = year + "-" + month + "-" + day;
	}
	return newDate;
}


// get today's date
var currentTime = new Date();
var dateNow = formatDate (currentTime,'DMY');
var dateNowYMD = formatDate (currentTime,'YMD');
var dateDay = currentTime.getDate();
var dateMonth = currentTime.getMonth() + 1;
var dateYear = currentTime.getFullYear();

//alert("dateMonth=" + dateMonth + " dateYear=" + dateYear);


function deBugThis (what) {
	if (deBugOn) { alert (what); }
}

CSAg = window.navigator.userAgent; 

CSBVers = parseInt(CSAg.charAt(CSAg.indexOf("index.html")+1),10);

CSIsW3CDOM = ((document.getElementById) && !(IsIE()&&CSBVers<6)) ? true : false;

//deBugThis("CSIsW3CDOM" + CSIsW3CDOM); 

function IsIE() { return CSAg.indexOf("MSIE") > 0;}

//alert ("Browser Version = " + IsIE() + ":" + CSBVers);

function CSIEStyl(s) { return document.all.tags("div")[s].style; }

function CSNSStyl(s) { if (CSIsW3CDOM) return document.getElementById(s).style; else return CSFindElement(s,0);  }

CSDInit=false;

// this function generates a warning because getElementsByTagName is empty
function CSIDOM() { 
	if (CSDInit) { return; }
	CSDInit=true; 
	if(document.getElementsByTagName) { 
		var n = document.getElementsByTagName('DIV'); 
		for (var i=0;i<n.length;i++) {
			deBugThis ("DIV " + i + " : " + n[i].id);
			CSICSS2Prop(n[i].id);
		}
	}
}

function CSICSS2Prop(id) { 
	var n = document.getElementsByTagName('STYLE');
	for (var i=0;i<n.length;i++) { 
		var cn = n[i].childNodes; 
		//deBugThis ("STYLE childnodes " + i + " : " + cn);
		for (var j=0;j<cn.length;j++) { 
			fetchstyle = CSFetchStyle(cn[j].data, id);
			//deBugThis ("fetchstyle " + j + " : " + fetchstyle);
			CSSetCSS2Props(fetchstyle,id); 
		}
	}
}


function CSFetchStyle(sc, id) {
	var s=sc; 
	while(s.indexOf("#")!=-1) { 
		s=s.substring(s.indexOf("#")+1,sc.length); 
		if (s.substring(0,s.indexOf("{")).toUpperCase().indexOf(id.toUpperCase())!=-1) {
			return(s.substring(s.indexOf("{")+1,s.indexOf("}")));
		}
	}
	return "";
}


function CSSetCSS2Props(si, id) {
	var el=document.getElementById(id);
	if (el==null) return;
	var style=document.getElementById(id).style;
	if (style) {
		if (style.left=="") style.left=CSGetStyleAttrValue(si,"left");
		if (style.top=="") style.top=CSGetStyleAttrValue(si,"top");
		if (style.width=="") style.width=CSGetStyleAttrValue(si,"width");
		if (style.height=="") style.height=CSGetStyleAttrValue(si,"height");
		if (style.visibility=="") style.visibility=CSGetStyleAttrValue(si,"visibility");
		if (style.zIndex=="") style.zIndex=CSGetStyleAttrValue(si,"z-index");
	}
}

// return the value of a style between : & ; or end of line
function CSGetStyleAttrValue (si, id) {
	// convert the whole style list in uppercase
	var s=si.toUpperCase();
	s=s.replace("  "," ");
	// convert the style to uppercase
	var myID=id.toUpperCase()+":";
	// get position of first car of this style in whole style list
	var id1=s.indexOf(myID);
	// if not found return empty
	if (id1==-1) {
		//deBugThis ("STYLE=" + myID + "- VALUE= not found");
		return "";
	}
	// remove string before this style in style list
	// IT WAS WRONG BEFORE !!! THIS ONLY WORKS IF THERE IS A SPACE AFTER :
	//s=s.substring(id1+myID.length+1,si.length);
	// NOW IT WILL WORK IN BOTH CASE
	// if there is a space after : take one more char right
	jump = ((s.substring(0,1) == " ") ? 0:1);
	s=s.substring(id1+myID.length+jump,si.length);
	// get position of ; after style value
	var id2=s.indexOf(";");
	// extract the value between style: and ; if exist
	var result=((id2==-1)?s:s.substring(0,id2));
	//deBugThis ("STYLE=" + myID + "- VALUE=" + result);
	return result;
}


function CSSetStyleVis(s,v) {
	//deBugThis ("CSSetStyleDis " + s + " : " + v);
	if (CSIsW3CDOM){
		//deBugThis ("getElementById"); // this is the one used on mac
		CSIDOM();
		//deBugThis ("CSSetStyleDis " + s + " : " + v + document.getElementById(s).style.visibility);
		document.getElementById(s).style.visibility=(v==0)?"hidden":"visible";
		//deBugThis ("done2");
	} else if (IsIE()) { 
		//deBugThis ("document.all.tags");
		CSIEStyl(s).visibility=(v==0)?"hidden":"visible";
	} else {
		//deBugThis ("CSNSStyl");
		CSNSStyl(s).visibility=(v==0)?'hide':'show';
	}
}

function CSSetStyleDis(s,v) {
	if (CSIsW3CDOM){CSIDOM();document.getElementById(s).style.display=(v==0)?"none":"block";}
	else if(IsIE())CSIEStyl(s).display=(v==0)?"none":"block";
	else CSNSStyl(s).display=(v==0)?'none':'block';
}

function CSGetStyleVis(s) {
	if (CSIsW3CDOM) {CSIDOM();return(document.getElementById(s).style.visibility=="hidden")?0:1;}
	else if(IsIE())return(CSIEStyl(s).visibility=="hidden")?0:1;
	else return(CSNSStyl(s).visibility=='hide')?0:1;
}

function CSGetStyleDis(s) {
	if (CSIsW3CDOM) {CSIDOM();return(document.getElementById(s).style.display=="none")?0:1;}
	else if(IsIE())return(CSIEStyl(s).display=="none")?0:1;
	else return(CSNSStyl(s).display=='none')?0:1;
}

CSImages=new Array();

function preloadImage(pathImage) {
	//deBugThis ("preload " + pathImage);
	if (document.images) { CSImages[CSImages.length]=new Image(); CSImages[CSImages.length-1].src=pathImage; }
}


// open page in frame (target = frame name) or in new page (target = _blank) or in self (target = empty)
function openPageInFrame(page,target) {
	nbrParam = openPageInFrame.arguments.length;
	//deBugThis ("page = " + page);
	//alert ("page = " + page);
	page = page.replace("&amp;","&"); // to avoid any problem
	//deBugThis ("nbrParam = " + nbrParam);
	//deBugThis ("page = " + page);
	if (nbrParam == 4) {
		widthWindow = openPageInFrame.arguments[2];
		heightWindow = openPageInFrame.arguments[3];
	} else {
		widthWindow = 800;
		heightWindow = 600;
	}
	if (target.length) {
		var hasFrame=false;
		for(i=0;i<parent.frames.length;i++) { if (parent.frames[i].name==target) { hasFrame=true; break;}}
		if (hasFrame==true) {
			parent.frames[target].location = page;
		} else {
			// location MUST be no for final version for Edit/View
			if (target == "Edit" | target == "Edit2" | target == "View"| target == "Print") { wf = "location=yes, resizable=yes, scrollbars=yes ,width=680, height=1200"; }
			else if (target == "Popup") { wf = "location=no, resizable=no, scrollbars=yes ,width=480, height=480"; }
			else if (target == "Video") { wf = "location=no, resizable=no, scrollbars=yes ,width=560, height=560"; }
			else if (target == "ViewEmail") { wf = "location=no, resizable=yes, scrollbars=yes ,width=688, height=1200"; }
			else if (target == "ViewImage") { wf = "location=no, resizable=yes, scrollbars=yes ,width=740, height=800, scrollbars=no"; }
			else if (target == "ViewSlideShow") { wf = "toolbar=no, location=no, directories=no, status=yes, resizable=yes, scrollbars=yes, menubar=no, copyhistory=no, width=1600, height=1200"; }
			//else if (target == "ViewSlideShow") { wf = "fullscreen=yes"; }
			else if (target == "ViewPano") { wf = "location=no, resizable=yes, scrollbars=yes ,width=" + widthWindow + ", height=" + heightWindow; }
			else { wf = "resizable=yes, scrollbars=yes, menubar=yes, toolbar=yes, directories=yes, location=yes, status=yes"; }
			//deBugThis ("open window " + target + wf);
			popupWindow = window.open (page,target,wf);
			popupWindow.focus();
		}
	}
	else location = page;
}


// open photo in popup window called Photo
function openPopupPhoto(page,width,height) {
	//deBugThis ("open window " + page + ": "+ width + "/" + height);
	wf = "location=no, resizable=no, scrollbars=yes ,width=" + width + ", height=" + height;
	//deBugThis ("open window " + target + wf);
	// if window photo exist then window.close('Photo');
	window.open (page,'Photo',wf);
}



// follow the link href or not
function clickReturn () {
	var bAgent = window.navigator.userAgent; 
	var bAppName = window.navigator.appName;
	if ((bAppName.indexOf("Explorer") >= 0) && (bAgent.indexOf("Mozilla/3") >= 0) && (bAgent.indexOf("Mac") >= 0))
		return true; // dont follow link
	else return false; // dont follow link
}




// hide all layers name_1 to name_n & show layer name_x (using visibility)
function showHideAll(name,n,x){
	//deBugThis ("show/hide all " + name + "(n/x) : " + n + "/" + x);
	// if n < 0 -> 0 index must be included
	if (n < 0) { i0 = 0; n = (-1 * n) - 1; } else { i0 = 1; }
	//deBugThis ("show/hide all from " + i0 + " to " + n + " : " + name + "(n/x) : " + n + "/" + x);
	for (var i=i0;i<=n;i++)	{ targetID = name + i; if (i==x) { CSSetStyleVis(targetID,1); } else { CSSetStyleVis(targetID,0); } }
	//deBugThis ("done");
}



// hide all layers name_1 to name_n & show layer name_x (using display)
function showHideDisAll(name,n,x){
	// if n < 0 -> 0 index must be included
	if (n < 0) { i0 = 0; n = (-1 * n) - 1; } else { i0 = 1; }
	for (var i=i0;i<=n;i++)	{ targetID = name + i; if (i==x) { CSSetStyleDis(targetID,1); } else { CSSetStyleDis(targetID,0); } }
}



// change visibility of layer
// visibility : 0=hide 1=show 2=toggle
function showHide(targetID, visibility) {
	//deBugThis ("show/hide " + targetID + " : " + visibility);
	//alert ("show/hide " + targetID + " : " + visibility);
	if (targetID == '') return;
	if(visibility==0) CSSetStyleVis(targetID,0);
	else if(visibility==1) CSSetStyleVis(targetID,1);
	else if(visibility==2) { 
		if (CSGetStyleVis(targetID) == 0) CSSetStyleVis(targetID,1);
		else CSSetStyleVis(targetID,0);
	}
	//alert ("show/hide done");
}



// change display of layer
// visibility : 0=none 1=block 2=toggle
function showHideDis(targetID, display) {
	if (targetID == '') return;
	if(display==0) CSSetStyleDis(targetID,0);
	else if(display==1) CSSetStyleDis(targetID,1);
	else if(display==2) { 
		if (CSGetStyleDis(targetID) == 0) CSSetStyleDis(targetID,1);
		else CSSetStyleDis(targetID,0);
	}
}



// go back one step in history
function CSGoBack1() { history.back() }




// change path of href of an image called by a name
function changeImage(imageName,fileName) {
	//deBugThis("imageName=" + imageName + "  fileName=" + fileName);
	//document.all(imageName).src = fileName; // this is for IE4 only but not safari
	//document.getElementById(imageName).src = fileName; // this is for WC3
	// apparently this call works in all browsers!!!
	document.images[imageName].src = fileName; // this is for NN4 & safari
}


// resize window to fixed width/height
function ResizeWindow(width,height) { 
	//deBugThis("Resize window to : " + width + "/" + height);
	if (screen.width < 1024) { width = 800; height = 600; }
	if (navigator.appVersion.charAt(0) >=4) { window.resizeTo (width,height) }
}



// toggle z-level of floating box targetId with z-level value
function changeDivLevel(targetId, zlevel){
	//deBugThis("toggle box " + targetId + " to " + zlevel);
	//target = document.all(targetId); // this is for IE4 only but not safari
	//target = document.all(targetId); // this is for IE4 only but not safari
	//target = document.getElementById(targetId);
	
	if (document.layers) {
		document.targetId.style.zIndex = zlevel;
	} else {
		if (document.getElementById) {
			target = document.getElementById(targetId).style.zIndex;
		} else {
			if (document.all) {
				document.all.targetId.style.zIndex = zlevel;

	      	}
	  	}
	}
	
	//deBugThis (target);
	//target.style.zIndex = zlevel;
}


// print a page (top window)
function printDocument(frame){
	alert("Please only print this page if necessary, save trees!");
	window.print();
	//window.close();
}



// print a page
function printDocumentOLD(frame){
//deBugThis(navigator.appName .indexOf("3.0"));
	if (navigator.appName .indexOf("Microsoft") == -1 && navigator.platform.indexOf("Mac") != -1 || navigator.appVersion.indexOf("3.0") != -1) {
		deBugThis("Please use your browser\'s print command to print this document.");
	} else { 
		(frame != "") ? (parent.frames[frame].print()) : (parent.print());
	}
}


// popup list that directly links to url when activated
function URLPopupShow(formName, popupName, target) {
	//deBugThis ("formName = " + formName + " / popupName = " + popupName + " / target = " + target);
	var form  = document.forms[formName];
	var popup = form.elements[popupName];
	urlName = popup.options[popup.selectedIndex].value;
	//deBugThis ("urlName = " + urlName);
	window.open(urlName, target);
	popup.selectedIndex = 0;
}


// on change value of a popup -> copy new value into a hidden field
function changePopupValue(formName, popupName, target) {
	//deBugThis ("formName = " + formName + " / popupName = " + popupName + " / target = " + target);
	var form  = document.forms[formName];
	var popup = form.elements[popupName];
	//deBugThis ("popupValue = " + popupValue);
	form.elements[target].value = popup.options[popup.selectedIndex].value;
}


// check resolution and write cookie with width x height value
function writeResolutionCookie(cookieName) {
	resolution = screen.width +"x"+ screen.height;
	SetCookie(cookieName,resolution);
	//deBugThis (resolution);
	//location = gotoPage;
 }



// check resolution and write cookie with width x height value
function writeSetupCookie(cookieName) {
	setup = screen.width + "-x-" + screen.height + "-x-" + BrowserDetect.OS + "-o-" + BrowserDetect.browser + "-o-" + BrowserDetect.version;
	//alert ( "Browser name : " +  BrowserDetect.browser + " - Browser version : " + BrowserDetect.version + " - OS name : " + BrowserDetect.OS );
	SetCookie(cookieName,setup);
	//deBugThis (setup);
	//location = gotoPage;
 }



// test if a frame exists
function testIfExistsFrame(frame) {
	//deBugThis ("Testing frames... " + parent.frames.length);
	var hasFrame=false;
	if (parent.frames.length > 0) {
		for(i=0;i<parent.frames.length;i++) { 
			//deBugThis ("this frame " + i + " : " + parent.frames[i].name);
			if (parent.frames[i].name==frame) { 
				hasFrame=true; break;
			}
		}
	}
	return hasFrame;
 }



// reload home page if subpage opens in wrong frameset
function reloadHomePageIfNoFrame(access,homePage,target) {
	if (testIfExistsFrame(target)) { 
		//deBugThis ("this page opens in the right frameset");
	} else {
		if (access == "admin") {
			deBugThis ("this page should have opened in a frameset, but doesn't -> reload home page : " + homePage);
		} else {
			openPageInFrame (homePage,'');
		}
	}
 }

// returns subfolder based on image_id or image filename
function getImageSubFolder(GWPic) {
	//$GWSplit = split("_",$GWPic);
	//$PicCode = $GWSplit[0];
	//$PicNumber = $GWSplit[1];
	//$PicNumber = str_replace(".jpg","",$PicNumber);
	//$PicNumber = str_replace(".psd","",$PicNumber);
	//$PicNumber = str_replace(".nef","",$PicNumber);
	//$PureNumber = 1*$PicNumber;
	//$BaseNumber = floor($PureNumber/500);
	//$NumberMin = substr(1000000+($BaseNumber*500)+1,1,6);
	//$NumberMax = substr(1000000+($BaseNumber+1)*500,1,6);
	//$PathSubFolder = $PicCode."_".$NumberMin."-".$NumberMax;
	//return $PathSubFolder;
}


// setup timer id for animation
var aniTimerID = 0;
var aniLoop = true;
var aniLoopX = 9;


// play animation movie from sceneStart to sceneEnd with a duration (millisec) for each scene (sceneID)
function playAniMovie(sceneID, sceneStart, sceneEnd, duration) {

	// timer is set to 0
    var timer = 0;
	
	timerX = timer * duration;
	aniTimerID = setTimeout("void(); ",(timerX));
	Msg = "void() - " + timerX;
	timer++;			

    // loop from start to end & inject the functions to do in set time out
	for (k = 0; k < aniLoopX; k++) {
		for (i = sceneStart; i < sceneEnd; i++) {
			j = i + 1;
			if (aniLoop && j == sceneEnd) { j = sceneStart; timer++; }
			timerX = timer * duration;
			aniTimerID = setTimeout("fadeOutIn('" + sceneID + i + "','" + sceneID + j + "', 3000); ",(timerX));
			Msg = Msg + "\rfadeOutIn " + sceneID + i + " - " + sceneID + j + " - " + timerX;
			timer++;
		}
	}
	//alert(Msg);
}


// stop animation movie defined by aniTimerID setTimeout
function stopAniMovie() {
	clearTimeout (aniTimerID);
}


// fade out one element (idout) and fade in (idin) the other in the same time
// at the beginning, idout is visible & idin is hidden, both at 100% opacity
// at the end, idin is visible & idout is hidden, both at 100% opacity
function fadeOutIn(idout, idin, millisec) {
 	//alert("Fade Out-" + idout + " In-" + idin);
 
	// speed is divided by 100 because of opacity 0-100
    var speed = Math.round(millisec/100);
	// timer is set to 0
    var timer = 0;
	// opacity 0-100 range
	var opacStart = 0;
	var opacEnd = 100;
	
	// change opacity of idin to 0% & make it visible
	changeOpac(0, idin); 
	showHide(idin,1);
	
	// change opacity of Text & Title of idout to 0% and make it invisible
	idoutTitle = idout + "_Title"; changeOpac(0,idoutTitle); showHide(idoutTitle,0);
	idoutText = idout + "_Text"; changeOpac(0,idoutText); showHide(idoutText,0);
	
	// change opacity of Text & Title of idin to 100% and make it visible
	idinTitle = idin + "_Title"; changeOpac(100,idinTitle); showHide(idinTitle,1);
	idinText = idin + "_Text"; changeOpac(100,idinText); showHide(idinText,1);
	
    // loop from start to end & inject the functions to do in setTimeout
	// the calculated value of timer * speed is to tell setTimeout to run the instruction only after some delay
	for (i = opacStart; i <= opacEnd; i++) {
		j = opacEnd - i;
		if (i == opacEnd) {
			// increase opacity of idout (less visible) + decrease opacity of idin (more visible)
			// + make idout hidden & change its opacity to 100% at the end
			setTimeout("changeOpac(" + i + ",'" + idin + "'); changeOpac(" + j + ",'" + idout + "'); showHide('" + idout + "',0); changeOpac(100, '" + idout + "');",(timer * speed));
		} else {
			// increase opacity of idout (less visible) + decrease opacity of idin (more visible)
			setTimeout("changeOpac(" + i + ",'" + idin + "'); changeOpac(" + j + ",'" + idout + "')",(timer * speed));
		}
		timer++;
	}
	
}


//change the opacity for different browsers
function changeOpac(opacity, id) {
	//alert ("Change Opacity of " + id + " to " + opacity);
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
} 


// browser detection
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

BrowserDetect.init();

// return height of div
function getDivHeight($DivID) {
  var boxHeight = document.getElementById($DivID).offsetHeight;
  //alert(boxHeight);
  return boxHeight;
}



// calculate line total + grand totals
// i = line number starting at 0
// j = column number starting at 0 (0 = Qt | 1 = EXCL | 2 = VAT | 3 = INCL)
// k = element number in form
// x = total nbr of lines
// z = nbr of fields per line
function calculateOrderTotal(formName,i,j,x,z) {
	k = (i * z) + j; // 9 fields on line : Qt | Name | Code | UnitEXCL | BaseVAT | Weight | EXCL | VAT | INCL
	q = (i * z); // element number for each Qt on line
	x = x - 1;
	Qt = document[formName].elements[q].value; // Qt value
	UnitEXCL = document[formName].elements[q+3].value; // UnitEXCL value
	BaseVAT = document[formName].elements[q+4].value; // BaseVAT value
	BaseWeight = document[formName].elements[q+5].value; // BaseWeight value
	if (j == 0) { // if Qt change
		EXCL = Qt * UnitEXCL;
		VAT = Qt * UnitEXCL * BaseVAT;
		INCL = EXCL + VAT;
		Weight = Qt * BaseWeight;
		//alert ("Qt=" + Qt + " - UnitEXCL=" + UnitEXCL + " - BaseVAT=" + BaseVAT + " - EXCL=" + EXCL + " - VAT=" + VAT + " - INCL=" + INCL);
		document[formName].elements[q+5].value = Weight.toFixed(2);
		document[formName].elements[q+6].value = EXCL.toFixed(2);
		document[formName].elements[q+7].value = VAT.toFixed(2);
		document[formName].elements[q+8].value = INCL.toFixed(2);
	}
	
	if (j == 6) { // if EXCL change (i.e. donation)
		EXCL = 1 * document[formName].elements[q+6].value; // EXCL value
		VAT = EXCL * BaseVAT;
		INCL = EXCL + VAT;
		//alert ("Qt=" + Qt + " - UnitEXCL=" + UnitEXCL + " - BaseVAT=" + BaseVAT + " - EXCL=" + EXCL + " - VAT=" + VAT + " - INCL=" + INCL);
		document[formName].elements[q+7].value = VAT.toFixed(2);
		document[formName].elements[q+8].value = INCL.toFixed(2);
	}
	
	// calculate shipping cost
	q = (x * z); // element number for last Qt on form
	Delivery = document[formName].elements[q].value; // Qt value
	if (Delivery < 0 || Delivery > 1) { Delivery = 1; }
	UnitEXCL = document[formName].elements[q+3].value; // UnitEXCL value for shipping
	BaseVAT = document[formName].elements[q+4].value; // BaseVAT value for shipping
	//alert ("q=" + q + " - UnitEXCL=" + UnitEXCL + " - BaseVAT=" + BaseVAT + " - Delivery=" + Delivery);
	// shipping cost via PTO
	// each book with packaging < 1 kg
	// econoparcel (< 1 kg) @ R17.05 (1 book with packaging)
	// ordinary parcel (>1 <2 kg) @ R28.35 (2 books with packaging)
	// >3 books @ R3.80 per kg (>2 books)
	TotW = 0;
	for (a = 0; a < x; a++) {
		q = (a * z);
		Qt = document[formName].elements[q].value; // Qt value
		Weight = 1 * document[formName].elements[q+5].value; // BaseWeight value
		TotW = TotW + Weight;
	}
	//alert ("TotW=" + TotW);
	if (TotW == 0) {
		PriceFactor = 0;
	} else if (TotW < 1) {
		PriceFactor = 1;
	} else if (TotW >= 1 && TotW < 2) {
		PriceFactor = 1.7;
	} else if (TotW >= 2) {
		PriceFactor = 1.7 + (TotW / 4);
	}
	EXCL = Delivery * PriceFactor * UnitEXCL;
	VAT = Delivery * PriceFactor * UnitEXCL * BaseVAT;
	INCL = EXCL + VAT;
	//alert ("Delivery=" + Delivery + " - PriceFactor=" + PriceFactor + " - UnitEXCL=" + UnitEXCL + " - BaseVAT=" + BaseVAT + " - EXCL=" + EXCL + " - VAT=" + VAT + " - INCL=" + INCL);
	q = (x * z); // element number for last Qt on form
	document[formName].elements[q].value = Delivery;
	document[formName].elements[q+5].value = Weight.toFixed(2);
	document[formName].elements[q+6].value = EXCL.toFixed(2);
	document[formName].elements[q+7].value = VAT.toFixed(2);
	document[formName].elements[q+8].value = INCL.toFixed(2);		

	
	// recalculate grand totals
	TotEXCL = 0;
	TotVAT = 0;
	TotINCL = 0;
	TotW = 0;
	Line = "";
	for (a = 0; a <= x; a++) {
		q = (a * z);
		Weight = 1 * document[formName].elements[q+5].value; // Weight value
		EXCL = 1 * document[formName].elements[q+6].value; // EXCL value
		VAT = 1 * document[formName].elements[q+7].value; // VAT value
		INCL = 1 * document[formName].elements[q+8].value; // INCL value
		//alert ("a/x/q=" + a + "/" + x + "/" + q + "Weight=" + Weight + " - EXCL=" + EXCL + " - VAT=" + VAT + " - INCL=" + INCL);
		TotEXCL = TotEXCL + EXCL;
		TotVAT = TotVAT + VAT;
		TotINCL = TotINCL + INCL;
		if (a < x) { TotW = TotW + Weight; } // do no include weight of shipping
		
		// compose order summary
		Qt = document[formName].elements[q].value; // Qt value
		Name = document[formName].elements[q+1].value; // Name value
		Code = document[formName].elements[q+2].value; // Code value
		Line = Line + Qt + ";" + Code + ";" + Name + ";" + EXCL + ";" + VAT + ";" + INCL + "\n";
		
	}
	//alert ("TotEXCL=" + TotEXCL + " - TotVAT=" + TotVAT + " - TotINCL=" + TotINCL);
	q = ((x + 1) * z);
	document[formName].elements[q].value = TotW.toFixed(2);
	document[formName].elements[q+1].value = TotEXCL.toFixed(2);
	document[formName].elements[q+2].value = TotVAT.toFixed(2);
	document[formName].elements[q+3].value = TotINCL.toFixed(2);
	
	// change field order in Form_OrderCalculator
	document['Form_OrderCalculator'].elements['Order'].value = Line;

	// change fields in Form_PGWvcs
	//document['Form_PGWvcs'].elements['m_1'].value = Line;
	document['Form_PGWvcs'].elements['p4'].value = TotINCL.toFixed(2); // total incl VAT

	// change field order in Form_Enquiry
	//document['Form_Enquiry'].elements['Order'].value = Line;


}

