// JS for the Trip Builder

// random string for anti-caching
function randomString() {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = 8;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

function connectionChoice() {
	var ChosenEvent = $('input[@name=trip_date][@checked]').val();
	var mainEid = $('#trip_builder_1 input[@name=eid]').val();
	var tripID = $('#trip_builder_1 input[@name=trip_id]').val();
	
	if (!mainEid) {
		return false;
	}

	if ($('#connections:visible')) {
		$('#connections').slideUp("normal");
	}
	
	// Find and load any connections
	// anti-caching param:
	var rand = randomString();
	$('#connections div.connection_content').load('/destinations/ajax/tripbuilder_connections/'+rand, {eid: ChosenEvent, main_eid: mainEid, trip_id: tripID},
		function (responseText, textStatus, XMLHttpRequest) {
			if (responseText) {
				$('#connections').slideDown("normal");
			}  					
		}
	);
	
	return false;
}


function eventChoice() {
	var ChosenEvent = $('input[@name=trip_date][@checked]').val();
	var mainEid = $('#trip_builder_1 input[@name=eid]').val();
	var tripID = $('#trip_builder_1 input[@name=trip_id]').val();
	$('#'+ChosenEvent).show();
	
	var rand = randomString();

	if ($('#extensions:visible')) {
		$('#extensions').slideUp('normal');
	}
	
	
	//Find and load any extensions
	$('#extensions div.extension_content').load('/destinations/ajax/tripbuilder_extensions/'+rand, {eid: ChosenEvent, main_eid: mainEid, trip_id: tripID},
		function (responseText, textStatus, XMLHttpRequest) {
			if (responseText) {
				$('#extensions').slideDown("normal", function() { $('#'+ChosenEvent).hide(); $('div.register_button').show();});
			} else {
				$('#'+ChosenEvent).hide(); $('div.register_button').show();
			}
		}
	);
	
	return false;
}

function refresh_messages() {
	if ($('#messages_content').length == 0) {
		return false; // Skip it
	}
	
	// skip it if messages are open. It's disruptive
	if ($('.message_open').length) {
		// set a new timeout
		setTimeout(function () { refresh_messages(); }, 10000);
		// and return
		return false;
	}
	
	var rand = randomString();

	var tripID = $('#trip_builder_1 input[@name=trip_id_save]').val();
	$('#messages_content').load('/destinations/ajax/trip_mailings/'+rand, {trip_id: tripID}, function() {		
		// manager -- open/close message detail, reset event handlers
		$('#messages_content a.open_message_detail').bind("click", function(){
			var mailing_id = $(this).attr("id");
			mailing_id = mailing_id.replace(/open_/, '');
			$('#message_'+mailing_id).slideToggle("normal", function() {
				if ($('#message_'+mailing_id).is(":visible")) {
					$('#message_'+mailing_id).addClass("message_open");
				} else {
					$('#message_'+mailing_id).removeClass("message_open");
				}
				
				if (mailing_id == "tripinfo") {
					if ($('#message_'+mailing_id).is(":visible")) {
						$('h3.tripinfo_show').slideUp();
					} else {
						$('h3.tripinfo_show').slideDown();
					}
				}
			});
			
			return false;
		});
	});
	
	// set a refresh
	setTimeout(function () { refresh_messages(); }, 10000);
	return false;
}

$(document).ready(function () {
	
	$.datePicker.setDateFormat('ymd','-');
	$('.datepicker').datePicker();

	// show connection choices
	connectionChoice();
	
	// check for set event choice radio
	var Chosen = $('input[@name=trip_date][@checked]').val();
	if (Chosen && Chosen > 0) {
		eventChoice();
	}

	$('input[@name=trip_date]').bind("click", function(){ eventChoice(); });
	
	$('a.payment_expand').click(function() {
		var PaymentNum = $(this).attr("id");
		$('#details_'+PaymentNum).slideToggle("normal", function(){
			if ($('#details_'+PaymentNum).is(":visible")) {
				$('#details_'+PaymentNum).attr("style", '');
				$('#img_'+PaymentNum).attr("src", '/destinations/images/admin/arrow_box_down.gif');
			} else {
				$('#img_'+PaymentNum).attr("src", '/destinations/images/admin/arrow_box.gif');
			}
		});
		return false;
	});
	$('a.payment_collapse').click(function() {
		var PaymentNum = $(this).attr("id");
		$('#details_'+PaymentNum).slideToggle("normal", function(){
			if ($('#details_'+PaymentNum).is(":visible")) {
				$('#details_'+PaymentNum).attr("style", '');
				$('#img_'+PaymentNum).attr("src", '/destinations/images/admin/arrow_box_down.gif');
			} else {
				$('#img_'+PaymentNum).attr("src", '/destinations/images/admin/arrow_box.gif');
			}
		});
		return false;
	});
	
	//fix colspan on any already-visible payment details
	$('.pay_detail').each(function() {
		if ($(this).is(":visible")) {
			$(this).attr("style", '');
			var PaymentNum = $(this).attr("id");
			PaymentNum = PaymentNum.replace(/details_/, '');
			$('#img_'+PaymentNum).attr("src", '/destinations/images/admin/arrow_box_down.gif');
		}
	});
	
	// refresh the messages right off
	refresh_messages();
		
	// manager -- open/close message detail
	$('a.open_message_detail').bind("click", function(){
		var mailing_id = $(this).attr("id");
		mailing_id = mailing_id.replace(/open_/, '');
		$('#message_'+mailing_id).slideToggle("normal", function() {
			if ($('#message_'+mailing_id).is(":visible")) {
				$('#message_'+mailing_id).addClass("message_open");
			} else {
				$('#message_'+mailing_id).removeClass("message_open");
			}
			if (mailing_id == "tripinfo") {
				if ($('#message_'+mailing_id).is(":visible")) {
					$('h3.tripinfo_show').slideUp();
				} else {
					$('h3.tripinfo_show').slideDown();
				}
			}
		});
		
		return false;
	});

	// manager -- show / hide the "fee_new" text field when other is selected on trip fees
	$('select[@name=fee_new_defaults]').change(function() {
		var chosen = $('select[@name=fee_new_defaults]').val();
		if (chosen == '__new__') {
			$('#fee_other').show();
		} else {
			$('#fee_other').hide();
		}
		return false;
	});
	
	$('select[@name=fee_new_defaults]').change(); // fire it, just in case

	// misc tripbuilder form actions
	$('#reg_affiliation').change(function() {
		var affiliation = $('#reg_affiliation').attr('value');
		if (affiliation == 'Other') {
			$('#reg_affiliation_other').slideDown('normal');
		} else if ($('#reg_affiliation_other').is(':visible')) {
			$('#reg_affiliation_other').slideUp('normal');
		}
	});

	$('#reg_how_did_you_hear').change(function() {
		var how = $('#reg_how_did_you_hear').attr('value');
		if (how == 'Other') {
			$('#reg_how_did_you_hear_other').slideDown('normal');
		} else if ($('#reg_how_did_you_hear_other').is(':visible')) {
			$('#reg_how_did_you_hear_other').slideUp('normal');
		}
	});
	
	// fire them on load
	$('#reg_how_did_you_hear').change();
	$('#reg_affiliation').change();
	
	// Payment form cost calculator
	$('#contribute input.checkradio').click(function() {
		$('#id_amount_other').attr('value', '');
		var radioVal = $("#contribute input.checkradio:checked").val();
		radioVal = radioVal.replace(/\$/, '');
		
		fullVal = parseFloat(radioVal);
		
		$('#total_line').html('$'+fullVal);
	});
	

	$('#id_amount_other').change(function() {
		$("#contribute input.checkradio").attr("checked", '');
		var otherVal = $("#id_amount_other").attr('value');
		otherVal = otherVal.replace(/\$/, '');
		otherVal = otherVal.replace(/[^0123456789\.]/, '');
		otherVal = parseFloat(otherVal);
		if (isNaN(otherVal)) {
			$("#id_amount_other").val("");
			$('#total_line').html('');
		} else {
			var min_max = $('#id_amount_other').attr("className");
			var minmax_array = min_max.split(/ /);
			
			for (i=0;i<2;i=i+1) {
				if (minmax_array[i] && minmax_array[i].match(/^max_/)) {
					max = minmax_array[i].replace(/max_/, '');
				} else if (minmax_array[i] && minmax_array[i].match(/^min_/)) {
					min = minmax_array[i].replace(/min_/, '');
				}
			}
			
			if (otherVal && max && parseFloat(otherVal) > parseFloat(max)) {
				otherVal = parseFloat(max);
			} else if (otherVal && min && parseFloat(otherVal) < parseFloat(min)) {
				otherVal = parseFloat(min);
			}
			
			otherVal = otherVal.toFixed(2);
			$('#id_amount_other').attr("value", otherVal);
			
			fullVal = parseFloat(otherVal);
			
			fullVal = fullVal.toFixed(2);
			$('#total_line').html('$'+fullVal);
		}
	});

	// Kill any blank amount values in contribute forms
	$('#contribute').submit(function() {
		if (!$('#id_amount_other').attr("value")) {
			$('#id_amount_other').remove();
		}	
	});

	// Tripfinder form hide / show
	$('#show_form').click(function() {
		$('#show_form').fadeOut('normal', function() {
			$('#tripfinder_form').slideDown('normal');
		});
		return false;
	});
	
	// Form tooltips
	$('.toolTip span.contents').bgiframe();
	$('.toolTip').hover(
	    function() {
	        $(this).css('z-index', 10);
	        $(this).children('.contents').addClass('show').show();
	    },
	    function() {
	        $(this).css('z-index', 0);
	        $(this).children('.contents').removeClass('show').hide();
	    }
	);

	$('.search_show_hide').bind('click', function() {
		$('#admin_search_details').slideToggle('normal', function() {
			if ($('#admin_search_details').is(':visible')) {
				$('.search_show_hide').html('« Hide search details');
			} else {
				$('.search_show_hide').html('Show search details »');
			}
		});
	});
	
	// admin search details show/hide
	if ($('#admin_search_details').length) {
		if ($('#admin_search_details').html().match('Examined the following')) {
			$('.search_show_hide').click();
		}
	}
	
	
});
