//	utilities.js features most of the anciliary functions needed for the Pri-Med site... 
//  These are functions that are used throughout the site in many contexts...
	


/* 

Function: scrub_class
scrub_class takes a DOM element and a string to search for in that element's class name... 
It returns its class name *without* the string...  No longer necessary (can be replaced with moo's removeClass), 
but still used in some places...

Parameters: 
el - DOM element.  Element to strip from which to strip class name
str - String.  Class name to remove.

*/


	
	function scrub_class(el, str) {
		var check = el.className.indexOf(str);
		var CleanClass=(check != -1) ? el.className.substring(0, check) + el.className.substr(check + str.length) : el.className;
		
		return CleanClass;
	}


/* 
  Function: findPos
  findPos take a DOM element as a parameter and returns its x,y coordinates in an array	
  
  Parameters: 
  obj - DOM Element. Element to evaluate the position of.
  
  Returns: 
  [curleft, curtop] - an array of integers representing the left and top coordinates respectively.    
  
  */
	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];
}

/* 

Function: open_helper
open_helper takes two DOM elements as parameters.  The first is a hidden div, the second is the object that is known 
as its referrer (usually a link.)  The function makes the first object visible and positions it near the referrer.  
Commonly used in Conferences and Exhibitions. 

Parameters: 
el - DOM Element. Object to display
referrer - DOM Element.  Object which has opened element el.  Function will position el relative to this element.

*/

function open_helper(el, referrer, optionsPassed) {
    try{
    var newPos = findPos(referrer);
    $(el).style.display='block';

    /* should probably be split up into whether top or left was passed
    -- assuming both either are passed or neither are */
    if (!optionsPassed || $(el).style.top == '')
        $(el).style.top= (newPos[1]-55)+'px';
    if (!optionsPassed || $(el).style.left == '')
        $(el).style.left= (newPos[0]-20)+'px';
    $(el).style.visibility= 'visible';
    }
    catch(err){
        alert(err.description);
    }

}


/* 

Function: tabClick
tabClick searches for a queryString of "tabIndex" and will execute the corresponding click behavior of the tabSet 
called 'homeTabs' (if it exists on the page and the queryString integer is in the range of homeTabs' length.)

*/


function tabClick() {
   
     var tI  = getQueryString('tabIndex');
     if(tI != false && homeTabs.links.length >= tI && homeTabs.links.length > 0 ){
         homeTabs.links[parseInt(tI)].fireEvent('click');
     }
 }

 /*
Pass tab Index to select a tab (without searching query strings)
*/

 function tabClick(tabIndex) { 
     if (tabIndex != false && homeTabs.links.length >= tabIndex && homeTabs.links.length > 0) {
         homeTabs.links[parseInt(tabIndex)].fireEvent('click');
     }
 }

 //  trunc truncates a text DOM element el, to the last space character before space integer val and appends an ellipsis.  
 //      Commonly used for document abstracts...
 function trunc(el, val) {
 el = el.substr(0,val);
 el = el.substr(0, el.lastIndexOf(" "));
 el += '...';
        
 return el;
 }
    



 /* 
 Function: truncSplit
 truncSplit is used to find an appropriate point to insert a break (<br/>) into the text of element el to the length of val. Most commonly used to auto-insert breaks into the labels of tabs (ie: "About Us", "Print CME", etc.)

 Parameters: 
 el - DOM element. 

 Returns: 
 retArray.join - Resulting string with breaks inserted.
 */
 
    function truncSplit(el, val){
        
        var retArray = el.toString().split(' ');
        var val2 = Math.round((retArray.length/2)-1);
        retArray[val2]+='<br/>';
        
        return retArray.join(' ');
    }
    
/*  
Function: getQueryString
getQueryString searches the document.location for the parameter key and returns its value (whatever follows the key and an '=')   

Parameters: 
key - string.  Token to search for in document.location

Returns: 
val - string.  Value associated with token key.

*/
     
    function getQueryString(key){
        var uri = document.location.toString();
        var val = '';    
            if(uri.indexOf('?') != -1){
                uri = uri.substring(uri.indexOf('?') + 1, uri.length);
                uri = uri.split('&');
                
                var index;
                for(i=0; i < uri.length; i++){
                   if(uri[i].indexOf(key) != -1){
                        var el = uri[i].split('=');
                        val = el[1];
                   }               
                }
            }
            val = (val == '')?false:val;
            return val;    
    }

/* 

Function: getHashVal
getHashVal searches the parameter hash for the parameter type and returns its value (whatever follows the type and an '-')      

Parameters: 
type - string.  Represents element to search for.
hash - string.  Where the function will search for type.
  
Returns: 
val - string.  The type's return value.

  */
    function getHashVal(type, hash){
        // need to break up something that looks like this: #tab-2;date-2
        var hashSet= hash.toString().substring(1,hash.toString().length).split(';');
        var val = ''
        if(hash != null){
            for(i=0; i < hashSet.length; i++){
                var el = hashSet[i].split('-');
                if(hashSet[i].indexOf(type) != -1){
                    val = el[1];
                }         
            }
        }
        val = (val == '')?false:val;
        return val;    
        
    }
    
    

/* 

Function: setDays
setDays is used exclusively on Live Events to search for a queryString of 'date' and match the IDs of tabSet called 'mtgTabs'.
If the queryString matches the ID of one of mtgTabs links, function executes click event of that day...  

*/

   
    function setDays(){
        var newDate = getQueryString("date");
        if(newDate!= false && self.mtgTabs) {
            self.homeTabs.links[1].fireEvent('click');
            self.mtgTabs.links.each(function(el){
                
                if (el.id == newDate){
                    el.fireEvent('click');
                }
            })

      }
      }
      
/* 

Function: checkDefault
Commonly used function to check input element el for a default string "val" and clear the element if its value is equal to 'val'.    

Parameters: 
el - 
val - 

*/

function checkDefault(el,val){
    if(el.value == ''){
        el.value = val;
    }
  }
      
   /* 
   
   Function: openWin   
   */
   
   /*
   Function: openEmail   
   */
   
   /*
   Function: openBio
   */
   
   /*
   Function: openAddAcc
   
   */
   
   /* 
   Function: openPubMed
   */
   
   /*
   Function: openHarvardTracker
   */
   
   /*
   Function: openFeedBack
   */
   
   /*
   Function: openPDF
   
   
   
   
   */
    
//  The following functions are used contextually to open various types of pop-up windows with various characteristics    
    function openWin(url){
        window.open(url, 'openWin',"width=500,height=400, resizable=yes");
    }
    
    function openFullWin(url) {
    window.open(url, 'openWin', "resizable=yes, toolbar=yes, location=yes, directories=yes, status=yes, menubar=yes, scrollbars=yes, copyhistory=yes, addressbar=yes, resizable=yes");
    }
    
     function openEmail(url){ 
        window.open(url, 'openWin',"width=530,height=470, resizable=no, resizable=yes");
    }
    
    function openBio(winId, actID){

        if(actID == undefined){        

        window.open('Biography.aspx?id='+winId, winId,"width=550,height=600, resizable=yes");}
        else{
        window.open('Biography.aspx?id='+winId + '&activity=' + actID, winId,"width=500,height=600, resizable=yes");
        }
    }
    
    function openAccStatement(eventCode, sessionId){
        window.open('AccreditationStatement.aspx?eventCode='+eventCode+' &sessionId='+ sessionId, sessionId,"width=500,height=600, resizable=yes");
    }
    
    function openAddAcc(activity){
        window.open('AdditionalAccreditation.aspx?activity='+activity, activity, "width=400,height=600,scrollbars=1, resizable=yes");
    }
    
    function openPubMed(id) {
    window.open('MedlineArticle.aspx?id='+id, id, "width=400,height=600,scrollbars=1, resizable=yes");
    }
    
    function openHarvardTracker(url) {
    window.open(url, 'Harvard', "width=600,height=600, resizable=yes, toolbar=yes, location=yes, directories=yes, status=yes, menubar=yes, scrollbars=yes, copyhistory=yes, addressbar=yes, resizable=yes");
    }
    
    function openFeedback(url) {
    window.open(url, 'Feedback', "width=575,height=700,scrollbars=1, resizable=yes");
    }
    
    function openPDF(url){
        window.open(url, 'openWin',"width=600,height=600, menubar=yes, scrollbars=1, resizable=yes, resizable=yes");
    }
    
    function openCommercialSponsor(url){
        window.open(url, 'openWin', "width=550,height=600, resizable=yes");
    }
    
    function openSyllabi(eventCode) {
       window.open('PrintSyllabiPopUp.aspx?eventCode='+eventCode, eventCode, "width=400,height=600, resizable=yes, scrollbars=1");
    }


/* 

Function: cancelManage
cancelManage handles the behavior for Account Management satisfying the rule that if the user changes any value in the form that 
a javascript confirmation window pops up before navigating away from the page.  

Returns: 
cancel - Boolean.  If user
 has modified form, indicates whether the user has decided to truly cancel or not.
true - If the user has not modified the form, function just passes Boolean true.

*/

function cancelManage(){
 if(self.changed == true){ 
   var cancel = (confirm('Are you sure you want to Navigate away from this page?\nAny changes you have made will not be saved.'))?true:false;
    return cancel;
   }
else{
    return true;}
    }

/* 

Function: cancelBehavior
cancelBehavior handles universal functionality of the cancel button throughout the site.      

Returns: 
cancel - Boolean.  Indicates whether the user has decided to truly cancel or not.

*/
	function cancelBehavior(){
        var cancel = (confirm('Are you sure you want to cancel?\nAny changes you have made will not be saved.'))?true:false;
        return cancel;
        }


/* 

Function: createLogin
Redirects users for global 'Login' nav element dependent at the time of click to account for Ajax tab navigation.

Parameters: 
appPath - String. Current page state's url (includes dynamic tab states)

*/


    function createLogin(appPath){
        var newHref = document.location.toString();
        newHref = newHref.substring(7,newHref.length);
        newHref = newHref.substring(newHref.indexOf('/'), newHref.length);
        document.location = appPath + '/Login.aspx?ReturnUrl=' + encodeURIComponent(encodeURI(newHref));        
    }

/* 

Function: check_for_other_check
functionality for 'other' checkboxes in forms.  If the element check is checked, the element otherDiv is displayed.  Otherwise, its style is set to display:none.

Parameters:
check - CheckBox element.  
otherDiv - DOM Element.  Usually Div which contains textbox to enter 'Other' value... 
 
*/
    

function check_for_other_check(check, otherDiv){
    if(check.checked == true) {
        otherDiv.style.display = 'block';
    }
    else{
        otherDiv.style.display = 'none';
        $E('#' + otherDiv.id + ' input').value = '';
    }
}

// string prototype normalize_space takes out excess space in text of passed string.
String.prototype.normalize_space = function() {

return this.replace(/^\s*|\s(?=\s)|\s*$/g, "");
}



/*

Function: RedirectExternalLinks 
RedirectExternalLinks searches every link on a page searching for links that don't share the same basic domain.  If a link
does not match, its href is modified to add Redirect.aspx and the original href as queryString parameter.

Parameters: 
localpath - url to match links with.

*/

function RedirectExternalLinks(localpath){
    $$('a').each(function(el, i){    
        var servLocal = document.location.toString().substring(7, document.location.toString().length);
        servLocal = servLocal.substring(0,servLocal.indexOf('/'))
        if(el.href.toString().indexOf("javascript:") == -1 && el.href.toString().indexOf(servLocal) == -1 && el.href.toString() != '#' && el.href.toString().indexOf("mailto:") == -1 && el.href.toString() != "" && el.disabled != true)
        {
            //alert(el.href + ': ' + localpath);
            el.href=localpath + '/Redirect.aspx?url=' + encodeURIComponent(encodeURI(el.href));
            el.target = '_blank' + i;
        }    
    }
)
}


/* Start Metrics Client-Side Functions */
function trackPrintCMEDownload (actID, url)
{
    var qs = Object.toQueryString({activity:actID, url:url});
    new Ajax('BinaryContentTaggingSupport.aspx', {method: 'get', data: qs, onComplete:sendWebTrends.bind(this)}).request();
    
    if (url != "")
    {
        openPDF(url);
    }
}

function trackSyllabusDownload (url)
{
    var type = "syllabusDL";
    var referrer = document.location.toString();
    var qs = Object.toQueryString({type:type, url:url, referrer:referrer});
    new Ajax('BinaryContentTaggingSupport.aspx', {method: 'get', data: qs, onComplete:sendWebTrends.bind(this)}).request();
    
    if (url != "")
    {
        openPDF(url);
    }
}

function TagClientSideTabSwitch(index, name, url)
{
    if (typeof(window['genericContentType']) != "undefined" && name != null)
    {
        var title = document.title;
        var qs = Object.toQueryString({type:genericContentType, index:index, name:name, url:url, title:title});
        new Ajax('TabbedContentTaggingSupport.aspx', {method: 'get', data: qs, onComplete:sendWebTrends.bind(this)}).request();
    }
}

// send ajax call to grab metatags for binary file
function GetBinaryContentMetadata(docID, url, openWin)
{
    var qs = Object.toQueryString({id:docID, url:url});
    new Ajax('BinaryContentTaggingSupport.aspx', {method: 'get', data: qs, onComplete:sendWebTrends.bind(this)}).request();
    
    if (url != "" && openWin)
    {
        openPDF(url);
    }
}

// send ajax call to grab metatags for certificates
function GetCertificateMetadata(actID, certId, creditType, url)
{
    var qs = Object.toQueryString({certActivityId:actID, certId:certId, creditType:creditType, url:url});
    new Ajax('BinaryContentTaggingSupport.aspx', {method: 'get', data: qs, onComplete:sendWebTrends.bind(this)}).request();
}

// called after an ajax function returns,
// sends metadata information to webtrends
function sendWebTrends(metadata)
{
    //alert(metadata);
    var argArray = metadata.split(",");
    
    //Call dcsMultiTrack function
    if (self['dcsMultiTrack']!= undefined && metadata != '')
    {
        self['dcsMultiTrack'].apply(this, argArray);
    }
}
/* End Metrics Client-Side Functions */


function removeButtonText(){
            var butSet = $$('input[type=submit]', 'input[type=button]')
            if (!(window.webkit)){
                
                
                butSet.each(function(el){
                    el.value = '';
                
                })            
           }
        }
     
  function getJSON(elem, className){
    
    for(i=0;i<elem.values.length;i++){
        
        if(elem.values[i].butClass == className){
            return elem.values[i].value;
        }        
    }
  
  }
  
  function SafariFix(){
    
    if(window.webkit){
        populateButtons();
    }
  
  }
       
  function populateButtons(){
        var buttonLookupTable =  
        {"values": [
        {"butClass":"btnAddLicense", "value":"Add License"},
        {"butClass":"btnAddSpecialty", "value":"Add Specialty"}, 
        {"butClass":"btnBack", "value":"Back"},
        {"butClass":"btnBegin", "value":"Begin"},
        {"butClass":"btnCalculate", "value": "Calculate"},
        {"butClass":"btnCancel", "value":"Cancel"}, 
        {"butClass":"btnCertifyforcredit", "value":"Certify for Credit"}, 
        {"butClass":"btnClaimcredit", "value": "Claim Credit"}, 
        {"butClass":"btnClose", "value": "Close"},
        {"butClass":"btnCloseWindow", "value":"Close Window"},
        {"butClass":"btnContinue", "value": "Continue"},
        {"butClass":"btnContinueRegistration", "value": "Continue Registration"},
        {"butClass":"btnCreate", "value": "Create"},
        {"butClass":"btnCreateAccountSignUp", "value": "Sign Up"},
        {"butClass":"btnDelete", "value": "Delete"},
        {"butClass":"btnDeletefolder", "value": "Delete Folder"},   
        {"butClass":"btnDownload", "value": "Download"},
        {"butClass":"btnEdit", "value": "Edit"}, 
        {"butClass":"btnFinish", "value":"Finish"}, 
        {"butClass":"btnGo", "value":"Go"}, 
        {"butClass":"btnLogin", "value":"Log in"}, 
        {"butClass":"btnMove", "value":"Move"}, 
        {"butClass":"btnNext", "value":"Next"}, 
        {"butClass":"btnNextGreyedout", "value":"Next"}, 
        {"butClass":"btnPosttest", "value":"Post-Test"}, 
        {"butClass":"btnPrevious", "value":"Previous"}, 
        {"butClass":"btnPreviousGreyedout", "value":"Previous"}, 
        {"butClass":"btnRegforthismeeting", "value":"Register for this Meeting"}, 
        {"butClass":"btnRegister", "value":"Register"}, 
        {"butClass":"btnResume", "value":"Resume"}, 
        {"butClass":"btnSave", "value":"Save"}, 
        {"butClass":"btnSaveresumelater", "value":"Save/Resume Later"}, 
        {"butClass":"btnSearch", "value":"Search"}, 
        {"butClass":"btnSignup", "value":"Sign up"}, 
        {"butClass":"btnStart", "value":"Start"}, 
        {"butClass":"btnSubmit", "value":"Submit"}, 
        {"butClass":"btnVerifycontinue", "value":"Verify and Continue"}, 
        {"butClass":"btnDownloadSummary", "value":"Download Summary"}, 
        {"butClass":"btnRequestFullReport", "value":"Request Full Report"}, 
        {"butClass":"btnMergeSelectedAccounts", "value":"Merge Selected"}, 
        {"butClass":"btnMergeSelectedAccounts_Greyedout", "value":"Merge Selected"}, 
        {"butClass":"btnDisplayAccount", "value":"Display Account"}, 
        {"butClass":"btnDisplayAccount_Greyedout", "value":"Display Account"}, 
        {"butClass":"btnClearSearch", "value":"Clear Search"}, 
        {"butClass":"btnClearSearch_Greyedout", "value":"Clearch Search"}, 
        {"butClass":"btnSendtoAlternateEmail", "value":"Send to Alternate Email"}, 
        {"butClass":"btnSendtoEmailonFile", "value":"Send to Email on File"}, 
        {"butClass":"btnUpdateRegistration", "value":"Update Registration"} 
        ]};
        
       
        
        var butSet = $$('input[type=submit]', 'input[type=button]')
        
        butSet.each(function(el,i){
               if(el.className != ""){
                    el.value = getJSON(buttonLookupTable, el.className);

               }
        })
        
        
        }
        
        function removeButtonValues(){
            var butSet = $$('input[type=submit]', 'input[type=button]')
            if (!(window.webkit)){
                
                
                butSet.each(function(el){
                    el.value = '';
                
                })            
           }
        }
        //used in Travel control on live events - print google Maps popup
        function printMap(sAddrID, eAddrID)
        {
            var url = "http://maps.google.com/maps?f=d&hl=en&ie=UTF8&z=9&layer=c&pw=2";
            var sAddr = document.getElementById(sAddrID).value;
            var eAddr = document.getElementById(eAddrID).value;
            url = url + "&saddr=" + sAddr + "&daddr=" + eAddr;
            window.open(url, 'openWin', "width=550,height=600, resizable=yes, scrollbars=yes");
        }
        
        function addTrans(divID)
        {
         divID = divID.replace(" ","");
         document.getElementById(divID).className=document.getElementById(divID).className.replace(' popup','');
         
        }
        
        function removeTrans(divID)
        {
          divID = divID.replace(" ",""); 
          document.getElementById(divID).className = document.getElementById(divID).className + ' popup';      
        }

var scroll;

function scrollerTop(objectId) 
        {
	       
	        var scrollName = objectId + 'Span';
	        scroll = new Fx.Scroll(scrollName, {duration: 0, wait: false}).toTop();

        }

function scrollerBottom(objectId) 
        {
	        
	   
	        var scrollName = objectId + 'Span';
	        //  alert(scrollName);
	//        event = new Event(event).stop();
	        scroll = new Fx.Scroll(scrollName, {duration: 100, wait: false}).toBottom();
	        ///alert(objectId); 
	        //var scrollBottom = objectId + 'Bottom';

	        //alert(scrollBottom);
	       // scroll.toElement(scrollBottom);
	        //scroll.toBottom();
	        //alert('here');
	        scroll.toTop.delay(5000, scroll);
        }
        
        
        
        //used in Travel control on live events - toggle google Maps
        function toggleMapSize(appPath)
        {
            document.getElementById("bt_Go").value="Go";
             document.getElementById("bt_Go").style.height="25px";
            if(document.getElementById("mapDiv").className == "gMap")
            {
                document.getElementById(gMapID1).className = "mapHidden";
                document.getElementById("mapBox").className = "travelMapExpand";
                document.getElementById("mapDiv").className = "gMapExpand";
                document.getElementById("mapDirection").className = "mapDirectionExpand";
                document.getElementById("mapArrow").src = appPath + "/images/icons/rightArrow.gif";
                document.getElementById("mapArrowTxt").innerHTML = "Collapse";
                document.getElementById("printMap").className = "mapVisible";
                showFullMap();
            }
            else
            {
                document.getElementById(gMapID1).className = "mapVisible";
                document.getElementById("mapBox").className = "travelMap";
                document.getElementById("mapDiv").className = "gMap";
                document.getElementById("mapDirection").className = "mapDirection";
                document.getElementById("mapArrow").src =  appPath + "/images/icons/leftArrow.gif";
                document.getElementById("mapArrowTxt").innerHTML = "Expand";
                document.getElementById("printMap").className = "mapHidden";
                showMiniMap();
            }
        }
        //used in Travel control on live events - print google Maps popup
        function printMap(sAddrID, eAddrID)
        {
            var url = "http://maps.google.com/maps?f=d&hl=en&ie=UTF8&z=9&layer=c&pw=2";
            var sAddr = document.getElementById(sAddrID).value;
            var eAddr = document.getElementById(eAddrID).value;
            url = url + "&saddr=" + sAddr + "&daddr=" + eAddr;
            window.open(url, 'openWin', "width=550,height=600, resizable=yes, scrollbars=yes");
        }