/*globals jQuery, window */

(function($) { 
    var ADVOC = {
		
        TRIM_REGEX       : /^\s*(\w+)\s*$/,
        
        PIX_PATH         : 'http://mysite.ncnetwork.net/millsj123/bloggerImages/advocTeam/',
        PIX_WIDTH        : '100',
        
        CONTAINER_ID     : 'advocTbl',
        ELEM_ID          : 'advocElem',
        TD_CLASS         : 'advocTd',
        CHAIR_CLASS      : 'chair',
        NAME_CLASS       : 'advocName',
        STATE_CLASS      : 'advocState',
        CREDS_CLASS      : 'advocCreds',
        PROFORGS_CLASS   : 'advocOrgs',
        WEBLIST_CLASS    : 'advocWeb',
        IMG_CLASS        : 'advocImg',
        IMG_LOADED_CLASS : 'loaded',
        WINDICON_CLASS   : 'advocIcon',
        
        ORGS_TITLE       : 'Professional Organizations',
        WEB_TITLE        : 'Website',
        
        IS_COCHAIRS      : false,
        
        
        /* *************************************************************************************************************
         *
         *        DATA BASE NOTES:
         *
         *        Image file editing:
         *            Image files should be cropped to 100px X 150px. DON'T use automatic scaling of images!
         *
         *        Image file naming conventions:
         *            The team memebers image file path names are concatenated from fields in each ADVOC.Members object.
         *            src = ADVOC.PIX_PATH + ADVOC.Members[i].first + ADVOC.Members[i].last + ADVOC.Members[i].pix
         *
         *            The first and last name should be title case so the file path names look like:
         *                http://mysite.ncnetwork.net/millsj123/bloggerImages/advocTeam/FirstLast.pix
         *
         *        CAREFUL:
         *            !! Watch for quotes, apostrophe's and extra spaces within the profOrg, creds fields.
         *
         *
         *        Fields:
         *            first, last -> strings contain first and last name. Should be title case.
         *            creds       -> string contains credentials, should be a comma-space delimited list. Should be all caps.
         *            state       -> string Title case
         *            pix         -> file extention in whatever case the file name has. (Should be lower case see
         *                            note about image file naming conventions.) EX: .jpg, .gif, .png)
         *            profOrg     -> string containing professional organizations a semi-colon delimited list.
         *            active      -> a boolean. True if the entry is included in the list.
         *            web         -> json object describing the Advocacy Team Member's website
         *                            {href:'someurl', title:'web page title'}
         *
         * ********************************************************************************************************** */
        
        Members : [
{ first:'Nicole', last:'Barnett', creds:'RN, MBA, DHSc', state:'California', pix:'.jpg', profOrg:'Adjunct Faculty Dominican University Graduate Nursing;Adjunct Faculty Touro University School of Public Health;American College of Healthcare Executives;International Association of Forensic Nurses', active:'YES', web:null, isChair:false},
{ first:'Beth ', last:'Barranco', creds:'RN, BSN', state:'South Carolina', pix:'.jpg', profOrg:'American Association of Critical Care Nurses; Shared Governance Council for University Hospital; Cardiac and Renal Council for University Hospital; Magnet Committee 2010', active:'YES', web:null, isChair:false},
{ first:'Kathleen', last:'Bartholomew', creds:'RN, MN', state:'Washington', pix:'.jpg', profOrg:'American Nurses Association;NW Organization of Nurse Executives;American Holistic Nurses Society', active:'YES', web:{href:'http://www.healthleadersmedia.com/content/LED-259052/Kathleen-Bartholomew-Standing-Up-to-Physician-Bad-Behavior.html', title:'Kathleen Bartholomew: Standing Up to Physician Bad Behavior'}, isChair:false},
{ first:'Rita', last:'Batchley', creds:'RN, BSN, PHN', state:'California', pix:'.jpg', profOrg:'Chief Nurse Rep: Ventura County Health Care Agency;American Nurses Association;California Nurses Association;Ventura College of Nursing Faculty', active:'YES', web:{href:'http://www.thenursesnurse.com', title:'The Nurses\' Nurse'}, isChair:false},
{ first:'Sally ', last:'Cadman', creds:'MS, ACNS-BC, CCRN, DNP Student', state:'New Hampshire', pix:'.jpg', profOrg:'American Association of Critical Care Nurses;American Holistic Nurses Association;Sigma Theta Tau', active:'YES', web:null, isChair:false},
{ first:'Tara ', last:'Candela', creds:'RN, BSN, JD', state:'Virginia', pix:'.jpg', profOrg:'American Bar Association, Health Law and Litigation sections', active:'YES', web:null, isChair:false},
{ first:'Keith ', last:'Carlson', creds:'RN, BSN', state:'New Mexico', pix:'.jpg', profOrg:'', active:'YES', web:{href:'http://digitaldoorway.blogspot.com', title:'Digital Doorway'}, isChair:false},
{ first:'Lew ', last:'Frederick', creds:'State Representative House District 43', state:'Oregon', pix:'.jpg', profOrg:'', active:'YES', web:{href:'http://www.leg.state.or.us/frederick/', title:'Oregon House of Representatives'}, isChair:false},
{ first:'Laura', last:'Gable', creds:'RN, BSN', state:'California', pix:'.jpg', profOrg:'California Nurses Association;American Nurses Association', active:'YES', web:null, isChair:false},
{ first:'Phyllis', last:'Gallagher', creds:'RN, JD', state:'California', pix:'.jpg', profOrg:'TAANA Board of Directors;Member, Municipal Advisory Committee (Wrightwood, CA); Bioethics Committee Member (Parkview Hospital, Riverside, CA)', active:'YES', web:null, isChair:false},
{ first:'Evalyn', last:'Gossett', creds:'RN, MSN', state:'Indiana', pix:'.jpg', profOrg:'American Association of Colleges of Nursing;American Association of University Professors;National League for Nursing;Society of Nurses in Advance Practice;Sigma Theta Tau International - Alpha and Epsilon Chapter', active:'YES', web:null, isChair:false},
{ first:'Lori ', last:'Graber', creds:'RN', state:'Alaska', pix:'.jpg', profOrg:'', active:'YES', web:null, isChair:false},
{ first:'Anne', last:'Gresbrink', creds:'LPN', state:'Oregon', pix:'.jpg', profOrg:'', active:'YES', web:null, isChair:false},
{ first:'Craig ', last:'Grover', creds:'RN', state:'Oregon', pix:'.jpg', profOrg:'', active:'YES', web:null, isChair:false},
{ first:'Paula ', last:'Guthat', creds:'', state:'Michigan', pix:'.jpg', profOrg:'UCDA (University and College Designers Association); CASE (Council for Advancement and Support of Education)', active:'YES', web:null, isChair:false},
{ first:'Lisa', last:'Hoffman', creds:'BSN, RN, MS', state:'Arizona', pix:'.jpg', profOrg:'American Nurses Association;American Public Health Association;American Association for the Advancement of Science;Arizona Public Health Association; Sigma Xi, The Scientific Research Society;Southern Arizona Red Cross;Arizona Nurses Association', active:'YES', web:null, isChair:false},
{ first:'Gail', last:'Holtz', creds:'RN/NP, MSN, CRRN, ACNS-BC, MS', state:'New York', pix:'.jpg', profOrg:'American Academy of Pain Management;National Association of Clinical Nurse Specialists;American of Clinical Nurse Specialists;Association of Rehabilitation Nurses;American Academy of Health Care Executives', active:'YES', web:null, isChair:false},
{ first:'Regina ', last:'Lane', creds:'RN, BSN, CPUR, MSN, MBA-HCA', state:'Maryland', pix:'.jpg', profOrg:'National Nurses Organization;  National Nurses Honor Society - Omicron chapter, Wilmington, DE; Cecil County Family Violence Subcommittee, Cecil County, MD ;Cecil College Advisory Member; Elk Preservation Society', active:'YES', web:null, isChair:false},
{ first:'Anne ', last:'Llewellyn', creds:'RN-BC, MS, BHSA, CCM, CRRN', state:'Florida', pix:'.jpg', profOrg:'Editor in Chief, Case Management Products and Services Dorland Health ', active:'YES', web:null, isChair:false},
{ first:'Kim', last:'McAllister', creds:'RN, BSN', state:'California', pix:'.jpg', profOrg:'American Nurses Association;Emergency Nurses Association;California Nurses Association;Sigma Theta Tau;National League for Nursing', active:'YES', web:null, isChair:false},
{ first:'Marcia ', last:'Moody', creds:'State Representative  District 12', state:'New Hampshire', pix:'.jpg', profOrg:'', active:'YES', web:null, isChair:false},
{ first:'Anne ', last:'Nowlin', creds:'BSN, RN', state:'Colorado', pix:'.jpg', profOrg:'Hospice Case Management', active:'YES', web:null, isChair:false},
{ first:'Kathy', last:'Quan', creds:'RN, BSN, PHN', state:'California', pix:'.jpg', profOrg:'CA Nurses Association;Hospice and Palliative Nurses Association', active:'YES', web:{href:'http://www.thenursingsiteblog.com', title:'The Nursing Site Blog'}, isChair:false},
{ first:'Karen ', last:'Reynolds', creds:'BSN, MSN, CNS, RN', state:'Florida', pix:'.jpg', profOrg:'American Nurses Association; Florida Nurses Association; American Gerontological Nurses Society', active:'YES', web:null, isChair:false},
{ first:'Mary Beth ', last:'Rosenstiel', creds:'RN, DNP', state:'Oregon', pix:'.jpg', profOrg:'Sigma Theta Tau International; Omicron Upsilon Chapter STTI;   American Holistic Nurses Association; Hospice and Palliative Nurses Association; Albina Early Head Start Health Services Advisory Committee ', active:'YES', web:null, isChair:false},
{ first:'Susan ', last:'Rowe', creds:'', state:'California', pix:'.jpg', profOrg:'Chair, Madera County (CA) Democratic Party', active:'YES', web:null, isChair:false},
{ first:'June ', last:'Schulte', creds:'', state:'Vermont', pix:'.jpg', profOrg:'', active:'YES', web:null, isChair:false},
{ first:'Dennis ', last:'Smith', creds:'', state:'New York', pix:'.jpg', profOrg:'International Association of Firefighters;International Association of Fire Chiefs;Congressional Fire Services Institute;National Firefighter Near-Miss Reporting System (Chairman);Tribute, at Ground Zero-Trustee;Boys and Girls Clubs of America-Board of Advisors', active:'YES', web:null, isChair:false},
{ first:'Jennifer ', last:'Stevens-Walters', creds:'RN', state:'Oregon', pix:'.jpg', profOrg:'Oregon Nurses Association;American Nurses Association', active:'YES', web:null, isChair:false},
{ first:'Laura ', last:'Stokowski', creds:'RN, MS', state:'Virginia', pix:'.jpg', profOrg:'Writer and Editor for Medscape Nurses;National Association of Neonatal Nurses- Co-Chair, Health Policy & Advocacy Committee;Editorial Board member- Advances in Neonatal Care', active:'YES', web:null, isChair:false},
{ first:'Georgia', last:'Swank', creds:'MS, RN, CDDN, NEA-BC', state:'Kentucky', pix:'.jpg', profOrg:'STTI (Sigma Theta Tau International);National DDNA (Developmental Disabilities Nurses Association) Chapter Committee Member;KYDDNA (Kentucky DDNA) President;INDDNA (Indiana DDNA) Board Member', active:'YES', web:null, isChair:false},
{ first:'Diana ', last:'Swihart', creds:'PhD, DMin, MSN, CS, APN, RN-BC', state:'Colorado', pix:'.jpg', profOrg:' Sigma Theta Tau International (STTI);  Nurses Organization of Veterans Affairs (NOVA); National Nursing Staff Development Organization (NNSDO);American Nurses Association; American Association for Preceptors;Forum for Shared Governance', active:'YES', web:null, isChair:false},
{ first:'Pat', last:'VanBetten', creds:'BSN, MEd', state:'Nevada', pix:'.jpg', profOrg:'American Nurses Association;Nevada Nurses Association', active:'YES', web:null, isChair:false},
{ first:'Joachim ', last:'Voss', creds:'PhD, RN, ACRN', state:'Washington', pix:'.jpg', profOrg:'Association of Nurses in AIDS Care; American Nurses Association;Oncology Nursing Society;WIN;Sigma Theta Tau International;CANS;IAS', active:'YES', web:null, isChair:false},
{ first:'Leandra', last:'Wallace', creds:'RN, MSN, PHN', state:'California', pix:'.jpg', profOrg:'Sigma Theta Tau International;American Association of Holistic Nurses', active:'YES', web:null, isChair:false},
{ first:'Michelle', last:'Wolff', creds:'BSN, RN', state:'Colorado', pix:'.jpg', profOrg:'', active:'YES', web:null, isChair:false},
{ first:'Sharon', last:'Wollschlager', creds:'', state:'Rhode Island', pix:'.jpg', profOrg:'SEIU/NAGE Local 79, Vice President-Rhode Island Department of Health;SEIU Rhode Island State Council;RI AFL-CIO; Working RI;Working East Bay;Certified Psychiatric Nurse, ANA', active:'YES', web:null, isChair:false}

    // REMOVE LAST COMMA
        ],
          
        create : function() {
            var activeList = [];
            var chairCount = 0;
			var chairList = [];
            var advocElem = document.getElementById(ADVOC.ELEM_ID);
            var leftTd = null;
            var rightTd = null;
			var i = 0;
            
            // Note: this keyword refers to one ADVOC.Members object
            //     Function called from jquery.each()
            //    Remove leading and trailing white space from object properties
            function trim () {
                var regexTrim = ADVOC.TRIM_REGEX;
                var regexDoubleSpace = /( ){2,}/g;
				var prop = '';
				
                for (prop in this) {
                    if(this.hasOwnProperty(this[prop])   && typeof this[prop] === 'string') {
                        this[prop] = this[prop].replace(regexTrim, '$1');
                        this[prop] = this[prop].replace(regexDoubleSpace, ' ');
                    }
                }
            }
            
            //    Create one <tr> element for each two Advocacy Team member
            //        Input:
            //            n -> the array index from activeList
            //        Output:    one <tr> with two child <td>. Each <td> contains data about one
            //            Advocacy Team member. If there is an odd number of members the
            //            last <td> is empty.
            //    Notes:
            //        1) this keyword refers to one activeList object.
            //         2) n refers to the array index of one activeList object.
            //        3) called from jquery.each().
            //
            function makeList(n) {
                var isEven = (n % 2 === 0)?true:false;
                var imgDiv = document.createElement('div');
                var img = document.createElement('img');
                var contentArry = null;
                var activeRow = null;
                var p1, p2, p3, p4, p5; //content
            
                function makeTd(parentTr) {
                    var newTd = document.createElement('td');
                    parentTr.appendChild(newTd);
                    return newTd;
                }
                
                function makeProfOrgs (orgs) {
                    var div = document.createElement('div');
                    var newP = document.createElement('p');
                    var newTitle = document.createElement('h4');
                    var orgList = orgs.split(';');
                    var orgItem = '';
                    
                    div.className = ADVOC.PROFORGS_CLASS;
                    newTitle.appendChild(document.createTextNode(ADVOC.ORGS_TITLE));
                    newP.className = ADVOC.PROFORGS_CLASS;
                    div.appendChild(newTitle);
                    $(orgList).each(function(n) {
                            orgItem = this.replace(ADVOC.TRIM_REGEX,'$1');                 
                            newP.appendChild(document.createTextNode((n+1) + ') ' + orgItem));
                            newP.appendChild(document.createElement('br'));
                    });
                    div.appendChild(newP);
                    return div;
                }
                
                function makeWebList(webObj) {
                    var div = document.createElement('div');
                    var newP = document.createElement('p');
                    var newTitle = document.createElement('h4');
                    var urlAnchor = document.createElement('a');
                    
                    function makeIcon() {
                        var icon = document.createElement('img');
                        icon.alt = 'Opens in new window or tab';
                        icon.title = icon.alt;
                        icon.className = ADVOC.WINDICON_CLASS;
                        icon.src = '/images/newWindow.png';
                        return icon;
                    }
                    newTitle.appendChild(document.createTextNode(ADVOC.WEB_TITLE));
                    div.className = ADVOC.WEBLIST_CLASS;
                    div.appendChild(newTitle);                 
                    urlAnchor.href = webObj.href;
                    urlAnchor.appendChild(document.createTextNode(webObj.title));
                    urlAnchor.target = '_blank';
                    newP.className = ADVOC.PROFORGS_CLASS;
                    newP.appendChild(urlAnchor);
                    newP.appendChild(document.createTextNode(' '));
                    newP.appendChild(makeIcon());
                    newP.appendChild(document.createElement('br'));
                    div.appendChild(newP);
                    return div;        
                }
                
                function makeP (text, cssClass, newElem) {
                    var t = null; 
					if(newElem) {
						t = document.createElement(newElem);
					}
					else {
				        t = document.createElement('p');
					}
                    t.appendChild(document.createTextNode(text));
                    t.className = cssClass;
                    return t;
                }
                
                function addContent (tdElem, apendElemsArry) {
					var i = 0;
                    tdElem.className = ADVOC.TD_CLASS;
                    for (; i < apendElemsArry.length; i += 1) {
						if(apendElemsArry[i]) {
							tdElem.appendChild(apendElemsArry[i]);
						}
					}
                }
				
				p1 = makeP(this.first + ' ' + this.last, ADVOC.NAME_CLASS, 'h3');
				p2 = makeP(this.state, ADVOC.STATE_CLASS);
				p3 = makeP(this.creds, ADVOC.CREDS_CLASS);
				p5 = (this.web)?makeWebList(this.web):null;
				p4 = (this.profOrg)?makeProfOrgs(this.profOrg):makeP('','');
				contentArry = [imgDiv, p1, p3, p2, p5, p4];
                imgDiv.className = ADVOC.IMG_CLASS;
                img.className = ADVOC.IMG_CLASS;
				if (this.pix) {
                	img.src = (ADVOC.PIX_PATH + this.first + this.last + this.pix).replace(/ /g,''); //remove spaces from path name
				}
                img.alt = this.first + ' ' + this.last;
                $(img).one('load', function(){ $(this).parent().addClass(ADVOC.IMG_LOADED_CLASS); });
                imgDiv.appendChild(img);
                
                if(this.isChair) {
                    var chairTitle = (ADVOC.IS_COCHAIRS)?'Advocacy Team Co-chair':'Advocacy Team Chair';
                    var h3 = document.createElement('h3');
                    h3.appendChild(document.createTextNode(chairTitle));
                    h3.classname = ADVOC.CHAIR_CLASS;
                    contentArry.unshift(h3);
                }
                
                if(isEven) {
                    activeRow = document.createElement('tr');    //start new row
                    leftTd = makeTd(activeRow);                  //create and append left cell    
                    rightTd = makeTd(activeRow);                 //create and append right cell
                    addContent(leftTd, contentArry);             //only have content for left cell
                    advocElem.appendChild(activeRow);            //append the new <tr> to <tbody>
                }
                else {
					addContent(rightTd, contentArry);    //add content for an already created right cell
				}
            } //end makeList
            
			$(ADVOC.Members).each(function() { 
				if (this.active){
					if(this.isChair) {
						chairCount += 1;
					}
					activeList.push(this);
				}
             });
            if(chairCount > 1) {
				ADVOC.IS_COCHAIRS = true;
			}            
            //Trim white space then sort
            $(activeList).each(trim);
            activeList.sort( function(a,b) {return a.first.localeCompare(b.first); } );
            activeList.sort( function(a,b) {return a.last.localeCompare(b.last); } );
			//remove chairpersons from activeList and save in chairList
			for(i = 0; i < activeList.length; i += 1) {
				if(activeList[i].isChair) {
					chairList.unshift((activeList.splice(i, 1))[0]);
				}
			}
			//push chairperson back onto the front of the activeList
			for(i = 0; i < chairList.length; i += 1) { 
				activeList.unshift(chairList[i]);						   
			}
            $(activeList).each(makeList);
        }, //end create
        
        init : function() {
            var advocElem = document.getElementById(ADVOC.ELEM_ID);
            if(advocElem && ADVOC.Members && ADVOC.Members.length){
                //remove the empty <tr><td></td></tr>elements
                while(advocElem.firstChild) {
					advocElem.removeChild(advocElem.firstChild);
				}
                ADVOC.create();
            }
        }//end init
    }; //end ADVOC
    
    $(document).ready( function() {
        ADVOC.init();      
    });
}(jQuery));
