// JavaScript Document
/*
*****************************************************************************************
*	All content, including (but not exclusive to) photos, videos, graphics, style, and	*
*	code are owned and copyrighted to Nineteen05. The use of these copyrighted 			*
*	materials is on a licensed basis and use will be revoked upon completion and		*
*	non-renewal of the license by the client.											*
*						© "nineteen 05" 2007. All rights reserved. 						*
*****************************************************************************************
*									Change Log											*
*	Authors: Paul D Prins																*
*	2008-04-26	PDP - Initial Implimentation of the LM									*
*	2008-07-20	PDP	- Added Block management											*
*	2009-12-19	PDP	- Updated to dynamically load additional js files here				*
*	2010-01-01	PDP	- Changed the date selector from CalendarPopup to jQuery.DatePicker	*
*	2010-01-02	PDP	- Added validatePassword() for use when setting passwords			*
*	2010-08-15	PDP	- Added Image fading and tool tips									*
*	2010-10-02	PDP	- Integrated the quick profile launching system						*
*	2010-11-09	PDP	- Added text expanding functionality								* 
*****************************************************************************************

Purpose:
lm - Load Manager handles all the on-load events for the nineteen05 software to make sure that multiple onloads are accomidated.
*/

// Function builds out the correct file path
// function getPath(){
// 	if( path != '' )
// 		return path;
// 
// 	tmpPath = $("[language=javascript][src*='lm.js']").attr('src');
// 	path = tmpPath.replace('/includes/js/lm.js', '') + '/';
// }

// Set the Global Variabls
var olms = new Array();
var ulms = new Array();
var jsnames = new Array();
var path = '';
//getPath();


/* the onLoad Manager */

	function olmOn() {
		window.onload = olmGo;
	}

	function olmGo() {
		for(var i = 0;i < olms.length;i++)
			eval(olms[i]);
	}

	function olmAdd(func) {
		olms[olms.length] = func;
	}

/* The unLoad Manager */

	function ulmUn() {
		window.unload = ulmGo;
	}

	function ulmGo() {
		for(var i = 0;i < ulms.length;i++)
			eval(ulms[i]);
	}

	function ulmAdd(func) {
		ulms[ulms.length] = func;
	}

/* Run the scripts */
	olmOn();
	ulmUn();


// Function converts an array to a literal string for use with 'in' function
	function oc( a ){
	  var o = {};

	  for( var i=0; i<a.length; i++){
	    o[a[i]]='';
	  }

	  return o;
	}


// Script to validate passwords during the setting process	
	function validatePassword( field1, field2, status ){
		// Set short password length status
		if( $('#'+field1).val() != '' && $('#'+field1).val().length < 6 ){
			$('#'+status).html('Password Must Be 6 Characters').show('fast');
			$('#'+field1).closest('form').contents().find(':submit').attr('disabled', true);
			return;
		}

		// Set non-matching password status
		if( $('#'+field2).val() != '' && $('#'+field1).val() != $('#'+field2).val() ){
			$('#'+status).html('Passwords must Match').show('fast');
			$('#'+field1).closest('form').contents().find(':submit').attr('disabled', true);
			return;
		}

		if( $('#'+field1).val().length >= 6 && $('#'+field1).val() == $('#'+field2).val() ){
			$('#'+field1).closest('form').contents().find(':submit').removeAttr('disabled'); }

		// Clear Status if we make it here
		$('#'+status).hide('normal').val('');
	}



	// 
	//	Functions that will display and hid the loader message
	function showLoader(Message) {
		$('#OverlayMessage').html(Message);
		$('#Overlay').fadeIn( 200 );
		$(document).bind('keyup', function(e) {
			if (e.keyCode == 27) { hideLoader(); }   // esc
		});
	}

	function hideLoader() {
		$(document).unbind('keyup');
		$('#Overlay').fadeOut( 400, function(){
			$('#OverlayContent').html(' ');		// Clear the content
			$('#OverlayHolder').hide();
			$('#OverlayLoader').show();
			$('#OverlayMessage').html('Default Message');
		} );
	}
	
	$(function(){
		$('#Overlay .OverlayCloser, #Overlay .OverlayBG').click(function(){
			hideLoader();
		});
	});
	//	Functions that will display and hid the loader message
	//


	// Variables for use in the quick profile system
	var _timer = 0,
		QPtype = null,
		QPid = null,
		QPref = null;


	//
	// Navigation Scriptings
	$('#Persistant').ready(function() {
		(function() {
			if($('#Persistant').css('position') == 'static')	// Hack to make it work in IE8
				return;

			//settings
			var fadeOutSpeed = 900, fadeInSpeed = 250, fadeTo = 0.3, topDistance = 2;
			var topbarME = function() { $('#Persistant').fadeTo(fadeInSpeed,1); }, topbarML = function() { $('#Persistant').fadeTo(fadeOutSpeed,fadeTo); };
			var inside = false;
			//do
			$(window).scroll(function() {
				position = $(window).scrollTop();
				if(position > topDistance && !inside) {
					//add events
					topbarML();
					$('#Persistant').bind('mouseenter',topbarME);
					$('#Persistant').bind('mouseleave',topbarML);
					inside = true;
				}
				else if(position < topDistance) {
					topbarME();
					$('#Persistant').unbind('mouseenter',topbarME);
					$('#Persistant').unbind('mouseleave',topbarML);
					inside = false;
				}
			});
		})();

		// Section Replacement
		$('.FunIconogrpahy.Section').hover(function() {
			$('#FunctionTitles').attr('class', $(this).children('div').attr('class'));
		}, function() {
			$('#FunctionTitles').attr('class', CurrentSection);
		});

		// Load the section navigation
		$('.FunIconogrpahy.Section').click(function() {
			CurrentSection = $(this).children('div').attr('class');
			$('.FunIconogrpahy.current').removeClass('current');
			$(this).addClass('current');

			if(!$(this).hasClass('IconLogout')) {
				$('#SectionNavigation').children('div').hide();
				$('#SectionNavigation').children('.Nav' + CurrentSection).show();
				$('html, body').animate({scrollTop:0}, 450);
			}
		});


		//
		// For the Quick Search in the Persistant Bar
		$('#TopAutoQS').tagdragon({
				'field':'TopQuickSearch',
				'url':'xml.members.php',
				'charMin':'2',
				postData:{'json':'true', 
							'search':'true',
							'AJAXinfo':'Address'},
				onSelectItem: function( obj ) {
					if ( obj.id === 'search' ){
					 	$('#TopQuickSearch').val('Search: '+ $('#TopQSAction').val() );
					}else{
					 	$('#TopQuickSearch').val('Loading: ' + obj.name );
						$('#TopQSID').val( obj.id );
					}

					submitTQS();
				} 
		});


		//
		// Handle the mouse over events
		$('#TopQuickSearch').hover(function(){
				if( $('#TopQuickSearch').attr('value') === 'Member Search' )
					$('#TopQuickSearch').val('');
			}, function(){
				if( $('#TopQuickSearch').val() === '' && !$("#TopQuickSearch").hasClass('focus') )
					$('#TopQuickSearch').val('Member Search');
		});

		$('#TopQuickSearch').focusin(function(){
			$('#TopQuickSearch').addClass('focus');	
			if( $('#TopQuickSearch').val() === 'Member Search' )
				$('#TopQuickSearch').val('');
		});

		$('#TopQuickSearch').focusout(function(){
			$('#TopQuickSearch').removeClass('focus');
			if( $('#TopQuickSearch').val() === '' )
				$('#TopQuickSearch').val('Member Search');
		});
		// Handle the mouse over events
		//

		$('#TopQuickSearch').keyup(function(){
			// Place the name being entered into the button value
			$('#TopQSAction').val($('#TopQuickSearch').val());
		});
		// For the Quick Search in the Persistant Bar
		//

		//
		// Notices
		$('.UserNotices').click(function(){
			if( $('.NoticeDropdown').css('display') === 'none' ){
				// Enable the notices
				$('.NoticeDropdown').slideDown();

				// Mark the notices as read
				if( $(this).children('.IconNotice').hasClass('BigRed') ){
					$.get("xml.system.php", { Notify: "1", seen: "1" },
						function(data){
							if( data === '1' ){
								// $('.NoticeDropdown .unseen').removeClass('unseen');
								$('.IconNotice.BigRed').removeClass('BigRed');
							}
					});
				}
			}
			else{
				$('.NoticeDropdown').fadeOut();
			}

			// Setup the event to close the notice window
			$('.NoticeDropdown').mouseenter(function(){
				$('.NoticeDropdown').mouseleave(function(){
					$('.NoticeDropdown').fadeOut();
				});
			});
		});

		$('.UserNotices').mouseup(function(e){	e.stopPropagation();	});	// Allow clicking on the notice menu
		$('body').mouseup(function(){ $('.NoticeDropdown').fadeOut(); });	// Hide notices when clicked elsewhere
		// Notices
		//

	});

	function submitTQS(){
		// Check if member was selected from drop down
		if ($('#TopQSID').val() === "search"){
			location.href = 'members_search.php?action=results&query=' + $('#TopQSAction').val();
			return false;
		}else if ($('#TopQSID').val() !== "0") {
			location.href = 'members_roster.php?action=overview&ID=' + $('#TopQSID').val();
			return false;
		}

		return false;
	};
	// Navigation Scriptings
	//


//
//
// Block hiding and reveiling for usability, requires the use of jquery
 $(function(){
	//
	// Make sure that the drop downs work on iOS devices	(Does not interfere with normal suckerfish menu opperation)
	$('#SectionNavigation li').click(function(){
		$('#SectionNavigation li').removeClass('hover');
		$(this).addClass('hover');
	});
	
	$('#SectionNavigation li').mouseleave(function(){ $(this).removeClass('hover'); });
	// Make sure that the drop downs work on iOS devices
	//



	// Set all the tabs to their page load settings
	$(".settingHidden").children("#inner").hide();	// Close all tabs not open by default

	// Sets the value for input images to use in the post
	$(":image").click(function() {
		// $(this).closest('form').children("input[name='ButtonValue']").val($(this).val());
		$("input[name='ButtonValue']").val($(this).val());	// Change every ButtonValue input item
	});


	//
	//
	// Handle item removal
	$(document).delegate('.RemoveItem[itemid][itemtype]', 'click', function(){
		showLoader('Loading the Remove Dialog');
		itemID = $(this).attr('itemid');
		itemType = $(this).attr('itemtype');
		$('#OverlayContent').load("ajax/remove_item.php",
			{'id':itemID,  'type':itemType},
			function(){
				$('#OverlayHolder').fadeIn();
				$('#OverlayLoader').fadeOut();
		});
	});
	// Handle item removal
	//
	//


	//
	// Start Checkbox selection functions

		/*	How to utilize these checkbox selection features
		*	<a rel="containing_elm_Class" href="#select_all">Select All</a>
		*	<a rel="containing_elm_Class" href="#select_none">Select None</a>
		*	<a rel="containing_elm_Class" href="#invert_selection">Invert Selection</a>
		*/

    // Select all
    $("A[href='#select_all']").click( function() {
		$("input." + $(this).attr('rel') + ":checkbox:not(:checked)").click();
		return false;
    });

    // Select none
    $("A[href='#select_none']").click( function() {
		$("input." + $(this).attr('rel') + ":checked").click();
        return false;
    });

    // Invert selection
    $("A[href='#invert_selection']").click( function() {
		$("input." + $(this).attr('rel') + ":checkbox").click();
        return false;
    });

	// Start Checkbox selection functions
	//



	//
	// Functions to show and hide long bodies of text
	$('.expandable .expand').click( function(){
		$(this).hide();
		$(this).parent('.expandable').children('.extra').slideDown();
	});

	$('.expandable .contract').click(function(){
		$(this).parent('.extra').slideUp('fast',function(){
			$(this).removeAttr('style');
			$(this).parents('.expandable').children('.expand').show('fast',function(){
				$(this).removeAttr('style');
			});
		});
	});
	// Functions to show and hide long bodies of text
	//

	//
	// Create the select and multi-select drop downs
	$(".makeButtonSet").buttonset();
	$("select[multiple]:not(.skip)").multiselect({
		height: 'auto',
		multiple: true,
		show: ['blind', 200],
		hide: ['blind', 75],
		// header: "Select an option",
		minWidth: 100,
		noneSelectedText: "Select an Option",
		selectedList: 0,
		close: function(event, ui){
			if( !$(this).attr('displayin') )
				return;
	
		    var values = [];
			$(this).children().filter(':selected').each(function(index, domElm) {
				values[index] = $(domElm).text();
			});
	
			$('#' + $(this).attr('displayin')).text(values.join(', '));
		}
	});
	
	
	$("select:not([multiple], .skip)").multiselect({
		header: false,
		height: 'auto',
		show: ['blind', 200],
		hide: ['blind', 75],
		minWidth: 'auto',
		multiple: false,
		noneSelectedText: " &nbsp;",
		selectedList: 1
	});

	$("form").submit(function(){
		$('form [name^="multiselect_"]').removeAttr('name');
		return true;
		// multiselect_
	});
	// Create the select and multi-select drop downs
	//



	//
	// Function will manage the list setting tabs and displays
	$('.listSettings').not('.listNarrow').addClass('ui-state-default');
	$('.listSettings.listDown').addClass('ui-state-active');
	$('.listSettings h3').click(function(){
		if( $(this).parent('.listSettings').hasClass('listExpand') ){
			// Colapse the Menu down
			$(this).parent('.listSettings').removeClass('listExpand').children('.setting-contents:not(.Hidden)').slideUp( 50, function(){
				$(this).parent('.listSettings').animate( { width: "180" }, 100 );
			});
		}
		else{
			$('.listSettings.listExpand h3').click();	// Colapse any expanded menus

			$(this).parent('.listSettings.listNarrow').addClass('listExpand').children('.setting-contents:not(.Hidden)').slideDown( 200 );
			$(this).parent('.listSettings').not('.listNarrow').addClass('listExpand').animate( { width:"748" }, 125, function(){
				$(this).children('.setting-contents:not(.Hidden)').slideDown( 200 );
			});
		}
	});
		// <div class="listSettings (fromRight) ui-state-active">
		// 	<h3>...</h3>
		// 	<div class="setting-contents">
		// 		<div class="content-item">
		// 			<span class="content-title">...</span>
		// 			...
		// 		</div>
		// 		<div class="content-submit">
		// 			<input type="submit" />
		// 		</div>
		// 	</div>
		// </div>
	// Function will manage the list setting tabs and displays
	//

	
	// Testing to hide the blocks
	$("H4").click(function(event) {
		if( $(this).siblings("#inner").is(":hidden") ) {
			$(this).siblings("#inner").slideDown("slow");
	
			if($(this).parent().hasClass("settingHidden")) {
				$(this).parent().removeClass("settingHidden");
			}
	
			if(!($(this).parent().hasClass("settingShow")) ) {
				$(this).parent().addClass("settingShow");
			}
	
		} else {
			$(this).siblings("#inner").slideUp("slow");
	
			if(!($(this).parent().hasClass("settingHidden")) ) {
				$(this).parent().addClass("settingHidden");
			}
	
			if($(this).parent().hasClass("settingShow")) {
				$(this).parent().removeClass("settingShow");
			}
		}
	}).end();


	//
	// Add email tool tips
	$('.Email-Black').attr('title','Member Opt-out');
	$('.Email-4').attr('title','Temporary Failure');
	$('.Email-5').attr('title','Not Working');
	$('.Email-Unsubscribe').attr('title','Unsubscribed');
	// Done adding email tool tips
	//


	//
	// Display the tool tips for images and inputs
	$('.textRight [title]:not(.TopMenus *, .ui-multiselect *, .ui-multiselect-menu *, #SectionNavigation *, .ui-widget)').qtip({
		content: { text: true },
		show: { solo: true },
		position: {
			at: "bottom right",
			my: "top right"	},
		style: {
			tip: true,
			classes: "ui-tooltip-light"
		}
	});

	$('[title]:not(.TopMenus *, .ui-multiselect *, .ui-multiselect-menu *, #SectionNavigation *, .textRight, .ui-widget)').qtip({
		content: { text: true },
		show: { solo: true },
		position: {
			at: "bottom center",
			my: "top center" },
		style: {
			tip: true,
			classes: "ui-tooltip-light"
		}
	});
	//  Done Displaying the tool tips
	//

	
	//
	// Dynamically load the member profiles
	$("[rel].MemberQP, [rel].GroupQP").live("mouseover mouseout", function(e){
		if(e.type == 'mouseover') {
			//
			// Set the variables for the quick profile
			QPref = $(this);
			QPid = $(this).attr('rel');
			if( $(this).hasClass('MemberQP')){
				QPtype = 'member';
			}
			else if( $(this).hasClass('GroupQP') ){
				QPtype = 'group';
			}
			// Set the variables for the quick profile
			//
	
			_timer=setTimeout( "QuickProfile()",1700);
		}
		else{
			clearTimeout( _timer );
		}
	});
	// Dynamically load the member profiles
	//
});
	
	
	
	
	function QuickProfile(){
		// Check if the pop-up already exists
		if( $(QPref).attr('tipped') == 'true' ){
			$(QPref).qtip("show");
			return true;
		}
	
		// Check if the profile should still be displayed or not
		if( $(QPref).attr('rel') == undefined )
			return false;
	
		$(QPref).attr('tipped', true );	// Set the catch
		$(QPref).qtip({
			content: '<div id="QProfile-' + QPtype + '-' + QPid + '" class="aQtip"><p class="textCenter"><img class="throbber" src="images/loading.gif" alt="Loading..." /><br />Loading the Profile</p></div>',
			position: {
				my: "bottom center",
				at: "top center"
			},
			show: {
				solo: true,
				event: "blur"
			},
			hide: {
				event: "unfocus"
			},
			style: {
				classes: "ui-tooltip-light ui-tooltip-shadow",
				tip: true,
				width: "376px"
			},
			events: {
				render: function (event, api) { $.post("ajax/quick_profile.php", {id: QPid, type: QPtype, quick: true}, function (data) {
						$("#QProfile-" + QPtype + "-" + QPid).html(data);
						$(QPref).qtip('reposition');
					}, "HTML"); }
			}
		});
		$(QPref).trigger("blur");
	};

	// Function will get the variables from the window location and return them in an object.
	function getUrlVars(){
		var vars = [], hash;
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
		for(var i = 0; i < hashes.length; i++){
			hash = hashes[i].split('=');
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}
	
		return vars;
	}



	// Function will set the default settings for the Validator plugin
	jQuery.validator.setDefaults({
		errorElement: "div"
	});

	// Function will get the values of an object into an array
	jQuery.fn.getObjectVal = function( attribute ){
		attribute = attribute || 'value';
	    var vals = []; 
	    var i = 0; 
	    this.each(function(){ 
	        vals[i++] = jQuery(this).attr( attribute ); 
	    }); 
	    return vals; 
	}

	<!--
		function Select( pageID, variable ){
			window.location.href = window.location.pathname + "?" + variable + "=" + pageID ;
		}
	-->
