/**
* Returns the value of the selected radio button in the radio group, null if
* none are selected, and false if the button group doesn't exist
*
* @param {radio Object} or {radio id} el
* OR
* @param {form Object} or {form id} el
* @param {radio group name} radioGroup
*/
function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        var radioGroup = $(el).name;
        var el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }
 
    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re) {return re.checked;}
    );
    return (checked) ? $F(checked) : null;
}

/*
	moves an element "up" in the DOM tree	
*/
function move_up(id) {
	var div = $(id);
	var previous = div.previous();

	if (previous != null) {
		div.remove();
		previous.insert({before:div});
	}
}

/*
	moves an element "down" in the DOM tree	
*/
function move_down(id) {
	var div = $(id);
	var next = div.next();

	if (next != null) {
		div.remove();
		next.insert({after:div});
	}
}

function showVideo(elementId) {
	var images = $$('#' + elementId + ' img');
	
	if (images.length == 1) {
		images[0].observe("load", function() {
			resizeAndShow(elementId);
		});
	} else {
		resizeAndShow(elementId);
	}
}

function resizeAndShow(elementId) {
    if(typeof window.innerHeight != 'undefined') {
         $(elementId).style.top = Math.round(document.viewport.getScrollOffsets().top + ((window.innerHeight - $(elementId).getHeight()))/2)+'px';
         $(elementId).style.left = Math.round(document.viewport.getScrollOffsets().left + ((window.innerWidth - $(elementId).getWidth()))/2)+'px';
    } else {
         $(elementId).style.top = Math.round(document.documentElement.scrollTop + (document.documentElement.clientHeight - $(elementId).getHeight())/2)+'px';
         $(elementId).style.left = Math.round(document.documentElement.scrollLeft + (document.documentElement.clientWidth - $(elementId).getWidth())/2)+'px';
	}
	
	$(elementId).show();
}

function showMultiItemList(element) {
	clearSelectedItemList();
	
	$$('input.hidden_divvy_ids_field').each(function(e) {
		addItemToSelectedList(e.value, e.getAttribute('divvy_title'));
	});
	
    if(typeof window.innerHeight != 'undefined') {
         $(element).style.top = 
              Math.round(document.viewport.getScrollOffsets().top + 
              ((window.innerHeight - $(element).getHeight()))/4)+'px';
         $(element).style.left = 
              Math.round(document.viewport.getScrollOffsets().left + 
              ((window.innerWidth - $(element).getWidth()))/2)+'px';
    } else {
		//alert("body scroll = " + document.body.scrollTop + ", " + document.body.scrollLeft + "\ndocumentElement scroll = " + document.documentElement.scrollTop + ", " + document.documentElement.scrollLeft + "\nclient h/w = " + $$('body')[0].clientHeight + ", " + $$('body')[0].clientWidth + "\ndocumentElement h/w = " + document.documentElement.clientHeight + ", " + document.documentElement.clientWidth + "\nelement h/w = " + $(element).getHeight() + ", " + $(element).getWidth());
         $(element).style.top = 
              Math.round(document.documentElement.scrollTop + 
              (document.documentElement.clientHeight - $(element).getHeight())/4)+'px';
         $(element).style.left = 
              Math.round(document.documentElement.scrollLeft + 
              (document.documentElement.clientWidth - $(element).getWidth())/2)+'px';
	}
	
	element.show();
}

function showItemListColumn(id) {
	$$('.item_list_column.second').each(function(e) { e.hide(); });
	$('divvy_group_' + id).show();
}

var selectedItemList = [];
function addItemToSelectedList(id, title) {
	var i = indexOfSelectedItem(id);

	if (i == -1) {
		selectedItemList.push({ id : id, title : title });
		drawSelectedItemList();
	}
}

function drawSelectedItemList() {
	$$('#selected_item_list li.added').each(function(e) { e.remove(); });
	selectedItemList.each(function(e) {
		var newLi = new Element("li", { 'class' : 'added', 'onMouseOver' : '$(this).firstDescendant().show()', 'onMouseOut' : '$(this).firstDescendant().hide()' }).update(e.title + " <a href=\"#\" onclick=\"removeSelectedItem(" + e.id + ")\" style=\"display:none\">[x]</a>");

		$('selected_item_list').insert(newLi);
	});
}

function indexOfSelectedItem(id) {
	for (var i = 0; i < selectedItemList.length; ++i) {
		if (selectedItemList[i].id == id)
			return i;
	}
	
	return -1;
}

function removeSelectedItem(id) {
	var i = indexOfSelectedItem(id);

	if (i != -1) {
		selectedItemList.splice(i, 1);
		drawSelectedItemList();
	}
}

function clearSelectedItemList() {
	selectedItemList = [];
	drawSelectedItemList();
}

function addItemsToSelectedList(list) {
	list.each(function(e) { 
		var i = indexOfSelectedItem(e[0]);
		if (i == -1)
			selectedItemList.push({ id : e[0], title : e[1] });
	});

	drawSelectedItemList();
}

function setSelectedItems() {
	if (selectedItemList.length == 0) {
		alert("You must select at least one item.");
		return;
	}

	$('multi_item_list').hide();
	
	$('selected_item').update("multiple items");

	var params = '';
	
	var current_location = window.location.pathname;
	var match = current_location.match("/divvies/(\\d+)/");

	if (match != null) {
		params = "divvy_id=" + match[1]
	}

	selectedItemList.each(function(e) {
		if (params != '')
			params += "&"
		params += encodeURIComponent("divvy_ids[]") + "=" + e.id;
	});

	$('form').update('');

	new Ajax.Updater('form', '/reservations/render_advanced_builder_form', {
		asynchronous: true, 
		evalScripts: true,
		method: 'get', 
		parameters: params
	});
}

function closeVideo(element) {
	element.hide();
}

function expand(prefix, group_id) {
	var e = $(prefix + '_' + group_id);
	
	if (e.visible()) {
		$(prefix + '_' + group_id + '_toggle').src = "/images/btn-toggle-open.gif";
	} else {
		$(prefix + '_' + group_id + '_toggle').src = "/images/btn-toggle-close.gif";
	}
	
	e.toggle();
}

function show_recurrence(freq) {
	$$('div.recurrence_freq').each(function(e) { e.hide(); });
	$$('div.recurrence_freq input, div.recurrence_freq select').each(function(e) { e.disable(); });
	$$('#recurrence_' + freq + ' input, #recurrence_' + freq + ' select').each(function(e) { e.enable(); });
	
	if (freq == 'monthly') {
		$$('input.monthly_repeat_date').each(function (e) { e.disable(); });
	}
	
	$('weekly_repeat_day_td_' + day_of_week()).setStyle({ backgroundColor: 'blue'});
	$('monthly_repeat_day_td_' + day_of_week()).setStyle({ backgroundColor: 'blue'});
	$('monthly_repeat_date_td_' + date_of_month()).setStyle({ backgroundColor: 'blue'});
	
	$('recurrence_' + freq).show();
}

function change_monthly() {
	if ($('reservation_view_recurrence_monthly_by_day').checked) {
		$$('input.monthly_repeat_day').each(function(e) { e.enable(); });
		$$('input.monthly_repeat_date').each(function(e) { e.disable(); });
		$$('#monthly_recurrence_table_by_date td').each(function(e) { 
			if (e.id != "monthly_repeat_date_td_" + date_of_month())
				e.setStyle({ backgroundColor: null}); 
		});
	} else {
		$$('input.monthly_repeat_day').each(function(e) { e.disable(); });
		$$('input.monthly_repeat_date').each(function(e) { e.enable(); });
		$$('#monthly_recurrence_table_by_day td').each(function(e) { 
			if (e.id != "monthly_repeat_day_td_" + day_of_week())
				e.setStyle({ backgroundColor: null}); 
		});
	}
}

function recurrence_table_click(e) {
  	var element = Event.element(e);

	if (element.tagName != "TD")
		return;

	if (!element.getElementsBySelector("input")[0].disabled && element.id != "weekly_repeat_day_td_" + day_of_week() && element.id != "monthly_repeat_day_td_" + day_of_week() && element.id != "monthly_repeat_date_td_" + date_of_month()) {

		//if (e.target.getStyle("background-color") == "rgba(0, 0, 0, 0)" || e.target.getStyle("background-color") == "transparent") {
		if (element.getStyle("background-color") != "blue") {
			element.setStyle({ backgroundColor: 'blue'});
			element.getElementsBySelector("input")[0].value = true;
		} else {
			element.setStyle({ backgroundColor: null});
			element.getElementsBySelector("input")[0].value = false;
		}
	}
}

function show_recurring() {
	$('repeat_div').show();
	$$('#repeat_div input, #repeat_div select').each(function(e) { e.enable() });
	
	var freq = $('reservation_view_recurrence_frequency').options[$('reservation_view_recurrence_frequency').selectedIndex].value;
	show_recurrence(freq);
}

function set_recurring() {
	$('repeat_div').hide();
}

function cancel_recurring() {
	if ($('repeat_div') != null) {
		$('repeat_div').hide();
		$$('#repeat_div input, #repeat_div select').each(function(e) { e.disable() });

		$$('.recurrence_table td').each(function(e) { 
			e.setStyle({ backgroundColor: null}); 
		});
	}
}

function update_nth_week() {
	var day = 1;
	
	if ($('adhoc_day_select') != null && $('adhoc_day_select').visible()) {
		day = $('reservation_view_day_adhoc').value;
	} else {
		day = $('reservation_view_day').value;
	}
	
	var nth_week = Math.ceil(day / 7);
	
	if (nth_week == 1)
		$('nth_week').update(nth_week + 'st');
	else if (nth_week == 2)
		$('nth_week').update(nth_week + 'nd');
	else
		$('nth_week').update(nth_week + 'th');
}

function setup_form_auto_disable() {
	// document.observe( 'dom:loaded', function() {
	//     $$( 'form' ).each( function( form ) {
	//         form.observe( 'submit', function() {
	//             $$( 'input[type="submit"]' ).invoke( 'disable' );
	//             $$( 'form' ).each( function( form) {
	// 				form.observe( 'submit', function( evt ) { // once any form is submitted
	//                 	evt.stop(); // prevent any other form submission
	// 				})
	//             } );
	//         } );
	//     } );
	// } );	
}

function enable_submits() {
	//     $$( 'form' ).each( function( form ) {
	// 	$$( 'input[type="submit"]' ).invoke( 'enable' );	
	// });
}