var gBrowser = "";
var ua = navigator.userAgent.toLowerCase();
var browsers = ["msie 5","msie 6","msie 7","gecko","safari"];
for (var i in browsers) {
	if (ua.indexOf(browsers[i]) > 1) {
		gBrowser = browsers[i];
	}
}
if (gBrowser=="gecko") {
	if (parseInt(navigator.productSub.substring(0,4)) < 2005) {
	 	//older versions of netscape/firefox
		gBrowser = "";
	}
}
var gOS = "";
if (ua.indexOf("mac") > 1) { gOS = "mac"; }
else if (ua.indexOf("windows") > 1) { gOS = "win"; }

/* previous method of browser detection (stop using) */
var ns = (window.Event) ? true : false;   // test for Netscape 4 & 6
var nsie5 = (document.documentElement) ? true : false;
if (nsie5) {
  var ieStrict = (document.documentElement.clientWidth > 0) ? true : false;
}
var ns6 = (ns && nsie5);
var ie = (document.all && ua.indexOf("msie")>1) ? true : false; 
var os_mac = (ua.indexOf("mac") > 1);
var mac = ( ie && os_mac ) ? true : false;
var ie5 = ( !mac && (ua.indexOf("msie 5.0") > 1) ) ? true : false;
var opera = (ua.indexOf("opera") != -1);
var safari = (ua.indexOf("safari") != -1);
var konq = (ua.indexOf("konquerer") != -1);

var checkBoxVal, menuStyle, gRow;
var submitted = 0;
var gTimeoutId = null, whenOpen = 0, menuOn = null, gMenuLink = null;

/* dhtml menu z-index must be 200+ */
/* these defaults should be overridden by specific site */
var gMenuStyles = null;
var gMenuXoffset, gMenuXoffsetMac, gMenuYoffset, gMenuYoffsetMac, gMenuYoffsetIe5;
var gQpMacLeft = 0, gQpMacTop = 0;
var wwEditor, fmWindow, _editor_version;
var gLang = getLang().substring(0,2).toLowerCase();
var gEmailsChecked = false;

function getElem(elemID) {
	return document.getElementById(elemID);
}

function getFormElem(nameOrId, index) {
	var el = null;
	for (var i=0; i<document.forms.length; i++) {
		if (document.forms[i].elements[nameOrId]) {
			el = document.forms[i].elements[nameOrId];
			break;
		}
	}
	if (!el) {
		if (getElem(nameOrId)) {
			el = getElem(nameOrId);
		} else {
		/* in case elem is not in a form (illegal):*/
			inputs = document.getElementsByTagName("INPUT");
			for (var i=0; i<inputs.length; i++) {
				if (inputs[i].name == nameOrId) {
					el = inputs[i];
					break;
				}
			}
		}
	} 
	if (el && index != null && el.length) return el[index];
	return el; //index is null or zero (el is not array);
}

function getTextNode(el) { //not used?
	return el.innerText || el.innerHTML.replace(/<[^>]+>/g, "").replace(/^\s+/, "").replace(/\s+$/, "");
}

function brSetup() {
	if (typeof beforeBrSetup == "function") { beforeBrSetup(); }
	if (gBrowser=="" || gOS=="") {
      try {
      	if (/\/((home|index)\.html)?/.test(location.pathname)) { // dont annoy people by showing error on every page, only home pages
        	alert(msg_incorrectBrowser);
      	}
      } catch (e) { //for older js that may not like regex
      	alert(msg_incorrectBrowser);
      }
	} 
  	switch (gBrowser) {
  		case "gecko" : 
  		case "safari" : //not tested yet
  			document.onclick = function (e) { return hideMenu(e); }; 
		 	document.onmouseover = function (e) { overTest(e); };
		 	break;
		case "msie 6" :
		case "msie 5" :
  			document.body.insertAdjacentHTML('beforeEnd','<!--[if lte IE 6]><iframe id="menuShim" src="javascript:false;" scrolling="no" frameborder="0" style="position:absolute;display:none;z-index:199;"></iframe><![endif]-->');
  			//falls thru
  		default: //all IE
  			document.onclick = hideMenu; 
		 	document.onmouseover = overTest;
	}
  	reportRequested = false;
  	if (getElem("loginForm")) {
        if (!navigator.cookieEnabled) alert(msg_CookiesDisabled);
        un = getFormElem("j_username");
        if (un) {
			un.focus();
			un.select();
        } 
  	} else if (getElem("wwArea")) {
  		if (typeof HTMLArea == "undefined") { alert("WYSIweb did not load properly. Try refreshing the page, or contact support@wysiweb.com."); return; }
  		HTMLArea.loadPlugin("ContextMenu");
  		if (typeof wwStyleMenu == "object") {
  			HTMLArea.loadPlugin("CSS");
  		}
  	 	HTMLArea.loadPlugin("TableOperations");
	  	//if(HTMLArea.is_gecko) HTMLArea.loadPlugin("EnterParagraphs");
  	 	getElem("wwArea").form.reset(); 
		HTMLArea.init();
		ww = getElem("wysiWeb");
		// if ww is a form, it is normal ww page; otherwise ww is a td and ww is a field
		brWwSetup((ww && ww.tagName.toLowerCase() != "form"));
  	} else {
  		if (getElem("listTable")) { //test for bedrock list
    		listSetup();
    	} else { 
  			brFindEmails();
  		} 
    	checkForCalendar();
  		findCurrency();
  		if (typeof reportPopup != "undefined") { makeReportPopup(); } 
  	} 
  	if (typeof afterBrSetup == "function") { afterBrSetup(); }
}

submitted = 0; //reset var for mac
// pageshow event fires in FF 1.5+ when page loads whether from cache or server; 
// load event does not fire when page loads from memory cache,
// so this solves back btn issue when form submitted
window.onpageshow = function() { submitted = 0; }; 

function moveup() {
	// dummy function 
}
function quickPick() {
	// dummy function for when bedrock_list.js has not yet loaded
}

function checkForCalendar() {
	var di = document.images;
	for (var i = di.length; --i > -1; ) {
		if (di[i].className=="calendarIcon") {
			brAddScript("/bedrock/date_picker.js");
			break;
		}
	}
}

function brAddScript(fileName) {
	//if (mac) {
	//	document.body.innerHTML += ('<scr' + 'ipt type="text/javascript" src="' + fileName + '"><\/script>');
	//} else if (nsie5) {
		var s = document.createElement('script');
		s.src = fileName;
    	document.body.appendChild(s);
	//}
}

function brCheckAdmin(evt) {  
	evt = (evt) ? evt : (window.event) ? window.event : ""; //get event object
	if (evt.shiftKey) {
		location.href = "/admin/";
	} else {
		location.href = "/"; //go to home page
	}
}

function findCurrency() {
    var inputs = document.getElementsByTagName("INPUT");
    if (inputs.length) {
        for (var i=inputs.length; --i > -1;) {
            if (inputs[i].type=="text" && inputs[i].className.indexOf("currency")!=-1
             && typeof inputs[i].onchange != "function") {
         	 inputs[i].onchange = function() { formatCurrency(this); }
            }
        }
    }
}

var rxSpace = /(\s|&nbsp;)+/g;

function brParseCurr(str, lang) {
    if (typeof str != "string") str = str.value;
    if (!lang) lang = gLang;
    str = (lang=="fr") ? str.replace(/,/,".") : str.replace(/,/g,"");
    str = str.replace(rxSpace,"").replace(/\$/g,"");
    if (str.indexOf("(")!=-1) { //negative
    	str = "-" + str.replace(/\x28/g,"").replace(/\x29/g,"");//remove parentheses
    }
    num = Number(str);
    if (isNaN(num)) return 0;
    return Math.round(num * 100) / 100; //in case of extra decimal places
}

var rxCurrencyFormat = /([0-9]+)([0-9]{3})/;

function formatCurrency(obj, format, hideSymbol) {
	if (typeof obj != "number") {
		obj = obj ? obj : this; // obj can be string, number or an input object
		if (!obj) return;
	}
    var lang = "en", comma, period;
    if (!format) {
        if (gLang=="fr") { 
            format = "x,xx $";
        } else {
            format = "$x.xx";
        }
    }
    if (format.indexOf(".")!=-1) {
		period = ".";
		comma = ",";
    } else { //french
		period = ",";
		comma = " ";
		lang = "fr";
    }
    var num = (typeof obj == "number") ? obj : brParseCurr(obj, lang);
    if (num==0) return "0";
    var str = "" + Math.abs(Math.round(num * 100));
    while (str.length < 3) { // need at least 3 chars, so add leading zeros
		str = "0" + str;
    }
    var decPoint = str.length - 2;
    str = str.substring(0,decPoint) + period + str.substring(decPoint,str.length);
    //check for match to search criteria
    while(rxCurrencyFormat.test(str)) {
       //replace original string with first group match,
       //a comma, then second group match
       str = str.replace(rxCurrencyFormat, '$1' + comma + '$2');
    }
    if (period==".") {
        if (num<0) {
            str = "-$" + str;
        } else {
            str = "$" + str;
        }
    } else { //french
        if (num<0) {
            str = "(" + str + "$)"; 
        } else {
            str = str + " $";
        }
    }
    if (format.indexOf("$")==-1 || hideSymbol) str = str.replace(/\$/,"");
    if (typeof obj == "object") obj.value = str;
    else return str;
}

function getLang() {
    if (document.documentElement && document.documentElement.lang != "") return document.documentElement.lang;
    var props = ["language","userLanguage","browserLanguage","systemLanguage"];
    for (var i in props) {
        if (navigator[props[i]]) return navigator[props[i]];
    }
    return "";
}

function brToggleClass(elem,classStr) {
	cn = elem.className;
	indexOfClassStr = cn.indexOf(classStr);
	if (indexOfClassStr == -1) { // add class if not found
		elem.className = (cn != "") ? (cn + " " + classStr) : classStr;
	} else { // otherwise remove
		elem.className = stripSpaces(cn.replace(classStr,""));
	}
}

function brAddClass(elem,classStr) {
	cn = elem.className;
	if (!cn) elem.className = classStr;
	else if (cn.indexOf(classStr) == -1) { // only add if not found
		//ie mac cant deal with leading whitespace
		elem.className = (cn != "") ? (cn + " " + classStr) : classStr;
	} 
}

function brRemoveClass(elem,classStr) { 
	elem.className = stripSpaces(elem.className.replace(classStr,""));
}

function makeEmail(recipient,domain) {
	if (!domain) domain = location.host;
	if (domain.indexOf("www")==0) domain = domain.substring(4);
	return (recipient + "@" + domain);
}

function emailLink(recipient,domain) {
	addr = makeEmail(recipient,domain);
	return '<a href="mailto:' + addr + '">' + addr + '</a>';
}

function brMail(recipient,domain) {
	document.write(emailLink(recipient,domain));
}

function mail(recipient) {
	document.write(emailLink(recipient));
}

function brFindEmails(elem) {
//var rxLinkIsMail = /<a[^>]href=['"](mailto:)?ismail:([\w-_\.]+)/; //not finished
//var rxISMail = /ismail:([\w-_\.]+)%([\w-_]+\.[\w\.]+\b)/gi;
//var rxISMailRecip = /[\w-_\.]+\b/g;

	//if (!nsie5) return;
	if (gEmailsChecked || getElem("wysiWeb")) { return; }
	for (var i = 0; i < document.links.length; i++) {
		href = document.links[i].href.toLowerCase();
		if (href.indexOf("ismail:")==0) {
			document.links[i].href = "mailto:" + convertEmail(href);
		}
	} 
	if (!elem) elem = document.body;
	do { //keep checking all html until we catch all instances
		html = elem.innerHTML;
		x = html.toLowerCase().indexOf("ismail:");
		if (x !=- 1) {
			endChunk = html.substring(x+7);
			startChunk = html.substring(0,x);
			addr = "";
			fullAddress = endChunk.match(/^[\w-_]+%[\w-_]+\.\w+\b/);
			if (fullAddress) {
				addr = fullAddress[0].split("%");
				addr = emailLink(addr[0],addr[1]);
				endChunk = endChunk.substring(fullAddress[0].length);					
			} else {
				recip = endChunk.match(/^[\w-_]+\b/);
				if (recip) {
					addr = emailLink(recip[0]);
					endChunk = endChunk.substring(recip[0].length);
				}
			}
			elem.innerHTML = startChunk + addr + endChunk;
		}
	} while (x != -1) 
	gEmailsChecked = true; //prevent duplicate run in custom setup functions
}

function convertEmail(text) {
	addr = stripSpaces(text.substring(7));
	fullAddress = addr.match(/^[\w-_]+%[\w-_]+\.\w+\b/);
	if (fullAddress) {
		addr = fullAddress[0].split("%");
		return makeEmail(addr[0],addr[1]);
	} 
	if (addr.match(/^[\w-_]+$/)) {
		return makeEmail(addr);
	}
	return "";
}

function resetTimer() {
	today = new Date();
    whenOpen = today.getTime();
}

function overTest(e) {
  if (menuOn) {
    source = ns6 ? e.target : event.srcElement;
    if (source) {
	  if (source.tagName!="A") { 
        today = new Date();
        now = today.getTime();
        delay = 800;
        if ( (now - whenOpen) > delay ) { 
          hideMenu();
        }
      } else {
        resetTimer();
      } 
  	}
  } else if (gRow) {
  	brRemoveClass(gRow,"qpHilite");
  }
}

function hideMenu(e) {
 	if (!menuOn) { return; }
  	var menuStyle = getElem(menuOn).style;
    if (menuOn=="quickPick") {
	  	if (window.event) {
			targetObj = event.srcElement;
		} else {
			if ( (e) && (typeof e == "object") && (e.target) ) {
				targetObj = e.target;
			}
		}
    	if (targetObj && targetObj.tagName=="A" && targetObj.id.indexOf("qp")==0) {
			//QP item selected; wait a bit before hiding menu
    		qpEnabled=false;
    		targetObj.style.cursor = "wait";
			gTimeoutId = setTimeout("restoreMenu('" + targetObj.id + "')",1000);
			return;
    	} else {
			menuStyle.visibility = "hidden";
      		brRemoveClass(gRow,"qpHilite");
      	}
	} else {
		if (e && e.which && e.which != 1) { return true; } //allow context menu in Firefox
    	menuStyle.visibility = "hidden";
		loseHoverStyle();
	}
	if (getElem("menuShim")) {
		getElem("menuShim").style.display = "none";
	}
    menuOn = null;
}

function restoreMenu(linkId) {
	if (getElem("qpCheck")) qpEnabled = getElem("qpCheck").checked;
	getElem(linkId).style.cursor = "auto";
	brRemoveClass(gRow,"qpHilite");
	if (menuOn) getElem(menuOn).style.visibility = "hidden";
	if (getElem("menuShim")) {
		getElem("menuShim").style.display = "none";
	}
}

function checkWindows() {
	if (ua.indexOf("windows") == -1) {
		document.write(' <strong class="red">You do not appear to be using Windows.</strong>');
	}
}

function checkCookies() {
	if (!navigator.cookieEnabled) {
		document.write(' <span class="red">Cookies appear to be disabled in your browser.</span>');
	}

}

function checkIE() {
	ieOffset = ua.indexOf("msie ");
	version = parseFloat(ua.substring(ieOffset + 5, ua.indexOf(";", ieOffset)));
	if (ieOffset != -1) {
		document.write(' <span class="red">You appear to be using IE version ' + version + '.</span> ');
	} else {
		document.write(' <strong class="red">You do not appear to be using Internet Explorer.</strong>');
	}
}

function showMenu(linkObj) {
	//if ( nsie5 && (!getElem('wysiWeb')) ) {  this line used in DairyCheq
	if (!nsie5) return;
	if (menuOn) hideMenu();
	linkPath = linkObj.pathname;
	slash = (linkPath.indexOf("\\")>-1) ? "\\" : "/";
	menuID="nav-" + linkPath.substring(linkPath.lastIndexOf(slash)+1,linkPath.lastIndexOf("."));
	if (!getElem(menuID)) return;  // make sure menu exists (page may not be fully loaded)
	var menu = getElem(menuID); //menuStyle = getElem(menuID).style;
	Xpos = getOffset(linkObj,"offsetLeft") + (mac ? gMenuXoffsetMac : gMenuXoffset); // + (ns6 ? 1 : 0);
	Ypos = getOffset(linkObj,"offsetTop") + (ie5 ? gMenuYoffsetIe5 : gMenuYoffset) + (mac ? gMenuYoffsetMac : 0); // + (ns6 ? 1 : 0);
	Xpos += "px"; Ypos += "px"; 
	with (menu.style) {
		left = Xpos; top = Ypos;
		visibility = "visible";
	}
	if (getElem("menuShim")) {
		with (getElem("menuShim").style) {
			left = Xpos; top = Ypos;
			height = menu.offsetHeight + "px";
			width = menu.offsetWidth + "px";
			display = "block";
		}
	}
	menuOn = menuID;
	keepHoverStyle(linkObj);
	resetTimer();
}

function keepHoverStyle(linkObj) {
	if (gMenuStyles) { //  where gMenuStyles[x] = new Array(cssProperty, hoverValue, defaultValue);
		for (var i=0; i<gMenuStyles.length; i++) {
			linkObj.style[gMenuStyles[i][0]] = gMenuStyles[i][1];
		}
		gMenuLink = linkObj;
	}
}

function loseHoverStyle() {
	if (gMenuLink) {
		var selected = (gMenuLink.className.indexOf("selected") != -1);
		if (gMenuStyles != null) { 
		  for (var i=0; i<gMenuStyles.length; i++) {
			restoreStyle = selected ? "" : gMenuStyles[i][2];
			gMenuLink.style[gMenuStyles[i][0]] = restoreStyle;
			//eval("gMenuLink.style." + gMenuStyles[i][0] + " = '" + restoreStyle + "'");
	      }
		}
		gMenuLink = null;
	}
}

function getOffset(el,offset) { // from menubarAPI4.js, Copyright 2001 Garrett S. Smith, DHTMLkitchen.com
	return el[offset] + (el.offsetParent ? getOffset(el.offsetParent,offset) : 0);
}

function setSubmitCommand(val) {
	getFormElem("submitCommand").value = val;
}
	
function submitForm(val) {
	if (wwEditor) wwEditor.wwSave(true);
	with (getFormElem("submitCommand")) {
		value = val;
		form.submit();
	}
}

function submit() {
	getElem("viewList").submit();
}

function verifySubmit() {
	if (!submitted) {
		submitted = 1;
		return true;
	} else {
		alert(msg_formSubmitted);
		return false;
	}
}

function executeIdCommand(command) {
	var f = getElem("viewList") || getFormElem("listSelection").form;
	var ls = f.listSelection;
	var id = checkBoxVal;
	if (id == null || id == "") {
		if (!ls.length) ls = [ls]; //convert to array
		for (var i=0; i<ls.length; i++) {
			if (ls[i].checked) {
				id = ls[i].value;
				break;
			}
		}
	}
	if (id != null && id != "") {
		var idurl = f.elements[command].value;
		if (f.elements[command + "Javascript"] == null) {
			if (idurl.indexOf("?") == -1) {
				idurl = idurl + "?";
			} else {
				idurl = idurl + "&";
			}
			idurl = idurl + "id=" + id;
			changeLocation(idurl);
		} else {
			eval(idurl +"(" + id + ")");
		}			
	}
}

function changeLocation(location) {
	document.location.href = location;
}

function makePopUp(url,w,h,showMenuBar) {
	var features = "status,titlebar,resizable,scrollbars,width="+w+",height="+h;
	if (showMenuBar) {
		features = "menubar," + features;
	}
	var targ = "";
	if (typeof url == "object") { //could be link obj or url string
		targ = url.target || ""; // window name needed when target='popup'
		url = url.href;
	} 
	newWindow = window.open(url,targ,features);
	newWindow.focus();
	return false; //just in case onclick=return makepopup
}

function stripSpaces(str) { 
  //remove leading and trailing spaces
  return str.replace(/^\s*/, "").replace(/\s*$/, ""); 
}

function brFixLinks(isWwEditor) {
  var i, link, url, domain = location.host, rx = /\.pdf$/i;
  if (isWwEditor) { 
	url = getFormElem('url').value.replace(/https?:\/\//,"");
	domain = url.substring(0, url.indexOf("/"));
  }
  if (typeof msg_newWindow != "string") { msg_newWindow = "Opens in new window"; }
  for (i = document.links.length - 1; --i > -1; ) {
    link = document.links[i];
    if (link.target != "" || link.href.indexOf("http") != 0) { 
    	//it seems IE sometimes does not return complete URLs before onload complete? or when links altered by js?
    	continue; 
    }
    if (link.href.indexOf(domain) == -1 || rx.test(link.href) || link.className=="external") { //external link
      link.target = "_blank";
      link.title = msg_newWindow;
    } else if (isWwEditor && typeof link.onclick != "function") { //internal link
    	link.onclick = function () { // ww Site nav
    		return menuNav(null,this.href);
    	};
    }
  }
}

function brFixTables() {
  if (nsie5) {
	tblArray = document.getElementsByTagName("TABLE"); 
	for (t=0; t<tblArray.length; t++) {
		elem = tblArray[t];
		if (elem.className=="data") {
			colourRows(elem);
		}
	}
  }
}
function colourRows(tbl) { //give even rows of table a grey stripe
  for (i=0; (i<tbl.rows.length && tbl.rows[i].className.indexOf("noStripes")==-1); i++) {
    var r = tbl.rows[i];
    brAddClass(r.cells[r.cells.length - 1], "last");
    if (i==0) continue;
    if (r.className.indexOf("subHeader")==-1 && i%2==0) {
	    brAddClass(r, "stripe");
	}
  }
}

function changeWizardPage(wizardPage) {
	with (getFormElem("wizardPage")) {
		value = wizardPage;
		form.submit();	
	}
}


/*
** JavaScript Cookies Library (version 1.1)
** =====================================================
** You may use and/or modify this JavaScript library
** provided that you maintain this copyright header.
** Copyright 1999, Richard Scott (version 1.1). All rights reserved.
** Copyright 1997, Christopher Doemel (version 1.0). All rights reserved.
**   This library combines the best features of Dortch's cookie functions, 
**   and the object-oriented design of Flanagan's cookie example.
*/
function Cookie(name, expires, domain, path, isSecure)
{
  this.name     = name;
  this.expires  = expires;
  this.domain   = domain;
  this.path     = path;
  this.isSecure = isSecure;
}
function Cookie_get() {
  var theWholeCookie = document.cookie;
  var cookieStart = theWholeCookie.indexOf(this.name);
  if (cookieStart == -1)
    return "";  // The cookie wasn't found, so we return an empty string.
  else
    cookieStart += this.name.length + 1;  var cookieEnd = theWholeCookie.indexOf(";", cookieStart);
  if (cookieEnd == -1)
    cookieEnd = theWholeCookie.length;  var theCookie = theWholeCookie.substring(cookieStart, cookieEnd);
  return unescape(theCookie);
}

function Cookie_store(string)
  {
  document.cookie = 
    this.name + "=" + escape(string) + 
    ((this.expires) ? "; expires=" + this.expires.toGMTString() : "") + 
    ((this.path) ? "; path=" + this.path : "") + 
    ((this.domain) ? "; domain="  + this.domain : "") + 
    ((this.isSecure) ? "; secure" : "");
  }

function Cookie_del()
  {
  document.cookie = 
    this.name + "=" +
    ((this.expires) ? "; expires=" + (new Date(0)).toGMTString() : "") + 
    ((this.path) ? "; path=" + this.path : "") + 
    ((this.domain) ? "; domain=" + this.domain : "");
  }

new Cookie();  // need to create a "dummy" Cookie object first
Cookie.prototype.store = Cookie_store;
Cookie.prototype.get   = Cookie_get;
Cookie.prototype.del   = Cookie_del;



