var isns = (navigator.appName.indexOf('Netscape')<0)?0:1;
var d = document;
var isie  = document.all ? 1 : 0;
var isns4 = document.layers ? 1 : 0;
var isdom = document.getElementById ? 1 : 0;

var userType = "";

function outputObjectTree(objectroot,showEmpty) {
	var output = "";
		for (property in objectroot) {
			switch (property) {

				default:
					if (showEmpty)
						output = output + property + " = " + objectroot[property] + ";";
					else if ((objectroot[property] != null) & (objectroot[property] != ""))
						output = output + property + " = " + objectroot[property] + ";"; 
			}
		}
	alert(output);
}

function outputObject(objectroot,iteration) {
	var output = "";
	indent = "";
	for (i=0;i<iteration;i++) {
		indent = indent + "    ";
	}
	for (property in objectroot) {
		if (typeof(objectroot[property])=="object") {
			output = output + "[" + property + "] =>\r\n" + outputObject(objectroot[property],iteration+1);
		} else if ((objectroot[property] != null) & (objectroot[property] != "")) {
			output = output + indent + "[" + property + "]" + " = " + objectroot[property] + ";\r\n"; 
		}
	}
	if (iteration==1) alert(output);
	else return output;
}

function enable_proceed() {
   if(document.forms[0].R1[0].checked == true) {
     document.forms[0].PROCEED.disabled=false;
   } else {
     document.forms[0].PROCEED.disabled=true;
   }
}

function ErrorMsg(errNum) {
    switch(errNum) {
        case 1:
			 document.forms['CHANGE_PWD'].elements["curpwd"].focus();
             break;
        case 2:
             alert("The current password you entered is incorrect!" );
			 document.forms['CHANGE_PWD'].elements["curpwd"].focus();
			 document.forms['CHANGE_PWD'].elements["curpwd"].select();	 
             break;
        case 3:
             alert("New password cannot be blank!");
			 document.forms['CHANGE_PWD'].elements["newpwd"].focus();	 
             break;
        case 4:
             alert("New password and current password cannot be the same!");
			 document.forms['CHANGE_PWD'].elements["newpwd"].focus();
			 document.forms['CHANGE_PWD'].elements["newpwd"].select();			 		 
             break;
        case 5:
             alert("New password and verification password do not match!");
			 document.forms['CHANGE_PWD'].elements["verpwd"].focus();
			 document.forms['CHANGE_PWD'].elements["verpwd"].select();			 			 
             break;
        case 6:
             alert("Password updated successfully.");	 
             location.replace("welcome.php");
             break;
        default :
             alert("Unknown error please notify cordell by email at\r\n ebulletin@cordell.com.au");
             break;
    }
}

function dataRefresh(catid,entryid,fName) {
	iframeObj = document.frames("data");	
	iframeObj.location = "data.php?catID="+catid+"&entryID="+entryid+"&fName="+fName;	
}

// Get the dimensions of the passed object
function getDivRect(divType,i) {
	divId = "tbl"+divType + i;
	menuObj = document.getElementById(divId);
	var obj = new Object;
	obj.top = menuObj.offsetTop;
	obj.left = menuObj.offsetLeft;
	obj.bottom = menuObj.offsetTop+menuObj.offsetHeight;
	obj.right = menuObj.offsetLeft+menuObj.offsetWidth;
	return obj;
}

function dims(t,l,b,r) {
	var obj = new Object;
	obj.top = t;
	obj.left = l;
	obj.bottom = b;
	obj.right = r;
	return obj;
}

function dimArray() {
	var args = dimArray.arguments;
	var argsl = args.length;
	var dimArr = new Array();
	for (i=0;i<argsl;i++) {
		dimArr[i]=args[i];
	}
	return dimArr;
}

function showCat(catid) {
	moveLocationTo("main.php?cat_id="+catid);
}

function showMenu_bak(divId) {
	var subdiv = document.getElementById("sub" + divId);
	var x = subdiv.offsetLeft;
	var y = subdiv.offsetHeight;
	var subdivimage = document.getElementById("i" + divId);
	var catdiv = document.getElementById("cat" + divId);
	var body = document.getElementById("body");
	if (subdiv.style.display != "block" ) {
        subdiv.style.display = "block";
		tmpsrc = subdivimage.src;
        subdivimage.src = subdivimage.lowsrc;
		subdivimage.lowsrc = tmpsrc;
		//scroll the selected element to the top of the frame
		body.scrollTop = catdiv.offsetTop;
		return true;
    } else {
        subdiv.style.display = "none";
        tmpsrc = subdivimage.src;
        subdivimage.src = subdivimage.lowsrc;
		subdivimage.lowsrc = tmpsrc;
		return false;
    }
}

function maximizeWindow() {
	window.moveTo(0,0);
	window.resizeTo(screen.width,screen.height);
}

function scrollTo(divId) {
	var catdiv = isdom ? d.getElementById("cat" + divId) : isie ? d.all["cat" + divId] : d.layers["main"].layers["cat" + divId];
	var scrollDiv = isdom ? d.getElementById("scrollDiv") : isie ? d.all["scrollDiv"] : d.layers["main"].layers["scrollDiv"];
	scrollDiv.scrollTop = catdiv.offsetTop;
}

function scrollEnd(divId) {
	var datagriddiv = isdom ? d.getElementById(divId) : isie ? d.all[divId] : d.layers[divId];
	datagriddiv.scrollTop = datagriddiv.scrollHeight;
}

function showData(catid,entryid) {
	//set the location in the data window to show the data for this category
	//and for the entry if passed
	moveDataTo("data.php?cat_id="+catid+"&entry_id="+entryid);
}

function showPDF(fName) {
	//set the location in the data frame to show the appropriate pdf file
	moveDataTo("data.php?fName="+fName);
}

// dynamically set the coordinates for the menu object if supported else use those passed
function showmenu(i,x,y) {
	yOffset = isns ? 13 : 12;
	xOffset = 0;
	if (!isns4) {
		menuItem = isdom ? d.getElementById("m"+i) : d.all["m"+i];
		navbar = (i != 6)?"topnav":"subnav";
		menubar = isdom ? d.getElementById(navbar) : d.all[navbar];	
		dmMenu = isdom ? d.getElementById("tblmenu"+i) : d.all["tblmenu"+i];
		y = menuItem.offsetTop + yOffset;
		x = menuItem.offsetLeft + xOffset;
		//if the menuitem overflows align it to the right
		if (i != 6) {
			menuEnd = x+dmMenu.offsetWidth;
			menuBarEnd = isdom ? d.getElementById("menubarend").offsetLeft : d.all["menubarend"].offsetLeft;
			x= x-((menuEnd > menuBarEnd)?(menuEnd-menuBarEnd):0);
		}
	} else {
		menuItem = document.layers["main"].layers["m"+i];
		//objectTree(menuItem,true);
		//x = menuItem.pageX;
		//y = menuItem.pageY;
	}
	
	//set the position of the dm
	var menuDiv = isdom ? d.getElementById("menu"+i+"Container") : isie ? d.all["menu"+i+"Container"] : d.layers["main"].layers["menu"+i+"Container"];
	menuStyle = isns4 ? menuDiv : menuDiv.style;
	menuStyle.top = y;
	menuStyle.left = x;
	
	//set the zIndex to force the menu to the front
	menuStyle.zIndex = 10;
	var contentDiv = isdom ? d.getElementById("menu"+i+"Content") : isie ? d.all["menu"+i+"Content"] : d.layers["main"].layers["menu"+i+"Container"].layers["menu"+i+"Content"];
	contentStyle = isns4 ? contentDiv : contentDiv.style;
	contentStyle.zIndex = 10;

	//show the menu
	slideOutMenu.showMenu("menu"+i);

}

// Hide the menu
function hidemenu(i) {
	//set the position of the dm
	var menuDiv = isdom ? d.getElementById("menu"+i+"Container") : isie ? d.all["menu"+i+"Container"] : d.layers["main"].layers["menu"+i+"Container"];
	menuStyle = isns4 ? menuDiv : menuDiv.style;
	
	//set the zIndex to force the menu to the front
	menuStyle.zIndex = 9;
	var contentDiv = isdom ? d.getElementById("menu"+i+"Content") : isie ? d.all["menu"+i+"Content"] : d.layers["main"].layers["menu"+i+"Container"].layers["menu"+i+"Content"];
	contentStyle = isns4 ? contentDiv : contentDiv.style;
	contentStyle.zIndex = 9;
	slideOutMenu.hideMenu("menu"+i);
}

function showsubscriptions (i,x,y) {
	
	yOffset = isns?-1:-1;
	xOffset = 0;
	if (!isns4) {
		menuitem = isdom ? d.getElementById("s"+i) : d.all["s"+i];
		offsets = objOffset (menuitem);
		subscriptions =  isdom ? d.getElementById("tblmenu"+i) : d.all["tblmenu"+i];
		y = offsets.offsetTop + yOffset;
		x = offsets.offsetLeft + xOffset;
	} else {
		// use the x, y co-ordinates passed
		menuitem = d.layers["main"].layers["s"+i];
		//objectTree(menuitem,true);
	}
	
	//set the position of the prodDiv
	var containerDiv = isdom ? d.getElementById("menu"+i+"Container") : isie ? d.all["menu"+i+"Container"] : d.layers["main"].layers["menu"+i+"Container"];
	containerStyle = isns4 ? containerDiv : containerDiv.style;
	containerStyle.top = y;
	containerStyle.left = x;
	
	//set the zIndex to force the menu to the front
	containerStyle.zIndex = 10;
	var contentDiv = isdom ? d.getElementById("menu"+i+"Content") : isie ? d.all["menu"+i+"Content"] : d.layers["main"].layers["menu"+i+"Container"].layers["menu"+i+"Content"];
	contentStyle = isns4 ? contentDiv : contentDiv.style;
	contentStyle.zIndex = 10;
	
	//show the menu
	slideOutMenu.showMenu("menu"+i);
}

// Hide the menu
function hidesubscriptions(i) {
	
	var menuDiv = isdom ? d.getElementById("menu"+i+"Container") : isie ? d.all["menu"+i+"Container"] : d.layers["main"].layers["menu"+i+"Container"];
	menuStyle = isns4 ? menuDiv : menuDiv.style;
	
	//set the zIndex to force the menu to the front
	menuStyle.zIndex = 9;
	var contentDiv = isdom ? d.getElementById("menu"+i+"Content") : isie ? d.all["menu"+i+"Content"] : d.layers["main"].layers["menu"+i+"Container"].layers["menu"+i+"Content"];
	contentStyle = isns4 ? contentDiv : contentDiv.style;
	contentStyle.zIndex = 9;
	slideOutMenu.hideMenu("menu"+i);
}

function objOffset (obj) {
	// recursively calls itself until there are no more parent objects adding offset values as it goes
	var objOffset = new Object;
	objOffset.offsetTop = 0;
	objOffset.offsetLeft = 0;
	while (obj != null) {
		objOffset.offsetTop = objOffset.offsetTop + obj.offsetTop;
		objOffset.offsetLeft = objOffset.offsetLeft + obj.offsetLeft;
		obj = obj.offsetParent;
	}
	return objOffset;
}

var currentTab = null;

function changeTab(tabId) 
{
	var newTabElement = document.getElementById("tab" + tabId);
	newTabElement.style.background = "#080055";
	newTabElement.style.color = "White";
	
	showTabDiv(tabId);
	if (currentTab != null) {
		var currentTabElement = document.getElementById("tab" + currentTab);
		currentTabElement.style.background = "#cccccc";			
		currentTabElement.style.color = "#080055";
		showTabDiv(currentTab);
	}
	currentTab = tabId;
}

function showTabDiv(divId) {
	var divstyle = document.getElementById("div" + divId).style;
	if (divstyle.display != "block") {
		divstyle.display = "block";
	} else {
		divstyle.display = "none";
	}
}

var currentRecipe = 0;

function showRecipeDiv(divId) 
{
	var divstyle = document.getElementById("ingredientsDiv" + divId).style;
	if (divstyle.display != "block") {
		divstyle.display = "block";
	} else {
		divstyle.display = "none";
	}
	var divstyle = document.getElementById("ingredientsDiv" + currentRecipe).style;
	if (divstyle.display != "block") {
		divstyle.display = "block";
	} else {
		divstyle.display = "none";
	}
	currentRecipe = divId;
}

function logout(){
	moveLocationTo('login.php?logout=true');
}

function doNada() {
}

function moveLocationTo(loc) {
	location = loc;
}

function moveDataTo(newLoc){
	parent.window.data.location = newLoc;
}

function moveResultsTo(newLoc) {
	window.results.location = newLoc;
}

var contextCatID=0;
var contextEntryID=0;
var contextItemID=0;
var border=0;

function showContextMenu(linkObj,recType,catid,entryid,itemid,defaultRecipe,e) { 
	contextType=linkObj.id;
	contextTypeType=linkObj.name;
	contextCatID=catid;
	contextEntryID=entryid;
	contextItemID=itemid;
	//alert(contextType+"-"+recType+"-"+catid+"-"+entryid+"-"+itemid+"-"+defaultRecipe+"-"+e);
	
	switch (contextType) {
		case "cat":
			var contextObj = isdom ? d.getElementById("catContextMenu") : isie ? d.all["catContextMenu"] : d.layers["catContextMenu"];
			var contextFrm = d.forms["catContextFrm"];
			//alert ("cat");
         break;
		case "entry":
			var contextObj = isdom ? d.getElementById("entryContextMenu") : isie ? d.all["entryContextMenu"] : d.layers["entryContextMenu"];
			var contextFrm = d.forms["entryContextFrm"];
			var heading = (contextTypeType=="H")?true:false;
			contextFrm.menuOpen.disabled = heading;
			contextFrm.menuInsertItem.disabled = heading;
			//alert ("entry");
			break;
		case "item":
			var contextObj = isdom ? d.getElementById("itemContextMenu") : isie ? d.all["itemContextMenu"] : d.layers["itemContextMenu"];
			var contextFrm = d.forms["itemContextFrm"];
			var sys_recipe = (contextTypeType=="sys_recipe")?true:false;
			var user_recipe = (contextTypeType=="user_recipe")?true:false;
			var isDefault = ((contextTypeType=="user_recipe")&&(itemid=="u"+defaultRecipe))?true:false;
			contextFrm.menuOpen.disabled = !(sys_recipe||user_recipe);
			contextFrm.menuDefaultRecipe.disabled = !user_recipe;
			contextFrm.menuAddRecipe.disabled = isDefault;
			contextFrm.menuItemAdjust.disabled = ((recType=="user")||(contextTypeType!="component"))?true:false;
			//alert ("item");
			break;
		default: // must be an entry
			alert("Invalid Context Type.");
	}
	
	//alert(contextObj.id);
	switch (recType) {
		case "user":
			//contextFrm.menuInsertItem.disabled = false;//samantha
			//contextFrm.menuInsertEntry = false;
			contextFrm.menuUp.disabled = false;
			contextFrm.menuDown.disabled = false;
			contextFrm.menuDelete.disabled = false;
			contextFrm.menuEdit.disabled = false;
			userType = "user"; //samantha
			//alert ("user");
			break;
		case "system":
			//contextFrm.menuInsertItem.disabled = true;
			//contextFrm.menuInsertEntry = true;
			contextFrm.menuUp.disabled = true;
			contextFrm.menuDown.disabled = true;
			contextFrm.menuDelete.disabled = true;
			contextFrm.menuEdit.disabled = true;
			userType = "system"; //samantha
			//alert ("system");
			break;
	}
	
	contextStyle = isns4 ? contextObj : contextObj.style;
	contextStyle.posLeft=0;
	contextStyle.posTop=0;
	
	var posx = 0;
	var posy = 0;
	
	//Working out floating menu box position --- BEGIN
	var isIE = (navigator.userAgent.indexOf('MSIE') != -1) ;
	
	if (!e)  var e = window.event;     		
	
	if (e.pageX || e.pageY)
	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY)
	{
		/*posx = e.clientX;
		posy = e.clientY;
		if (isIE)
		{
			alert("IE");
			posx += document.body.scrollLeft;
			posy += document.body.scrollTop;
		} */
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
		
	}
	//contextStyle.posLeft=e.clientX+10;
	contextStyle.left=e.clientX+10;
	
	if (180+e.clientY > 575) 
	{	
		//contextStyle.posTop=posy-((e.clientY+190)-575);	
		contextStyle.top=posy-((e.clientY+190)-575);	
	}	
	else 
	{	
		//contextStyle.posTop=posy;	
		contextStyle.top=posy;
	}
	//Working out floating menu box position --- END
	contextStyle.border = "thin solid #696969";
	contextStyle.height = "auto";
	contextStyle.display="block";
	
	//if (isie) 
	//{	contextObj.setCapture(false);	}
}

function clickCatContext(e) {
	var contextObj = isdom ? d.getElementById("catContextMenu") : isie ? d.all["catContextMenu"] : d.layers["catContextMenu"];
	contextStyle = isns4 ? contextObj : contextObj.style;
	//contextObj.releaseCapture();
	contextStyle.display="none";
	
	//el=window.event.srcElement;
	var el;
	if (!e)
	{	var e = window.event;	}
	
	if (e.target)
	{	el = e.target;	}
	else if (e.srcElement)
	{	el = e.srcElement;	}
	
	
	switch(el.id) {
		case "menuOpen":
			showData(contextCatID,contextEntryID);
			break;
		case "menuInsertCat":
			moveDataTo("db_record.php?action_type=add&record_type=cat&cat_id="+contextCatID);
			break;
		case "menuInsertEntry":
			if (userType=="user")//samantha
	    	{
			moveDataTo("db_record.php?action_type=add&record_type=entry&cat_id="+contextCatID);
			}
			else
		    {
				alert("You can not Inset a group into system items,select & expand the category item and add your group");
		    }
			break;
		case "menuUp":
			if (userType=="user")//samantha
	    	{
			moveLocationTo("db_record.php?action_type=swap&record_type=catUp&cat_id="+contextCatID);
			}
			else
		    {
				alert("You can not move up system items");
		    }
			break;
		case "menuDown":
			if (userType=="user")//samantha
	    	{
			moveLocationTo("db_record.php?action_type=swap&record_type=catDown&cat_id="+contextCatID);
			}
			else
		    {
				alert("You can not move down system items");
		    }
			break;
		case "menuDelete":
			if (userType=="user")//samantha
	    	{
				if (confirm("Are you sure you want to DELETE this category and all sub entries?")) {
				moveLocationTo("db_record.php?action_type=delete&record_type=cat&cat_id="+contextCatID);}
			}
			else
		    {
				alert("You can not delete system items");
		    }
			
			break;
		case "menuEdit":
			if (userType=="user")//samantha
	    	{
		 	moveDataTo("db_record.php?action_type=edit&record_type=cat&cat_id="+contextCatID);
			}
			else
		    {
				alert("You can not edit system items");
		    }
			break;
		case "menuCancel":
			// do nothing just close the menu
			break;
		default :
			break;
	}
}

function clickEntryContext(e) {
	var contextObj = isdom ? d.getElementById("entryContextMenu") : isie ? d.all["entryContextMenu"] : d.layers["entryContextMenu"];
	contextStyle = isns4 ? contextObj : contextObj.style;
	//contextObj.releaseCapture();
	contextStyle.display="none";
	
	var el;
	if (!e)
	{	var e = window.event;	}
	
	if (e.target)
	{	el = e.target;	}
	else if (e.srcElement)
	{	el = e.srcElement;	}
	//el=window.event.srcElement;
	
	switch(el.id) {
		case "menuOpen":
			showData(contextCatID,contextEntryID);
			break;
		case "menuInsertEntry":
			moveDataTo("db_record.php?action_type=add&record_type=entry&cat_id="+contextCatID);
			break;
		case "menuInsertItem":
			if (userType=="user")//samantha
			{
				moveDataTo("db_record.php?action_type=add&record_type=item&cat_id="+contextCatID+"&entry_id="+contextEntryID);
			}
			else
			{
				alert ("You cannot insert items in system components");
				
			}
			break;
		case "menuUp":
			if (userType=="user")//samantha
			{
				moveLocationTo("db_record.php?action_type=swap&record_type=entryUp&cat_id="+contextCatID+"&entry_id="+contextEntryID);
			}
			else
		    {
				alert ("You cannot move up system items");
            }
			//moveLocationTo("db_record.php?action_type=swap&record_type=entryUp&cat_id="+contextCatID+"&entry_id="+contextEntryID);
			break;
		case "menuDown":
			if (userType=="user")//samantha
			{
				moveLocationTo("db_record.php?action_type=swap&record_type=entryDown&cat_id="+contextCatID+"&entry_id="+contextEntryID);
			}
			else
			{
			  alert ("You cannot move down system items");
	        }
			break;
		case "menuDelete":
			if (userType=="user")//samantha
			{
				if (confirm("Are you sure you want to DELETE this group and all sub items?")) {
					moveLocationTo("db_record.php?action_type=delete&record_type=entry&cat_id="+contextCatID+"&entry_id="+contextEntryID);
				}
			}
			else
			{
				alert ("You cannot delete system items");
			}
			/*if (confirm("Are you sure you want to DELETE this group and all sub items?")) {
			moveLocationTo("db_record.php?action_type=delete&record_type=entry&cat_id="+contextCatID+"&entry_id="+contextEntryID);
			}*/
			break;
		case "menuEdit":
			if (userType=="user")//samantha
			{
				moveDataTo("db_record.php?action_type=edit&record_type=entry&cat_id="+contextCatID+"&entry_id="+contextEntryID);
			}
			else
			{
				alert ("You cannot Edit system items");
			}
			break;
		case "menuCancel":
			// do nothing just close the menu
			break;
		default :
			break;
	}
}

function clickItemContext(e) {
	var contextObj = isdom ? d.getElementById("itemContextMenu") : isie ? d.all["itemContextMenu"] : d.layers["itemContextMenu"];
	contextStyle = isns4 ? contextObj : contextObj.style;
	//contextObj.releaseCapture();
	contextStyle.display="none";
	
	var el;
	if (!e)
	{	var e = window.event;	}
	
	if (e.target)
	{	el = e.target;	}
	else if (e.srcElement)
	{	el = e.srcElement;	}
	
	//el=window.event.srcElement;
		
	
	switch(el.id) {
		case "menuOpen":
			showData(contextCatID,contextEntryID);
			break;
		case "menuItemAdjust":
			moveDataTo("db_record.php?action_type=add&record_type=adjustment&cat_id="+contextCatID+"&entry_id="+contextEntryID+"&item_id="+contextItemID);
			break;
		case "menuAddEstimate":
			moveResultsTo("estimates.php?action_type=add_item&record_type=item&cat_id="+contextCatID+"&entry_id="+contextEntryID+"&item_id="+contextItemID);
			break;
		case "menuAddRecipe":
			moveResultsTo("db_record.php?action_type=add_recipe&record_type=item&cat_id="+contextCatID+"&entry_id="+contextEntryID+"&item_id="+contextItemID);
			break;
		case "menuDefaultRecipe":
			moveDataTo("db_record.php?action_type=default_recipe&record_type=item&cat_id="+contextCatID+"&entry_id="+contextEntryID+"&item_id="+contextItemID);
			break;
		case "menuUp":
			moveLocationTo("db_record.php?action_type=swap&record_type=itemUp&cat_id="+contextCatID+"&entry_id="+contextEntryID+"&item_id="+contextItemID);
			break;
		case "menuDown":
			moveLocationTo("db_record.php?action_type=swap&record_type=itemDown&cat_id="+contextCatID+"&entry_id="+contextEntryID+"&item_id="+contextItemID);
			break;
		case "menuDelete":
			if (confirm("Are you sure you want to DELETE this item?")) {
				moveDataTo("db_record.php?action_type=delete&record_type=item&cat_id="+contextCatID+"&entry_id="+contextEntryID+"&item_id="+contextItemID);
			}
			break;
		case "menuEdit":
			moveDataTo("db_record.php?action_type=edit&record_type=item&cat_id="+contextCatID+"&entry_id="+contextEntryID+"&item_id="+contextItemID);
			break;
		case "menuCancel":
			// do nothing just close the menu
			break;
		default :
			break;
	}
}

function switchMenu(e) {
	//el = window.event.srcElement;	}
	
	var el;
	if (!e)
	{	var e = window.event;	}
	
	if (e.target)
	{	el = e.target;	}
	else if (e.srcElement)
	{	el = e.srcElement;	}
	//alert(el.className);
	
	if (el.className == "contextButton") {
		if (!el.disabled) el.className="contextButtonH";
	} else if (el.className == "contextButtonH") {
		el.className="contextButton";
	}
}

function showDivWindow(divId)
{
	var ele = document.getElementById(divId);
   if(ele.style.display == "none") ele.style.display = "block";
   else                            ele.style.display = "none";
}

var currentEntry = false;
function highlightEntry(tdObj) {
	if (currentEntry!=false) currentEntry.className="";
	tdObj.className = "highlighted";
	currentEntry = tdObj;
}

function openEstimate(est_id) {
	window.open("estimate.php?action_type=NORMAL&est_id="+est_id,"","toolbar=0,location=0,directories=0,fullscreen=0,status=1,menubar=0,scrollbars=0,resizable=1");
	return false;
}

function openTemplate(temp_id) {
	window.open("template.php?action_type=NORMAL&temp_id="+temp_id,"","toolbar=0,location=0,directories=0,fullscreen=0,status=1,menubar=0,scrollbars=0,resizable=1");
	return false;
}

function openReports(est_id) {
	window.open("reports.php?est_id="+est_id,"","width=300, height=270,toolbar=0,location=0,directories=0,fullscreen=0,status=1,menubar=1,scrollbars=0,resizable=1");
	return false;
}

function openPriceRequest(cid,username,supplier_id,est_id) {
	window.open("http://reports.rcd.com.au/testreport.php?cid="+cid+"&username="+username+"&supplier_id="+supplier_id+"&est_id="+est_id+"&report_type=price_request","","width=300, height=200,toolbar=0,location=0,directories=0,fullscreen=0,status=1,menubar=1,scrollbars=0,resizable=1");
	return false;
}

function openPriceRequestC(cid,username,supplier_id,est_id) {
	window.open("http://reports.rcd.com.au/testreport.php?cid="+cid+"&username="+username+"&supplier_id="+supplier_id+"&est_id="+est_id+"&report_type=price_request_c","","width=300, height=200,toolbar=0,location=0,directories=0,fullscreen=0,status=1,menubar=1,scrollbars=0,resizable=1");
	return false;
}

function openHelp() {
	window.open("http://estimator.rcd.com.au/help.php","","toolbar=0,location=0,directories=0,fullscreen=0,status=1,menubar=1,scrollbars=0,resizable=1");
	return false;
}

function checkLastEntered(passed_obj) {
	//Filters out all alpha characters
	passed_value = passed_obj.value;

	if (isNaN(passed_value)) {
		//Now loop through each character and reconstruct string without alpha chars
		var temp_concat = "";
		var current_char = "";
		for (i=0;i<passed_value.length;i++) {
			lengthTo = i+1;
			last_char = current_char;
			current_char = passed_value.substring(i,lengthTo);
			if ((i==0) && (current_char==".")) {
				temp_concat += "0"+current_char;
			} else if ((i==0) && (current_char=="-")) {
				temp_concat += current_char;
			} else if ((i==1)&&(current_char==".")&&(last_char=="-")) {
				temp_concat += "0"+current_char;
			} else {
				if (!isNaN(current_char)) {
					temp_concat += current_char;
				}
			}
		}
		passed_obj.value = temp_concat;
	}
}

function cursorKeys(event, cellObj) {
	var rownum = parseInt(cellObj.form.id.substr(4));
	var colnums = new Object;
   colnums["row_num"]=1;
	colnums["qty"]=2;
	colnums["unit"]=3;
	colnums["labour"]=4;
	colnums["materials"]=5;
	colnums["plant"]=6;
	colnums["subcontractor"]=7;
	colnums["checkbox"]=8;
	var colnum = colnums[cellObj.id];
	switch (event.keyCode) {
		case 37: //Leftarrow
			if (colnum==1) {
				colnum=8;
				rownum--;
			} else {
				colnum--;
			}
			gotoNextItem(rownum,colnum);
			break;
		case 38: //Uparrow
			if (rownum>0) rownum--;
			gotoNextItem(rownum,colnum);
			break;
		case 39: //Rightarrow
			if (colnum==8) {
				colnum=1;
				rownum++;
			} else {
				colnum++;
			}
			gotoNextItem(rownum,colnum);
			break;
		case 40: //Downarrow
			rownum++;
			gotoNextItem(rownum,colnum);
			break;
		default:		
	}

}

function gotoNextItem(rownum,colnum) {
	var colnames = new Array()
   colnames[1]="row_num";
	colnames[2]="qty";
	colnames[3]="unit";
	colnames[4]="labour";
	colnames[5]="materials";
	colnames[6]="plant";
	colnames[7]="subcontractor";
	colnames[8]="checkbox";
	eval("var nextObj = d.forms.item"+rownum+"."+colnames[colnum]);
	nextObj.focus();
	nextObj.select();
}

function roundTo(val) { 
	var t;
	var s=new String(Math.round(val*100));
	while (s.length<3) 
		s='0'+s;
	return s.substr(0, t=(s.length-2)) + '.' + s.substr(t, 2);
}

function roundToF(value)
{
   return round_decimals(value, 2);
}



/* This script is Copyright (c) Paul McFedries and 
Logophilia Limited (http://www.mcfedries.com/).
Permission is granted to use this script as long as 
this Copyright notice remains in place.*/

function round_decimals(original_number, decimals) {
    var result1 = original_number * Math.pow(10, decimals)
    var result2 = Math.round(result1)
    var result3 = result2 / Math.pow(10, decimals)
    return pad_with_zeros(result3, decimals)
}

function pad_with_zeros(rounded_value, decimal_places) {

    // Convert the number to a string
    var value_string = rounded_value.toString()
    
    // Locate the decimal point
    var decimal_location = value_string.indexOf(".")

    // Is there a decimal point?
    if (decimal_location == -1) {
        
        // If no, then all decimal places will be padded with 0s
        decimal_part_length = 0
        
        // If decimal_places is greater than zero, tack on a decimal point
        value_string += decimal_places > 0 ? "." : ""
    }
    else {

        // If yes, then only the extra decimal places will be padded with 0s
        decimal_part_length = value_string.length - decimal_location - 1
    }
    
    // Calculate the number of decimal places that need to be padded with 0s
    var pad_total = decimal_places - decimal_part_length
    
    if (pad_total > 0) {
        
        // Pad the string with 0s
        for (var counter = 1; counter <= pad_total; counter++) 
            value_string += "0"
        }
    return value_string
}

/* (end script) */

function currencyFormat(amount,delimiter) {
	amount = new String(amount);
	var a = amount.split('.',2);
	var d = a[1];
	var i = parseInt(a[0]);
	if (isNaN(i)) return "";
	var minus = '';
	if (i < 0) minus = '-';
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3) {
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) a.unshift(n);
	n = a.join(delimiter);
	if(d.length < 1) amount = n;
	else amount = n + '.' + d;
	amount = minus + amount;
	return amount;
}


function roundNumber(val,dps) { 
	var t;
	var s=new String(Math.round(val*100));
	while (s.length<=dps) 
		s='0'+s;
	return s.substr(0, t=(s.length-dps)) + '.' + s.substr(t, dps);
}

// form valiadation functions

function isEmailAddr(email)
{
  var result = false;
  var theStr = new String(email);
  var index = theStr.indexOf("@");
  if (index > 0)
  {
    var pindex = theStr.indexOf(".",index);
    if ((pindex > index+1) && (theStr.length > pindex+1))
	result = true;
  }
  return result;
}

function isEmailAddress(address) {
	var s = "", re;

	s = "" + address + "";
	//x@x.xx is the smallest address => length must be greater than 5 to continue.
	s = s.replace(/^\s*|\s*$/g, "");
	if (s == "undefined" || s.length < 6) return false;
	//test for spaces before checking syntax. spaces are illegal 
	re = /\s+/g;
	if (re.test(s)) return false;
	// remove apostrophe's as they are valid but I don't know how to include them in the reg exp below.
	s = s.replace(/'/, "");
	//validate email address syntax and remove any emails that don't match the basic syntax pattern below.
	re = /^(\w|[^_]\.|[\-])+((\@){1}([^_]))(([a-z]|[\d]|[\-]|\.)+|([^_]\.[^_])*)+\.[a-z]{2,6}$/i;
	if (!re.test(s)) return false;
	//validate domain part of the email against all known TLDs as of May 2001 
	re = /\.(a[c-gil-oq-uwz]|b[a-bd-jm-or-tvwyz]|c[acdf-ik-orsuvx-z]|d[ejkmoz]|e[ceghr-u]|f[i-kmorx]|g[abd-ilmnp-uwy]|h[kmnrtu]|i[delm-oq-t]|j[emop]|k[eg-imnprwyz]|l[a-cikr-vy]|m[acdghk-z]|n[ace-giloprtuz]|om|p[ae-hk-nrtwy]|qa|r[eouw]|s[a-eg-ort-vyz]|t[cdf-hjkm-prtvwz]|u[agkmsyz]|v[aceginu]|w[fs]|y[etu]|z[admrw]|com|edu|net|org|mil|gov|biz|pro|aero|coop|info|name|museum)$/i;
	if (!re.test(s)) return false;
	//check for '..'
	re = /\.\./;
	if (re.test(s)) return false;
	//check for '@@'
	re = /\@\@/;
	return(!re.test(s));
}

function validRequired(formField,fieldLabel) {
	var result = true;
	if (formField.value == "") {
		alert('Please enter a value for the "' + fieldLabel +'" field.');
		formField.focus();
		result = false;
	}
	return result;
}

function allDigits(str) {
	return inValidCharSet(str,"0123456789");
}

function inValidCharSet(str,charset) {
	var result = true;
	// Note: doesn't use regular expressions to avoid early Mac browser bugs	
	for (var i=0;i<str.length;i++)
		if (charset.indexOf(str.substr(i,1))<0) {
			result = false;
			break;
		}
	return result;
}

function validEmail(formField,fieldLabel,required) {
	var result = true;
	if (required && !validRequired(formField,fieldLabel)) result = false;
	if (result && !isEmailAddress(formField.value)) {
		alert("This field should be a complete email address in the form: yourname@yourdomain.com");
		formField.focus();
		result = false;
	}
  return result;
}

function validNum(formField,fieldLabel,required) {
	var result = true;
	if (required && !validRequired(formField,fieldLabel)) result = false;
 	if (result) {
 		if (!allDigits(formField.value)) {
 			alert(fieldLabel);
			formField.focus();		
			result = false;
		}
	} 
	return result;
}

function validInt(formField,fieldLabel,required) {
	var result = true;
	if (required && !validRequired(formField,fieldLabel)) result = false;
 	if (result) {
 		var num = parseInt(formField.value);
 		if (isNaN(num)) {
 			alert(fieldLabel);
			formField.focus();		
			result = false;
		}
	} 
	return result;
}

function validDate(formField,fieldLabel,required) {
	var result = true;
	if (required && !validRequired(formField,fieldLabel)) result = false;
 	if (result) {
 		var elems = formField.value.split("/");
 		result = (elems.length == 3); // should be three components
 		if (result) {
 			var month = parseInt(elems[0]);
  			var day = parseInt(elems[1]);
 			var year = parseInt(elems[2]);
			result = allDigits(elems[0]) && (month > 0) && (month < 13) &&
					 allDigits(elems[1]) && (day > 0) && (day < 32) &&
					 allDigits(elems[2]) && ((elems[2].length == 2) || (elems[2].length == 4));
 		}
  		if (!result) {
 			alert('Please enter a date in the format MM/DD/YYYY.');
			formField.focus();		
		}
	} 
	return result;
}


function confirmExit()
  {
    return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
  }