// JavaScript Document, requires jQuery to be loaded first

$(document).ready(function() {
	IHD.init();

});

var IHD = function() {
	
    /*******************************************************************************************
     	PRIVATE PROPERTIES AND METHODS
     *******************************************************************************************/

	// a little browser sniffing
//    var ie6 = ($.browser.msie && parseInt(jQuery.browser.version) < 7) ? true : false;
//    var ie7 = ($.browser.msie && parseInt(jQuery.browser.version) < 8) ? true : false;
	
	/***************************** "Constants" ******************************/
	
	var SITE_URL = 'http://www.informedmedicaldecisions.org'; 
	//var SITE_URL = 'http://webserver/www/informedmedicaldecisions.org';
	var slideshowimgpath = SITE_URL + '/images/homeslideshow/';

    /***************************** Private Properties *****************************/
    
    var pageId;
    var pageClasses; // array
    // list of dynamically loaded files for loadPlugins
    var filelist = [];
	
	// form validation data for use with jquery.validate plugin
	/* FORMAT:
	var pagerules = {
		page_id : {
			field_id :		{rule: true},
			token :			{required : true,
								remote: {
									type :	'post',
									url :	AJAX_URL+'token.php',
									data :	{
										hash : function() {
											return Cookie.read('token');
										}
									}
								}
							}	
		}
	}
	var pagemessages = {
		page_id : {
			field_id : 'Message'
		}
	}
	*/
	
	// "did you know" rotating copy
	var didyouknow = []; 
		didyouknow[0] = 'For at least 70% of people who have heart bypass surgery, the survival rate is no better than if they had chosen to take medication alone.';
		didyouknow[1] = 'On average, women with early stage breast cancer who have a lumpectomy and radiation live as long as those who have a mastectomy.';
		didyouknow[2] = 'Whether or not they receive active treatment, most men diagnosed with early stage prostate cancer will die of something else.';
		didyouknow[3] = 'Back patients in Idaho Falls, Idaho, are 20 times more likely to have lumbar fusion surgery than those in Bangor, Maine, with no clear difference in outcomes or quality of life.';
		didyouknow[4] = 'The best plan for managing prostate cancer depends on personal preference; there is no approach to treatment that is clearly better than the others.';
		didyouknow[5] = 'For most women with early stage breast cancer, waiting four weeks to make a treatment decision would not affect their chances of survival.';
		didyouknow[6] = 'Health care for the average Medicare patient costs nearly twice as much a year in New Jersey ($8,076) as it does in North Dakota ($4,766).';
		didyouknow[7] = 'In their last six months of life, the average patient in Oregon spends eight days in the hospital and sees 14 doctors. The average patient in New York spends 35 days in the hospital and sees 35 doctors.';
		didyouknow[8] = 'There are almost twice as many hip replacements per capita in Palo Alto as there are in San Francisco, just 35 miles away.';
		didyouknow[9] = 'Over the last 20 years, gains in heart attack survival rates have been smallest in regions of the United States that spend the most on healthcare. ';
		didyouknow[10] = 'More care does not equal better outcomes; patients in regions that provide the best outcomes see fewer specialists and spend less time in the hospital than patients in lower-performing regions.';
		didyouknow[11] = 'During their last six months of life, patients in Miami see five times as many specialists as their counterparts in Minneapolis, yet do not live any longer.';
		didyouknow[12] = 'About 25% of Medicare dollars are spent on patients in their last 60 days of life.';
		didyouknow[13] = 'A recent study found that doctors and others who make decisions on behalf of seriously ill patients are often unaware of those patients preferences.';
		didyouknow[14] = 'Only about half of patients who do not wish to receive CPR or other rescue interventions have Do-Not-Resuscitate orders.';
		didyouknow[15] = 'Most people with back and leg pain due to a herniated disc do not need surgery; the pain will usually get better on its own.';
		didyouknow[16] = 'After two years, people who had surgery for a herniated disc are only slightly more satisfied with their symptoms than people who did not have surgery.';
		didyouknow[17] = 'There is good evidence that weight loss can be helpful for people with knee pain. However, researchers do not know if losing excess weight helps reduce hip pain.';
		didyouknow[18] = 'Bed rest for back pain is no longer recommended. In fact, too much bed rest can actually be harmful.';
		didyouknow[19] = 'Most people with back pain do not need x-rays or other tests to manage the problem. Back pain often improves within days or weeks, even without any specific treatment.';
		didyouknow[20] = 'There is no reliable blood or imaging test to detect ovarian cancer early.';
		didyouknow[21] = 'Screening tests for colon cancer - stool test, sigmoidoscopy, colonoscopy and imaging tests - are similarly effective; the choice should simply be based on individual preference.';
		didyouknow[22] = 'If an x-ray or an MRI shows a back problem, such as a bulging disc, it does not mean that is the cause of pain. Imaging tests often find abnormalities in people not in pain.';
		didyouknow[23] = 'Although losing excess weight may have many health benefits, there is no good evidence that shedding extra pounds helps prevent back pain.';
		didyouknow[24] = 'In many people with stable heart disease, medications are just as good as stents or bypass surgery at lowering the chance of heart attack.';
		didyouknow[25] = 'Of women without breast cancer who have ten mammograms, as many as half will have at least one false-positive result, and one in five will have a breast biopsy.';
		didyouknow[26] = 'There is no harm in waiting to have surgery for herniated disc. Those who wait a month or more have just as much pain relief as those who have surgery right away.';
		didyouknow[27] = 'After weight loss surgery, 20% of people will gain back most or all of the weight they lost.';
		didyouknow[28] = 'If a woman does not have coronary heart disease, taking a statin to lower her cholesterol may not change her risk of having a heart attack or dying.';
	
	var slides = [];
		/* slides[1] = {
			img: null,
			videolink: 'http://www.dhmc.org/webpage.cfm?site_id=2&org_id=108&morg_id=0&sec_id=0&gsec_id=39700&item_id=45569',
			rel: 'external',
			imgsrc: 'dale2.jpg',
			h2_copy: 'A Model of Breast Cancer Care',
			body_copy: '<p>At the Dartmouth Hitchcock Medical Center, the protocol for patients with breast cancer involves the use of decision aids and shared decision-making for all aspects of treatment decisions.  This video demonstrates the way care is delivered and preferences are acknowledged for all patients at the Norris Cotton Cancer Center.</p>'
		}; */
		slides[0] = {
			img: null,
			videolink: 'http://www.informedmedicaldecisions.org/vid_prostate.html',
			rel: 'video',
			imgsrc: 'Barry_screenshot.jpg',
			h2_copy: 'PSA Screening has to be a Shared Medical Decision',
			body_copy: 'Dr. Michael Barry, Foundation president, explains the PSA screening test for prostate cancer and discusses why patients need to be informed before deciding whether or not the test is right for them.'
		};
		slides[1] = {
			img: null,
			videolink: 'http://www.informedmedicaldecisions.org/sdm-animation.html',
			rel: 'video',
			imgsrc: 'sdm_animation.jpg',
			h2_copy: 'Shared Decision Making Made Simple',
			body_copy: "<p>Watch this animated short to see how the skills you use to make big life decisions &mdash; buying a car, choosing a school, or deciding where to live &mdash; can help you make a shared medical decision.</p>",
		};
		slides[2] = {
			img: null,
			videolink: 'http://www.informedmedicaldecisions.org/vid4.htm',
			rel: 'video',
			imgsrc: 'change.jpg',
			h2_copy: 'Change That Works',
			body_copy: "<p>Watch this short video to hear from clinicians as they reflect on their first year of implementing shared decision making as part of the Foundation's demonstration site project</p>",
		};
		slides[3] = {
			img: null,
			videolink: 'http://www.informedmedicaldecisions.org/vid3.htm',
			rel: 'video',
			imgsrc:	'Howard.jpg',
			h2_copy: 'Transforming the Patient Experience',
			body_copy: '<p>Listen to the stories of four patients who took action to become active participants in their medical decisions: Howard, who decided not to have bypass surgery for coronary heart disease; Loretta, who made a decision about how her diabetes would be managed;  Phil, who decided not to have repeat surgery for a back condition; and Kathy, who chose mastectomy over lumpectomy for early stage breast cancer.</p>'
		};
		/* slides[2] = {
			img: null,
			videolink: 'http://www.informedmedicaldecisions.org/vid2.htm',
			rel: 'video',
			imgsrc: 'gettingcare.jpg',
			h2_copy: 'Getting the Care That\'s Right for You',
			body_copy: '<p>The health care system is not only difficult to navigate, but often patients receive care they do not need or want.  This 20-minute video provides helpful ideas about how to work with your health care providers to know when decisions are being made and how to be actively informed and involved in your care.</p>'
		}; */
		/* slides[3] = {
			img: null,
			videolink: 'http://www.informedmedicaldecisions.org/vid1.htm',
			rel: 'video',
			imgsrc: 'peter.jpg',
			h2_copy: 'A Shared Decision Making Story',
			body_copy: '<p>Listen and watch a real patient\'s story about a decision whether or not to have back surgery. By getting additional information about treatment options for back pain and then engaging with his physician in a shared decision-making process, Peter was able to choose the treatment that best fit his personal needs and preferences.</p>'
		}; */
		
	// to make life a bit easier, keep track of current slide
	var currentslide = 0;
	
    /***************************** Dynamically loaded items *****************************/

	// Plugins. Note: plugin_data can only uses one entry for a page, if both needed, use entry for id, which overrides class. NOTE: css loading doesn't seem to work for IE6
    /* FORMAT:
     var plugin_data = {
     mypage_id_or_class: {
	     filestoget:		[myfilepath1, myfilepath2], // put js last
	     callback:		'myfunction' // callback for last js function
     }
     };
     */

	// Global functions: array of functions to fire onready for every page
    var globalfunctions = ['externallinks'];
    
    // Page functions, based on page id (default) and page class
    var pagefunctions = {
		// pageid	: ['function1', 'function2']
		'home'		: ['rotateKnow', 'doSlideshow']
    };
    
    //var imgCache = [];
    
    /********************************* Helpers *********************************/
    
    // helper for plugin loader
    function createCallback(methodName){
    	var that = this;
        return function(){
            that[methodName]();
        };
    }
 
    // preloads regular images
    function preloadImages(src){
        //$('<img>').attr('src', src);
        var cacheImg = document.createElement('img');
		cacheImg.src = src;
      	//imgCache.push(cacheImg);
      	return cacheImg;
    }
    
    // cookie functions
    var Cookie = {
        create: function(name, value, days){
            var expires;
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                expires = "; expires=" + date.toGMTString();
            }
            else {
                expires = "";
            }
            document.cookie = name + "=" + value + expires + "; path=/";
        },
        
        read: function(name){
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) === ' ') {
                    c = c.substring(1, c.length);
                }
                if (c.indexOf(nameEQ) === 0) {
                    return c.substring(nameEQ.length, c.length);
                }
            }
            return null;
        },
        
        erase: function(name){
            document.cookie = name + "= ; max-age=-1; path=/";
        },
        
        test: function(){
            // try to create a cookie
            this.create('test', 'testing');
            // then read it
            if (this.read('test') === 'testing') {
                this.erase('test');
                return true;
            }
            else {
                return false;
            }
        }
    };
        
	/***************************** Private Methods *****************************/
    
	// do the actual data change for the slideshow
	function changeSlide(index) {
		$('a.current').removeClass('current');
		var src = slideshowimgpath + slides[index].imgsrc;
		$('.slideshow img').fadeOut('slow', function(){
			//$(this).attr('src', src);
			$(this).replaceWith(slides[index].img);
			$('.slideshow img').addClass('slide').attr('width', '368').attr('height', '268');
			$(this).fadeIn('slow');
		});
		$('.slideshow h2').fadeOut('slow', function(){
			$(this).html(slides[index].h2_copy);
			$(this).fadeIn('slow');
		});
		$('.slideshow .ss_content').fadeOut('slow', function(){
			var html = slides[index].body_copy;
			html += '<p class="watchvideo"><a rel="' + slides[index].rel + '" href="' + slides[index].videolink + '">Watch This Video</a></p>';
			$(this).html(html);
			$(this).fadeIn('slow');
		});
		$('#ss_nav a:contains("'+(index+1)+'")').addClass('current');
		$('.slideshow a[rel="video"]').attr('href', slides[index].videolink);
	}
	
	function cycleSlideShow() { 
		ss_interval = setInterval(function(){ 
			currentslide = (currentslide < 3) ? currentslide+1 : 0;
			changeSlide(currentslide);	
		}, 15000)	
	}

	/*******************************************************************************************
    	PUBLIC PROPERTIES AND METHODS
    *******************************************************************************************/
        

	return {
		
		// starts the ball rolling
		init: function() {
			// get the page id and classes
			this.getPageIdentities();
		    // load any global functions	
		    this.globalLoadFunctions();
		    // load any page-specific files and callbacks
		    this.loadPlugins();
		    // load any page-specific (non-plugin) functions
		    this.pageLoadFunctions();			
		},
		
        /***************************** Dynamic Loaders *****************************/
        
        // global on-ready functions
        globalLoadFunctions: function(){   
            try {
                for (var i = 0; i < globalfunctions.length; i++) {
                    this[globalfunctions[i]]();
                }
            } 
            catch (ex) {
            }
        },
        
        // the plugin loader, callbacks below
        loadPlugins: function(){ 
			// rename the object
			var that = this;  
            // disable for ie lte6
            //if (ie6) 
                //return;
            var filecount, filetype, filepath, callback, i, j;
            
            // first the classes
            for (j = 0; j < pageClasses.length; j++) { 
                try {
                    // load the file(s)
                    filecount = plugin_data.pageClasses[j].filestoget.length; 
                    //callback = (plugin_data[pageClasses[j]]['callback'] == null)?  plugin_data[pageClasses[j]]['callback'] : false;
                    callback = plugin_data.pageClasses[j].callback;
                    for (i = 0; i < filecount; i++) {
                        // check filetype
                        filepath = plugin_data[pageId].filestoget[i];
                        filetype = filepath.substr(filepath.lastIndexOf('.') + 1);
                        if (filetype === 'css') {
                            // first, has it already been loaded?
                            //if (hasBeenLoaded(filepath)) 
                            if ($('link[href="'+filepath+'"]').length > 0)
                                continue;
                            // load the css file
                            $('head').append('<link rel="stylesheet" type="text/css" href="' + filepath + '" />');
                        }
                        else {
                            // load the script file, run callback on last one only
                            if (i === filecount - 1) {
                                $.getScript(filepath, function(){
                                    if (callback) that[callback]();
                                });
                            }
                            else {
                                $.getScript(filepath);
                            }
                        }
                        filelist.push(filepath);
                    }
                } 
                catch (e1) {
                    // in case it's not used
                }
            }
       
            // now do the id
           try { 
                // load the file(s)
                filecount = plugin_data[pageId].filestoget.length;	
                callback = plugin_data[pageId].callback; 
                for (i = 0; i < filecount; i++) { 
                    // check filetype
                    filepath = plugin_data[pageId].filestoget[i];
                    filetype = filepath.substr(filepath.lastIndexOf('.') + 1);
                    if (filetype === 'css') { 
                        // first, has it already been loaded?
                        if (hasBeenLoaded(filepath)) 
                            continue;
                        // load the css file
                        $('head').append('<link rel="stylesheet" type="text/css" href="' + filepath + '" />');
                    } else {
                        // load the script file, run callback on last one only
                        if (i === filecount - 1) {
                            $.getScript(filepath, function(){
                                if (callback) that[callback]();
                            });
                        }
                        else {
                            $.getScript(filepath);
                        }
                    }
                    filelist.push(filepath);
                }
            }  catch (e2) {
                // in case it's not used
            }
        },
        
        // specific page-function loader, methods below        
        pageLoadFunctions: function(){
            var f, i;
            if (pagefunctions[pageId]) {
                try {
                    f = pagefunctions[pageId];
                    if (f.length > 1) {
                        for (i = 0; i < f.length; i++) {
                            this[f[i]]();
                        }
                    }
                    else {
                        this[f]();
                    }
                } 
                catch (e3) {
                }
            } else {             	
                var count = pageClasses ? pageClasses.length : 0;
                for (i = 0; i < count; i++) {
                    try {
                        var className = pageClasses[i];
                        f = pagefunctions[className];
                        if (f.length > 1) {
                            for (var j = 0; j < f.length; j++) {
                                this[f[j]]();
                            }
                        }
                        else {
                            this[f]();
                        }
                    } 
                    catch (e4) {
                    }
                }
            }
        },
        
        /***************************** Global Helpers *****************************/
        
        // put the page id and page classes into "globals" for access whenever needed
        getPageIdentities: function(){
            pageId = $(document.body).attr('id');
            var pageClass = $(document.body).attr('class');
            pageClasses = pageClass.split(' ');
        },

		// input placeholders, add as global
		placeholder: function() {
			$(':text').each(function(){
				// quit if there's support for html5 placeholder
				if ($this[0] && 'placeholder' in document.createElement('input')) return;	
				
				// set the attribute in the data() cache
				$(this).data('placeholder', $(this).attr('placeholder'));
				
			}).live('focusin', function(){
				if ($(this).val() === $(this).data('placeholder')) {
					$(this).val('');
				}
			}).live('focusout', function(){
				if ($(this).val() === '') {
					$(this).val($(this).data('placeholder'));
				}
			});
		},
		        
        /***************************** Plugin Callbacks *****************************/
        
        // when you don't need one
        dummy: function(){
            // do nothing
        },
               
        /***************************** Global Functions, all pages *****************************/
        
        // open external (like pdfs) links in new window
        externallinks: function(){  
			var href, win;
        	$('a[rel="video"]').live('click', function(){
				href = $(this).attr('href');
				win = window.open(href, '', 'width=575,height=475,scrollbars,resizable');
				return false;
			});
        	$('a[rel="external"]').live('click', function(){ 
				href = $(this).attr('href');
				win = window.open(href, '', 'resizable,scrollbars');
				return false;
			});
			$('a[rel="pdf"]').live('click', function(){ 
				href = $(this).attr('href');
				win = window.open(href, '', 'resizable,scrollbars');
				return false;
			});
			$('a[rel="presentation"]').live('click', function(){
				href = $(this).attr('href');
				win = window.open(href, '', 'width=840,height=675,scrollbars,resizable');
				return false;
			});
			$('a[rel="newwin"]').live('click', function(){ 
				href = $(this).attr('href');
				win = window.open(href, '', 'toolbar,menubar,status,resizable,scrollbars');
				return false;
			});
			// a video popup
			$('a[rel="popup"]').live('click', function(){
				href = $(this).attr('href');
				win = window.open(href, '', 'width=840,height=675,scrollbars,resizable');
				return false;
			});
		},
        
		/***************************** On-ready Functions, specific pages *****************************/
		
		// client-side validation for forms, requires jquery.validate.js to be loaded, either dynamically or regular
		validateForm: function() { 
			
			// get the token for the secure form
			$.get(AJAX_URL+'token.php', function(txt) {
				$('form.secure').append('<input type="hidden" name="ts" id="ts" value="'+txt+'" />');
			});
			
			$('form').each(function(){ 
				formId = $(this).attr('id');
				$('#' + formId).validate({
					//debug:	true,
					errorContainer:			'#formerrors', // the div
					errorLabelContainer: 	'#formerrors ul', // the ul				
					errorElement:			'li', // the error
					highlight: 				function(element, errorClass) {
											     $(element.form).find("label[for=" + element.id + "]").addClass(errorClass);
											  },
					unhighlight:			function(element, errorClass) {
											     $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);
											  },
											
					invalidHandler:			function(){
												var bodyheight = $('body').height();
												$('#formerrors').css('display', 'block');
												$('#formerrors').animate({
													top:	bodyheight/2
												}, 1000);	
											},
					rules: 					pagerules[formId],
					messages:				pagemessages[formId]
				});
			});
			// bind the close event
			$('#formerrors a.close').click(function(){ 
				$('#formerrors').fadeOut(function(){$('#formerrors').css({'top': '-350px', 'display': 'none'});});
				return false;
			});
		},
		
		// changing content for "Did you know"
		rotateKnow: function() {
			setInterval(function(){
				var i = Math.round(Math.random()*(didyouknow.length - 1));
				$('#know_rotate').fadeOut('slow', function(){
					$(this).html(didyouknow[i]);
					$(this).fadeIn('slow');
				})
			}, 15000);	
		},
		
		// the slideshow
		doSlideshow: function() { 
			// preload the imgs
			for (var i=0; i<slides.length; i++) {
				slides[i].img = preloadImages(slideshowimgpath + slides[i].imgsrc);
			}
			
			// bind the click events for the numbered items, this could be dynamic
			$('#ss_nav a.definite').each(function(){
				$(this).click(function(){
					var j = parseInt($(this).html()) - 1;
					if (currentslide === j) return;
					changeSlide(j);
					currentslide = j;
					return false;
				});
			});
			$('#ss_nav a.backnav').click(function(){
				currentslide = (currentslide > 0) ? currentslide-1 : 3;
				changeSlide(currentslide);
				return false;
			});
			$('#ss_nav a.nextnav').click(function(){
				currentslide = (currentslide < 3) ? currentslide+1 : 0;
				changeSlide(currentslide);
				return false;
			});
			
			// start the cycle 
			cycleSlideShow();
			
		}
		
};	
}();

jQuery('a[rel="popup"]').click(function(){ 
	var href = jQuery(this).attr('href');
	
	window.open(href, '', 'width=840,height=810,scrollbars,resizable');
	return false;
});
$('a[rel="external"]').click(function(){
	var href = jQuery(this).attr('href');
	window.open(href, '', 'scrollbars,resizable,menubar,toolbar,status');
	return false;
});    
	

