
//
// Copyright 2000, Point2 Intenet Systems, Inc. All rights reserved.
// $Id: p2_utils.js,v 1.40 2001/10/01 21:19:48 awolinski Exp $
//


function Is() {
    var agt=navigator.userAgent.toLowerCase(); 

    // *** BROWSER VERSION *** 
    // Note: On IE5, these return 4, so use is.ie5up to detect IE5. 
    this.major = parseInt(navigator.appVersion); 
    this.minor = parseFloat(navigator.appVersion); 

    this.nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1) 
                && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1) 
                && (agt.indexOf('webtv')==-1)); 
	this.nav2 = (this.nav && (this.major == 2));
	this.nav3 = (this.nav && (this.major == 3));
    this.nav4 = (this.nav && (this.major == 4)); 
    this.nav4up = (this.nav && (this.major >= 4)); 
    this.navonly      = (this.nav && ((agt.indexOf(";nav") != -1) || 
                          (agt.indexOf("; nav") != -1)) ); 
    this.nav5 = (this.nav && (this.major == 5)); 
    this.nav5up = (this.nav && (this.major >= 5)); 

    this.ie   = (agt.indexOf("msie") != -1); 
	this.ie3 = (this.ie && (this.major < 4));
    this.ie4  = (this.ie && (this.major == 4) && (agt.indexOf("msie 4")!=-1) ); 
    this.ie4up  = (this.ie  && (this.major >= 4)); 
    this.ie5  = (this.ie && (this.major == 4) && (agt.indexOf("msie 5")!=-1) ); 
    this.ie5up  = (this.ie  && !this.ie3 && !this.ie4); 
	this.ie6  = (this.ie && (this.major == 4) && (agt.indexOf("msie 6")!=-1) ); 
    this.ie6up  = (this.ie  && !this.ie3 && !this.ie4 && !this.ie5); 
}

var is = new Is(); 


function popwindow(src, name, toolbar, status, scrollbars, location, width, height, resizable, menubar, left, top){
 	popWindow=window.open(src, name,"toolbar="+toolbar+",status="+status+",scrollbars="+scrollbars+",location="+location+",width="+width+",height="+height+",resizable="+resizable+", menubar="+menubar+",left="+left+",top="+top);
 	if (popWindow.focus) {
 		popWindow.focus();
 	}	   

 }


function P2_preloadImage(nameArg, srcArg)
{
	if (document.images) {
		if (typeof(document.P2images) == 'undefined') {
			document.P2images = new Object();
		}

		eval('document.P2images.' + nameArg + ' = new Image();');
		eval('document.P2images.' + nameArg + '.src = "' + srcArg + '";');
	}
}

function P2_imageSwap(daImage, daSrc)
{
	var objStr, obj;

	if (document.images) {

		if (typeof(daImage) == 'string') {
			objStr = 'document.' + daImage;
			obj = eval(objStr);
			obj.src = daSrc;

		}
		else if ((typeof(daImage) == 'object') && daImage && daImage.src) {
			daImage.src = daSrc;
		}
	}
}



//
// This is the function that the MLString text box and images call.
//
function P2_clickLanguageImage(formName, tagID, newLanguage, imageRoot)
{

	var dataValuePointer = null;
	var dataValue = null;
	var dataCurrentLanguage = null;
	var dataTemp = null;

	// assign variables for the actual value (via the pointer value), the current language hidden field, and the temp field.
	eval("dataValuePointer=document.forms." + formName + "." + tagID + "pointer;");
	eval("dataValue=document.forms." + formName + "." + dataValuePointer.value + ";");
	eval("dataCurrentLanguage=document.forms." + formName + "." + tagID + "currlanguage;");
	eval("dataTemp=document.forms." + formName + "." + tagID + "temp;");

	// check validity of the variables we just found
	if ((dataValue == null) || (dataCurrentLanguage == null) || (dataTemp == null)) {
		alert("BIG JAVASCRIPT ERROR -- COULD NOT ASSIGN VALUES PROPERLY");
		return false;
	}

	var currentLang = dataCurrentLanguage.value;
	//var image = findImage("image" + tagID + "_" + currentLang);
	var image = document.images["image" + tagID + "_" + currentLang];

	// process ONCHANGE
	if (newLanguage == null) {
		// alter graphic
		if (dataTemp.value == "") {
			image.src = imageRoot + "-" + currentLang + "-on.gif";
		}
		else {
			image.src = imageRoot + "-" + currentLang + "-on-filled.gif";
		}

		// compute value of the MLString hidden field
		dataValue.value = addLanguageString(dataValue.value, dataCurrentLanguage.value, dataTemp.value);

		return true;
	}


	// process ONCLICK
	else {
		// alter image of current language
		if (dataTemp.value == "") {
			image.src = imageRoot + "-" + currentLang + "-off.gif";
		}
		else {
			image.src = imageRoot + "-" + currentLang + "-off-filled.gif";
		}


		// alter image of new language
		var newImage = findImage("image" + tagID + "_" + newLanguage);

		if (retrieveLanguageString(dataValue.value, newLanguage) == "") {
			newImage.src = imageRoot + "-" + newLanguage + "-on.gif";
		}
		else {
			newImage.src = imageRoot + "-" + newLanguage + "-on-filled.gif";
		}

		// store the value of the MLString in the hidden field
		dataValue.value = addLanguageString(dataValue.value, dataCurrentLanguage.value, dataTemp.value);

		// put new value into the text box for a particular language that the user sees on the screen
		dataTemp.value = retrieveLanguageString(dataValue.value, newLanguage);

		// put new value into currlanguage hidden field
		dataCurrentLanguage.value = newLanguage;

		return false;
	}
}


//
// This functions returns the image with the name 'name'.
//
function findImage(name)
{
	image = null;

	// loop through images and search for the one with the name 'name'
	for (i=0; (i<document.images.length); i++) {
		if (document.images[i].name == name) {
			image = document.images[i];
		}
	}

	if (image == null) {
		alert("JAVASCRIPT ERROR -- COULD NOT FIND IMAGE WITH NAME '" + name + "'");
		return null;
	}

	return image;
}



//
// This method retrieves a language string from a given encoded string. The encoded string is encoded like:
//
//	en|This%2dis%2dthe%2dencoded%2dstring|fr|mon%2dfrancais|
//
// The encoded string is the same type of encoding as com.point2.phoenix.util.MLString
//
function retrieveLanguageString(encodedString, lang)
{
	if (encodedString == null || encodedString == "") {
		return "";
	}

	stringArray = encodedString.split('|');
	for (i = 0; i < stringArray.length-1; i += 2) {
		if (stringArray[i] == lang) {
			return mlDecode(stringArray[i+1]);
		}
	}
	return "";
}

//
// This method adds the string and the language to the given encoded string, returning the new encoded string
//
function addLanguageString(encodedString, lang, str)
{
	if (encodedString == null || encodedString == "") {
		if (str != null && str != "") {
			return lang + '|' + mlEncode(str) + '|';
		}
		else {
			return "";
		}
	}

	var returnString = new String();
	stringArray = encodedString.split('|');
	for (i = 0; i < stringArray.length-1; i += 2) {
		if (stringArray[i] == lang) {
			// do nothing - we'll add the new one later
		}
		else {
			returnString = returnString + stringArray[i] + '|' + stringArray[i+1] + '|';
		}
	}
	// append the new one to the end
	if (str != null && str != "") {
		returnString = returnString + lang + '|' + mlEncode(str) + '|';
	}

	return returnString;
}


var ENCODING_SEPARATOR = "|";
var ENCODING_REPLACEMENT = "+";
var ENCODING_REPLACEMENT_ESCAPE = "\\";
//
// Changes the ENCODING_SEPARATOR symbol to the ENCODING_REPLACEMENT. Also
// escapes any ENCODING_REPLACEMENT characters in the original string.
// MUST MATCH MLString.encode()!!!
//
function mlEncode(str)
{
//alert("Encoding: " + str);
	var sb = new String();
	if(str==null)
	{
		return sb;
	}
	for (i = 0; i < str.length; i++) {
		if (str.charAt(i) == ENCODING_SEPARATOR) {
			sb = sb + ENCODING_REPLACEMENT;
		}
		else if (str.charAt(i) == ENCODING_REPLACEMENT) {
			sb = sb + ENCODING_REPLACEMENT_ESCAPE;
			sb = sb + ENCODING_REPLACEMENT;
		}
		else {
			sb = sb + str.charAt(i);
		}
	}
//alert("Encoded: " + sb);
	return sb;
}

//
// Changes the ENCODING_REPLACEMENT character back to the ENCODING_SEPARATOR
// character, unless it is escaped.
// MUST MATCH MLString.decode()!!!
//
function mlDecode(str)
{
//alert("Decoding: " + str);
	var sb = new String();
//alert("HERE 0");
	for (i = 0; i < str.length; i++) {
//alert("HERE 1 i:" + i + "	char:" + str.charAt(i));
		if (str.charAt(i) == ENCODING_REPLACEMENT_ESCAPE) {
//alert("HERE 2");
			if (i == str.length-1) {
//alert("HERE 3");
				sb = sb + ENCODING_REPLACEMENT_ESCAPE;
			}
			else {
//alert("HERE 4");
				if (str.charAt(i+1) == ENCODING_REPLACEMENT) {
//alert("HERE 5");
					sb = sb + ENCODING_REPLACEMENT;
					i += 1;
				}
				else {
//alert("HERE 6");
					sb = sb + ENCODING_REPLACEMENT_ESCAPE;
//alert("HERE 6a");
				}
			}
		}
		else if (str.charAt(i) == ENCODING_REPLACEMENT) {
//alert("HERE 7");
			sb = sb + ENCODING_SEPARATOR;
		}
		else {
//alert("HERE 8");
			sb = sb + str.charAt(i);
		}
	}
	return sb;
//alert("Decoded: " + sb);
}


//
// Simply appends the currency ID to the currency amount. For use with the
// p2:moneyinputtext tag (INTERNAL USE ONLY)
//
function newCurrency(currencyHidden, currencyText, currencySelect )
{	
	if(currencyText != null && currencySelect != null && currencyHidden != null)
	{
		amount = trim(currencyText.value);
		currency = currencySelect.options[currencySelect.selectedIndex].value;
		if(amount == "" || currency == "")
		{
			currencyHidden.value = null;
		}
		else
		{
			currencyHidden.value = amount + " " + currency;
		}
	}
}

//function to remove white space from a string

function trim(str) {
	 strings = "";
	//alert("in trim") 
	for(i=0; i<str.length; i++) {
		if(str.charAt(i) != " ") {
			strings += str.charAt(i);
		}				
	}
	return strings;
}





//
// This function transfers an item (OPTION) from one SELECT list to another.
//
function P2_selectSwap(fromList, toList)
{
	toList.selectedIndex = -1;

	// loop through the OPTIONs of fromList to see if they are SELECTED
	for (i=1; i<fromList.options.length; i++) {
		if (fromList.options[i].selected) {	
			newPos = toList.length;
			toList.options[newPos]	= new Option(fromList.options[i].text, fromList.options[i].value);
			toList.options[newPos].selected = true;

			//if(i+1<fromList.length) fromList.options[i+1].selected = true;
			//else if(i-1>0) fromList.options[i-1].selected = true;
			fromList.options[i]	= null;
			i--;
		}
	}
}


// This function moves list items
//
function P2_moveListItem(theList, increment)
{
	if(increment<0) {			// move up
		for (i=1; i<theList.options.length; i++) {
			if (theList.options[i].selected) {
				if( i+increment < 1) return;

				// swap 
				var oldVal = theList.options[i + increment].value;
				var oldText = theList.options[i + increment].text;
				theList.options[i + increment].value = theList.options[i].value;
				theList.options[i + increment].text = theList.options[i].text;
				theList.options[i + increment].selected = true;
				theList.options[i].value = oldVal;
				theList.options[i].text = oldText;
				theList.options[i].selected = false;
			}
		}
	}
	else {								// move down
		for (i=theList.options.length-1; i>=1; i--) {
			if (theList.options[i].selected) {
				if( i+increment >= theList.options.length) return;

				// swap 
				var oldVal = theList.options[i + increment].value;
				var oldText = theList.options[i + increment].text;
				theList.options[i + increment].value = theList.options[i].value;
				theList.options[i + increment].text = theList.options[i].text;
				theList.options[i + increment].selected = true;
				theList.options[i].value = oldVal;
				theList.options[i].text = oldText;
				theList.options[i].selected = false;
			}
		}
	}
}


//
// This function adds the values from a SELECT field into a HIDDEN field.	
// The value of the hidden field is a comma-seperated list of the values contained in the SELECT.
//
function P2_copyListToHiddenField(list, hiddenField)
{

	hiddenField.value = "";

	// loop through and add the fields to hiddenField
	for (i=1; i<list.length; i++) {
		if (hiddenField.value!= "") { hiddenField.value += ","; }
		hiddenField.value += list.options[i].value;
	}
}


//
// This function prepares or checks form values when the user presses 'submit.'
// The functions this performs are:
//		1. Find a SELECT tag that needs all of its attributes to be SELECTED
//

//
// Selects all OPTIONs of a SELECT tag.
//
function selectall(list)
{
	for (var i=0; i<list.length; i++) {
		list.options[i].selected = true;
	}
}


// combines form elements into a query string
function collectElementsIntoQueryString(theForm, theElementName)
{
	result = '';

	for(i=0; i<document.forms[theForm].elements.length; i++) {

		if( (document.forms[theForm].elements[i].name==theElementName) &&
				(document.forms[theForm].elements[i].checked==true) )
		{
			if(result.length>0) result = result + '&';
			result = result + theElementName + '=' + escape(document.forms[theForm].elements[i].value);
		}
	}

	return result;
}


// sets the options for a select box, from an array
// @param theSelect the select box to fill
// @param theValues the array of Option objects to use

	function setSelectOptions(theSelect, theValues)
	{
		// remove old options from theSelect
		for(i=theSelect.options.length; i>=theValues.length; i--) {
			theSelect.options[i] = null;
		}	

		// populate theSelect with theValues
		for(i=0; i<theValues.length; i++) {
			theSelect.options[i] = theValues[i];
		}
	}

// date input function to be run when the year box is changed in a date widget
// checks the entered value to ensure that it is a number (neccessary for older browsers)
// @param theYear a 4 digit text box
// @param theMonth a select list of months
// @param theDay a select list of days
// @param theHidden a hidden input holding the calculated value of the field
function yearChange(theYear, theMonth, theDay, theHidden, theAllownulls) {
	tempValue = parseInt(theYear.value);
	if (isNaN(tempValue) || (theYear.value.length < 4)) {
		if (theAllownulls.value == "yes")
		{
			setNullDate(theYear, theMonth, theDay, theHidden);
			return;
		} else {
			theHidden.value="NaN";
			return;
		}
	} else {
		theMonth.disabled = false;
		theDay.disabled = false;
		datePopulate(theYear, theMonth, theDay, theHidden)		
	}
}

// date input function
// populates the date drop down box based on the selected year and month
// @param theYear a 4 digit text box
// @param theMonth a select list of months
// @param theDay a select list of days
// @param theHidden a hidden input holding the calculated value of the field
function datePopulate(theYear, theMonth, theDay, theHidden, theAllownulls) {
	tempValue = parseInt(theYear.value);
	if ((theYear.value.length < 4) || (isNaN(tempValue)))
	{
		if (theAllownulls.value == "yes")
		{
			setNullDate(theYear, theMonth, theDay, theHidden);
			return;
		} else {
			theHidden.value="NaN";
			return;		
		}
	}
	timeA = new Date(theYear.value, theMonth.options[theMonth.selectedIndex].value, 1);
	timeDifference = timeA - 86400000;
	timeB = new Date(timeDifference);
	var daysInMonth = timeB.getDate();
	var oldDay = theDay.selectedIndex;
	for (var i = 0; i < theDay.length; i++) {
		theDay.options[0] = null;
	}
	for (var i = 0; i < daysInMonth; i++) {
		theDay.options[i] = new Option(i+1);
	}
	if ((oldDay < theDay.length) && (oldDay > -1)) {
		theDay.options[oldDay].selected = true;
	} else {
		theDay.options[theDay.length-1].selected = true;
	}
	dateParse(theYear, theMonth, theDay, theHidden, theAllownulls);
}

// date input function
// fills the hidden form field with the selected date
// @param theYear a 4 digit text box
// @param theMonth a select list of months
// @param theDay a select list of days
// @param theHidden a hidden input holding the calculated value of the field
function dateParse(theYear, theMonth, theDay, theHidden, theAllownulls) {
	tempValue = parseInt(theYear.value);
	if (isNaN(tempValue) || (theYear.value.length < 4)) {
		if (theAllownulls.value == "yes")
		{
			setNullDate(theYear, theMonth, theDay, theHidden);
			return;
		} else {
			theHidden.value="NaN";
			return;
		}
	}
	var dom = parseInt(theDay.options[theDay.selectedIndex].text);
	var domString;
	if (dom < 10)
	{
		domString = "0" + dom;
	} else {
		domString = "" + dom;
	}
	theHidden.value = theMonth.options[theMonth.selectedIndex].value + '/' + domString + '/' + theYear.value;
}


function setNullDate(theYear, theMonth, theDay, theHidden) {
	theYear.value="NONE";
	theMonth.disabled = true;
	theDay.disabled = true;
	theHidden.value="";
}
