// (c) AdviceReady.com. All rights reserved.
// $Id: vclib.js,v 1.4 2009/07/16 11:56:05 andy Exp $

if (typeof getFlash == 'undefined') {	// #IFDEF

function getFlash(name) {
	if(navigator.appName.indexOf("Microsoft") != -1) {
    	flash = window[name];
  	} else {
    	flash = window.document[name];
  	}
	return flash;
}

function OBU(name) {
	//alert(getFlash(name));
	getFlash(name).onUnload();
}

var fnOBU;
function insertHook(name) {
	fnOBU = window.onunload;
	window.onunload = function() {
		if (fnOBU) fnOBU();
		OBU(name);
	}
}

function $(id) {
	return document.getElementById(id);
}

function normalize(strInput, options) {
	var str = strInput;
	str = str.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/&quot;/g, '"');
	
	if (!options || (options && !options.noNl2Br)) {
		str = str.replace(/(\r?\n)+/g,"<br/>");
	}
	return str;
}

function trim(str) {
	return str.replace(/^[\s\n]+|[\s\n]+$/g, "");
}

function stripTags(strHtml) {
	return trim(strHtml.replace(/<br.{0,2}?>/ig,'\n').replace(/<\/?\w+?.*?>/g, ""));
}

function shorten(txt, maxlen) {
	if (maxlen==undefined) maxlen=12;
	if (txt.length > maxlen) {
		txt = txt.substr(0,maxlen) + '...';
	}
	
	return txt;
}

function fmtCurrency(num, negativeWithParentheses) {
	var neg = false;
	
	if (negativeWithParentheses && num < 0) {
		neg = true; num = -num;
	}
	
	if (num=='') num = 0;
	num = parseInt(num * 100 + 0.505)/100; // round to 2 decimals

	var txtnum = num + '';
	var idx;
	if ((idx=txtnum.indexOf('.')) == -1) {
		txtnum += '.00';
	} else {
		while (txtnum.length - idx - 1 < 2) {
			txtnum += '0';
		}
	}
	
	if (negativeWithParentheses && neg) txtnum = '(' + txtnum + ')';
	
	return txtnum;
}

function countSelected(theForm, optFnCallback) {
	var cnt=0;
	for( var z=0; z<theForm.length; z++) {
		// if the checkbox doesn't have a name, then it's not counted
		if (theForm[z].type == 'checkbox' && theForm[z].name 
			&& theForm[z].checked ) {
			
				cnt++;
				if (optFnCallback) optFnCallback(theForm[z]);
				
		}
	}
	
	return cnt;
}

function encodeURIExcept(uri, strException) {
	// encode the URI except for chars in strException
	var euri = encodeURI(uri);
	var ex = strException.split('');
	for (var i in ex) {
		var eex = encodeURI(ex[i]);
		euri = euri.replace(new RegExp(eex, 'g'), ex[i]);
	}
	return euri;
}

function getUrlParam(paramname, url) {
	var h = (!url) ? location.href : url;
	paramname = paramname.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var m = h.match(new RegExp("[#&?]" + paramname + "=(.+?)([&?#]|$)","i"));
	if (m && m[1]) return decodeURIComponent(m[1]);
		else return null;
}

function setUrlParam(paramname, value, separator, href) {
	var h = !href ? location.href : href;
	if (!separator) separator = h.indexOf('?') > -1 ? '&' : '?'; 
	
	// escape [ and ] chars in paramname 
	paramname = paramname.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	
	// remove previously set paramname=value from href
	var x = h.replace(new RegExp("[&?#]" + paramname + "(?:\\=(?:.*?)|(?:.*?))([&?#]|$)","i"), "$1");
	
	return x + separator + paramname + (value ? '=' + encodeURIComponent(value) : '');
}

function setClass(target, attr, bSet) {
	if (!target) return null;
	if (!target.className) target.className = '';
	var prevset = target.className.indexOf(attr) != -1;
	
	if (bSet == 'toggle') 
		bSet = !prevset;
	
	if (!prevset && bSet) {
		target.className += ' ' + attr;
	} else if (prevset && !bSet) {
		// remove attr from classname
		var x = target.className.split(' ');
		var out = '';
		for (var i in x) {
			if (x[i] != attr) out += x[i] + ' ';
		}
		target.className = out;
	}
	
	return prevset;
}

//////////////////////////////////// Treeview /////////////////////////////////////////////
function TreeView(name) {
	this.data = [];
	this.data['selected'] = 0;
	
	this.name = name;
	
	this.onEvent = function(event) {
		// Creates a collapsible treeview where by clicking '+' sign, the branch expands
		// Requires: MM_effectBlind and appropirate .treeview CSS
		// Adapted from: http://ooyes.net/simple-javascript-treeview
		// Sample .treeview or #name CSS :
		//			#name *{list-style:none; margin:0px 0px 0px 1px; padding:0px 0px 0px 0px;}
		//			#name a{text-decoration:none;}
		//			/* #name hr {margin:-5px -5px -5px -5px; } */
		//			#name br {line-height:10px;}
		//			#name ul {width:300px;}
		//			#name ul li {clear:both; float:left; cursor:pointer; width:300px;}
		//			#name ul li ul {display:none; padding-left:20px; width:300px;}
		//			#name ul li.active ul{display:block; } 
		// Google: treeview seo ul
		// USAGE:
		// Note, the ids of the tags can be pre-pended with this.name
		// In script tag: var tv=new TreeView("");
		/*	<div class="treeview" onclick="tv.onEvent(event)" id="sel">
				<ul id='ul0'>
					<li id='l2'><a href="#" class="expander">+</a> <span id='sl2' class='litext'>link 2</span>
						<ul id='ul2'>
							<li><label><input type='checkbox'/><a href="#">sublink</a></label></li>
							<li><a href="#">sublink</a></li>
							<li><a href="#">sublink</a></li>
						</ul>
					</li>
					<li id='l3'><a href="#" class="expander">+</a> <span id='litext'>link 3</span>
						<ul id='ul3'>
							<li><a href="#">sublink</a></li>
							<li><a href="#">sublink</a></li>
							<li><a href="#">sublink</a></li>
						</ul>
					</li>       
				</ul>
			</div>
		*/
		var target = event.target || window.event.srcElement;
		
		if (target.tagName == 'INPUT' && target.type=='checkbox') {
			this.onSelected(target);
			return;
		}	
		
		if (!(target.tagName == 'A' && target.className=='expander'))
			return;
		
		var elm;
		if ((elm = target.parentNode) && elm.tagName == 'LI' && elm.id) {
							
			if (elm.className.indexOf('active') == -1) 
				target.innerHTML = '-';
			else
				target.innerHTML = '+';
			
			setClass(elm, 'active', 'toggle');
		}
	}
	
	this.expandAll = function (options) {
		// just expand the 1st branches
		var elm = $(this.name + "ul0");
		for (var i in elm.childNodes) {
			if (elm.childNodes[i].id && elm.childNodes[i].tagName=='LI')
				var numid = elm.childNodes[i].id.replace(/.*?l([0-9]+)/, "$1");
				if (numid) this.expandChild(numid, options);
		}
		
		if (options && options.collapse) {
			// NOTE: Assumption: the DIV name of this object is "sel" + this.name, eg: "selcats"
			$("sel" + this.name).scrollTop = 0;
		}
	}
	
	////////// from here on it's the Checkbox Tree View ////////////////////////////
	this.selectItem = function(selItem, bSelect) {
		
		var strCbNodeId = "cb" + this.name + "l" + selItem;
		var ckbox =$(strCbNodeId);
		ckbox.checked = bSelect;
		this.onSelected(ckbox);
		this.expandChild(selItem, {markSelectedNode:true});
	}
	
	this.onSelected = function(ckbox) {
		// report the selected items to "divTvSelTxt_" + treeId	
	
		this.data['selected'] += ckbox.checked ? 1:-1;
		//var e = $("idTvSelTxt_" + this.name);		
		//e.innerHTML = ", " + this.data['selected'] + " selected";
		
		// now mark the checkbox's category parent with # selected items
		// but first we must know how many are selected
		// NOTE: This assumes that the tree is only 2 branches deep with a certain structure
		var ulnode = ckbox.parentNode.parentNode.parentNode;
		var numChecked = 0;
		if (ulnode.tagName!='UL') {
			// we're at depth 1
			numChecked += ckbox.checked ? 1 : 0;
			// find the ul node of the child
			ulnode = $(ckbox.id.replace(/.*?([0-9]+)/, this.name + "ul$1"));
		} else {
			// we're at depth 2
			// find depth 1's checkbox and count it
			numChecked += $(ulnode.id.replace(/.*?([0-9]+)/, "cb" + this.name + "l$1")).checked ? 1:0;
		}
		
		var cbCounted = []; // has this checkbox been counted?
		var liNodes = ulnode.childNodes;
		for (var i in liNodes) {
			var cbName;
			if (liNodes[i].tagName=="LI" && liNodes[i].id
				&& (cbName = "cb" + liNodes[i].id) && !cbCounted[cbName]
			   ) {
					var cb = $(cbName);
					numChecked += (cb.checked ? 1 : 0);
					
					// it seems that the Opera browser counts this twice, so
					// make sure it's not double counted
					cbCounted[cbName] = 1; 	
			}
		}
			
		// now mark the checkbox's category parent with # selected items
		var liulnode = ulnode.parentNode;
		var infoNodeText = $("i" + liulnode.id);
		infoNodeText.innerHTML = numChecked ? " (" + numChecked + " selected)" : "";
	}
	
	this.expandChild = function(selItem, options) {
		var strLiNodeId = this.name + "l" + selItem;
		var elm = $(strLiNodeId);	
		var collapse = options && options.collapse;
		
		// iterate up and mark as active until we find a ul whose id = "ul0"
		do {
			if (elm.tagName == 'LI') {
				setClass(elm, 'active', !collapse);			
										
				// now find the child which has the '+' sign and change to '-'
				for (var i in elm.childNodes) {
					var c = elm.childNodes[i];
					if (c.tagName == 'A' && c.className == 'expander') {
						c.innerHTML = (collapse) ? '+' : '-';
						break;
					}
				}
			}
		} while ((elm=elm.parentNode) && !(elm.tagName=='UL' && elm.id.indexOf('ul0')!=-1))
	
		if (options && options.markSelectedNode) {
			// mark the SPAN 's' node as selected if possible, if not, just the node
			if (setClass($('s' + strLiNodeId), 'selecteditem', true) == null) {
				setClass($(strLiNodeId), 'selecteditem', true) 
			}
		}
	}
		
	this.onTreeViewExpandCollapseCtl = function() {
		var e = $('tvecc_' + this.name);
		var options = {};
		if (e.innerHTML.indexOf('Hide') != -1) options.collapse = true;
		this.expandAll(options);
		e.innerHTML = (options.collapse ? 'Expand' : 'Hide') + ' all';
	}
}

function MM_effectAppearFade(targetElement, duration, from, to, toggle)
{
	Spry.Effect.DoFade(targetElement, {duration: duration, from: from, to: to, toggle: toggle});
}
function MM_effectBlind(targetElement, duration, from, to, toggle)
{
	Spry.Effect.DoBlind(targetElement, {duration: duration, from: from, to: to, toggle: toggle});
}
function MM_effectGrowShrink(targetElement, duration, from, to, toggle, referHeight, growFromCenter)
{
	Spry.Effect.DoGrow(targetElement, {duration: duration, from: from, to: to, toggle: toggle, referHeight: referHeight, growCenter: growFromCenter});
}
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 disableScreen(bDisable) {
	// Disables the whole screen
	/* Requires:
		<div id='progressBackgroundFilter'></div>
	   and:
		#progressBackgroundFilter {
		  position:absolute;
		  top:0px;
		  left:0px;
		  width:100%;
		  height:200%;
		  overflow:hidden;
		  padding:0;
		  margin:0;
		  background-color:#000; 
		  filter:alpha(opacity=50);
		  opacity:0.5;
		  z-index:900;
		  visibility:hidden;
		}
*/
	var elm = $("progressBackgroundFilter");
	elm.style.visibility = bDisable ? 'visible' : 'hidden';
	elm.style.height = (document.height ? document.height : (document.body && document.body.clientHeight ? document.body.clientHeight : 800)) + 'px';
	elm.style.width = (document.width ? document.width : (document.body && document.body.clientWidth ? document.body.clientWidth : 1200)) + 'px';
}

function showModal(strId, bShow) {
	// shows strId as a modal dialog. Note strId's z-index must be >= 1000
	if (bShow) {
		disableScreen(bShow);
		MM_effectGrowShrink(strId, 1000, '0%', '100%', false, false, true);	
		$(strId).style.visibility = 'visible';
	} else {
		MM_effectGrowShrink(strId, 100, '100%', '0%', false, false, true);	
		disableScreen(bShow);
		$(strId).style.visibility = 'hidden';
	}
}

function printDiv(divId) {
	// sent the contents of divId to the printer

	var a = window.open('','','scrollbars=yes');
	
	a.document.open("text/html");
	a.document.write('<html><head><style type="text/css">#frame{background-image:none;background-color:#FFFFFF;}</style></head><body style="padding-left:20px;background-image:none;background-color:#FFFFFF;">');
	a.document.write($(divId).innerHTML);
	a.document.write('</body></html>');
	a.document.close();
	a.print();
}

function encodeForm(form, optStrNameBnClicked) {
	// Encode the form
	
	// Doesn't support file types in the form
	
	var formData = '';
	for (var i=0; i < form.length; i++) {
		var x = form[i];
		var value = null;
		
		if (!(x && x.name && !x.disabled)) continue;
				   
		if (x.tagName=='INPUT' || x.tagName=='TEXTAREA') {
			
			if (x.type=='checkbox' || x.type=='radio' ) {
				if (x.checked) value = x.value ? x.value : 1;
				
			} else if ('button|submit|image'.indexOf(x.type) >= 0) { 
				if (optStrNameBnClicked && optStrNameBnClicked==x.name) value = x.value;
				
			} else if (x.type=='file') {
				// File is not supported
			} else {
				value = x.value;
			}
			
		}
		
		if (value!==null) formData += '&' + encodeURIComponent(x.name) + '=' + encodeURIComponent(value);
		
		// SELECT has to be done here since it may contain multiple selections
		if (x.tagName=='SELECT') {
			for (var j=0; j<x.options.length; j++) 
				if (x.options[j].selected && x.options[j].value != null) 
					formData += '&' + encodeURIComponent(x.name) + '=' + encodeURIComponent(x.options[j].value); 
		}
	}
	
	if (!formData) return null;
	formData = formData.substring(1); // remove the first '&'
	
	return formData;

}

function ajaxCall(url, method,	// method is GET or PUT 
				  form, fnResult, 	// fnResult(txtResult, httpStatus, objRequest): callback fn when complete
				  optStrNameBnClicked) { 
			// optStrNameBnClicked: the name of the button whose value is to be sent (optional), if not specified 
			// then no button value will be sent regardless whether it's clicked
		
	// Requires SpryData.js
	
	// Encode the form
	var formData = null;
	if (!form) {
		// that's fine if there's no form, just continue
	} else {
		// there's a form, so encode it
		formData = encodeForm(form, optStrNameBnClicked);
		if (!formData) return; // but if there's nothing to encode, then don't do stuff
	}
	
	// packing completed, now GET/POST the form
	if (method=='POST') {
		Spry.Utils.loadURL('POST', url, true, function(request) {
												fnResult(request.xhRequest.responseText, request.xhRequest.status, request);
											  }, 
				{postData: formData, 
					headers: {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}});
	} else {
		Spry.Utils.loadURL('GET', url + (url.indexOf('?') >= 0 ? '&' : '?') + formData, 
				true, function(request) {
						fnResult(request.xhRequest.responseText, request.xhRequest.status, request);
					  });
	}
}

///////////////////////////////////////////////////////////////////////////////////////////
// Example:

// alert( readCookie("myCookie") );

function readCookie(name)

{

  var cookieValue = "";

  var search = name + "=";

  if(document.cookie.length > 0)

  { 

    offset = document.cookie.indexOf(search);

    if (offset != -1)

    { 

      offset += search.length;

      end = document.cookie.indexOf(";", offset);

      if (end == -1) end = document.cookie.length;

      cookieValue = unescape(document.cookie.substring(offset, end))

    }

  }

  return cookieValue;

}

// Example:

// writeCookie("myCookie", "my name", 24);

// Stores the string "my name" in the cookie "myCookie" which expires after 24 hours.

function writeCookie(name, value, hours)

{

  var expire = "";

  if(hours != null)

  {

    expire = new Date((new Date()).getTime() + hours * 3600000);

    expire = "; expires=" + expire.toGMTString();

  }

  document.cookie = name + "=" + escape(value) + expire;

}



} // END #IFDEF
