// Copyright © 1999 Khanh Nguyen
// http://www.mongolianhorde.com/
// This site was made for Netscape Navigator 4.0 and Internet Explorer 4.0 or better.

function Is() {
	var agent = navigator.userAgent.toLowerCase();
	this.major = parseInt(navigator.appVersion);
	this.minor = parseFloat(navigator.appVersion);
	this.ns  = ((agent.indexOf('mozilla')!=-1) && ((agent.indexOf('spoofer')==-1) && (agent.indexOf('compatible') == -1)));
	this.ns2 = (this.ns && (this.major == 2));
	this.ns3 = (this.ns && (this.major == 3));
	//this.ns4 = (this.ns && (this.major >= 4));   // line causes problem with new menu (unable to click links on menu)
	this.ie   = (agent.indexOf("msie") != -1);
	this.ie3  = (this.ie && (this.major == 2));
	this.ie4  = (this.ie && (this.major >= 4));
    this.ie5  = (this.ie && ((agent.indexOf('msie 5'))!=-1));
    this.ie6  = (this.ie && ((agent.indexOf('msie 6'))!=-1));
    this.ie7  = (this.ie && ((agent.indexOf('msie 7'))!= -1));
	this.op3 = (agent.indexOf("opera") != -1);
	this.platform = (navigator.appVersion.indexOf("Mac") != -1) ? "mac" : "win";
	this.ns4up = (this.ns && (this.major >= 4));
}

var is  = new Is();
menu_visibility = false;

if(is.ns4) {
	doc = "document";
	sty = "";
	htm = ".document"
} else if(is.ie4) {
	doc = "document.all";
	sty = ".style";
	htm = ""
}

function showLayer(whichOne)
{
	// NS 4
	if (document.layers)
		document.layers[whichOne].visibility="show"
	// IE 5 & 6
	if (document.all)
		document.all[whichOne].style.visibility="visible"
	// NS 6
	if (document.getElementById && !document.all)
		document.getElementById(whichOne).style.visibility="visible"

	return;
}


function toggle_menu()
{
  menu_bar = eval(doc + '["menubar"]' + sty);
  if (menu_visibility)
  {
    menu_bar.top = -800;
    menu_visibility = false;
  }
  else
  {
    menu_visibility = true;
    menu_bar.top = 82;
  }
}

document.onmousemove = mouseMove;
if (is.ns4) document.captureEvents(Event.MOUSEMOVE | Event.MOUSEMOVE);

function mouseMove(e){
	var x;
	var y;
	if (is.ns4){ x = e.pageX; y = e.pageY }
	if (is.ie4){ x = event.x; y = event.y }
}

function swap_image(image_path,image_name,image_value)
{
  document.images[image_name].src = image_path + image_name + image_value + ".gif";
}

function swap_sequenced_image(image_path,image_name,image_value,image_seq)
{
  document.images[image_name + image_seq].src = image_path + image_name + image_value + ".gif";
}

function write_description(text){
  description_box = eval(doc + '["description"]' + htm);
	if(is.ns4) {
		description_box.write(text);
		description_box.close();
	} else {
		description_box.innerHTML = text;
	}
}

function maketheBalloon(id, width, message)
{
   var theString = '<STYLE TYPE="text/css">#'+id+'{width:'+width+';}</STYLE>';
   theString+='<DIV CLASS="balloon" id="'+id+'">'+message+'</DIV>';
   document.write(theString);
}

function makeItVisible( id, object )
{
	// NS 4
	if (document.layers)
		document.layers[id].visibility="show"
	// IE 5 & 6
	if (document.all)
		document.all[id].style.visibility="visible"
	// NS 6
	if (document.getElementById && !document.all)
		document.getElementById(id).style.visibility="visible"

	return;
}

function hideHelp(id)
{
  is.ns4 ? document.layers[id].visibility="hide" : document.all[id].style.visibility="hidden";
}

function clear_form(form_name)
{
  var this_form = eval( "document."+form_name);
  this_form.reset();
}

function launch_help()
{
}

function launch_clipboard()
{
  window.open('clipboard.html','clipboard','width=670,height=300,status=no,location=no,toolbar=no,menubar=no,scrollbars=yes,resizable=yes');
}

function SetCookie (name, value) {
  var argv = SetCookie.arguments;
  var argc = SetCookie.arguments.length;
  var expires = (argc > 2) ? argv[2] : null;
  var path = (argc > 3) ? argv[3] : null;
  var domain = (argc > 4) ? argv[4] : null;
  var secure = (argc > 5) ? argv[5] : false;
  document.cookie = name + "=" + escape (value) +
  ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
  ((path == null) ? "" : ("; path=" + path)) +
  ((domain == null) ? "" : ("; domain=" + domain)) +
  ((secure == true) ? "; secure" : "");
//alert("SC: name = " + name + " value = " +  escape (value));
//alert("SC: document.cookie = " + document.cookie);
}

function DeleteCookie () {
  var exp = new Date();
  exp.setTime (exp.getTime() - 1000000000);  // This cookie is history
  var cval = GetCookie ('FreeStuffL');
  document.cookie ='FreeStuffL' + "=" + cval + "; expires=" + exp.toGMTString();
}

function getCookieVal (offset) {
  var endstr = document.cookie.indexOf (";", offset);
  if (endstr == -1)
    endstr = document.cookie.length;
//alert("GCV: " + unescape(document.cookie.substring(offset, endstr)));
  return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name)  {
  var arg = name + "=";
//alert("GC: name=" + name);
//alert("GC: document.cookie=" + unescape(document.cookie));
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen)  {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
      return getCookieVal (j);i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break;
  }
  return null;
}

document.onmouseup = mouseup;
if (is.ns4) document.captureEvents( Event.MOUSEUP | Event.MOUSEUP);

function mouseup(e){
  if (menu_visibility)
  {
    menu_bar = eval(doc + '["menubar"]' + sty);
    menu_bar.top = -800;
    menu_visibility = false;
  }
}
var keywordsearch = false;

function trapEnter(document,e)
{
var keycode;
if (keywordsearch)  return true;

 if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;

if (keycode == 13)
   {
   EnterHandler();
   return false;
   }
else
   return true;
}

function disableEnterKey()
{
   if (window.event.keyCode == 13) window.event.keyCode = 0;
}

function closePopUps()
{
	    var feedbackval = GetCookie ("feedback");
	    var basketval = GetCookie ("basket");
	    var preferenceval = GetCookie ("preference");
	    var gethelpval = GetCookie ("gethelp");
	    var previewval = GetCookie ("preview");
	    var messagesval = GetCookie ("msgsPopUp");
	    var aboutVal = GetCookie('about_window');
	    var reorderSetVal = GetCookie("reorderSetVal");
	    var reorderPDLVal = GetCookie("reorderPDLVal");
	    var MimeTypes = GetCookie("MimeTypes");
	    var comment_window = GetCookie("comment_window");
	    var task_window = GetCookie("task_window");
      var update_window = GetCookie("update_window");
	    var logEntry = GetCookie("logEntry");
	    var viewAssetVal = GetCookie("view_asset");
	    var participantSearchVal = GetCookie("ParticipantSearch");
	    var userSearchVal = GetCookie("UserSearch");
	    var adminSearchVal = GetCookie("AdminSearch");
            //alert("viewAssetVal = " + viewAssetVal);

	    if (aboutVal != null && aboutVal == "true")
        	{
        	 aboutWindow = window.open("","AboutWindow","height=1,width=1");
             aboutWindow.close();
        	}

        if (feedbackval != null && feedbackval == "true")
        	{
        	feedbackWindow = window.open("", "Feedback","height=1,width=1");
            feedbackWindow.close();
        	}
        if (basketval != null && basketval == "true")
        	{
        	 basketWindow = window.open("", "Basket","height=1,width=1");
             basketWindow.close();
        	}
        if (preferenceval != null && preferenceval == "true")
        	{
        	 personalWindow = window.open("", "Personalize","height=1,width=1");
             personalWindow.close();
        	}
        if (gethelpval != null && gethelpval == "true")
        	{
        	 helpWindow = window.open("","Help","height=1,width=1");
             helpWindow.close();
        	}
        if (previewval != null && previewval == "true")
        	{
        	 previewWindow = window.open("","Preview","height=1,width=1");
             previewWindow.close();
        	}
        if (messagesval != null && messagesval == "true")
        	{
        	 messagesWindow = window.open("","messages","height=1,width=1");
             messagesWindow.close();
        	}

        	if (reorderSetVal != null && reorderSetVal == "true")
        	{
        	 aboutWindow = window.open("","reorderAssets","height=1,width=1");
             aboutWindow.close();
        	}

        	if (reorderPDLVal != null && reorderPDLVal == "true")
        	{
        	 aboutWindow = window.open("","reorderVideos","height=1,width=1");
             aboutWindow.close();
        	}

        	if (MimeTypes != null && MimeTypes == "true")
        	{
        	 aboutWindow = window.open("","MimeTypes","height=1,width=1");
             aboutWindow.close();
        	}

        	if (comment_window != null && comment_window == "true")
        	{
        	 aboutWindow = window.open("","comment_window","height=1,width=1");
             aboutWindow.close();
        	}

        	if (task_window != null && task_window == "true")
        	{
        	 aboutWindow = window.open("","task_window","height=1,width=1");
             aboutWindow.close();
        	}

        	if (update_window != null && update_window == "true")
        	{
        	 aboutWindow = window.open("","update_window","height=1,width=1");
             aboutWindow.close();
        	}

        	if (logEntry != null && logEntry == "true")
        	{
        	 aboutWindow = window.open("","logEntry","height=1,width=1");
             aboutWindow.close();
        	}

        	if (viewAssetVal != null && viewAssetVal == "true")
        	{
        	 viewAssetWindow = window.open("","view_asset","height=1,width=1");
             viewAssetWindow.close();
        	}

        	if (participantSearchVal != null && participantSearchVal == "true")
        	{
        	 participantSearchWindow = window.open("","ParticipantSearch","height=1,width=1");
             participantSearchWindow.close();
        	}

        	if (userSearchVal != null && userSearchVal == "true")
        	{
        	 userSearchVal = window.open("","UserSearch","height=1,width=1");
             userSearchVal.close();
        	}

        	if (adminSearchVal != null && adminSearchVal == "true")
        	{
        	 adminSearchVal = window.open("","AdminSearch","height=1,width=1");
             adminSearchVal.close();
        	}
      }

function checkLimit( textObj, maxlength )
{
  if(textObj != null && textObj.value != null)
  {
    len = textObj.value.length;
    if(len > maxlength)
    {
      textObj.value = textObj.value.substr(0, len-1);
    }
  }
}

function getNumCheckedCheckboxesWithinForm(formName)
{
    formObject = eval("document." + formName + ";");
//    alert("formName = " + formName);
//    alert("formObject = " + formObject);
    var count = 0;
    
//	alert("number of elements = " + formObject.elements.length);    
    for(var i=0;i<formObject.elements.length; i++)
    {
//	 alert("i = " + i);
//	 alert("formObject.elements[i].name = " + formObject.elements[i].name);
	 if ( (formObject.elements[i].type == "checkbox") && (formObject.elements[i].checked == true) )
	 {
		 count++;
	 }
	 
	}
//	 alert("number of selected checkboxes = " + count);
	 return count;
 }

// the following 4 functions are to support workflow and its popup searching...
//
// the contract is that:
//   1. the checkboxes on the form all start with the name 'item'
//   2. the values of the checkboxes consist of '{id}:{name}'
//   3. the form that displays the checkboxes has the name 'tableform'
//   4. the browser window (i.e., the 'opener') that opened the search window has
//      a javascript method called 'processResults ( [array] )', where
//      the array consists of items each of which has a name and and id property.
//      when the popup is shown and the user makes selections and clicks OK,
//      the processResults method is called on the opener, with the array
//      containing the id's and name's of the selected items.

function Item(id, name)
{
 this.id = id;
 this.name = name;
}

function makeItemFromValue (unparsedValue)
{
  var xpos = unparsedValue.indexOf ( ":" );
	var xid = unparsedValue.substring(0,xpos);
	var xname = unparsedValue.substring(xpos+1, unparsedValue.length);
	var xitem = new Item ( xid,  xname );
	return xitem;
}

function getIDNamesForCheckboxes(msg)
{
 formObject = document.tableForm;
 var xitems = new Array();
 var xcnt = 0;
 for(i=0;i<formObject.elements.length; i++)
 {
   var xpos = formObject.elements[i].name.indexOf ("item");
   if ( xpos == -1 )
	 		continue;
	 var xitem;

	 if ( formObject.elements[i].checked )
	 {
	 	 xitem = makeItemFromValue ( formObject.elements[i].value );
		 xitems[xcnt] = xitem;
		 xcnt = xcnt + 1;
	 }
 }
 if (xitems.length > 0)
 {
    opener.processResults ( xitems );
    window.close();
 }
 else
 {
    alert(msg);
 }
}

function popSearchWin(url)
{
  popup = window.open(url, "ParticipantSearch", "height=600,width=750,top=100,left=100,scrollbars=yes,resizable=yes");
  popup.focus();
}

function popParticipantWin(url)
{
    popup=window.open(url, "ParticipantDetail", "height=400,width=825,top=100,left=150,scrollbars=yes,resizable=yes");
    popup.focus();
}

function showParticipantDetails(url, isPopup)
{
  if ( isPopup == true )
  {
    popParticipantWin (url);
  }
  else
  {
    window.location=url;
  }
}


function popUpdateWin(url)
{
  updateWindow = window.open(url, "update_window","height=450,width=510,top=100,left=250,dependent=yes,scrollbars=yes,status=no");
  updateWindow.focus();
}


// postUpdateURL variable MUST be defined PRIOR to util.js is included for all pages that display the "action project"
// option to the user.
// This option is usually invoked by using the method popUpdateWin() -- defined above.
// if the page does not set the postUpdateURL, then handlePostTaskUpdate() will just reload
// the page that was showing in the main window. This can be dangerous, because maybe the page that
// gets refreshed resubmits a form or something... so play it safe and just define the variable already!
function handlePostTaskUpdate(msg, wasSuccessful)
{
  var msgParam;
  if ( wasSuccessful == true && msg != null )
	{
	  msgParam="&infoMsg=" + msg;
	}
	if ( msgParam == null && msg != null )
	{
	  msgParam="&errMsg=" + msg;
	}

	if ( msgParam == null )
	{
	  msgParam="";
	}

        if ( !window.postUpdateURL )
	{
	  window.location = window.location+msgParam;
	}
	else
	{
	  window.location = window.postUpdateURL + msgParam;
	}

}




function moveUp(whichField,whichForm) {
  theSelect = eval( "document." + whichForm + "." + whichField + ";" );
  fieldOrder = eval( "document." + whichForm + "." + whichField + "_order;" );
  selectedFieldIndex = theSelect.selectedIndex;
  if ((selectedFieldIndex > 0) && (selectedFieldIndex != -1)) {
    var temptext = new Array();
    var tempvalues = new Array();
    for (i=0; i < theSelect.length; i++) {
      temptext[ i ] = theSelect.options[i].text;
      tempvalues[ i ] = theSelect.options[i].value;
    }
    temptext[ selectedFieldIndex - 1 ] = theSelect.options[selectedFieldIndex].text;
    temptext[ selectedFieldIndex ] =theSelect.options[ selectedFieldIndex - 1 ].text;
    tempvalues[ selectedFieldIndex - 1 ] = theSelect.options[selectedFieldIndex].value;
    tempvalues[ selectedFieldIndex ] = theSelect.options[ selectedFieldIndex - 1 ].value;
    for (i = 0; i < theSelect.length; i++) {
      theSelect.options[i].text = temptext[i];
      theSelect.options[i].value = tempvalues[i];
      fieldOrder[i].value = tempvalues[i];
    }
    theSelect.options[ selectedFieldIndex ].selected = false;
    theSelect.options[ selectedFieldIndex - 1].selected = true;
  }
}

function moveDown(whichField,whichForm) {
  theSelect = eval( "document." + whichForm + "." + whichField + ";" );
  fieldOrder = eval( "document." + whichForm + "." + whichField + "_order;" );
  selectedFieldIndex = theSelect.selectedIndex;
  if ((selectedFieldIndex < theSelect.length - 1) && (selectedFieldIndex != -1)) {
    var temptext = new Array();
    var tempvalues = new Array();
    for (i=0; i < theSelect.length; i++) {
      temptext[ i ] = theSelect.options[i].text;
      tempvalues[ i ] = theSelect.options[i].value;
    }
    temptext[ selectedFieldIndex + 1 ] = theSelect.options[selectedFieldIndex].text;
    temptext[ selectedFieldIndex ] = theSelect.options[ selectedFieldIndex + 1 ].text;
    tempvalues[ selectedFieldIndex + 1 ] = theSelect.options[selectedFieldIndex].value;
    tempvalues[ selectedFieldIndex ] = theSelect.options[ selectedFieldIndex + 1 ].value;
    for (i = 0; i < theSelect.length; i++) {
      theSelect.options[i].text = temptext[i];
      theSelect.options[i].value = tempvalues[i];
      fieldOrder[i].value = tempvalues[i];
    }
    theSelect.options[ selectedFieldIndex ].selected = false;
    theSelect.options[ selectedFieldIndex + 1].selected = true;
  }
}

/* Submit Functions */
function submitForm(form)
{
    if (form != null)
    {
        form.submit();
    }
}

function submitForm(form, actionURL)
{
//        alert('form: ' + form);
//        alert('actionURL: ' + actionURL);
    if ((form != null) && (actionURL != null))
    {
        form.action.value = actionURL;
        //form.action = actionURL;
        form.submit();
    }
}

function submitForm(form, actionURL, target)
{
        //alert('form: ' + form);
        //alert('target: ' + target);
        //alert('actionURL: ' + actionURL);
    if ((form != null) && (actionURL != null))
    {
        form.action.value = actionURL;
        if (target != null)
            form.target = target;
//        alert("Set values");
        form.submit();
    }
}

function submitFormWithValidate(form, actionURL)
{
    if (validateWithRequiredFieldCheck(form) == false)
        return;
    else
        submitForm(form, actionURL);
}

/* Methods for messages */
function setErrorMessage(message)
{
    if ((message != null) && (message != ""))
    {
        top.document.getElementById('errorMessageBlock').style.display = 'block';
        top.document.getElementById('errorMessage').innerHTML = message;
    }
}

function setInfoMessage(message)
{
    if ((message != null) && (message != ""))
    {
        top.document.getElementById('infoMessageBlock').style.display = 'block';
        top.document.getElementById('infoMessage').innerHTML = message;
    }
}

function resetMessages()
{
    top.document.getElementById('infoMessageBlock').style.display = 'none';
    top.document.getElementById('infoMessage').innerHTML = "";
    top.document.getElementById('errorMessageBlock').style.display = 'none';
    top.document.getElementById('errorMessage').innerHTML = "";
}

function resetStatusMessages()
{
   top.document.getElementById('statusMessageBlock').style.display = 'none';
   top.document.getElementById('statusMessage').innerHTML = "";
}

function setStatusMessage(message, type)
{
   if ((message != null) && (message != ""))
   {
      top.document.getElementById('statusMessageBlock').style.display = 'block';
      top.document.getElementById('statusMessage').innerHTML = message;
      if (type == "error")
      {
         top.document.getElementById('statusMessage').className = "statusMessageError";
      }
      else if (type == "info")
      {
         top.document.getElementById('statusMessage').className = "statusMessageInfo";
      }
      else
      {
         top.document.getElementById('statusMessage').className = "statusMessageError";
      }
   }
}

function popupWindowNamed(url, popupName)
{
	popup = window.open(url,popupName,"height=750,width=750,scrollbars=yes,resizable=yes,status");
}

// Function to set the state hidden field within a given form.  Its purpose is to allow a Struts action to analyze that state and possibly go
// to another action
function setState(form, value)
{
    form.state.value = value;
}

/* Validation Methods */
function selectAllCheckboxes(checkbox, value) {
  if (checkbox != null) {
    checkbox.checked = value;
    for (var i = 0; i < (checkbox.length); i++) {
      checkbox[i].checked = value;
    }
  }
}

function validateCheckboxesWithConfirm(form, checkboxMessage, confirmMessage)
{
    if (validateCheckboxes(form, checkboxMessage) == false)
    {
        return false;
    }
    return confirm(confirmMessage);
}

function validateCheckboxes(form, message)
{
    if (form == null)
        return false;

    // Count how many checkboxes are checked within form
    if (getNumCheckedCheckboxesWithinForm(form.name) == 0)
    {
        alert(message);
        return false;
    }
    else
        return true;
}

function validateWithRequiredFieldCheck(form)
{
    if (form == null)
        return false;

    return (requiredFieldNotDefaultCheck() && validate(form.name));
}

/* Frame Methods */
function breakoutFrames()
{
  //alert("frameBreakout();");
  if (top.location != location)
  {
    top.location.replace(document.location.href);
  }
}

function breakoutFramesBySubmit(form)
{
  //alert("frameBreakoutWithSubmit();");
  if (top.location != location)
  {
    form.submit();
  }
}

/* Utility Find Method */
function findField(form, name)
{
    //alert("name = " + name);
    for (var i = 0; i < form.length; i++)
    {
        var e = form.elements[i];
        //alert("current element: " + e.name);
        if (name == e.name)
        {
            //alert("Found match");
            return e;
        }
    }
    return null;
}

function traverseURLWithConfirmation(destinationURL, confirmationMessage)
{
    if (confirm(confirmationMessage) == true)
    {
        window.location = destinationURL;
    }
}

function submitFormWithRequiredValidation(form, actionURL)
{
    if (form == null)
        return false;

    if(requiredFieldNotDefaultCheck() && validate(form.name))
    {
      submitForm(form, actionURL);
    }

    return true;
}

function submitFormWithRequiredValidation(form, actionURL, target)
{
    if (form == null)
        return false;

    if(requiredFieldNotDefaultCheck() && validate(form.name))
    {
      submitForm(form, actionURL, target);
    }

    return true;
}

function validateWithRequiredFieldCheck(form)
{
    if (form == null)
        return false;

    return (requiredFieldNotDefaultCheck() && validate(form.name));
}

function ignoreEnterKey(evt)
{
    evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode :
         ((evt.which) ? evt.which : evt.keyCode);
    if (charCode == 13 || charCode == 3)
    {
        //alert("returning false");
        return false;
    }
    else
    {
        return true;
    }
}




