
// common.js

// share the $
var $j = jQuery;
// active4D will interprelate $j as a local var.
// eventually switch all jquery calls to this name
var j$ = jQuery;
jQuery.noConflict();

// hide the old image buttons and replace them with customizable links and spans
j$(function(){
    j$('.imageButton').hide();
	j$('.jsButton').show();
	})

// used with buttons above. Submit the form that encloses the link
function submitEnclosingForm(obj) {
    // Ex: submitEnclosingForm(this)
	var node = obj.parentNode;
          while (node.tagName !='FORM' && node !=null && node.tagName!='HTML'){
           node = node.parentNode;
          }
         if (node.tagName == 'HTML') {
			// no from found
			alert('No form found in function submitEnclosingForm');
         } 
		else {
			node.submit();
		}
 }
 
// preload the button images
var busyImage = new Image();
busyImage.src = "/images/busy.gif";
var saveImage = new Image();
saveImage.src = "/images/buttons/save-disabled.gif";

function busy(ObjectID,isBusy){
	if($(ObjectID)){
		if(isBusy){
			$(ObjectID).innerHTML='<img style="height:16px;width:16px" src="/images/busy.gif" alt="busy"/>';
		} else {
			$(ObjectID).innerHTML= '';
		}
	}
}

function cleanWordEncoding(obj) {
	/*
		Based on code from jonathan Hedley as cleanWordClipboard : 
			http://jonathanhedley.com/articles/2008/03/convert-microsoft-word-to-plain-text
			
		Renamed and modifed to act directly on the reference to the object passed in.
		bl - 7/31/2008
	*/
	var swapCodes   = new Array(8211, 8212, 8216, 8217, 8220, 8221, 8226, 8230, 8482, 63743); // dec codes from char at
	var swapStrings = new Array("--", "--", "'",  "'",  '"',  '"',  "*",  "...", "(tm)", "apple");  
	
	var output = obj.value;
   // debug for new codes
   //  for (i = 0; i < output.length; i++)  alert("'" + output.charAt(i) + "': " + output.charCodeAt(i));

    for (i = 0; i < swapCodes.length; i++) {
        var swapper = new RegExp("\\u" + swapCodes[i].toString(16), "g"); // hex codes
        output = output.replace(swapper, swapStrings[i]);
    }

	obj.value = output;
}


// Hide or show an object
function displayElement(objectID,showMe) {
	if(showMe){
		$(objectID).style.display = 'block';
	}
	else{
		$(objectID).style.display = 'none';
	}
}

// Handle the insertion and removal of Regions in select lists
// Clicking on one list inserts element in the other. 
// Clicking the element in the receiving list removes it from that list

function insertOption(fromSelectObj,toSelect,maxOptions,maxResionText)
{
	if (!maxOptions) var maxOptions = 0;
	if ((!maxResionText) || (maxResionText =="")) var maxResionText = "Limit Reached";
	var x=document.getElementById(toSelect);
	var y=document.createElement('option');
	y.text=fromSelectObj.options[fromSelectObj.selectedIndex].text;
	y.value=fromSelectObj.options[fromSelectObj.selectedIndex].value;
	var inList = false;
	var optValue = y.value;
	for (i=0;i<x.length;i++)
   {
		if (x.options[i].value == optValue) {
			inList = true;
			break;
		}
	}
	
	// test limit
	if ((maxOptions == 0) || (x.length < maxOptions )) {
		if (!inList)
		{
	 	  try
	 	    {
	 	    x.add(y,null); // standards compliant
	 	    }
	 	  catch(ex)
	 	    {
	 	    x.add(y); // IE only
			} //catch
 	    } // not in list
	} // within limit
	else if (!inList) {
		alert(maxResionText);
	} // exceeded limit
} // insertOption

function deleteOption(selectObj)
{
  var x=selectObj;
  x.remove(x.selectedIndex);
}

function selectAllOptions(selectID) {
	// Select All the options in the select object
	var x = $(selectID);
	for (i=0;i<x.length;i++)
	{
		x.options[i].selected = true;
	}
}

// Pause script execution for a bit
function executeLater(scriptToRun,pauseTime) {
	// pass pauseTime as seconds
	if(!pauseTime) var pauseTime = 2;
	if(!scriptToRun) var scriptToRun = "";
	pauseTime = pauseTime * 1000; // convert to miliseconds
	var pauseTimer = setTimeout(scriptToRun,pauseTime);
}


// Code to determine the Mouse postition and display a popup div
// Used to display preview of sample images.

<!-- //Copyright 2006,2007 Bontrager Connection, LLC
// http://bontragerconnection.com/ and http://willmaster.com/
// Version: July 28, 2007
//http://www.willmaster.com/blog/css/Floating_Layer_At_Cursor_Position.html
var cX = 0; var cY = 0; var rX = 0; var rY = 0;
function UpdateCursorPosition(e){ cX = e.pageX; cY = e.pageY;}
function UpdateCursorPositionDocAll(e){ cX = event.clientX; cY = event.clientY;}
if(document.all) { document.onmousemove = UpdateCursorPositionDocAll; }
else { document.onmousemove = UpdateCursorPosition; }
function AssignPosition(d) {
if(self.pageYOffset) {
	rX = self.pageXOffset;
	rY = self.pageYOffset;
	}
else if(document.documentElement && document.documentElement.scrollTop) {
	rX = document.documentElement.scrollLeft;
	rY = document.documentElement.scrollTop;
	}
else if(document.body) {
	rX = document.body.scrollLeft;
	rY = document.body.scrollTop;
	}
if(document.all) {
	cX += rX; 
	cY += rY;
	}
d.style.left = (cX+6) + "px";
d.style.top = (cY+0) + "px";
}
var contentTimer;
function HideContent(d) {
if(d.length < 1) { return; }
if(!$(d)) {return;}
contentTimer = setTimeout('$("'+d+'").style.display = "none"',1000);
}

function KeepContent(d) {
if(d.length < 1) { return; }
clearTimeout(contentTimer);
}

//function ShowContent(d) {
function ShowContent(d,loc,url) {
if(d.length < 1) { return; }
clearTimeout(contentTimer);
var dd = $(d);
//AssignPosition(dd);
var loc; // object used to set the popup location
var coords = [0, 0];
coords = findPos($(loc));
dd.style.display = "block";
dd.style.position = "absolute";
dd.style.left = (coords[0]+24) + "px";
dd.style.top = (coords[1]+6) + "px";
busy(d,true);
setTimeout('ajaxRequest(\''+d+'\',\''+url+'\',\'\',\'\',true,true)',0);
}

// get the position of an object
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

var wimpyUserAgent = navigator.appName.indexOf("Microsoft");
var wimpyButtonIDs = wimpyButtonIDs || Array();
function wimpyButtonStopOthers(myid_in){
	for(i=0; i<wimpyButtonIDs.length; i++){
		if(wimpyButtonIDs[i] != myid_in){
			if (wimpyUserAgent != -1) {
				window[wimpyButtonIDs[i]].js_wimpy_pause();
			} else {
				document[wimpyButtonIDs[i]].js_wimpy_pause();
			}
		}
	}
}
// 10/23/08 - BL - renamed function and added parm
//was: function writeWimpyButton(theFile, wimpyWidth, wimpyHeight, wimpyConfigs, backgroundColor){
function writeWimpyButton4(theFile, wimpyWidth, wimpyHeight, wimpyConfigs, backgroundColor, regCode){
	var wimpyReg = (regCode == null) ? "" : regCode; // get regCode from parm now
	var defaultWidth = 20;
	var defaultHeight = 20;
	var defaultConfigs = "";
	var baseURL = "";
	var wimpySwf = "/assets/wimpy_button4.swf";
	var wimpyWidth = (wimpyWidth == null) ? defaultWidth : wimpyWidth;
	var wimpyHeight = (wimpyHeight == null) ? defaultHeight : wimpyHeight;
	var wimpyConfigs = (wimpyConfigs == null) ? defaultConfigs : wimpyConfigs;
	var backgroundColor = (backgroundColor == null) ? false : backgroundColor;
	var myid = "wimpybutton"+Math.round((Math.random()*1000)+1);
	wimpyButtonIDs[wimpyButtonIDs.length] = myid;
	var flashCode = "";
	var newlineChar = "\n";
	var backgroundColor = (backgroundColor == null) ? false : backgroundColor;
	if(typeof(backgroundColor) == "string"){
		var Astring = backgroundColor.split("");
		if(Astring[0] == "#"){
			Astring.shift();
			backgroundColor = Astring.join("");
		}
	}
	if(backgroundColor == false){
		tptParam = '<param name="wmode" value="transparent" />'+newlineChar;
		tptEmbed = ' wmode="transparent"';
	} else {
		tptParam = '<param name="bgcolor" value="#'+backgroundColor+'" />'+newlineChar;
		tptEmbed = ' bgcolor="#'+backgroundColor+'"';
	}
	flashCode += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="'+wimpyWidth+'" height="'+wimpyHeight+'" id="'+myid+'">'+newlineChar;
	flashCode += '<param name="movie" value="'+wimpySwf+'" />'+newlineChar;
	flashCode += '<param name="loop" value="false" />'+newlineChar;
	flashCode += '<param name="menu" value="false" />'+newlineChar;
	flashCode += '<param name="quality" value="high" />'+newlineChar;
	flashCode += '<param name="wmode" value="transparent" />'+newlineChar;
	flashCode += '<param name="flashvars" value="theFile='+baseURL+theFile+wimpyConfigs+'&wimpyReg='+wimpyReg+'&myid='+myid+'" />'+newlineChar;
	flashCode += '<embed src="'+wimpySwf+'" width="'+wimpyWidth+'" height="'+wimpyHeight+'" flashvars="theFile='+baseURL+theFile+wimpyConfigs+'&wimpyReg='+wimpyReg+'&myid='+myid+'"'+tptEmbed+' loop="false" menu="false" quality="high" name="'+myid+'" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>'+newlineChar;
	//document.write('<br>'+myid+'<br><textarea name="textarea" cols="40" rows="3">'+flashCode+'</textarea><br>')+newlineChar;
	document.write(flashCode);
}


/*
Ajax using the prototype.js routines
*/
function ajaxRequest(ObjectID,url,params,FormID ,noScroll ,noEval){
	// Ex: ajaxRequest('descriptionDisplay',$XFA_onSubmit,'mode=cancel','DescForm')
	var formParams = "";
	var pars = "";
	
	if(params){
		pars = params;
	}
	
	if(FormID){
		formParams=Form.serialize(FormID);
		pars += "&" +formParams;
	}
	
	// Sending a post with no params doesn't seem to be allowed
	var requestMethod = 'post';
	if (pars == "") {
		requestMethod = 'get';
	}
	
	var myAjax = new Ajax.Request(
		url, 
		{
			method: requestMethod, 
			parameters: pars, 
			onComplete: ajaxResponse
		});
		
	function ajaxResponse(originalRequest)
	{
		var response=originalRequest.responseText;
		var theStatus = originalRequest.status;
		//alert('Status ->'+theStatus);
		//alert('Object ->'+ObjectID);
		//alert('Object Exitsts ->'+$(ObjectID));
		if(theStatus == 200){
			var s;
			s = response.toUpperCase();
			s = s.substr(0,20); //the redirect is close to front
			var redirectStart = s.search('REDIRECT');
			if(redirectStart != -1){
				// This is a real kludge. Need to  find a more dependable way to do this
				// User is being redirected to a new location, most likely the login page
				if (window == top) {
					window.location = response.substr(redirectStart+8);
				} 
				else {
					// We are in side a frame, pop up to the top
					top.location.href =response.substr(redirectStart+8);
				}
			} else if($(ObjectID)){
					// a target object was specified, otherwise, there is nothing to do
					var obj = $(ObjectID)
					obj.innerHTML=response;
					if ( ! (noEval)){
						response.evalScripts(); //evaluate any scripts in the return
					}
					// When updating fields that require validation, the div id 'completedContain' gets refreshed
					// we don't want to  scroll to completedContain
					if ( ! (noScroll)){
						obj.scrollIntoView(true);
						window.scrollBy(0,-160);
					}

			}
		} else {
			// We were sent something unusual, display in own window
			window.location = response;
		}
	}
}

// Update the Profile incomplete warning
function profileComplete() {
	//find out if the target object exists
	if($('completedContain')){
		ajaxRequest('completedContain','/index.a4d','action=profile.testComplete&ajaxResponse=true','',true,false);
	}
}

// this replaces the target="_blank" deprication issue
// call as: <a href="http://www.foo.com" rel="external">
function externalLinks() { 
	if (!document.getElementsByTagName) return; 
	var anchors = document.getElementsByTagName("a"); 
	for (var i=0; i<anchors.length; i++) { 
		var anchor = anchors[i]; 
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") anchor.target = "_blank"; 
	} 
}
window.onload = externalLinks;


function getOffset(objectID,topORleft) {
	if($(objectID)) {
		alert($(objectID))
		var obj  = $(objectID);
		// thanks to www.quirksmode.org for scroll detection
		var topOffset = 0;
		var leftOffset = 0;
			if (document.documentElement && document.documentElement.scrollTop)
			{	//IE 6
				topOffset = document.documentElement.scrollTop;
				leftOffset = document.documentElement.scrollLeft;
			}
			else if (document.body)
			{	//IE 5
				  topOffset = document.body.scrollTop;
				  leftOffset = document.body.scrollLeft;
			}
			else 
			{
				topOffset = window.pageYOffset;
				leftOffset = window.pageXOffset;
			}
			if(topORleft = 'left') 
			{
				return leftOffset;
			} 
			else 
			{
				return topOffset;
			}
			
	} else { return 0; }
}



// Paint the screen with a translucent div to simulate a modal dialog
function setModal(objectID,modalState) {
	if($(objectID)) {
		var obj  = $(objectID);
		if(modalState) {
			// display the div
			obj.style.display = 'block';
		}
		else {
			//hide the div
			obj.style.display = 'none';
		}
	}
}

function setModalPosition (objectID) {
	// as of 11-16-06, this doesn't work...
	// set the position of a modal dialog
	if($(objectID)) {
		var obj  = $(objectID);
		var myTop = getOffset(objectID,'top');
		alert(myTop)
		if(myTop > 0) 
		{
			obj.style.top = myTop+60;
		}
		else
		{
			obj.style.top = "60";
		}
	}
}

// Open a new window to view special content

function OpenViewer(openparams,theHeight,theWidth, theWindowName){
	if (theHeight == null) {
		var theHeight = 400;  //Default height
	}
	if (theWidth == null) {
		var theWidth = 750;  //Default width
	}
	if (theWindowName == null) {
		var theWindowName = 'viewer';  //Default window name
	}
	
	theNewWindow=window.open(openparams,theWindowName,"location=yes,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=yes,height=" + theHeight + ",width=" + theWidth)
	theNewWindow.focus();
}

function ShowViewer(openparams){
	OpenViewer(openparams,"500","750")
}

function helpViewer(openparams){
	OpenViewer(openparams,"500","500",'Help');
}

function VideoViewer(openparams){
	OpenViewer(openparams,"650","670");
}

// Show the Review Window
function readreview(entid){
var openparams = "/BrowseW_GetReview?id="+entid;
OpenViewer(openparams,"300","300");
}

function ShowSampleSearch(openparams){
OpenViewer(openparams,"500","800");
}

function ShowSamplePage(openparams){
OpenViewer(openparams,"700","800");
}


// Handle the user clicks in the Regions Multi select objects
function OptionsToList(){
	var regionsListTemp = "";
	var OptionTemp = "";
	for(i=0; i< document.SearchForm.Regions.options.length; i++){
		if(document.SearchForm.Regions.options[i].selected){
		OptionTemp=document.SearchForm.Regions.options[i].text.replace(/\W{3,4}/,"");
			if(regionsListTemp!=""){
			regionsListTemp = regionsListTemp + ", " + OptionTemp;
			}// add to list
			else
			{
				regionsListTemp = OptionTemp;
			} //  first region
		} // if selected
	} //for
	
	if(regionsListTemp==""){ 
		regionsListTemp = "- All Regions -";
	} // no regions selected

	document.SearchForm.RegionList.value=regionsListTemp.replace(/ \(\d+\)/g,"");
}//ListOptions


// check the radio button associated with most recently change member name field
function checktherightone(theone, thetext){
	if(document.getElementById(thetext).value != ""){
	document.getElementById(theone).checked=true
	}
}

// The MacroMedia swap image routines
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_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) { //v4.01
  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);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

	function scrollTop() {
      	window.scrollTo(0,0);
      }
      
      function checkboxes(checkem,checkboxname){
	      var elements=checkboxname
	      if(elements.length){
		      if(checkem=="all"){
			      for (i=0;i<elements.length;++i){
				      if(elements[i].disabled){
				      }else{
					      elements[i].checked=true
				      }
			      }
		      }else if(checkem=="none"){
			      for (i=0;i<elements.length;++i){
				      if(elements[i].disabled){
				      }else{
					      elements[i].checked=false
				      }
			      }
		      }
	      }else{
		   if(checkem=="all"){
				      if(elements.disabled){
				      }else{
					      elements.checked=true
				      }
		      }else if(checkem=="none"){
				      if(elements.disabled){
				      }else{
					      elements.checked=false
				      }
		      }   
	      }
      }
      function uncheck(uncheck){
	      //$(uncheck).checked=false
			// Avoid conflict between libraries
		if(document.getElementById(uncheck)) {
	      document.getElementById(uncheck).checked=false
		}
      }


