/**********************************************************************************************
 * JAFFA - Java Application Framework For All - Copyright (C) 2002 JAFFA Development Group
 *
 * This library is free software; you can redistribute it and/or modify it under the terms
 * of the GNU Lesser General Public License (version 2.1 any later).
 * 
 * See http://jaffa.sourceforge.net/site/legal.html for more details.
 *********************************************************************************************/

//////////////////////////////////////
// PageHeader.js - Page Header Java Script
// By Paul Extance
//
// Should be included at the top of the Outer Page.
// In the case of PageLayouts and Panels, this should be 
// included once in the panel.
//
// The WebWidgets rely on functions in this file
//
// Version: 1.0a
// Modified: 28-Jun-2001 
////////////////////////////////////////////////////
// Modified the postForm function to support packing
// data for lazy widgets, and to build extra form fields
// into an XML document and post as a hidden field
//
// Version: 1.1
// Modified: 1-Aug-2001 
////////////////////////////////////////////////////


// Variable to hold Error Messages
var messageList = new Array();
var index = 0;
// Get the value of a page level cookie based on name
// Returns null if cookie not found
function getCookie(name) {
	//Load cookie
	var allcookies = document.cookie;
	//alert("Looking For Cookie :" + allcookies);
	var pos = allcookies.indexOf(name + "=");
	if(pos != -1) {
		//alert("Found Cookie");
	        var start = pos + name.length + 1;
	        var end = allcookies.indexOf(";", start);
	        if(end==-1) end = allcookies.length;
	        value = unescape(allcookies.substring(start, end));
                //alert("Cookie " + name + "=" + value);
                return value;
	} else {
                return null;
        }
}


// Find the next field to prompt to.....
// The next field is either the next higher anywhere
// Or one with the same index later on.
function nextField(field) {
	
	fieldTab = field.tabIndex;
	
	if(fieldTab == "" || fieldTab == null) fieldTba = 0;
	sameField = null;
	higherField = null;
	passedCurrent = false;
	//new code that actually works
	var indexOfField;
	for(var d = 0; d < document.forms.length; d++) {
			for(var e = 0; e < document.forms[d].elements.length; e++) {
							if (e != elements.length - 1) {
								if (document.forms[d].elements[e] == field) {
									return document.forms[d].elements[e+1];
								} else {
									return document.forms[d].elements[0];
								}
							}
			}
	}



/*
	for(var d = 0; d < document.forms.length; d++) {
		for(var e = 0; e < document.forms[d].elements.length; e++) {
		
			if(passedCurrent && document.forms[d].elements[e].tabIndex == fieldTab && sameField == null) {
				sameField = document.forms[d].elements[e];
				status = "Found Same Index";
			}
			if(document.forms[d].elements[e].tabIndex > fieldTab)
				if(higherField == null || (document.forms[d].elements[e].tabIndex < higherField.tabIndex) ) {
					higherField = document.forms[d].elements[e];
					status = "Found Higher Field";
				}

			if(document.forms[d].elements[e].id == field.id)
				// At the current field
				status = "Found Same Field";
				passedCurrent = true;
		}
	}
*/
	if (sameField != null) return sameField;
	return higherField;
}


// Common routine used to post the form.
// This should always be used, NEVER use the form.submit() directly!
// The field is optional, but if specified it will go to the next field on return
function preProcess(frm, fld) {
	
	debug("Posting Form...");
	var xml = ""
	for(var i = 0; i < document.forms.length; i++) {
		var formObj = document.forms[i];
		var cf = (formObj == frm);
		debug("Processing Form :" + formObj.name + " " + cf);
		if(!cf) {
			xml += "<form name=\""+ formObj.name + "\">\n";
		}
		for(var j = 0; j < formObj.elements.length; j++) {
			var el = formObj.elements[j];
			if(el.name != "")
				debug("Looking at Element: " + el.name + "," + el.className.substr(0,6));
			if(el.name != "" && el.className.substr(0,6) == "Widget") {
				debug("Found Widget: " + el.name);
				var widgetName = el.className.substr(6);
				var name;
				// Take the WV of the end of the widget
				if(el.name.substr(el.name.length-2)=="WV")
					name = el.name.substr(0, el.name.length-2);
				else
					name = el.name;

				try {
					if(widgetName=="TableTree")
						tableTreePack(formObj, name);
					else if(widgetName=="Grid")
						gridPack(formObj, name);
					else if(widgetName=="UserGrid"){
						userGridPack(formObj, name);
						}
					else if(widgetName=="Tree")
						treePack(formObj, name);
					else {
                        	                debug("Widget: " + el.name + " = " + el.value);
						// This is an active widget, encode if needed
               					if(!cf) {
			        		       // if this is not the form being posted make the active widgets data XML friendly	
			        		       el.value = toXML(el.value);
				        	}
					}
				} catch (e) {
					alert("Error When Packing Widget\nForm :" + formObj.name + "\nField :" + name +"\nWidget Type :" + widgetName +"\nReason:" + e.message);
				}
				
				// if this is not the form being posted then write to XML Buffer
            			if(!cf && (widgetName != "RadioButton" || (widgetName == "RadioButton" && el.checked))) {
					xml += "<widget name=\""+ name + "\">" + el.value + "</widget>\n";
					debug("XML Now is\n" + xml);
				}
			}
		}			
		if(!cf) {
			xml += "</form>\n";
		}
	}
        // Incase there is no hidden field, ignore this...
	try { frm.extraContext.value = xml; } catch (e) {}

	var curr = "";
        if(fld != null) curr = fld.id;
	document.cookie = "focus=" + curr;
}

function postForm(frm, fld) {
        debug("Doing form submit NOW...");
        preProcess(frm, fld);
	frm.submit();
}

// Convert a string in to an XML Friendly String
// Used by various widgets for packing data
function toXML(txt) {
	var regexp = /&/g
	var s = txt.replace(regexp, "&amp;");
	regexp = /</g
	s = s.replace(regexp, "&lt;");
	regexp = />/g
	s = s.replace(regexp, "&gt;");
	regexp = /'/g
	s = s.replace(regexp, "&apos;");
	regexp = /"/g
	s = s.replace(regexp, "&quot;");
	return s;
}


// Control Debug Messages...
function debug(msg) {
        // Uncomment for messages...
	//alert(msg);
}


// Display Error Messages
function showMessages(i) {
    if (i < messageList.length) {
        document.getElementById("msg").innerText = messageList[i];
    }
}

function previous() {
    if (index != 0) {
    index--;
    showMessages(index);
   if (document.getElementById("calendardd") != null) {
        document.getElementById("calendardd").disabled = false;
    }
    }
}

function next() {
    if (index < messageList.length - 1) {
    index++;
    showMessages(index);
       if (document.getElementById("calendardd") != null) {
        document.getElementById("calendardd").disabled = false;
    }
    }
}

function okerror() {
	document.all.errorBox.style.display = "none" ;
   if (document.getElementById("calendardd") != null) {
        document.getElementById("calendardd").disabled = true;
    }
}

// Add an Error Message to the variable
function addMessage(ermsg) {
    messageList[messageList.length] = ermsg;
}


function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v3.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


function expand(spanId , imageName , expandOnly) {

    pathname = location.pathname;
    myDomain = pathname.substring(0,pathname.lastIndexOf('/')) +'/';


    if (expandOnly == null) {

		if (document.getElementById(spanId).style.display == "none") {
			MM_swapImage(imageName,'','jaffa/imgs/foldingsection/arrowminimize.gif',1);
			document.getElementById(spanId).style.display = "block";
			setCookieId(spanId , true);
		} else {
			MM_swapImage(imageName,'','jaffa/imgs/foldingsection/arrowexpand.gif',1);
			document.getElementById(spanId).style.display = "none";
			setCookieId(spanId , false);
		}
    } else {
    
    			MM_swapImage(imageName,'','jaffa/imgs/foldingsection/arrowminimize.gif',1);
    			window.location.hash = spanId + "section";
    			document.getElementById(spanId).style.display = "block";
			setCookieId(spanId , true);
    }
}

  function setCookieId(spanId , boolValue) {
    
 
   var curcookie = getCookieId(spanId);
   document.cookie=spanId+"="+boolValue+";";
   var cookieafter = getCookieId(spanId);

 }
 
  function getCookieId(spanId) {
    var data;
    if (document.cookie) {
      index=document.cookie.indexOf(spanId);
      if (index != -1) {
        namestart=(document.cookie.indexOf("=",index)+1);
        nameend=document.cookie.indexOf(";",index);
        if (nameend==-1) {
          nameend=document.cookie.length;
        }
        data=document.cookie.substring(namestart,nameend);
        return data;
      }
    }
    return null;
  }
  
  function setDefaultState(spanId , imageName) {	
	if (getCookieId(spanId) == "false") {
	    expand(spanId , imageName);
	}
	
  }

function initialExpand(spanId , imageName) {
    if (getCookieId(spanId) == null) {
	    expand(spanId , imageName);
     } else {
     	    setDefaultState(spanId , imageName);
     }
}

