//************************************************************************
//init vars
var edflag=0;
var subact=0;
var delact=0;
var errormsg="";

//************************************************************************
// add a new entry into a select list/box
// the value for the select option is not set beacuse the value is an auto number in the DB and is created by the DB. 
//hence we only set text part of the option tag.
// the newCategory TEXT field and CategoryIs form fields are required.
// ok ok.. its not the best function i have written..:) or u have seen..:)
function addOption(formObject,newCategory,addto,hiddencat,objectname) 
{
object = eval(formObject);

if (trim(object[hiddencat].value))
{
	alert('You can add only one '+objectname+'.')
	return;
}

	if (trim(object[newCategory].value))
	{
	    var defaultSelected = true;
	    var selected = true;
		var length = object[addto].length;
		var optionName = new Option(trim(object[newCategory].value), "", defaultSelected, selected); // set the TEXT part of the option tag.
		YesAdd = 1;
		for (i=0; i < length; i++)
			{
				if(object[addto].options[i].text == trim(object[newCategory].value))
					{
						YesAdd = 0;
						break;
					}
			}
	    
		if(YesAdd)
			{
				object[addto].options[length] = optionName;
				object[hiddencat].value = trim(object[newCategory].value);
			}
		else
			alert("The "+objectname+" already exists.");		
	}
	else
		{
		//alert("'"+object.newCategory.value+"'")
		alert("Please enter a valid "+objectname+".");
		}
}

//************************************************************************
// trims a form element
function trim(tmpStr) 
{
  var atChar;
 
  if (tmpStr.length > 0) atChar = tmpStr.charAt(0);
  while (isSpace(atChar)) 
  {
    tmpStr = tmpStr.substring(1, tmpStr.length);
    atChar = tmpStr.charAt(0);
  }
  if (tmpStr.length > 0) atChar = tmpStr.charAt(tmpStr.length-1);
  while (isSpace(atChar)) 
  {
    tmpStr = tmpStr.substring(0,( tmpStr.length-1));
    atChar = tmpStr.charAt(tmpStr.length-1);
  }
	// alert("here'"+tmpStr+"'");
  return tmpStr;
}

//************************************************************************
function setHiddenFromSelect(FieldToGet, FieldToSet, listSep)
{
	if (!listSep) listSep = ",";
	var length = FieldToGet.length;
	var strS = "";
	for (i=0; i < length; i++)
	{
		if (trim(FieldToGet.options[i].value) != "")
		{
			if (strS == "")
				strS += trim(FieldToGet.options[i].value);
			else
				strS += listSep + trim(FieldToGet.options[i].value); 	
		}	
	}
	FieldToSet.value = strS;
}
//************************************************************************
function getSelectValue(objSelect)
{
	var strS = "";
	if (isEmptySelect(objSelect))
		return "";
	var iIndex = objSelect.selectedIndex;
	
	strS = trim(objSelect[iIndex].value);
	return strS;
}
//************************************************************************
function isSpace(inChar) 
{
  return (inChar == ' ' | inChar == '\t' || inChar == '\n' || inChar == '\r');
}

//checks if a string is empty
function isEmpty(inStr){
	if(trim(inStr).length == 0){
		return true;
	}else{
		return false;
	}
}

//checks if a textbox is empty - replaced by checkTextBox
function isEmptyText(field)
{	
	var strS = trim(field.value);
	if (strS.length == 0 || strS == "")	return true;
	return false;
} 

// checks if at least one of a set of radios is selected 	
function isEmptyRadio(field)
{
	if (field.length)
	{
	 	for (i=0; i < field.length; i++)
		{
			if (field[i].checked)
				return false;
		}
	}	
	else {
		if (field.checked)	
			return false;
	}
	return true;
}

// checks if a valid option has been selected 	
function isEmptySelect(field)
{
	var strS = "";
	iIndex = field.selectedIndex;
	if (iIndex == -1) // || iIndex == 0 - removed as first option can be valid
	{
		field.selectedIndex = -1;
		return true;
	}
	if (iIndex != null)
	{
		strS = field[iIndex].value;
	}	
	if (trim(strS) == "") return true;
	return false;
}

//checks if the checkbox is selected or at least one of the array is selected
function isEmptyCheck(field)
{
	if (field.length)
	{
		for (i=0; i < field.length; i++)
		{
			if (field[i].checked)
				return false;
		}
	} else {
		if (field.checked)
			return false;
	}
	return true;
}

//************************************************************************

function doPreview()
{
	document.frm.target = "_blank";
    document.frm.encoding="application/x-www-form-urlencoded"	
	document.frm.action = "preview.cfm";
	document.frm.submit();
	return false;
}


//************************************************************************

function isValidEmail(str)
{
	str += '';
	namestr= '';
	domainstr = '';
	namestr = str.substring(0,str.indexOf("@")); // get all the info before the "@"
	domainstr = str.substring(str.indexOf("@")+1,str.length); // get all the info after the "@"
	tailstr = str.substring(str.indexOf(".")+1,str.length) // after the first "." how many chars are they

	if( (namestr.length == 0) || (domainstr.indexOf(".") <= 0) || (domainstr.length == 0) || (domainstr.indexOf("@") != -1) || tailstr.length == 0) return false;
	
	return true;
}
//************************************************************************
function isValidURL(str)
{
	 //var exp = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
	 var exp = /^(((ht|f)tp(s?))\:\/\/)?(www.|[a-zA-Z].)[a-zA-Z0-9\-\.]+\.([a-zA-Z]+)(\:[0-9]+)*(\/($|[a-zA-Z0-9\.\,\;\?\'\\\+&%\$#\=~_\-]+))*$/;
	 var regex = new RegExp(exp);
     var result;

     if (str.length > 0)
     {
          return regex.test(str);          
     }
     else
     {
	     return false;
	 }
}
//************************************************************************

function openWinLink(urlLink)
{
// remember you will need to put this form in the page yo call this JS function from
//<form name="locator" action="location.cfm" method="post" target="locatorWin">
//	<input type="hidden" name="url_string" value="">
//</form>

// and you will need the location.cfm page also to display the page

	tempFormValue = "document.frm."+urlLink+".value";
	tempFormValue = eval(tempFormValue);
    firstChar = tempFormValue.charAt(0);

	if(firstChar =="/")
	{
		// testing a absolute link
		sendUrl = "http://"+location.hostname+tempFormValue;
		openWindow(sendUrl,'', '', '', '', '', '', '', '', '', '');		
//		document.locator.url_string.value= sendUrl;
//		document.locator.submit();
		return true;	
	}
	else
	{
		// testing a http link
		var VarHTTP = document.frm[urlLink].value;
		if (document.frm[urlLink].value=="")
		{
			alert('You must enter a valid URL to show');
			return false;
		}
		else
		{
			sStr = VarHTTP.substring(0,7);
			if (sStr.toLowerCase() != "http://")
			{
				alert('You must enter "http://" before: '+VarHTTP);	
				return false;
			}
		}	

		openWindow(document.frm[urlLink].value,'', '', '', '', '', '', '', '', '', '');
//		document.locator.url_string.value=document.frm[urlLink].value;
//		document.locator.submit();
		return true;
	}
	return false;
}

//************************************************************************
function y2k(number) { return (number < 1000) ? number + 1900 : number; }
 
var reason = '';


function checkDate(field,sep) 
{
	//returns -1 if a missing date, -2 if invalid separators, -3 if invalid date, 0 for valid date
	
	//set default separator
	if (!sep) sep = "/";
	var myDate = trim(field.value);
	
	//check if exists
	if (myDate == "") return -1;
	
	//check existence of correct separator	
	var index1 = myDate.indexOf(sep);
	if (index1 == -1) return -2;
		
 	var dateArrayFrom = myDate.split(sep);
	var date = dateArrayFrom[0];
	var month = dateArrayFrom[1];
	var year = dateArrayFrom[2];
	 
    var test = new Date(year,month-1,date);
 	if (year == y2k(test.getYear()) && (month-1 == test.getMonth()) && (date == test.getDate())) 
   	{
       //reason = '';
       return 0;
    } else {
       //reason = 'Valid format but an invalid date.';
       return -3;
    }
}

//************************************************************************
//returns -1 if missing time, -2 for invalid separators, -3 if invalid time, 0 if correct time
function checkTime(field,sep)
{
	var myTime = trim(field.value);
	
	//check if exists
	if (myTime.length == 0) return -1;
	
	//check existence of correct separator
	var sep = ":";
	var index1 = myTime.indexOf(":");
	
	if (index1 == -1) 
	{
		index1 = myTime.indexOf(".");
		if (index1 != -1) sep = "."
	}	
	
	if (index1 == -1) return -2; //invalid separator
	
   	var timeArrayFrom = myTime.split(sep);
	hours = timeArrayFrom[0]
	mins = timeArrayFrom[1]
	totalHM = parseInt(hours)+parseInt(mins);
	
	 if(!trim(myTime))//empty
 		return -3;
	 if(parseInt(totalHM) > 1259)
 		return -3;
	 if(parseInt(hours) > 12)// 12 hours time base
	 	return -3;
	 if(parseInt(mins) > 59)// 60 min time base
 		return -3;
	 if( isNaN(hours) || isNaN(mins) )// min or hour value is not a number
 		return -3;
	 if( (hours.length == 0) || (hours.length > 2) ) //hours can have only two digit at the max
 		return -3;
	 if( (mins.length == 0) || (mins.length > 2) )// mins can have two digit at the max
 		return -3;
	
	// ** not required cckdate.cfm converts .'s to :'s anyway
	//field.value = myTime.replace(sep,":"); //first convert any other separators to : format - 
		
	// passed all the test hence it is a valid time
	return 0;
	
}
//***************************************************************************

//use check boxes as radio boxes
function checkChoice(field, i) 
{
	if (field[i].checked == true) 
	{
		for (j = 0; j < field.length; j++)
			{
				if (j != i)
				{
					field[j].checked = false;
				}
    		}	
	}
}
//call it this way
//loop through and create a number of checkboxes... "#FieldValue#_small" is the unquie names #jcount# is the position in the loop
//<input type="Checkbox" name="#FieldValue#_small" value="#i#" onclick="checkChoice(document.frm.#FieldValue#_small,#jcount#)">

//***************************************************************************
// used in related artilce sections
// when user select the drop down box, its appropriate radio button is checked.
function SelectToRadioFocuss(formObject)
{
// formObject.checked = true;
 formObject.click();
}
//***************************************************************************
// add http infront of url
function addhttp(Formvalue)
{
	// check to see if the http:// exists in the string else add it
	rExp = /http:/gi;
	validstring = document.frm[Formvalue].value.search(rExp);

	if (validstring == -1)
		document.frm[Formvalue].value = "http://"+document.frm[Formvalue].value;
}

//***************************************************************************
// validate phone numbers
function validatePhone(string) {

    var Chars = "0123456789() ";
 
    for (var i = 0; i < string.length; i++) 
	{
       if (Chars.indexOf(string.charAt(i)) == -1)
	    return false;
    }
    return true;
}

// validate phone numbers
function isValidPhone(string) 
{
    var Chars = "0123456789() -";
 
    for (var i = 0; i < string.length; i++) 
	{
       if (Chars.indexOf(string.charAt(i)) == -1)
	    return false;
    }
    return true;
}

//returns -1 if fields is required and is null, returns -2 if it exceeds maxlength, returns -3 if type is invalid, otherwise returns 0
function checkTextBox(field,brequired,maxlength,type)
{	
	var strS = trim(field.value);
	if (brequired)
	{	
		if (strS.length == 0 || strS == "")	return -1;
	}
	if (maxlength) 
	{
		if (maxlength > 0)
			if (strS.length > maxlength) return -2;
	}
	if (type)
	{
		if (type == "email") 
		{
			if (strS.length != 0 && strS != "")
			{
				if (!isValidEmail(strS)) return -3;
			}	
		}	
	}
	return 0;
}

//***************************************************************************
function validateListSeparators(string) {

    var Chars = "~^";
 
    for (var i = 0; i < string.length; i++) 
	{
       if (Chars.indexOf(string.charAt(i)) != -1)
	    return true;
    }
    return false;
}
//***************************************************************************

/* START JS Browser detect code */
var bow="n";
var bow1="n";

bName = navigator.appName;
bVer = parseInt(navigator.appVersion);

if (bName == "Netscape" && bVer >= 3)
{
	bow = "ok";
	bow1 = "ok";
}
else if (bName == "Microsoft Internet Explorer" && bVer > 3)
{
	bow = "ok";
	bow1="ok";
}
else if (bName == "Microsoft Internet Explorer" && bVer >=2)
{
	bow = "ok";
}

var IS_AOL=0;

if (navigator.userAgent)
{
	if (navigator.userAgent.indexOf("AOL") >=0)
	{
		IS_AOL=1;
		bow1="n";
	}
}
else
{
	bow="n"
	bow1="n";
}
/* END JS Browser detect code */

function fOpenContentPoolWindow(contentPoolURL)
{
	return openWindow(contentPoolURL,'contentPoolWin', 'yes', 'yes', 'yes', 'yes', '800', '800', 'yes', 'no', 'no');	
}

function openWindow(f, t, m, l, s, r, w, h, st, tool, d)
{
	var fn_filename = "";
	var fn_target = "_blank";
	var fn_menubar = "yes";
	var fn_location = "yes";
	var fn_scrollbars = "yes";
	var fn_resizable = "yes";
	var fn_width = "600";
	var fn_height = "400";
	var fn_status = "yes";
	var fn_toolbar = "yes";
	var fn_directories = "yes";
	
	if (arguments.length > 0)
	{
		if (f != "" || f != null) fn_filename = f;
		if (t != "" || t != null) fn_target = t;
		if (m == "no") fn_menubar = m;
		if (l == "no") fn_location = l;
		if (s == "no") fn_scrollbars = s;
		if (r == "no") fn_resizable = r;
		if (w > 0) fn_width = w;
		if (h > 0) fn_height = h;
		if (st == "no") fn_status = st;
		if (tool == "no") fn_toolbar = tool;
		if (d == "no") fn_directories = d;
	}
	
	self.name="mainWin";
	
    if (bow!="ok") return (true);
	
	argumentString = 'menubar='+fn_menubar+',location='+fn_location+',scrollbars='+fn_scrollbars+',resizable='+fn_resizable+',width='+fn_width+',height='+fn_height+',status='+fn_status+',toolbar='+fn_toolbar+',directories='+fn_directories;
	
	remote =  window.open(fn_filename,fn_target,argumentString);

    if (remote == null) return true;

    if(bow1 == "ok"){
		window.setTimeout('focusWin()',1000);
	}
	return (false);
}

function focusWin(){
	if(!remote.closed){
		remote.focus();
	}
}
//***************************************************************************
function replaceSubstring(inputString, fromString, toString) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function
//returns the value currently selected in an array of radio buttons

//***************************************************************************
function getSelectedRadioValue(field)
{
	if (field.length)
	{
		for (i=0; i < field.length; i++)
		{
			if (field[i].checked)
				return trim(field[i].value);
		}
	} else {
		if (field.checked)
			return trim(field.value);
	}
	return "";
}
//***************************************************************************
// move the selected objects up and down
function fMoveSelectedOption(objSelect,prefix,Direction)
{
	var objSelected = objSelect;
	var sel_field = prefix + "Selected";			// selected items select box
	var sel_list = prefix + "IDList";				// list of selected items in hidden form field for form submission
	var sel_filter = prefix + "Opts";
	var objFormMain = document.frm;
		
	//get selected id from fieldselect
	fieldselectInd = objSelected.selectedIndex;

	//alert(fieldselectInd);
	if (fieldselectInd == null||fieldselectInd<=0)
		return;	
	
	if ((Direction=="Up"&&fieldselectInd<=1)||(Direction=="Down"&&fieldselectInd>=(objSelected.length-1)))
		return;
	
	if (Direction == "Up")
		fieldtoswapInd = fieldselectInd -1;
	else 
		fieldtoswapInd = fieldselectInd +1;
	
	//get the value & text of the option of the selected option
	var strValue1 = objSelected.options[fieldselectInd].value;
	var strText1 = objSelected.options[fieldselectInd].text;
	
	//get the value & text of the option to swap this one with
	var strValue2 = objSelected.options[fieldtoswapInd].value;
	var strText2 = objSelected.options[fieldtoswapInd].text;
			
	var orderDisplayNum1 = fieldselectInd;
	var orderDisplayNum2 = fieldtoswapInd;

	//set the values of the one we are swapping with the selected
	objSelected.options[fieldtoswapInd].value = strValue1;
	objSelected.options[fieldtoswapInd].text = orderDisplayNum2 + strText1.substring(1,strText1.length);
	
	//set the selected items values to the swapped items values
	objSelected.options[fieldselectInd].value = strValue2; 
	objSelected.options[fieldselectInd].text = orderDisplayNum1 + strText2.substring(1,strText2.length);
	
	objSelected.selectedIndex = fieldtoswapInd;
	//changeEditOption(objForm,FieldPrefix);
	edflag = 1;
	setHiddenFromSelect(objFormMain[sel_field], objFormMain[sel_list], ",");
}

//***************************************************************************
function fCheckOpenerWindow(errorMessage)
{
	if (!errorMessage)
		errorMessage = "You may have closed the window containing the form to update. Please re-open the Entry Form to try again.\n";
	//if window has been closed
	if (top.window.opener.closed)
	{
		alert(errorMessage);
		top.close();
		return false;
	}	
	return true;
}	


//create temp form for passing image attributes as form elements
function fResetImageForm()
{	
	formName = "TempImageForm";
	if (!document.forms[formName])
	{
		//create form
		newForm = document.createElement("<form name=\""+ formName + "\"></form>"); 
		newForm.method = "POST";
		newForm.target = "windowLibrary";
		document.appendChild(newForm); 
		
		//gain reference to form
		objImageForm = document.forms[formName];
		
		//create hidden input fields
		objObjectID = document.createElement("<input type=\"hidden\" name=\"objectID\" value=\"\">");
		objImageCaption = document.createElement("<input type=\"hidden\" name=\"caption\" value=\"\">");
		objImageAlignment = document.createElement("<input type=\"hidden\" name=\"alignment\" value=\"\">");
		objImageDefaultCaption = document.createElement("<input type=\"hidden\" name=\"blnDefaultCaption\" value=\"\">");
		
		//add inputs to image form
		objImageForm.appendChild(objObjectID);
		objImageForm.appendChild(objImageCaption);
		
		objImageForm.appendChild(objImageAlignment);
		objImageForm.appendChild(objImageDefaultCaption);
		
	}	
	//reset values
	objImageForm.action = SiteURL + "library/image/instance_frameset.cfm?";

	//hidden form fields	
	objImageForm.objectID.value = '';
	objImageForm.caption.value = '';
	objImageForm.alignment.value = '';
	objImageForm.blnDefaultCaption.value = '';
	
}

//set the image form
function fSetImageForm(sImageID, sImageFileName, sImageCaption, sImageAlignment, bDefaultCaption)
{
	objImageForm.objectID.value = sImageID;
	objImageForm.caption.value = sImageCaption;
	objImageForm.alignment.value = sImageAlignment;
	objImageForm.blnDefaultCaption.value = bDefaultCaption;
}

function stripHTML(str)
{
	a = str.indexOf('<');
	b = str.indexOf('>');
	len = str.length;
	c = str.substring(0, a);

	if(b == -1) {
		b = a;
	}

	d = str.substring((b + 1), len);
	str = c + d;
	cont = str.indexOf('<');
	if (cont != -1) {
		str = stripHTML(str);
	}
	return str;	
}
function makeDateInMS(tDate, sep)
{
	if (!sep) sep = "/";
	var dateArrayFrom = tDate.split(sep);
	var date = dateArrayFrom[0];
	var month = dateArrayFrom[1];
	var year = dateArrayFrom[2];
 	//alert(tDate);
    var rDate = new Date(year,month-1,date);
	//alert(rDate);
	return rDate.getTime();
}

function dateCompare(startdate,enddate)
{
 	if (!isValidDate(startdate) || !isValidDate(enddate))
		return -2;
		
	var sDate = makeDateInMS(startdate.value);
	var eDate = makeDateInMS(enddate.value);

	if (sDate < eDate)
		return -1;
		
	if (sDate == eDate)
		return 0;

	if (sDate > eDate)
		return 1;

}

function isValidDate(field) 
{

	//set default separator
	var myDate = trim(field.value);

	//check if exists
	if (myDate.length == 0) return 0;
		
	//check existence of correct separator	
	var sep = "/";
	var index1 = myDate.indexOf("/");
	
	if (index1 == -1) 
	{
		index1 = myDate.indexOf("-");
		if (index1 != -1) sep = "-"
	}	
	
	if (index1 == -1) return 0; //invalid separator
		
 	var dateArrayFrom = myDate.split(sep);
	var date = dateArrayFrom[0];
	var month = dateArrayFrom[1];
	var year = dateArrayFrom[2];
	 
    var myDateObj = new Date(year,month-1,date);
 	if (year == y2k(myDateObj.getYear()) && (month-1 == myDateObj.getMonth()) && (date == myDateObj.getDate())) 
       return 1;
    else
		return 0; //reason = 'Valid format but an invalid date.';
       
}

