
// ##########################################
// primitives
// ##########################################

function isArray(variable)
{
	 return Boolean( typeof variable == 'object' && variable.length >= 0 );
}

// a "proper" implementation of the escape() routine; 
function httpEscape(str)
{

	var		i, c;
	var		output = "";

	if (!str || (typeof str != "string"))
		return str;

	for (i = 0; i < str.length; i++) {
		c = str.charAt(i);
		if (c.match(/[a-z0-9\/-]/i)) {
			output += c;
			continue;
		}
		c = str.charCodeAt(i);
		output += "%" + c.toString(16);
	}

	return output;
}

// returns number of elements in a formvar multiple
function getElementLength(fVar)
{
	if (!fVar)
		return 0;
	else
		return (fVar.length) ? fVar.length : 1;
}

// checks if a formvar is blank or whitespace;
function checkBlank(fVar, message)
{
	if (fVar.value.search(/^ *$/) == -1)
		return true;
	
	if (message) alert("Please enter " + message + ".");
	return false;
}

// returns number of items that are checked
function checkCount(fVar)
{

	if (!fVar)
		return false;

	var count = 0;
	var n = getElementLength(fVar);

	switch (n) {
		case 0:
			return 0;
		case 1:
			return (fVar.checked) ? 1 : 0;
		default:
			for (var i = 0; i < n; i++) {
				count += ((fVar[i].checked) ? 1 : 0);
			}
			return count;
	}
}

function checkSize(fVar, maxsize, name)
{
	if (!fVar) return true;

	var		n = fVar.value.length;
	if (n > maxsize) {
		var diff = n - maxsize;
		alert("The maximum size of the field \"" + name + "\" is " + maxsize +
		      " characters; you have entered " + n + " characters.\n" +
		      "Please reduce your entry by at least " + diff + " characters.");
		fVar.focus();
		return false;
	} else return true;
}

// sets all checkboxes from element[0] to the specified value
function cbSet(fVar, value)
{
	var n = getElementLength(fVar);

	switch (n) {
		case null:
		case false:
		case 0:
			return;
		case true:
		case 1:	
			fVar.checked = value;
			break;
		default:
			for (var i = 0; i < n; i++) {
				fVar[i].checked = value;
			}
	}
}


// returns value of the specified fVar
// NOTE: it returns an ARRAY, not a single value
// skipHidden determines if getVal retrieves hidden variables or not
function getVal(fVar, skipHidden)
{
	var		val = new Array();
	var		type = null;

	if (!fVar) return null;

	if (!skipHidden) skipHidden = false;
	
	if (fVar.type) type = fVar.type;
	else if (getElementLength(fVar)) type = fVar[0].type;

	switch (type) {
	case "select-one":
		val.push(fVar.options[fVar.selectedIndex].value);
		break;
	case "select-multiple":
		for (var i = 0; i < fVar.length; i++) {
			if (fVar.options[i].selected)
				val.push(fVar.options[i].value);
		} 
		break;
	case "checkbox":
	case "radio":
		if (getElementLength(fVar) > 1) {
			for (var i = 0; i < fVar.length; i++) {
				if (fVar[i].checked)
					val.push(fVar[i].value);
			}
		} else 
			val.push((fVar.checked) ? fVar.value : null);
		break;
	case "text":
	case "textarea":
	case "password":
		val.push(fVar.value);
		break;
	case "hidden":
		val.push((skipHidden) ? null : fVar.value);
		break;
	default:
		val.push(null);
	}

	return val;
}


// single variable wrapper for getVal
function getValSingle(fVar, skipHidden)
{
	if (!skipHidden) skipHidden = false;

	var		val = getVal(fVar, skipHidden);
	
	if (val) return val[0];
	else return null;
}

function setVal(fVar, val)
{
// attempts to set a fVar's value to the value specified by "val";
// NOTE: val must be an array!!! for non-multiple formvars, pass the
// desired value in val[0].
	var		i, j;

	if (!fVar) return;
	
	if ((typeof val) != 'object')
		val = [val];

	switch (fVar.type) {
		case "select-one":
		case "select-multiple":
			if (!val || !val.length) {
				fVar.selectedIndex = 0;
				break;
			}
			for (i = 0; i < val.length; i++) {
				for (j = 0; j < fVar.length; j++) {
					if (fVar.options[j].value == val[i]) {
						fVar.options[j].selected = true;
						break;
					}
				}
			}
			break;
		case "checkbox":
		case "radio":
			if (!val || !val.length) {
				fVar.checked = false;
			} else {
				for (i = 0; i < val.length; i++) {
					if (fVar.value == val[i]) {
						fVar.checked = true;
						break;
					} else {
						fVar.checked = false;
					}
				}
			}
			break;
		case "text":
		case "textarea":
		case "password":
			fVar.value = (val && val.length) ? val[0] : "";
			break;
	}
	return;
}


function getCookieData(labelName)
{
	 var labelLen = labelName.length;
	 var cookieData = document.cookie;
	 var cLen = cookieData.length;
	 var i = 0;
	 var cEnd;
	 while (i < cLen) {
		  var j = i + labelLen;
		  if (cookieData.substring(i,j+1) == labelName + '=') {
			   cEnd = cookieData.indexOf(";",j);
			   if (cEnd == -1) {
				    cEnd = cookieData.length;
			   }
			   return unescape(cookieData.substring(j+1, cEnd))
		  }
		  i++;
	 }
	 return ""
}


// ##########################################
// more specific form handling functions...
// ##########################################

function detectSelect(formName, varName) 
{

	var objCheckbox = document.forms[formName].elements[varName];

	var objArray = new Array();

	if (isArray(objCheckbox)) {
		for (i=0; i < objCheckbox.length; i++) {
			if (objCheckbox[i].checked == true) {
				objArray.push(objCheckbox[i].value);
			}
		}
	} else {
		objArray.push(objCheckbox.value);
	}
	return objArray;
}

function toggle(divname)
{
	if (document.all) {
		if (document.all[divname].style.display==''||document.all[divname].style.display=='block'){
			document.all[divname].style.display='none';
		} else {
			document.all[divname].style.display='';
		}
	} else if (document.getElementById) {
		if (document.getElementById(divname).style.display=='block'||document.getElementById(divname).style.display=='') {
			document.getElementById(divname).style.display='none';
		} else {
			document.getElementById(divname).style.display='block';
		}
 	}
}

function checkSel(fVar) {
	if (!fVar)
		return false;
		
	var count = 0;
	var n = getElementLength(fVar);
	
	switch(n) {
		case 0:
			return false;
			break;
		case 1: 
			return (fVar.checked) ? true : false;
			break;
		default: 
			for (var i = 0; i < n; i++) {
				count += ((fVar[i].checked) ? 1 : 0);
			}
			if (count > 0) return true; else return false;
			break;
	}
}

var SUBMIT_ONCE_FLAG = false;

function submitOnce(fObj, f_nosubmit)
{
    if (!SUBMIT_ONCE_FLAG) {
	SUBMIT_ONCE_FLAG = true;
	try {
		fObj.submitButton.value = " Please wait... ";
		fObj.submitButton.disabled = true;
	} catch (e) {}
	if (!f_nosubmit) fObj.submit();
    }

    return false;
}

function selectState(state, country)
{
	if (country.options[country.selectedIndex].value == "USA" ||
	    state.options[state.selectedIndex].value != '') {
		for (i = 0; i < country.length; i++) {
			if (country.options[i].value == "USA") {
				country.selectedIndex = i;
				break;
			}
		}
	}
}

var stateBuffer = new Array();

function selectCountry(country, state)
{
	if (state.options[state.selectedIndex].value != "")
		stateBuffer[state.name] = state.selectedIndex;

	if (country.options[country.selectedIndex].value != "USA")
		state.selectedIndex = 0;
	else if (stateBuffer[state.name])
		state.selectedIndex = stateBuffer[state.name];
}

function clearDateVal(fVar)
{
	 if (!fVar.value.match(/[0-9]{1,}/))
		  fVar.value = '';
}

function catBillDate(fObj, alias)
{
	if (!alias) alias = 'BI';

	// skip for invoice type - kind of a hack for BI_METHOD radio
	if (fObj.BI_METHOD && fObj.BI_METHOD.length > 1 && fObj.BI_METHOD[1].checked)
		return true;

	// set CC_EXP
	if (!fObj.elements[alias + '_CC_EXP__MM'].selectedIndex ||
	    !fObj.elements[alias + '_CC_EXP__YY'].selectedIndex) {
		alert('Please select your credit card expiration date.');
		return false;
	} else
		fObj.elements[alias + '_CC_EXP'].value = getValSingle(fObj.elements[alias + '_CC_EXP__MM']) + getValSingle(fObj.elements[alias + '_CC_EXP__YY']);

	return true;
}


// ##########################################
// misc. front-end stuff
// ##########################################

var             ACT_SRC_DIR = "/img/act/";

function actImgOver(imgName,imgSrc,mode) {
	if (mode == 1) {
    		document[imgName].src = ACT_SRC_DIR + imgSrc + "-over.gif";
	} else {
    		document[imgName].src = ACT_SRC_DIR + imgSrc + ".gif"; 
	}
}

var splashMe = null;
function splash()
{
	 var w = 500;
	 var h = 100;
	 var win1 = ((screen.width - w) / 2);
	 var win2 = ((screen.height - h) / 2);
	 var url = '/mem/upload_splash.html';
	 var settings = 'height='+h+',';
	     settings += 'width='+w+',';
	     settings += 'top='+win2+',';
	     settings += 'left='+win1+','
	     settings += 'resizable=no,scrollbars=no';
	 splashMe = window.open(url,"",settings);
	 return true;	      
}

function closeSplash()
{
	if(window.splashMe) {
	 	splashMe.close();
	}
}

function popupWin(url, width, height, name)
{
	if (!name) name = "popup";

	var foo = window.open(url, name, "resizable=yes,scrollbars=yes,location=no,menubar=no,width=" + width + ",height=" + height);
	if (foo) foo.focus();
}

function helpPop(help, width, height)
{
	if (!width) width = 850;
	if (!height) height = 600;

	popupWin('/help/pop/' + help, width, height);
}

function convertBytes(bytes)
{
	var			unit;
	var			n;
	
	if (bytes/(1024) < 1) {
		unit = 'bytes';
		n = Math.floor(bytes);
	} else if (bytes/(1024*1024) < 1) {
		unit = 'KB';
		n = Math.floor(10*bytes/(1024))/10;
	} else if (bytes/(1024*1024*1024) < 1) {
		unit = 'MB';
		n = Math.floor(10*bytes/(1024*1024))/10;
	} else {
		unit = 'GB';
		n = Math.floor(10*bytes/(1024*1024*1024))/10;
	}
	
	n = n.toString();
	if (n.indexOf('.') < 0) n += '.0';

	return n + unit;
}

function blockToggle (obj)
{
	var div = obj.parentNode;
	var f = _bsDom.hasClass(div, 'open');
	if (!f) _bsDom.addClass(div, 'open');
	else _bsDom.delClass(div, 'open');
};

function _seoIcon (obj)
{
	var str = "This field can affect your search engine optimization (SEO).<br><b>&raquo;</b> <a href=\"/" + PS.app.pvGet('area') + "/home/help/tut/seo\" class=\"bold\" target=\"_blank\">Learn More</a>";
	_balloon(obj, '<h3>SEO</h3>', str)
}

function seoIcon (f_write, style)
{
	var str = '<a href="javascript:void(0);" onClick="_seoIcon(this);"';
	if (style) str += ' style="' + style + '"';
	str += ' class="seoIcon">';
	str += '<img src="/img/icon/seo.gif" width="24" height="11" alt="SEO" border="0">';
	str += '</a>';

	if (f_write) document.write(str);
	else return str;
}

