var waitId = '';
var lastRequestedPackage = '';
var commDisplay = false;
var dependentSelected = '';

function setRequestedPackage(val){
	lastRequestedPackage = val;
};

function togglePackageView(id){
	var body = $(id+'Body');
	var img = $(id+'Img');
	lastRequestedPackage = id;

	if(img.src.indexOf('_down') > -1){
		Effect.BlindDown(body, {duration:.7});
		img.src = 'apps/resources/self_service/images/page_spearmint_up.gif';
	}else{
		Effect.BlindUp(body, {duration:.7});
		img.src = 'apps/resources/self_service/images/page_spearmint_down.gif';
	}
}

function toggleCourseView(id, color){
	var body = $(id+'_body');
	var img = $(id+'_img');
	var client_switch = '';
	
	if(body){
		if(img.src.indexOf('_down') > -1){
			if(img.src.indexOf('images/arrow_down') == -1){client_switch = img.src.substring(img.src.indexOf('images/')+7, img.src.indexOf('arrow_down'));}
			Effect.BlindDown(body, {duration:.7});
			img.src = 'apps/resources/self_service/images/'+client_switch+'arrow_right_'+color+'.gif';
		}else{
			if(img.src.indexOf('images/arrow_right') == -1){client_switch = img.src.substring(img.src.indexOf('images/')+7, img.src.indexOf('arrow_right'));}
			Effect.BlindUp(body, {duration:.7});
			img.src = 'apps/resources/self_service/images/'+client_switch+'arrow_down_'+color+'.gif';
		}
	}
}

function showTestInstructions(lang){
	var currInstructions = $('testinstructions'+lang);
	var newInstructions = $('testinstructions'+lang+'-holder');
	
	newInstructions.innerHTML = currInstructions.innerHTML+'<table width="100%" cellpadding="0" cellspacing="0"><tr><td align="center"><a href="#" onClick="Element.toggle(\'testinstructions'+lang+'-holder\');">close</a></td></tr></table>';
	Element.toggle(newInstructions);
}

function highlightCourse(obj){
	obj.style.background = '#ffff99';
} 

function revertCourse(obj){
	obj.style.background = '#e4dfd3';
}

function showMyAccount(id){
	if(id == 'account_settings' && $('account_settings')){
		// hide email reminder if it is there
		
		if($('email_reminder')){
			Element.hide('email_reminder');
		$('email_reminder_tab').className = 'tabHeaderRight notselected';
		}
		//hide dependent if it is there
		if($('dependent')){
			Element.hide('dependent');
			$('dependent_tab').className = 'tabHeaderRight notselected';
		}
		$('account_settings_tab').className = 'tabHeaderLeft selected';
	}else{
		//hide account settings if it is there
		if($('account_settings')){
			Element.hide('account_settings');
			$('account_settings_tab').className = 'tabHeaderLeft notselected';
		}
		if(id == 'email_reminder'){
			//hide dependent if it is there
			if($('dependent')){
				Element.hide('dependent');
				$('dependent_tab').className = 'tabHeaderRight notselected';
			}
			$('email_reminder_tab').className = 'tabHeaderRight selected';
		}else if(id == 'dependent'){
			if($('email_reminder')){
				// hide email reminder if it is there
				Element.hide('email_reminder');
				if($('account_settings')){
					$('email_reminder_tab').className = 'tabHeaderRight notselected';
				}else{
					$('email_reminder_tab').className = 'tabHeaderRight notselected altborder';
				}
			}
			$('dependent_tab').className = 'tabHeaderRight selected';
		}
	}
	
	Element.show(id);
}

  /* showTestResults - Used to switch tabs in the test results pane
     ---------------
     Passed an ID of a requested tab's body.
     Assumes the tab's ID is the same string plus '_tab'

     Sets the non-requested tab's classes
     Hides the non-requested tab's bodies
     Sets the requested tab's class
     Shows the requested tab's body
   */
function showTestResults(id){
  var els = [
    'test_results_overview', 'test_results_prof', 'test_results_survey'
  ];

  els.each(function(el){
    if (el != id) {
      var tab = $(el+'_tab'); if (tab) {
        tab.addClassName('notselected').removeClassName('selected');
        Element.hide(el);
      }
    }
  });

  $(id+'_tab').addClassName('selected').removeClassName('notselected');
	Element.show(id);
}

function showFrequencyDay(value, idsuffix){
   // idsuffix allows us to address multiple frequency controls for
   // separate emails. The default of '' recreates the earlier
   // behavior for controls which do not specify.
   if (typeof(idsuffix) == 'undefined') idsuffix = '';

	if (value == '3') {
      // Show frequency options for monthly reminders:
		Element.show('eremind_frequency_day_row' + idsuffix);
		$('eremind_frequency_day' + idsuffix).innerHTML = 'of Month';
		Element.hide('eremind_weekly_row' + idsuffix);
		$('eremind_weekly' + idsuffix).value = '';
		Element.show('eremind_monthly_row' + idsuffix);
	}
   else if (value == '2') {
      // Show frequency options for weekly reminders:
		Element.show('eremind_frequency_day_row' + idsuffix);
		$('eremind_frequency_day' + idsuffix).innerHTML = 'of Week';
		Element.hide('eremind_monthly_row' + idsuffix);
		$('eremind_monthly' + idsuffix).value = '';
		Element.show('eremind_weekly_row' + idsuffix);
	}
   else {
      // No frequency options for daily reminders or "don't remind me"
		Element.hide('eremind_weekly_row' + idsuffix);
		Element.hide('eremind_monthly_row' + idsuffix);
		Element.hide('eremind_frequency_day_row' + idsuffix);
		$('eremind_frequency_day' + idsuffix).innerHTML = '';
	}
}

function displayWait(id){
	Element.hide(id+'_submit');
	Element.show(id+'_wait');
	waitId = id;
}

function revertWait(){
	Element.show(waitId+'_submit');
	Element.hide(waitId+'_wait');
}

// CONTENT AREA FUNCTIONS
function setContentHeight() {
	var contElem = $('container-inner');
	var contInn = $('pagecontent-inner');
	var hVal = Element.getHeight(contElem);
	
	contInn.style.height = hVal - 180 - 55 +'px';
}

function initSearch(){
	//focus on search box
	$('search_text').focus();
	//set enter key function
}

function transferToViewCourses(courseId, courseTitle){
	processAjax('AHJViewCourses', 'process', 'popCourse,'+courseId+','+courseTitle+','+lastRequestedPackage);
}

function noopSS(){
	return true;
}

function pausecomp(millis){
	var date = new Date();
	var curDate = null;

	do{ curDate = new Date(); }
	while(curDate-date < millis);
} 



// OUTLOOK REMINDERS
function setIcsFile(icsAnchor) {
	var str = '/apps/resources/self_service/ics/reminder';
	if ($('emailreminder_form').eremind_frequency.value == '5') {
		icsAnchor.href = '#';
		return;
	}
	str += '_' + $('emailreminder_form').eremind_frequency.value;
	
	switch($('emailreminder_form').eremind_frequency.value) {
		case '2':
			str += '_' + $('emailreminder_form').eremind_weekly.value;
			break;
		case '3':
			str += '_' + $('emailreminder_form').eremind_monthly.value;
			break;
		default:
	}
	
	str += '.ics';
	
	icsAnchor.href = str;
	
}

function courseHoverShowDescription(courseDescriptionId) {
  var element = courseHoverShowDescription.element = $(courseDescriptionId);
  courseHoverShowDescription.courseDescriptionId = courseDescriptionId;
  var mouseX, mouseY;

  if (element === null) return;

  if (! element.hasClassName('tooltip-configured')) {
    element.addClassName('tooltip-configured');

    Event.observe(document, 'mousemove', function(e){
        mouseX = courseHoverShowDescription.mouseX = Event.pointerX(e);
        mouseY = courseHoverShowDescription.mouseY = Event.pointerY(e);
        element.setStyle({
            left: mouseX + 13 + 'px', top: mouseY + 13 + 'px'
        });
    });

    document.body.appendChild(element);

    element.setStyle({
        position: 'absolute',
          width: '40ex',
          'background-color': 'white',
          padding: '13px',
          border: '3px solid rgb(153, 204, 102)',
          color: 'rgb(63, 191, 104)'
          });
  }
  element.setStyle({ display: 'block' });
};
function courseHoverHideDescription(courseDescriptionId) {
  /* Due to the fact that "Home" and "View Courses" are loaded
   * dynamically rather then being actual pages, when you switch it
   * can cause duplicates of our description divs.  Since I don't know
   * where the switching code is to iron them out there, this function
   * uses a Prototype CSS selector to get all elements with the
   * correct ID, rather than assuming there is only one.
   */
  var elements = courseHoverHideDescription.element
    = $$('[id='+courseDescriptionId+']');
  if (elements.size = 0) return;
  elements.each(function(element){ element.setStyle({ display: 'none' }); });
};
function courseHoverHideAllDescriptions() {
  var elements = courseHoverHideDescription.element
    = $$('.course-description-tooltip');
  if (elements.size = 0) return;
  elements.each(function(element){ element.setStyle({ display: 'none' }); });
};
  

  var ahutil = {};
  ahutil.usercreate_form = {}
  ahutil.usercreate_form.names = function() {
     var first = $('usercreate_firstname');
     var last = $('usercreate_lastname');
     var user = $('usercreate_newusername');
     if(first.value.length > 0 && last.value.length > 0) {
        user.value = first.value.charAt(0).toLowerCase()
        + last.value.toLowerCase();
        new Effect.Highlight(user,
                             { startcolor: '#ffff99',
                               endcolor: '#ffffff' });
     }
  };
  ahutil.usercreate_form.fixdate = function(fieldid, setpwflag) {
     var date = new Date($(fieldid).value);
     var validateError = '';

     // Validate date is readable and within MS SQL datetime constraints
     if ($(fieldid).value == '')
        validateError = 'Date is required';
     else if (isNaN(date)
              || date.getFullYear() < 1753 || date.getFullYear > 9999)
        validateError = 'Invalid date';

     if (validateError != '') {
        var validation = $(fieldid + '-validation');
        validation.update(validateError);
        return;
     }
     else $(fieldid + '-validation').update('');

     var month = date.getMonth()+1;
     var dayofmonth = date.getDate();

     $(fieldid).value
        = (month < 10 ? '0' : '') + month
        + '/' + (dayofmonth < 10 ? '0' : '') + dayofmonth
        + '/' + date.getFullYear();

     if (setpwflag == true) {
        document.usercreate_form.usercreate_newpassword.value
           = (month < 10 ? '0' : '') + month
           + (dayofmonth < 10 ? '0' : '') + dayofmonth
           + date.getFullYear();
        new Effect.Highlight('usercreate_newpassword',
                             { startcolor: '#ffff99', endcolor: '#ffffff' });
     }
  };
  ahutil.usercreate_form.zip = function() {
     var validation = $('usercreate_zip-validation');
     if ($('usercreate_zip').value.search(/^\d{5}$/) == -1)
        validation.update('Invalid ZIP code');
     else validation.update('');
  };

  ahutil.blockui = function(message, width, height, bg) {
     // Block all user interface, cover the window with an overlay and
     // a waiting icon.

     var body = document.getElementsByTagName("body").item(0);
     var overlay; var dialog;

     if (!ahutil.blockui.overlay) {
        overlay = ahutil.blockui.overlay = document.createElement("div");
        overlay.setAttribute('id','ahutil_blockui_overlay');
        overlay.style.display = 'none';
        overlay.style.position = 'absolute';
        overlay.style.backgroundImage
           = 'url(apps/resources/shared/images/black-70.png)';
        overlay.style.top = '0';
        overlay.style.left = '0';
        overlay.style.zIndex = '1100';
        overlay.style.width = '100%';
        body.insertBefore(overlay, body.firstChild);
     }
     else overlay = ahutil.blockui.overlay;

     if (!ahutil.blockui.dialog) {
        dialog = ahutil.blockui.dialog = document.createElement("div");
        dialog.setAttribute('id','ahutil_blockui_dialog');
        dialog.style.display = 'none';
        dialog.style.position = 'absolute';
        dialog.style.backgroundRepeat = 'no-repeat';
        dialog.style.backgroundPosition = 'center 85%';
        dialog.style.backgroundColor = '#F0F0F0';
        dialog.style.textAlign = 'center';
        dialog.style.padding = '8px';
        dialog.style.zIndex = '1101';
        body.insertBefore(dialog, overlay.nextSibling);
     }
     else dialog = ahutil.blockui.dialog;

     if (bg) dialog.style.backgroundImage = bg;
     else dialog.style.backgroundImage
        = 'url(apps/resources/shared/images/ajax-loading.gif)';

     var windowHeight; var windowWidth;
     if (window.innerHeight) {
        windowWidth = window.innerWidth;
        windowHeight = window.innerHeight;
     }
     else if (document.documentElement&&document.documentElement.clientHeight) {
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
     }
     else if (document.body) {
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
     }

     overlay.style.height = windowHeight + 'px';
     overlay.style.width = windowWidth + 'px';

     dialog.style.height = height + 'px'; dialog.style.width = width + 'px';
     dialog.style.top = ((windowHeight - height) / 2) + 'px';
     dialog.style.left = ((windowWidth - width) / 2) + 'px';

     dialog.innerHTML = message;

     overlay.style.display = 'block';
     dialog.style.display = 'block';
  };
  ahutil.unblockui = function() {
     //Unblock the user interface, reverse of the above
     ahutil.blockui.overlay.style.display = 'none';
     ahutil.blockui.dialog.style.display = 'none';
  };

// This function is flagged as 1 once the home page is displayed
var jsLoggedIn = new setLoggedIn(0);
function setLoggedIn (flag){
	 if(flag == null) {
	 	flag = 0;
	 }
	 this.loggedIn = flag;
}
 
//////////////////////////////////////////////////////////////
	// START //
	// Detect Screen Activity //
//////////////////////////////////////////////////////////////
var ScreenInactive = function (waitTime) {
	  this.lastActivity = new Date().getTime();
	  this.waitTime = waitTime;

	  var $this = this;
	  this._timer = setInterval(function () { $this._checkTime.call($this) }, 1000);
	  document.onmousemove = function () { $this._mouseHandler.call($this) };
};

ScreenInactive.prototype = {
	_timer: null,

	lastActivity: 0,
	started: false,
	waitTime: 0,

	onstart: function () {},
	onend: function () {},

	dispose: function () {
		if (this._timer) clearInterval(this._timer);
	  		document.onmousemove = null;
	},

	_checkTime: function () {
        if (!this.started && new Date().getTime() - this.lastActivity >= this.waitTime) {
        	this.started = true;
        	this.onstart();
        }

        var hac = $('hac_frame');
        var hac_doc = null;

        if(hac){
        	hac_doc = hac.contentWindow || hac.contentDocument;
        	if (hac_doc.document) {
            	hac_doc = hac_doc.document;
            }
              
            if(hac_doc.onmousemove == undefined || hac_doc.onmousemove == null){
                    hac_doc.onmousemove = function(){
                    	parent.notactive._mouseHandler();
                    };
            }
        }
	},
  
	_mouseHandler: function () {
		this.lastActivity = new Date().getTime();
		if (this.started) {
			this.started = false;
			this.onend();
		}
	}
};

var notactive = new ScreenInactive(300000);

notactive.onstart = function () {
	if(jsLoggedIn.loggedIn == 1){
		showDialog('Confirmation','You are about to be logged out due to inactivity.','prompt',5);
	}
};

notactive.onend = function () {
	// enter code here if you'd like something to happen when activity is detected before timer ends
		  
};
//////////////////////////////////////////////////////////////
		// END //
		// Detect Screen Activity //
//////////////////////////////////////////////////////////////
	  
	  
//////////////////////////////////////////////////////////////	  
	  	// START //
	  	// Inactivity Logout Dialog Box //
//////////////////////////////////////////////////////////////
var TIMER = 5;
var SPEED = 100;
var WRAPPER = 'content';

// calculate the current window width //
function pageWidth() {
	return window.innerWidth != null ? window.innerWidth : document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
}

// calculate the current window height //
function pageHeight() {
	return window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;
}

// calculate the current window vertical offset //
function topPosition() {
	return typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;
}

// calculate the position starting at the left of the window //
function leftPosition() {
	return typeof window.pageXOffset != 'undefined' ? window.pageXOffset : document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;
}

// build/show the dialog box, populate the data and call the fadeDialog function //
function showDialog(title,message,type,autohide,buttons) {
	if(!type) {
		type = 'error';
	}
	var dialog;
	var dialogheader;
	var dialogclose;
	var dialogtitle;
	var dialogcontent;
	var dialogmask;
   var buttonlayout;
   if (buttons) buttonlayout = buttons;
   else buttonlayout = '<div><br/><br/><br/><center><table><tr><td><input name="continue" type="button" value="Continue" onClick="hideDialog();"/></td><td width="30px;"></td><td><input name="logout" type="button" value="Log Out" onClick="processLogoutInactive();" /></td></tr></table></center></div>';
	if(!document.getElementById('dialog')) {
		dialog = document.createElement('div');
		dialog.id = 'dialog';
		dialogheader = document.createElement('div');
		dialogheader.id = 'dialog-header';
		dialogtitle = document.createElement('div');
		dialogtitle.id = 'dialog-title';
		dialogclose = document.createElement('div');
		dialogclose.id = 'dialog-close'
		dialogcontent = document.createElement('div');
		dialogcontent.id = 'dialog-content';
		dialogmask = document.createElement('div');
		dialogmask.id = 'dialog-mask';
		document.body.appendChild(dialogmask);
		document.body.appendChild(dialog);
		dialog.appendChild(dialogheader);
		dialogheader.appendChild(dialogtitle);
		dialogheader.appendChild(dialogclose);
		dialog.appendChild(dialogcontent);;
		dialogclose.setAttribute('onclick','hideDialog()');
		dialogclose.onclick = hideDialog;
	} else {
		dialog = document.getElementById('dialog');
		dialogheader = document.getElementById('dialog-header');
		dialogtitle = document.getElementById('dialog-title');
		dialogclose = document.getElementById('dialog-close');
		dialogcontent = document.getElementById('dialog-content');
		dialogmask = document.getElementById('dialog-mask');
		dialogmask.style.visibility = "visible";
		dialog.style.visibility = "visible";
	}
	dialog.style.opacity = .00;
	dialog.style.filter = 'alpha(opacity=0)';
	dialog.alpha = 0;
	var width = pageWidth();
	var height = pageHeight();
	var left = leftPosition();
	var top = topPosition();
	var dialogwidth = dialog.offsetWidth;
	var dialogheight = dialog.offsetHeight;
	var topposition = top + (height / 3) - (dialogheight / 2);
	var leftposition = left + (width / 2) - (dialogwidth / 2);
	dialog.style.top = topposition + "px";
	dialog.style.left = leftposition + "px";
	dialogheader.className = type + "header";
	dialogtitle.innerHTML = title;
	dialogcontent.className = type;
	dialogcontent.innerHTML = message + buttonlayout;
	var content = document.getElementById(WRAPPER);
	dialog.timer = setInterval("fadeDialog(1)", TIMER);
	if(autohide) {
		dialogclose.style.visibility = "hidden";
      if (!isNaN(autohide))
		   window.autotimeout = setInterval("processLogoutInactive()", 30000);
	} else {
		dialogclose.style.visibility = "visible";
	}
}

// hide the dialog box //
function hideDialog() {
	var dialog = document.getElementById('dialog');
	clearInterval(dialog.timer);
	clearInterval(window.autotimeout);
	dialog.timer = setInterval("fadeDialog(0)", TIMER);
}

// fade-in the dialog box //
function fadeDialog(flag) {
	if(flag == null) {
		flag = 1;
	}
	var dialog = document.getElementById('dialog');
	var value;
	if(flag == 1) {
		value = dialog.alpha + SPEED;
	} else {
		value = dialog.alpha - SPEED;
	}
	dialog.alpha = value;
	dialog.style.opacity = (value / 100);
	dialog.style.filter = 'alpha(opacity=' + value + ')';
	if(value >= 99) {
		clearInterval(dialog.timer);
		dialog.timer = null;
	} else if(value <= 1) {
		dialog.style.visibility = "hidden";
		document.getElementById('dialog-mask').style.visibility = "hidden";
		clearInterval(dialog.timer);
	}
}
//////////////////////////////////////////////////////////////
	  	// END //
	  	// Inactivity Logout Dialog Box //
//////////////////////////////////////////////////////////////