// JavaScript Document, requires jQuery to be loaded first

//google.load("jquery", "1.4.1");
//google.setOnLoadCallback(function() {
	//jQuery.noConflict();
	$(document).ready(function() {
		DHA.init();
	});
//});
var DHA = 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 = site_url; // site_url written in header.php
	var THEME_URL = SITE_URL + '/wp-content/themes/deltahealth/';
	var AJAX_URL = THEME_URL + 'ajaxfunctions/';

    /***************************** Private Properties *****************************/
    
    var pageId;
    var pageClasses; // array
    // list of dynamically loaded files for loadPlugins
    var filelist = [];
	
	// title attr content
	var titledata;
	
	// timer & timeout names
	var slidetimer;
	var mmTimeout;
	
	// staff div heights
	var divHeights = [];
	
	// form validation data for use with jquery.validate plugin
 	var pagerules = {
		contactForm : {
			recipient :		{required: true},
			name :			{required: true},
			email :			{required: true, email: true},
			subject :		{required: true},
			message :		{required: true},
			ts :			{required : true,
								remote: {
									type :	'post',
									url :	AJAX_URL+'token.php',
									data :	{
										hash : function() {
											return Cookie.read('token');
										}
									}
								}
							} 	
		}
	};
	var pagemessages = {
		contactForm : {
			recipient : 	'Please choose a recipient for your email',
			name :			'Your name is required',
			email :			'Your email address is required',
			subject :		'The subject of your email is required',
			message :		'A message is required',
			ts :			'Please enable cookies on your browser, reload the page and try again'
		}
	}; 
	
    /***************************** 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
     }
     };
     
	var plugin_data = {
		contact: {
			filestoget:	 	[THEME_URL+'js/jquery.validate.min.js', THEME_URL+'js/additional-methods.js'],
			callback:		['validateForm']	
		}	
	};*/
	
	// Global functions: array of functions to fire onready for every page
    var globalfunctions = ['fixNavParents', 'doCalendar', 'ie6_megamenu', 'ie6_fixImgs', 'resizeChildImgs', 'linkBehavior', 'placeholder', 'megaMenu']; // , 'megamenu_functions'
    
    // Page functions, based on page id (default) and page class
    // NOTE: to prevent js error, wrap id's with "-" in quotes
    var pagefunctions = {
		// pageid	: ['function1', 'function2']
		home		: ['bindPsaVids', 'slideshow'],
		contact		: ['validateForm'],
		feedback	: ['validateForm'],
		"dha-staff"	: ['staffTabs']
    };
    
    /********************************* 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);
    }
    
    // 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 *****************************/
    
	function loopSlideshow(show) { 
		// start by fading out #1
		
		var currentclass = 'show-' + show;
		var next;
		if (show === 3) {
			next = 1;
		} else {
			next = show + 1;
		}
		var nextclass = 'show-' + next;

		$('img.'+currentclass).fadeOut('slow', function(){
			$(this).removeClass('activeslide');
			$('#slideshow img.'+nextclass).addClass('activeslide');
			$('#slideshowlinks a.activeslide').removeClass('activeslide');			
			$('#slideshow img.'+nextclass).fadeIn('slow', function(){
				$(this).addClass('activeslide');
				$('#slideshowlinks a.'+nextclass).addClass('activeslide');
			});
		});
		slideTimer = setTimeout(function(){
			loopSlideshow(next);
		}, 5000);
		
	}
	
	function resetMegaMenu(el) {
		if ($(el).parent('li').children('ul.megamenu').is(':hidden')) {
			$(el).parent('li').children('ul.megamenu').css({left: 0});
			clearTimeout(mmTimeout);
		} else {
			// recurse as necessary
			mmTimeout = setTimeout(function(mega){ resetMegaMenu(el); }, 500);
		}
	}
	
	/*******************************************************************************************
    	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() { 
				$('input: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'));
					
					// and add it to the input
					$(this).val($(this).data('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
        },
        
		// js validator for forms
		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+'" />');
			});
			
			$('#maincontent 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 + "] span").addClass(errorClass);
											  },
					unhighlight:			function(element, errorClass) {
											     $(element.form).find("label[for=" + element.id + "] span").removeClass(errorClass);
											  },
											
					invalidHandler:			function(){
												var bodyheight = $('body').height();
												$('#formerrors').css('display', 'block');
												$('#formerrors').animate({
													top:	bodyheight/2-200
												}, 1000);	
											},
					submitHandler:			function(form){
												var mid;
												switch(formId) {
													case 'contactForm':
														mid = '#success-message';
													break;
												}
												var bodyheight = $('body').height();
												
												var ajaxoptions = {
													url: 		AJAX_URL + 'ajaxmail.php',
													type:		'POST',
													success:	function(statusText) {
																	if (statusText === 'ok') {
																		$(mid).css('display', 'block');
																		$(mid).animate({
																			top:	bodyheight/2-200
																		}, 1000);	
																	}	
																},
													resetForm:		true
												};
												$(form).ajaxSubmit(ajaxoptions);
												
												$(mid + ' a.close').click(function(){ 
													$(mid).fadeOut(function(){$(mid).css({'top': '-350px', 'display': 'none'});});
													return false;
												});												
											},
					rules: 					pagerules[formId],
					messages:				pagemessages[formId]
				});
			});

			$('#success-message').css('display', 'block');
															
			// bind the close event
			$('#formerrors a.close').click(function(){ 
				$('#formerrors').fadeOut(function(){$('#formerrors').css({'top': '-350px', 'display': 'none'});});
				return false;
			});
		},
		         
		/***************************** Global Functions, called on all pages *****************************/
		
		// adds class to top level nav item to highlight for child pages
		fixNavParents: function() {
			$('#mainnav li.current_page_item').parents('li').addClass('current_page_item');
			$('#mainnav li.current_page_item').parents('li').parents('li').addClass('current_page_item');
			
		},
		
		doCalendar: function() {
			if ($('#sb-calendar').length == 0) return;
			// the "tooltip"
			$('#outerwrap').append('<p id="eventinfo"></p>');
			/* $('#sb-calendar tbody a').each(function(){
				$(this).mouseover(function(){ 
					// get the position
					var pos = $(this).position();
					titledata = $(this).attr('title'); // "global" variable
					$(this).removeAttr('title');
					$('#eventinfo').css({
						left:			(pos.left + 10) + 'px',
						top:			(pos.top + 10) + 'px'
					}).html(titledata).fadeIn('fast');
				});
				$(this).mouseout(function(){
					//$('#eventinfo').css('display', 'none');
					$('#eventinfo').html('').fadeOut('fast');
					$(this).attr('title', titledata);
				});
			}); */
			$('#sb-calendar tbody a').live('mouseover', function(){
				// get the position
				var pos = $(this).position();
				titledata = $(this).attr('title'); // "global" variable
				$(this).removeAttr('title');
				var data_arr = titledata.split(',');
				var datastring = '';
				for (var i=0; i<data_arr.length; i++) {
					datastring += '<p>' + data_arr[i] + '</p>';
				}
				$('#eventinfo').css({
					left:			(pos.left + 10) + 'px',
					top:			(pos.top + 18) + 'px'
				}).html(datastring).fadeIn('fast');
			});
			$('#sb-calendar tbody a').live('mouseout', function(){
				$('#eventinfo').html('').fadeOut('fast');
				$(this).attr('title', titledata);
			});
			
			$('#sb-calendar a.changemonth').live('click', function(){
				var datedata = $(this).attr('rel');
				$.ajax({
					data:		datedata,
					url:		AJAX_URL + 'calendar.php',
					dataType:	'html',
					success:	function(data) {
									$('#sb-calendar div').html(data);
								}	
				});	
				return false;
			});	
		},
		
		// reposition the megamenu if necessary		
		megaMenu: function() {
			var leftM, offA, offC, that;
			// get the position of #container			
			offC = $('#container').offset();
			$('li.top > a').mouseover(function(){
				that = this;
				// get the position of the anchor hovered on
				offA = $(this).offset(); 
				// check to see if this puts megamenu too far to right by default; reposition if necessary
				if (offA['left'] - offC['left'] > 940 - 625) { 
					leftM = 315 - Math.floor(offA['left'] - offC['left']);
					$(this).parents('li').children('ul.megamenu').animate({
						left: leftM
					}, 500, function(){
						// reset to "default" so animation happens again
						resetMegaMenu(that);
					});
				} 
			});
		},
		/* megamenu_functions: function() { 			
			var content;
			$('a.item').hover(function(){
				content = $(this).attr('title');
				var html = '<div class="item-content">' + content + '</div>';
				
				// get the item heading
				var li_position = $(this).parent('li').parent('ul').parent('li.heading').position();
				
				// and the item itself
				var item_position = $(this).parent('li').position();
				
				// add the div to the megamenu and position it
				$(this).parent('li').parent('ul').parent('li').parent('ul.megamenu').append(html);
				$('.item-content').css({
					top: li_position.top + item_position.top - 20 + 'px',
					left: li_position.left + item_position.left + 25 + 'px',
					//position: 'absolute',
					//zIndex: '500'
				});	
			}, function(){
				$('#mainnav .item-content').remove();	
			});
		}, */
		
		// hover for ie6
		ie6_megamenu: function() {
			if (!ie6) return;
			$('#mainnav li.top').hover(function(){
				$(this).children('ul').css({display: 'block'});
			}, function(){
				$(this).children('ul').css({display: 'none'});
			});		
		},
		
		// resize images in sidebar (specifically homepage #success_stories)
		ie6_fixImgs: function(){
			//if (!ie6) return;
			$('#success-stories img, .sb-block img').each(function(){
				var oldheight = $(this).height();
				var oldwidth = $(this).width();
				if (oldwidth > 186) {
					$(this).attr('width', '186');
					$(this).attr('height', parseInt((oldheight/oldwidth)*186));
				}					
			});
		},
		
		// "resize" images to fit in child-page sidebar
		resizeChildImgs: function() {
			$('#maincontent-sidebar .child-page img').each(function(){
				var oldwidth = $(this).width();
				var oldheight = $(this).height();
				var newheight = (oldheight/oldwidth) * 186;
				$(this).attr('width', '186').attr('height', newheight);
			});	
		},
		
		// reads anchor rel attribute to see whether link opens in new window
		linkBehavior: function() {
			$('a[rel]').each(function(){
				var rel = $(this).attr('rel');
				var href = $(this).attr('href');
				switch (rel) {
					case 'pdf':
						$(this).click(function(){
							window.open(href, '', 'scrollbars,resizable');
							return false;
						});
						break;	
				}
			});
		},
				
        /***************************** On-ready Functions, specific pages *****************************/
				
		// do the homepage slideshow
		slideshow: function() { 
			// scroll the slideshow after a sec
			setTimeout(function(){
				loopSlideshow(1);
			}, 5000);
			
						
			// bind the "links"
			$('#slideshowlinks a').click(function(){ 
				// stop the slideshow!
				clearTimeout(slidetimer);
				
				// stop if active clicked
				if ($(this).hasClass('activeslide')) return false;
									
				var imgclass = $(this).attr('class');
				var that = this;
				// fade out
				$('#slideshow img.activeslide').fadeOut('slow', function(){
					// remove the active class from links and imgs
					$(this).removeClass('activeslide');
					$('#slideshowlinks a.activeslide').removeClass('activeslide');
					// fade in the new one and add classes
					$('#slideshow img.'+imgclass).fadeIn('slow', function(){
						$(this).addClass('activeslide');
						$(that).addClass('activeslide');		
					});	
				});
				
				return false;	
			});
		},
		
		// put the psa vids in a gorillabox for the homepage
		bindPsaVids: function() { 
			$('#public-service .announcement a').each(function(){
				var vid_title = $(this).attr('title');
				var vid_id = $(this).attr('id');
				var vid_url = 'http://www.youtube.com/v/' + vid_id;
				var vid_img = 'http://img.youtube.com/vi/' + vid_id + '/0.jpg';
				var script = '<script type="text/javascript">';
				script += 'var flashvars = {file:"' +vid_url+ '",image:"' +vid_img+ '"};';
				script += 'var params = {allowfullscreen:"true", wmode:"opaque"};';
				script += 'var attributes = {id:"' + vid_id + '"};';				
				script += 'swfobject.embedSWF("'+THEME_URL+'/video/player-4.6-licensed.swf", "p-' + vid_id + '", "400", "300", "9", false, flashvars, params, false);';				
				script += '</script>';
				
				var html = '<div id="gb-video">'; 
				html += script;
				html += '<h3 style="color:#fff;">' + vid_title + '</h3>';
				html += '<p id="p-'+vid_id+'" class="flashvideo"></p>';
				html += '</div>';
				
				$(this).gorillabox({html:html, width:400});
				
				/* var title = '<h3 style="color:#fff;">' + vid_title + '</h3>';
				var embed = '<embed src="' + THEME_URL + '/video/player-viral.swf"';
				embed += 'width="400"';
				embed += 'height="300"';
				embed += 'allowscriptaccess="always"';
				embed += 'allowfullscreen="true"';	
				embed += 'id="player1"';
				embed += 'name="player1"';			
				embed += 'flashvars="file=http://www.youtube.com/v/' + vid_id + '&image=http://img.youtube.com/vi/' + vid_id + '/0.jpg" />';
				
				var html = '<div id="gb-video">' + title + embed + '</div>';
				
				$(this).gorillabox({html: html, width: 400}); */
				
			});			
		},
		
		// show the success message when contact email sent
		showSuccess: function() {
			var bodyheight = $('body').height();
			$('#success-message').css('display', 'block');
			$('#success-message').animate({
				top:	bodyheight/2-200
			}, 1000);
			$('#success-message a.close').click(function(){ 
				$('#success-message').fadeOut(function(){$('#formerrors').css({'top': '-350px', 'display': 'none'});});
				return false;
			});
	
		},

		
		// tabs for staff page
		staffTabs: function() { 
			// create a list from the h3 content
			var tabhtml = '<ul id="tabs">';
			$('.tabbed h3').each(function(){
				tabhtml += '<li><a href="#" rel="' + $(this).parent('div').attr('id') + '">' + $(this).html() + '</a></li>';
				$(this).remove();
			});
			tabhtml += '</ul>';
			$('.entry-content').prepend(tabhtml);
			
			// hide all the divs
			$('div.tabbed').css({display: 'none'});
			// get their ids for the divHeights array elements
			$('div.tabbed').each(function(){
				divHeights[$(this).attr('id')] = 0;
			});
			
			// show the first 
			$('#tabs').next('div.tabbed').css({display: 'block'});
			// give the first tab active class
			$('#tabs li:first-child a').addClass('active');
			
			// get the heights
			// the nav first
			var nav_height = $('#tabs').height();
			// the div height
			var div_height = $('#tabs').next('div.tabbed').height();
			// and its id
			var div_id = $('#tabs').next('div.tabbed').attr('id'); 
			// add the two and put it in the array
			divHeights[div_id] = nav_height + div_height;
			// set the intial height
			$('.entry-content').css({
				position:	'relative',
				height:		divHeights[div_id] + 'px'
			}); 
			// set the positioning of all the content divs
			$('div.tabbed').css({
				position:	'absolute',
				left:		0,
				top:		nav_height + 'px'
			}).addClass('currentDiv');
			// bind the events
			$('#tabs a').click(function(){
				if ($(this).hasClass('active')) return;
				// change bg colors, etc.
				$('#tabs a').removeClass('active');
				$(this).addClass('active');
				
				// hide all the divs and show the proper one
				var divid = $(this).attr('rel');
				// get its height if don't already have it
				if (divHeights[divid] == 0) {
					divHeights[divid] = $('#'+divid).height() + nav_height;
				}

				// animate the opacity of the current to 0
				$('div.currentDiv').animate({opacity: 0}, 300, 'linear', function(){
					// then hide it and remove its class
					$(this).css({display:'none'}).removeClass('currentDiv');
					// set the opacity of the desired div to 0 and show it and add class
					$('#'+divid).css({
						opacity:	0,
						display:	'block'
					}).addClass('currentDiv');

					
						
					// animate .entry-content to the height it needs
					$('.entry-content').animate({height: divHeights[divid]+'px'}, 100, 'linear', function(){
						// and animate the new content's opacity
					$('#'+divid).animate({opacity: 1}, 300);
						$('#maincontent').css({
							height:	(divHeights[divid] + nav_height + 12) + 'px'
						});
						
						
					});
						
				});
				
				
				/* $('div.tabbed').fadeOut('slow', function(){
					$('#'+divid).fadeIn('slow');
				}); */
				
				return false;
			});
		}
		
		
	};	
}();

