
/* ********************************************************************* */
/*
	build a tcl list out of the inputs
*/
function openwindow(url) {
window.open(url,'break_window','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,height=470,width=530');
}

function bnopenwindow(url) {
window.open(url,'break_window','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,height=470,width=530');
}

function ssopenwindow (url,windowname,vsize,hsize) {
window.open(url,windowname,'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,height=vsize,width=hsize');
}


/* ********************************************************************* */


/*
	build a tcl list out of the inputs
*/
function Consolidate() {
	
	/* get the number of arguments that were passed in... */
	var numArguments = arguments.length;
	
	/* form is the first argument */
	theForm = arguments[0];
	
	
	/* process each argument */
	for (var i = 1; i < numArguments; i=i+2) {
		theSelect = arguments[i];
		theHidden = arguments[i+1];
		cons_str = "{";
		for (j=0; j < theSelect.length; j++) {
			cons_str += "{" + theSelect.options[j].value + "} ";
		}
		cons_str += "}";
		theForm[theHidden].value = cons_str;
	}
	return true;
}


/* ********************************************************************* */


/*
	validate form values
*/
function Validate() {
/* should probably also perform validation for radio buttons */
	
	/* get the number of arguments that were passed in... */
	var numArguments = arguments.length;
	
	/* initialize the return value */
	var returnValue = true;
	var returnMessage = "";
	
	/* initialize the error flags */
	var textErr = false;
	var textareaErr = false;
	var singleselectErr = false;

	/* for each argument, verify that the form field has a value */
	for (var i = 0; i < numArguments; i++) {
		
		if (arguments[i].type == "text") {
			if (arguments[i].value == "") {
				if (textErr == false) {
					returnMessage += "Please fill in all required text fields.\n";
					textErr = true;
				}
				arguments[i].focus();
				returnValue = false;
			}
		} else if (arguments[i].type == "textarea") {
			if (arguments[i].value == "") {
				if (textareaErr == false) {
					returnMessage += "Please fill in all required text areas.\n";
					textareaErr = true;
				}
				arguments[i].focus();
				returnValue = false;
			}		
		} else if (arguments[i].type == "select-one") {
			if (arguments[i].options[arguments[i].selectedIndex].value == "") {
				if (singleselectErr == false) {
					returnMessage += "Please fill in all required select box fields.\n";
					singleselectErr = true;
				}
				arguments[i].focus();
				returnValue = false;
			}
		}
	}
	
	/* present error message if errors encountered */
	if (returnValue == false) {
		alert(returnMessage);
	}
	
	return returnValue;
}


/* ********************************************************************* */


/*	
	the category and sub-category select boxes depend on one another,
	so populate them accordingly.  this code is only used within the
	admin pages
*/
function BuildSelectOptions(category1, category2, changedArray) {
	/* get the arrays of new options */
	if (category1.selectedIndex == 0 && changedArray == category1) {
		/* set all arrays empty */
		category2.options.length = 0;
		category2.options[0] = new Option("----- None -----", ""); 
		category2.selectedIndex = 0;
		return;
	} else if (changedArray == category1) {
		var index1 = (3 * category1.selectedIndex) - 1;
		var category2Array = categoryArray[index1];
	} else {
		var index1 = (3 * category1.selectedIndex) - 1;
		var index2 = (3 * category2.selectedIndex) - 1;
		var category2Array = categoryArray[index1];
	}
	
	/* rebuild the option lists */
	if (changedArray == category1) {
		category2.options.length = 0;
		if (category2Array.length == 0) {
			category2.options[0] = new Option("----- None -----", "");
			startidx = 0;
		} else {
			startidx = 1;
		}

	for (i=1; i < category2Array.length; i=i+3) {
			category2.options[((i+2)/3)-startidx] = new Option(category2Array[i-1], category2Array[i]);
		}
			category2.selectedIndex = 0;
	}
}

/* ********************************************************************* */

/*	
	the category and sub-category select boxes depend on one another,
	so populate them accordingly.  this code is only used within the
	admin pages
*/
function BuildListingSelectOptions(category1, category2) {
	/* get the arrays of new options */
	if (category1.selectedIndex == 0) {
		/* set all arrays empty */
		category2.options.length = 0;
		category2.options[0] = new Option("----- None -----", ""); 
		category2.selectedIndex = 0;
		return;
	} else {
		var index = (3 * category1.selectedIndex) - 1;
		var category2Array = listingCategoryArray[index];
		category2.options.length = 0;
		category2.options[0] = new Option("----- None -----", "");
		for (i=1; i < category2Array.length; i=i+2) {
			category2.options[(i+1)/2] = new Option(category2Array[i-1], category2Array[i]);
		}
		if (i > 1) {
			category2.selectedIndex = 1;
		} else {
			category2.selectedIndex = 0;
		}
	}
}

/* ********************************************************************* */

/*	
	similar to the above two functions (can't i make them all common?)
	populate some select lists based on values selected from other
	boxes
*/
function BuildSimpleSelectOptions(selectArray, select1, select2) {
	/* get the arrays of new options */
	if (select1.selectedIndex == 0) {
		/* set all arrays empty */
		select2.options.length = 0;
		select2.options[0] = new Option("----- None -----", ""); 
		select2.selectedIndex = 0;
		return;
	} else {
		var index = (2 * select1.selectedIndex) - 1;
		var selectArrayValue = selectArray[index];
		select2.options.length = 0;
		select2.options[0] = new Option("----- None -----", "");
		for (j = 0; j < selectArrayValue.length; j=j+2) {
			select2.options[(j/2)+1] = new Option(selectArrayValue[j+1], selectArrayValue[j]);
		}
		if (j > 1) {
			select2.selectedIndex = 1;
		} else {
			select2.selectedIndex = 0;
		}
	}
}

/* ********************************************************************* */


/*	
	before submitting a form make sure all select box options from a
	specified select box are selected.  this is useful when we are
	asking a user to order their favorites, for example.
*/
function SelectAll (selbox) {
	
	for (i=0; i < selbox.length; i++) {
		selbox.options[i].selected = true;
	}
	return true;
}


/* ********************************************************************* */


/*	
	surprisingly enough, this function moves an item up within a
	select box.
*/
function MoveItemUp (selbox) {
	selection = selbox.selectedIndex;
	if (selection == -1) {
		alert("Please select content topic first.");
	} else if (selection == 0 ) {
		// Already at top
	} else {
		// Obtain current selection
		SelValue = selbox.options[selection].value;
		SelText  = selbox.options[selection].text;
		
		// Swap Em with the one above
		selbox.options[selection].value = selbox.options[selection-1].value;
		selbox.options[selection].text = selbox.options[selection-1].text;
    
		selbox.options[selection-1].value = SelValue;
		selbox.options[selection-1].text = SelText;
    
		// Set next selection so that it stays on the same item
		selbox.selectedIndex--;
	}
}


/* ********************************************************************* */


/*	
	...and this function moves an item down within a select box.
*/
function MoveItemDown (selbox) {
	selection = selbox.selectedIndex;
	if (selection == -1) {
		alert("Please select content topic first.");
	} else if (selection == selbox.length-1 ) {
		// Already at bottom
	} else {
		// Obtain current selection
		SelValue = selbox.options[selection].value;
		SelText  = selbox.options[selection].text;
    
		// Swap Em with the one below
		selbox.options[selection].value = selbox.options[selection+1].value;
		selbox.options[selection].text = selbox.options[selection+1].text;
    
		selbox.options[selection+1].value = SelValue;
		selbox.options[selection+1].text = SelText;
    
		// Set next selection so that it stays on the same item
		selbox.selectedIndex++;
	}
}


/* ********************************************************************* */


/*
	before submitting a form set a hidden value to hold the select
	box value.  this is used primarily with the admin templates
*/
function AdminSelectValue(theSelect, theForm, theHidden) {
	if (theSelect.selectedIndex != 0) {
		theHidden.value = theSelect.options[theSelect.selectedIndex].value;
		theForm.submit()
	}
}

/* ********************************************************************* */

/*
	when a value is updated, set a radio value to the first
	element in the radio button array.
*/
function UpdateRadio(theForm, theRadioName) {

	/*	
		loop through the form, looking for radio buttons with
		the right name.  Note that this is necessary because
		redio buttons are stored as arrays, and we want to
		avoid using []'s in Vignette code whenever possible.
	*/
	
	for (i=0; i < theForm.length; i++) {
		if (theForm[i].type == "radio" && theForm[i].name == theRadioName) {
			theForm[i].checked = true;
			break;
		}
	}
	return;
}


/* ********************************************************************* */


function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

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 MM_findObj(n, d) { //v3.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_showHideLayers() { //v3.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v='hide')?'hidden':v; }
    obj.visibility=v; }
}

function MM_nbGroup(event, grpName) { //v3.0
  var i,img,nbArr,args=MM_nbGroup.arguments;
  if (event == "init" && args.length > 2) {
    if ((img = MM_findObj(args[2])) != null && !img.MM_init) {
      img.MM_init = true; img.MM_up = args[3]; img.MM_dn = img.src;
      if ((nbArr = document[grpName]) == null) nbArr = document[grpName] = new Array();
      nbArr[nbArr.length] = img;
      for (i=4; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
        if (!img.MM_up) img.MM_up = img.src;
        img.src = img.MM_dn = args[i+1];
        nbArr[nbArr.length] = img;
    } }
  } else if (event == "over") {
    document.MM_nbOver = nbArr = new Array();
    for (i=1; i < args.length-1; i+=3) if ((img = MM_findObj(args[i])) != null) {
      if (!img.MM_up) img.MM_up = img.src;
      img.src = (img.MM_dn && args[i+2]) ? args[i+2] : args[i+1];
      nbArr[nbArr.length] = img;
    }
  } else if (event == "out" ) {
    for (i=0; i < document.MM_nbOver.length; i++) {
      img = document.MM_nbOver[i]; img.src = (img.MM_dn) ? img.MM_dn : img.MM_up; }
  } else if (event == "down") {
    if ((nbArr = document[grpName]) != null)
      for (i=0; i < nbArr.length; i++) { img=nbArr[i]; img.src = img.MM_up; img.MM_dn = 0; }
    document[grpName] = nbArr = new Array();
    for (i=2; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
      if (!img.MM_up) img.MM_up = img.src;
      img.src = img.MM_dn = args[i+1];
      nbArr[nbArr.length] = img;
  } }
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}


/* ********************************************************************* */


/*
	before submitting the form for sendmail, validate the fields to ensure
	that they are filled up and of the correct format (for email addresses).
*/


function validateFields(toField, fromField) {
	// Check that the To: and From: fields are not empty
	if (toField == "") {
		alert("Please fill in the email address(es) to send to.");
		return false;
	}
	else if (fromField == "") {
		alert("Please fill in the email address you are sending from.");
		return false;
	}
	else {
	// Split the email addresses which are separated by commas or semi-colons into separate elements of an array.
	var result = toField.split(/(\s*,\s*)|(\s*;\s*)/);

	// Define the regular expression to match the format of an email address.
	var pattern = new RegExp("[a-z0-9]+@*+[\.][a-z0-9]+.*", "i");
	
	// Try to match each element of the array with the regular expression to check for valid email address format.
	for(var i = 0; i < result.length; i++) {
		if (!(pattern.test(result[i]))) {
			alert(result[i] + " is not a valid email address format.");
			return false;
		}
	}
	return true; 
	}	
}


/* ********************************************************************* */


/*
	open a new window to use when searching for articles
*/

function openWin(theURL) {
	searchWin = window.open(theURL, '', 'width=450,height=450,stat=no,resizeable=no,scrollbars=yes');
}


/* ********************************************************************* */


/*
	set headline and article ID from a search query.  note that
	we search through the window that opened this window, searching
	for our fields by name.  this is done because there is no easy
	way to pass a reference to the forms to this function.
*/

function SetArticle(headline, id, theID, theHeadline, theHeadlineOld, theForm) {
	var i = 0;
	var j = 0;
	var k = 0;
	var l = 0;
	while (i < 100 && window.opener.document.forms[i].name != theForm) {
		i++;
	}
	/* the form has been found, find the ID */
	while (j < 100 && window.opener.document.forms[i].elements[j].name != theID) {
		j++;
	}
	if (j == 100) {
		alert("Error setting article ID");
		return;
	}
	/* the ID has been found, set it */
	window.opener.document.forms[i].elements[j].value = id;
	/* find the headline */
	while (k < 100 && window.opener.document.forms[i].elements[k].name != theHeadline) {
		k++;
	}
	if (k == 100) {
		alert("Error setting article headline");
		return;
	}
	/* the headline has been found, set it */
	window.opener.document.forms[i].elements[k].value = headline;
	/* find the old headline */
	while (l < 100 && window.opener.document.forms[i].elements[l].name != theHeadlineOld) {
		l++;
	}
	if (l == 100) {
		alert("Error setting article headline");
		return;
	}
	/* the old headline has been found, set it */
	window.opener.document.forms[i].elements[l].value = headline;
	/* close this window */
	window.close();
}

/*
	scripts for ecards
*/

function setImagePath(theForm)
{		
	// Used by Ecards(admin).
	//  Cards Directory	
	var ecards_basePath = "http://straitstimes.asia1.com.sg/mnt/html/ecards/";
	var ecards_basePath_nday2001 = "http://straitstimes.asia1.com.sg/mnt/html/webspecial/nday2001/ecards/";
		
	if (theForm.form_cat.value == "nday2001")
	{
		theForm.form_fpath.value = ecards_basePath_nday2001;
		theForm.form_tpath.value = ecards_basePath_nday2001;
	}
}
	
function selectImg(theForm, theHidden, theValue) 
{
	// Used by Ecards(admin).
	theHidden.value = theValue;
	theForm.submit();
}

function checkEcardId(theForm) 
{
	// Used by Ecards(public).
	
	// Check image_ID
	if (theForm.form_did.value == -1) 
	{
		alert("Please select a card before proceeding.");					
		return false;
	}
		
}

function checkFormValues(theForm) 
{
	// Used by Ecards(public).

	// Set email alert 
	if (theForm.form_emailalert.checked) {
		theForm.form_emailalert_val.value = 1;
	} else {
		theForm.form_emailalert_val.value = 0;	
	}
	
	// Verify Sender's Email
	if ((theForm.form_sem.value.indexOf("@") == -1) || (theForm.form_sem.value.indexOf(".") == -1))
	{
		alert("Please check your email address.");
		return false;
	}
			
	// Verify Recipients' Email
	if ((theForm.form_rem.value.indexOf("@") == -1) || (theForm.form_rem.value.indexOf(".") == -1))
	{
		alert("Please check your recipient's email address.");
		return false;
	}
			
}

function setPreviewFlag(theForm, theValue)
{
	// Used by Ecards(public).	
	theForm.form_preview_flag.value = theValue;	
}

function selectCard(theForm, theValue)
{
	document.form1.form_cid.value = theValue;
	theForm.submit();
}

function setWinLocation()
{
	var cookieName = 'testCookie' + (new Date().getTime());
	document.cookie = cookieName + '=cookieValue';
	if (document.cookie.indexOf(cookieName) == -1) {
	   alert('Please enable cookies in your browser so that this function will work correctly.');
	}

	cookie_name = "back_count";
	if(document.cookie) {
		index = document.cookie.indexOf(cookie_name);
		if (index != -1) {
			namestart = (document.cookie.indexOf("=", index) + 1);
			nameend = document.cookie.indexOf(";", index);
			if (nameend == -1) {
				nameend = document.cookie.length;
			}
			hit_count = document.cookie.substring(namestart, nameend);
			p_his = -(parseInt(hit_count) + 1);
			hit_count = 0;
			document.cookie=cookie_name+"="+hit_count+";";
			history.go(p_his);
		} else {
			history.back();
		}
	}
}

function incrHistory()
{
	cookie_name = "back_count";
	if(document.cookie) { 
		index = document.cookie.indexOf(cookie_name);
	} else { 
		index = -1;
	}
	if (index == -1) {
		hit_count = 1;
		document.cookie=cookie_name+"="+hit_count+";";
	} else {
		namestart = (document.cookie.indexOf("=", index) + 1);
		nameend = document.cookie.indexOf(";", index);
		if (nameend == -1) { 
			nameend = document.cookie.length;
		}
		hit_count = document.cookie.substring(namestart, nameend);
		hit_count = parseInt(hit_count) + 1;
		document.cookie=cookie_name+"="+hit_count+";";
	}
}

/*
	Set expiry date
*/

function setAdminExpiryDate(theForm) {
	if (theForm.cat1.options[theForm.cat1.selectedIndex].value == 230000) {		
		if (theForm.cat2.options[theForm.cat2.selectedIndex].value == 230100) {
			if (theForm.releaseDay.selectedIndex >= theForm.expireDay.length) {			
				theForm.expireDay.selectedIndex = theForm.expireDay.length - 1;				
			} else {
				theForm.expireDay.selectedIndex = theForm.releaseDay.selectedIndex;
			}			
			if (theForm.releaseMonth.selectedIndex == 11) {
				theForm.expireMonth.selectedIndex = 0;
				theForm.expireYear.selectedIndex = theForm.releaseYear.selectedIndex + 1;
			} else { 																		 
				theForm.expireMonth.selectedIndex = theForm.releaseMonth.selectedIndex + 1;
				theForm.expireYear.selectedIndex = theForm.releaseYear.selectedIndex;
			}	
		} else if (theForm.cat2.options[theForm.cat2.selectedIndex].value == 230300) {
			if (theForm.releaseDay.selectedIndex >= theForm.expireDay.length) {
				theForm.expireDay.selectedIndex = theForm.expireDay.length - 1;
			} else {
				theForm.expireDay.selectedIndex = theForm.releaseDay.selectedIndex;
			}													 
			if (theForm.releaseMonth.selectedIndex >= 9) {
				theForm.expireMonth.selectedIndex = theForm.releaseMonth.selectedIndex - 9;
				theForm.expireYear.selectedIndex = theForm.releaseYear.selectedIndex + 1;
			} else { 																		 
				theForm.expireMonth.selectedIndex = theForm.releaseMonth.selectedIndex + 3;
				theForm.expireYear.selectedIndex = theForm.releaseYear.selectedIndex;
			}													
		} else {
			if (theForm.releaseDay.selectedIndex >= theForm.expireDay.length) {
				theForm.expireDay.selectedIndex = theForm.expireDay.length - 1;
			} else {
				theForm.expireDay.selectedIndex = theForm.releaseDay.selectedIndex;
			}													 
			if (theForm.releaseMonth.selectedIndex > 5) {
				theForm.expireMonth.selectedIndex = theForm.releaseMonth.selectedIndex - 6;
				theForm.expireYear.selectedIndex = theForm.releaseYear.selectedIndex + 1;
			} else { 																		 
				theForm.expireMonth.selectedIndex = theForm.releaseMonth.selectedIndex + 6;
				theForm.expireYear.selectedIndex = theForm.releaseYear.selectedIndex;
			}				
		}		
		theForm.expireHour.selectedIndex = theForm.releaseHour.selectedIndex;
		theForm.expireMinute.selectedIndex = theForm.releaseMinute.selectedIndex; 
		theForm.expireAMPM.selectedIndex = theForm.releaseAMPM.selectedIndex;						
	}
}


/*
	NewsInPics specific settings
*/

function setAdminNewsInPicsValues(theForm) {
	if (theForm.loc.options[theForm.loc.selectedIndex].value == "newsinpicturesdisplay") {		
		if (theForm.pos.options[theForm.pos.selectedIndex].value == 3065) {
		   if (theForm.src.value == "/mnt/media/image/staging/") {
		   	  theForm.src.value = "/mnt/media/image/staging/" + theForm.objm.value + ".jpg";
		   } else {
              	
			  sourceString = theForm.src.value;
			  sourcelength = sourceString.length; 
			  firstPos = 0;			 
		   	  lastPos = sourceString.lastIndexOf('/');
			  newPathString = sourceString.substring(firstPos, lastPos + 1);		     	  
		   	  theForm.src.value =  newPathString + theForm.objm.value + ".jpg";		   
		   }
		   //theForm.releaseHour.selectedIndex = 2;
		   //theForm.releaseMinute.selectedIndex = 0; 
		   //theForm.releaseAMPM.selectedIndex = 1;
		   /*
		   theForm.expireHour.selectedIndex = theForm.releaseHour.selectedIndex;
		   theForm.expireMinute.selectedIndex = theForm.releaseMinute.selectedIndex; 
		   theForm.expireAMPM.selectedIndex = theForm.releaseAMPM.selectedIndex;								   
		   if ((theForm.releaseDay.selectedIndex + 7) >= theForm.releaseDay.length) {			
			  theForm.expireDay.selectedIndex = 7 - (theForm.releaseDay.length - theForm.releaseDay.selectedIndex);
		   	  if (theForm.releaseMonth.selectedIndex == 11) {
			  	 theForm.expireMonth.selectedIndex = 0;
			  	 theForm.expireYear.selectedIndex = theForm.releaseYear.selectedIndex + 1;
		   	  } else { 																		 
			  	 theForm.expireMonth.selectedIndex = theForm.releaseMonth.selectedIndex + 1;
			  	 theForm.expireYear.selectedIndex = theForm.releaseYear.selectedIndex;
		   	  }			  				
		   } else {
			  theForm.expireDay.selectedIndex = theForm.releaseDay.selectedIndex + 7;
		   }
		   */				   					   
		}		
	}
}

function setAdminNewsInPicsPosition(theForm) {
	if (theForm.loc.options[theForm.loc.selectedIndex].value == "newsinpicturesdisplay") {		
		if (theForm.pos.options[theForm.pos.selectedIndex].value == 3065) {
			underscorePos = theForm.src.value.lastIndexOf('_');
			dotPos = theForm.src.value.lastIndexOf('.');			
			index = theForm.src.value.substring(underscorePos + 1, dotPos);
			theForm.f_objectLinkPosition.selectedIndex = index * 10;
		}
	}
}			   

