var windowW = screen.width;
var totalW = 0;
var picsW = 0;
var speed = 100;
var pic, numImgs, arrLeft, i, totalWidth, n, myInterval; 

prefixes = ['-moz-','-webkit-'];
$(document).ready(function() {
	$('.noscript').remove();
	$('.js_tool').show();
	can_haz_cols = getStyle('header','column-count');
	if(!can_haz_cols)
	{
		for(i=0; i< prefixes.length;i++)
		{
			can_haz_cols = getStyle('header',prefixes[i]+'column-count');
			if(can_haz_cols)
			{
				break;
			}
		}
	}

	$('#home #events li:gt(1):not(.more_link)').remove();
	$('#home #events').show();

	// email obfuscation
	str = jQuery('.nospam').text().replace(" at ", "@").replace(" dot ",".");
	jQuery('.nospam').text(str).wrap('<a href="mailto:'+str+'" title="send email to '+jQuery('.nospam').text()+'"></a>');
	

	//nav SECONDARY
	$('li li li.here ul, li li li.parent_here ul').slideDown('slow');
	var url = window.location.toString();
	if(url.indexOf('news_archive')>=0)
	{
		$(".nav_secondary a:contains('News Archive')").parent('li').addClass('here');
		$(".nav_secondary a:contains('News and Notification')").parent('li').addClass('here');
	}
	$('.nav_secondary li a').each(function()
	{
		var sibs = $(this).siblings('ul');
		if(sibs.length < 1)
		{
			$(this).addClass('no-accordion');
		}
	}).delay(200);
/*	$(".nav_secondary").accordion({
		header: 'li li li.here a:not(li li li li a, a.no_accordion), li li li.parent_here a:not(li li li li a, a.no_accordion)',
		collapsible: true,
		autoHeight: false,
		active: '.parent_here>.ui-accordion-header, .here>.ui-accordion-header'
	});*/
	//NAV Primary
	//changed to using a plugin, so we're not using the css3 column stuff... so it doesn't matter if it can haz columns
//	if(can_haz_cols)
//	{
			$('#nav_primary li ul').each(function()
			{
					var h = $(this).height();
					if(h > 164)
					{
						cols = Math.ceil(h/164);
						w = 221*cols + 10*(cols-1);
						$(this).css(
							{
								'width' : w+'px',
								'max-height': '164px'
							}
							).columnize({columns: cols, lastNeverTallest: true});
						$(this).children('li').addClass("dontsplit");
					}

			});
	//	}

	$('#nav li ul').hide();
	$('#nav li:not(li li)').hover(function()
	{
		$(this).children('ul').fadeIn('fast');
	},
	function()
	{
		$(this).children('ul').fadeOut('fast');
	});
	
	//CONTENT ACCORDION
	$('.accordion').accordion({
		header: 'h3',
		active: 'none', 
		collapsible: true,
		autoHeight: false,
		icons: { 'header': 'ui-icon-triangle-1-e', 'headerSelected': 'ui-icon-triangle-1-s' }
	});
	$('.ud_accordion h4').each(function(index, value)
	{
		$(this).attr("id","header_"+index).addClass('h3').contents().wrap("<a>");
		$('#header_'+index).nextUntil("h4").wrapAll("<div>");
	});
	$('.ud_accordion').accordion({
		header: 'h4',
		active: 'none', 
		collapsible: true,
		autoHeight: false,
		icons: { 'header': 'ui-icon-triangle-1-e', 'headerSelected': 'ui-icon-triangle-1-s' }
	});	
	
	//Print page
	$('a.print').live('click',function()
	{
		if (window.print)
		{
			window.print();
			return false;
		}
		else
		{
			alert("Sorry. Your browser does not support printing by this method. You need to choose Print from the File menu.")
			return false;
		}
	});
	
	//obfuscate and make a link for the nat'l office e-mail
	var sText = "nationaloffice";
	sText += "@";
	sText += "aephi";
	sText += ".org";
	var sHref = "ma";
	sHref += "il";
	sHref += "to";
	sHref += ":";
	sHref +=sText;
	$('#footer .email_container').html('<a class="email" href="'+sHref+'" >'+sText+'</a>');

		
		
	//add new fields to a form...
	$('.add_new').click(function()
	{
		var table = $.query.get('new');
        $('#'+table+' tbody>tr:last').clone(true).insertAfter('#'+table+' tbody>tr:last');
		$('#'+table+' tbody>tr:last input').val('');
		$('#'+table+' tbody>tr:last select').each(function() {this.selectedIndex = -1;});
		return false;
	});

	//update fields on other field change
	$('.position_holder').change(function()
	{
		midn = $(this).val();
		j = $(this).attr('id').substring( $(this).attr('id').lastIndexOf('_')+1 );
		$('#street_address_'+j).val(members[midn]['street_address']);
		$('#city_'+j).val(members[midn]['city']);
		$('#state_'+j).val(members[midn]['state']);
		$('#zip_code_'+j).val(members[midn]['zip_code']);
		$('#home_phone_'+j).val(members[midn]['home_phone']);
		$('#work_phone_'+j).val(members[midn]['work_phone']);
		$('#mobile_phone_'+j).val(members[midn]['mobile_phone']);
		$('#email_'+j).val(members[midn]['email']);
	});
	$('.member_info input').blur(function()
	{
		data = $(this).val();
		i = $(this).attr('id').substring( $(this).attr('id').lastIndexOf('_')+1 );
		field = $(this).attr('id').substring(0,$(this).attr('id').lastIndexOf('_') );
		midn = $('#midn_'+i).val()
				
		$('.position_holder').each(function()
		{
			if($(this).val() == midn)
			{
				j = $(this).attr('id').substring( $(this).attr('id').lastIndexOf('_')+1 );
				$('#'+field+'_'+j).val(data);
			}
		});
		
		members[midn][field] = data;
		
		
	});
	$('.member_info select').not('.position_holder').change(function()
	{
		data = $(this).val();
		i = $(this).attr('id').substring( $(this).attr('id').lastIndexOf('_')+1 );
		field = $(this).attr('id').substring(0,$(this).attr('id').lastIndexOf('_') );
		midn = $('#midn_'+i).val()

		$('.position_holder').each(function()
		{
			if($(this).val() == midn)
			{
				j = $(this).attr('id').substring( $(this).attr('id').lastIndexOf('_')+1 );
				$('#'+field+'_'+j).val(data);
			}
		});

		members[midn][field] = data;
		
	});
	
	//member roster... change status effective date based on selected status
			$('select.changer').change(function()
			{
				switch ($(this).val()) 
				{
					case 'Active':
						status_name =  'Activated';
						break;
					case 'Abroad':
						status_name =  'Date_Abroad';
						break;
					case 'New Member':
						status_name =  'Pledge';
						break;
					case 'Pledge':
						status_name =  'Pledge';
						break;
					case 'Transferred':
						status_name =  'Last_Transfer';
						break;
					case 'Withdrawn from School':
						status_name =  'Disaffiliated';
						break;
					case 'Deceased':
						status_name =  'Date_Deceased';
						break;
					default:
						status_name =  $(this).val();
						break;
				}
				index = $(this).attr('id').substring( $(this).attr('id').lastIndexOf('_')+1 );
				$('#status_effective_date_'+index).val(members_original_status_dates[index][status_name]);
			});
			$('.status_effective_date').blur(function()
			{
				data = $(this).val();
				index = $(this).attr('id').substring( $(this).attr('id').lastIndexOf('_')+1 );
				switch ($('#Status_'+index).val()) 
				{
					case 'Active':
						field =  'Activated';
						break;
					case 'Abroad':
						field =  'Date_Abroad';
						break;
					case 'New Member':
						field =  'Pledge';
						break;
					case 'Pledge':
						field =  'Pledge';
						break;
					case 'Transferred':
						field =  'Last_Transfer';
						break;
					case 'Withdrawn from School':
						field =  'Disaffiliated';
						break;
					case 'Deceased':
						field =  'Date_Deceased';
						break;
					default:
						field =  $('#Status_'+index).val();
						break;
				}
				
				members_original_status_dates[index][field] = data;
		
			});
	
	
	//show add'l fields on select change
	$('.exposer_rel, .exposer_val').change(function()
	{
		index = $(this).attr('id').substring( $(this).attr('id').lastIndexOf('_')+1 );
		if ($(this).hasClass('exposer_val')) 
		{
			var classes = $(this).attr('class').split(" ");
			for(i in classes)
			{
				if($(this).val() == classes[i])
				{
					if(!isNaN(index))
					{
						$('#'+$(this).val()+'_'+index).show();
					}
					else
					{
						$('#'+$(this).val()).show();
					}
				}
				else
				{
					if(!isNaN(index))
					{
						$('#'+classes[i]+'_'+index+' option:eq(0)').attr("selected", true);
						$('#'+classes[i]+'_'+index).val('').hide();
					}
					else
					{
						$('#'+classes[i]+' option:eq(0)').attr("selected", true);
						$('#'+classes[i]).val('').hide();
					}
				}
			}
			
		};
		if($(this).hasClass('exposer_rel'))
		{
			if($(this).val() != 'Active' && $(this).val() != 'New Member')
			{
				$('#'+$(this).attr('rel')).show();
			}
			else
			{
				$('#'+$(this).attr('rel')).val('').hide();
			}
		}
		
	});
	
	//show add'l field on check
	$('.exposer').click(function()
	{
		$('#'+$(this).attr('rel')).show();
		
	});
	//hide add'l field on check
	$('.concealer').click(function()
	{
		$('#'+$(this).attr('rel')).hide();
		
	});
	
	
	//form field date picker
	$(function() {
		$(".date").datepicker(
			{
				changeMonth: true,
				changeYear: true,
				showOtherMonths: true,
				selectOtherMonths: true,
				yearRange:'c-100:c'
			});
	});

	$('.fancybox').fancybox();
	
	$(".video_fancybox").click(function() {
		$.fancybox({
				'padding'		: 0,
				'autoScale'		: false,
				'transitionIn'	: 'none',
				'transitionOut'	: 'none',
				'title'			: this.title,
				'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
				'type'			: 'swf',
				'swf'			: {
				   	 'wmode'		: 'transparent',
					'allowfullscreen'	: 'true'
				}
			});

		return false;
	});
	$('.delete').live('click', function(event)
	{
		  $(this).parent('.removable').remove();
	});
	
	$('.delete').empty().append('<a class="ui-icon ui-icon-trash">Remove</a>');
	
	$('.add_office_link').live('click', function(e)
	{
		e.preventDefault();
		var uniquifier = new Date().getTime();
		var list_id = $(this).closest('tfoot').prev('.offices_held_list').attr('id');
		var office_type = list_id.substring(0,list_id.indexOf('_')).capitalize_first_letter();
		$(this).closest('tfoot').prev('.offices_held_list').append('<tr class="removable"><td><input type="hidden" name="'+office_type+'OfficeHeldUserEntered['+uniquifier+']" value="'+uniquifier+'"  /><input type="text" name="'+office_type+'OfficeHeldUserEntered_office['+uniquifier+']"  /></td><td><input type="text" name="'+office_type+'OfficeHeldUserEntered_year['+uniquifier+']"  /></td><td class="delete"><a class="ui-icon ui-icon-trash">Remove</a></td></tr>');
	});
	$('form #profile_chapter_offices_held, form #profile_alumnae_offices_held').append('<tfoot><tr><td colspan="3"><a href="#" class="add_office_link">Add another</a></td></tr></tfoot>');
	
	
	/* ** form validation ** */
		$('input.validate').blur(function()
		{
			$this = $(this);
			var text = $(this).val();
			var validations = $(this).attr('class').split(/\s+/);
			var failed = false;
			var messages = new Array();
			$.each( validations, function(index, item){
			    if (item==='length') {
					var characters = text.length;
					$message = $this.next('.validation_messages').children('.length');
					$min = $message.children('.minimum');
					$max = $message.children('.length').children('.maximum');
					if(text != '' && $min.size() == 1 && !isNaN($min.text()))
					{
						var min_length = parseInt($min.text());
						if(characters < min_length)
						{
							messages.push($message)
							failed = true;
						}
						
					}
					if($max.size() == 1 && !isNaN($max.text()))
					{
						var max_length = $max.text();
						if(characters > max_length)
						{
							messages.push($message)
							failed = true;
						}
					}
			      
			    }
			if(failed)
			{
				$.each(messages, function(index, item)
				{
					$(this).show().effect("highlight", {}, 3000);;
				});
				$this.addClass('invalid');
			}
			else
			{
				if($this.hasClass('invalid'))
				{
					$this.next('.validation_messages').children('.message').hide();
					$this.removeClass('invalid');
				}
			}
			});
		});
		
		/* subpage header movement */
		pic = $('#header_images').children("img");
		numImgs= pic.length;
		if(numImgs > 0)
		{
			$('#header_images img').each(function()
			{
				picsW += $(this).width();
			});
			if (picsW <= windowW)
			{
				wDiff = windowW - picsW;
				$pics_to_clone = $('#header_images').children('img');
				clones_needed = Math.ceil(wDiff/picsW);
				for(i=1; i<=clones_needed; i++)
				{
					$pics_to_clone.clone().appendTo($('#header_images'));
				}
				pic = $('#header_images').children("img");
				numImgs= pic.length;
			}
			arrLeft = new Array(numImgs);
			for (i=0;i<numImgs;i++){

				totalWidth=0;
				for(n=0;n<i;n++){
					totalWidth += $(pic[n]).width();
				}

				arrLeft[i] = totalWidth;
				$(pic[i]).css("left",totalWidth);
			}

			myInterval = setInterval("flexiScroll()",speed);
			$(pic).show();			
		}

	
	
});
String.prototype.capitalize_first_letter = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}
function flexiScroll(){

	for (i=0;i<numImgs;i++){
		arrLeft[i] -= 1;		

		if (arrLeft[i] == -($(pic[i]).width())){	
			totalWidth = 0;	
			for (n=0;n<numImgs;n++){
				if (n!=i){	
					totalWidth += $(pic[n]).width();
				}			
			}	
			arrLeft[i] =  totalWidth;	
		}					
		$(pic[i]).css("left",arrLeft[i]);
	}
}

function getStyle(el,styleProp)
{
	var x = document.getElementById(el);
	if (x.currentStyle)
		var y = x.currentStyle[styleProp];
	else if (window.getComputedStyle)
		var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
	return y;
}
