
var currentCrumb;
$(document).ready(function() {

	///
	/// fix all IE6 issues.
	///
	if(IE6) {
		/// PNGs
		$("img[src$='.png']").each(function() {
			var src = $(this).attr('src');
			$(this).attr("src", "http://www.dynamit.us/img/spacer.gif").attr("style", "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "');");
		});

		/// lack of CSS selector support
		$("input[type='text']").addClass('txt');
	}


	///
	/// search box focus/blur effect
	///
	$('input#searchbox').focus(function() {
		var init = $(this).attr('init');
		if(!init || init.length == 0) {
			init = $(this).val();
			$(this).attr('init', init);
		}

		if($(this).val() == init) $(this).val('');
	}).blur(function() {
		var init = $(this).attr('init');
		if($(this).val() == '') $(this).val(init);
	});


	///
	/// create tabbed-pane functionality for ajax dialogs.
	///
	$('ul.tabs>li').live('click', function() {
		var index = $('ul.tabs li').index(this);
		$content = $(this).parent().next('ul.tabs-content');
		$content.children('li').hide();
		$content.children('li').eq(index).show();
		$('ul.tabs li').removeClass('on');
		$(this).addClass('on');
	});

	$('.btnCancel').live('click', dynamItCloseDialog);


	///
	/// fancy breadcrumb
	///

	$('ul#breadcrumb li.bcctrl').click( function() {
		currentCrumb = $(this).prev('li').children('ul').eq(0);
		closeBreadcrumb();

		if( $(this).prev('li').children('ul:visible').length ) {
			currentCrumb = null;
			$(this).prev('li').children('ul').slideUp('slow');
		} else {
			$(this).prev('li').children('ul').slideDown('slow');
		}

		return false;
	});

	$('ul#breadcrumb').mouseout( function() {
		currentCrumb = null;
		crumbTimeout = setTimeout('closeBreadcrumb()', 2000);
	}).mouseover( function() {
		clearTimeout(crumbTimeout);
	});


	///
	/// drop down menus
	///
	$('ul#nav').dynamItDrop();

	///
	/// implement jQuery datepicker
	///
	$('.dateselect').datepicker();
	$('.daterangeselect').datepicker({rangeSelect: true});



	$('input.prefbill').click( function() {
		if(this.checked) {
			$('input.prefbill').not(this).each( function() {
				this.checked = false;
			});
		}
	});

	$('input.prefmail').click( function() {
		if(this.checked) {
			$('input.prefmail').not(this).each( function() {
				this.checked = false;
			});
		}
	});



	///
	/// HOMEPAGE slideshow flip
	///
	var flipTimeout = null;
	var $last = $('ul#bannerfeatures li').eq(1);

	$('ul#bannerfeatures li').not('.cap, .cup').click( function() {
		clearTimeout(flipTimeout);

		var previd = '#' + $last.attr('id') + '_img';
		var myid = '#' + $(this).attr('id') + '_img';

		$('#osmaimg img').not(previd).hide();
		$(previd).fadeOut('slow');
		$(myid).fadeIn('slow');

		$last.removeClass('active');
		$last = $(this).addClass('active');

		flipTimeout = setTimeout(function() {
			$next = $last.next();
			if(!$next.length)
				$next = $('ul#bannerfeatures li').eq(1);
			$next.click();
		}, 7000);
	});

	$last.click();
	$('#osmaimg img').click( function() {
		var id = $(this).attr('id').split('_');
		var href = $('#' + id[0] + '_' + id[1]).children('a').attr('href');
		location.href = href;
	});

});

var crumbTimeout;
function closeBreadcrumb(obj) {
	if( currentCrumb )
		$('ul#breadcrumb li').children('ul').not(currentCrumb).slideUp('slow');
	else
		$('ul#breadcrumb li').children('ul').slideUp('slow');
	clearTimeout(crumbTimeout);
}

function toggleLabel(fieldset, active) {
	$("a.notch").css('font-weight', 'normal');
	$("a[title='" + active + "']").css('font-weight', 'bold');
	$("#" + fieldset + " label.opt").hide();
	$("#" + fieldset + " label[for='" + active + "']").show();
}

function joinFindYourself(f) {
	var url = '/dues/member/find';

	url += '?a=' + f.a.value;
	url += '&firstname=' + f.firstname.value;
	url += '&lastname=' + f.lastname.value;
	url += '&menumber=' + f.menumber.value;

	dynamItLoad(url, null, 420, 'auto', null);
	return false;
}

function renewFindYourself(f) {
	var url = '/dues/member/find?a=renew';
	if(f.coid.value > 0)		url += '&coid=' + f.coid.value;
	if(f.practice.value.length)		url += '&practice=' + f.practice.value;
	if(f.lastname.value.length)		url += '&lastname=' + f.lastname.value;
	if(f.firstname.value.length)		url += '&firstname=' + f.firstname.value;

	dynamItLoad(url, null, 420, 'auto', null);
	return false;
}

function verifyMemberInfo(members) {
	// loop through member radios and get the checked one.
	var mid = -1;
	if(members.length) {
		for( var i = 0; i < members.length; i++ ) {
			if(members[i].checked) {
				mid = members[i].value;
			}
		}
	} else {
		mid = members.value;
	}

	if( mid != -1 ) {
		dynamItLoad('/dues/member/verify?member=' + mid, null, 420, 'auto', null);
	} else {
		alert('Please select your name from the list. If it is not to be found, please contact us.');
	}
	return false;
}

function editMemberInfo(id) {
	dynamItLoad('/dues/member/edit?member=' + id, null, 420, 'auto', null);
	return false;
}

function renewAddMember(html) {
	if( html.substring(0,3) == '***' ) {

		dynamItOpenDialog('');
		dynamItConfDialog(html.substring(3));

	} else {
		$('#renewMembers').append(html);
		$('#notify').fadeIn('slow');
		setTimeout("$('#notify').fadeOut('slow');", 3000);

		var $tbl = $('#renewMembers .duesmember:last');
		var fname = $tbl.find('td.firstname').html();
		var lname = $tbl.find('td.lastname').html();
		$('#notifyname').html( fname + ' ' + lname );
		$('#notifynum').html( $('#renewMembers .duesmember').length );
	}
}

function updateNewsletterPref(checked) {
	var url = '/members/preferences/';
	url += '?newsletter=' + ( (checked) ? 1 : 0 );
	dynamItSend(url);
}

function eventsFindYourself(f, eventcode) {
	var url = '/events/attendee/find?method=register&eventcode=' + eventcode;

	if(f.coid.value > 0)		url += '&coid=' + f.coid.value;
	if(f.practice.value.length)		url += '&practice=' + f.practice.value;
	if(f.lastname.value.length)		url += '&lastname=' + f.lastname.value;
	if(f.firstname.value.length)		url += '&firstname=' + f.firstname.value;

	dynamItLoad(url, null, 420, 'auto', null);
	return false;
}


function eventsNewAttendee(ev) {
	eventsNewAttendee(ev,0, '');
}

function eventsNewAttendee(ev, coid, company) {
    var url = '/events/attendee/new?event=' + ev + '&coid=' + coid + '&company=' + urlencode(company);
    dynamItLoad(url, null, 420, 'auto', null);
}

function eventsAddAttendee(html) {
	if(html == "zero") {
		alert('No attendees were selected. Please search again and select an attendee from among the results.');
	} else {
		$('#eventAttendees').append(html);
		$('#notify').fadeIn('slow');
		setTimeout("$('#notify').fadeOut('slow');", 3000);

		var $tbl = $('#eventAttendees fieldset:last').find('table.simpletbl').eq(0);
		var name = $tbl.find('tr').eq(0).children('td').children('b').html();
		$('#notifyname').html( name );
		$('#notifynum').html( $('#eventAttendees fieldset').length );
		updateAttendeeTotal();

	}
}

function updateAttendeeTotal() {
	var total = 0;
	$('td.subtotal').add('div.extraprice').each( function() {
		var totalstr = str_replace(',', '', $(this).html().substring(1))
		var amt = parseFloat( totalstr );
		if( isNaN(amt) ) amt = 0;
		total += amt;
	});

	$('td#totalcell').html('$' + total.toFixed(2));
}

function launchNotification(msg) {
	$('#notify').children('div').html(msg);
	$('#notify').fadeIn('slow');
	setTimeout("$('#notify').fadeOut('slow');", 3000);

}


function swapPhoto(src) {
	$('#productphoto').attr('src', src);
}


function memberRemoveAddress(aid) {
	dynamItSendOnConfirm('/members/deleteaddress?aid=' + aid, 'Are you sure you wish to permanently delete this address?');
}

function memberNewAddress() {
	$("#newaddressform").slideDown('slow');
	$("#newaddress").val('1');
}

function updateTotal() {
	var total = 0;
	$('input.subrow').each( function() {
		total += parseFloat( $(this).val() );
	});

	$('#totalbox').html( '$' + total.toFixed(2) );
	$('#x_amount').val(total);
}

function removeMember(mid) {
	var url = '/dues/renew/remmember';
	url += '?member=' + mid;
	dynamItSend(url);
}

function radioValue(grp) {

	for(var j = 0; j < grp.length; j++)
		if(grp[j].checked)
			return grp[j].value;

	return grp.value;
}

function removeAttendee(event, attendee) {
	dynamItSend('/events/attendee/remove?eid=' + event + '&mid=' + attendee);
}

function removeAttendeeExtra(event, attendee, extra) {
	dynamItSend('/events/attendee/removeextra?eid=' + event + '&mid=' + attendee + '&extra=' + extra);
}

function eventCheckout(f) {
	var go = true;
	$('select.regclass').each(function() {
		if( $(this).val().length == 0 ) {
			go = false;
			$(this).after('<div class="error">Please select your price.</div>').focus( function() {
				$(this).siblings('div.error').remove();
			});
		}
	});

	if( go ) location.href = '/cart/view';
}


function fixPhone(o) {
	var phone = o.value;
	var newphone;

	phone = phone.replace(/[^0-9]+/g, '');
	if( phone.length ) {
		if( phone.substring(0,1) == 1 )
			if( phone.length > 11 )
				newphone = '+1 (' + phone.substring(1,4) + ') ' + phone.substring(4,7) + '-' + phone.substring(7,11) + ' x' + phone.substring(11);
			else
				newphone = '+1 (' + phone.substring(1,4) + ') ' + phone.substring(4,7) + '-' + phone.substring(7);
		else if( phone.length > 10 )
			newphone = '(' + phone.substring(0,3) + ') ' + phone.substring(3,6) + '-' + phone.substring(6,10) + ' x' + phone.substring(10);
		else
			newphone = '(' + phone.substring(0,3) + ') ' + phone.substring(3,6) + '-' + phone.substring(6);

		o.value = newphone;
	}
}

function matchBilling(f) {
	f.ship_contact.value = f.contact.value;
	f.ship_addrline1.value = f.addrline1.value;
	f.ship_addrline2.value = f.addrline2.value;
	f.ship_city.value = f.city.value;
	f.ship_stateprovince.value = f.stateprovince.value;
	f.ship_postalcode.value = f.postalcode.value;
}

function onEventFormChange(sel) {
    // An IE6 and IE7 workaround... both browsers allow the selection of a <option disabled='disabled'>
    // So, we check the option value to see if its blank, if so, we do not submit. The rendering code
    // must blank the option's value to support this function.
    if ( sel && sel.options && "" == sel.options[sel.selectedIndex].value ) return;
    
    $(".regclass:enabled").attr('disabled','true');
    $('#formEventAttendees').fadeTo(0,0.5);

    dynamItPublish( $('#formEventAttendees')[0],
                    function(html) {
                        $('#formEventAttendees').replaceWith(html);
                    }
                  );
}

var cartUpdateTimer = null;

function onCartFormLimbo() {
    $('.fadeonchange').fadeTo('slow',0.5);

    if ( cartUpdateTimer ) clearTimeout(cartUpdateTimer);
    cartUpdateTimer = setTimeout( 'onCartFormChange()', 2000);
}

function onCartFormChange() {
    $(".cartqty:enabled").attr('disabled','true');

    if ( cartUpdateTimer ) {
        clearTimeout(cartUpdateTimer);
        cartUpdateTimer = null;
    }

    dynamItPublish( $('#cartform')[0],
                    function(html) {
                        $('#cartform').hide(); // Work around an IE rendering bug
                        $('#cartform').replaceWith(html);
                    }
                  );

    // Safe guard in case another timer starts during the above AJAX call
    if ( cartUpdateTimer ) {
        clearTimeout(cartUpdateTimer);
        cartUpdateTimer = null;
    }
}

function onCartProductRemoval(inputname) {
    $('[name='+inputname+']').val('0');
    onCartFormChange();
}