var imgZoomOptions = { loadingImg: '/bcr/img/loading.gif' };

function initMainTabs() {
	$('#m-tabs').tabs({ cache: true });
}

function onGenusMenuClick(e) {
	var target = e.target || e.srcElement,
		href = $(target).attr('href');
	loadControl(null, href);
	return false;
}

function onClickCultivarList(e) {
	var target = e.target || e.srcElement, cssClass = $(target).attr('class');
	//allow some minor formatting inside the anchor
	if (!cssClass) {
		target = $(target).parent();
		cssClass = target.attr('class');
		if ( cssClass )
			target = target[0];
	}
	if (cssClass == 'C-spl' || cssClass == 'C-ppl') {
		onShowRelatedLinkClick.call(target, e);
	} else if (cssClass == 'regl') {
		onShowRegLinkClick.call(target, e);
	} else if (cssClass == "wn-reg") {
		onToggleRegLinkClick.call(target, e);
	} else if (cssClass == "show-reg" || cssClass == "show-images") {
		onToggleRegLinkClick.call(target, e);
	} else if (cssClass == 'v-img') {
		//change the class so we don't hook it again
		$(target).attr('class', 'v-img-h').imgZoom(imgZoomOptions).trigger('click');
	}
	return false;
}

function onShowRelatedLinkClick() {
	var $dataSrc = $(this).closest('li'),
		href = $(this).attr('href'),
		key = $(this).attr('value');
	//see if there already is one
	if ($dataSrc.children('#e-' + key).length == 0) {
		//just add the entry to the li
		loadControl($dataSrc, href, {}, { appendTo: true, filterFn: trimContentPage });
	}
}

function onShowRegLinkClick() {
	var $dataSrc = $(this).closest('li'),
		key = $(this).attr('value'),
		href = $(this).attr('href');
	//see if there already is one
	if ($dataSrc.children('#e-' + key).length == 0) {
		//just add the entry to the li wrapped in a div with the key
		loadControl($dataSrc, href, {}, { appendTo: true, filterFn: function(data) { return trimContentPage(data, key); } });
	}
}

function onToggleRegLinkClick() {
	var $dataSrc = $(this).parent(),
		href = $(this).attr('href'),
		key = $dataSrc.attr('value'),
		$itemToAdd = $dataSrc.next('.reg-added');
	//see if there already is one
	if ($itemToAdd.length == 1) {
		$itemToAdd.toggleClass("hidden");
	}
	else {
		//add a new li with a div and stick it in that div
		$dataSrc.after('<li value="' + key + '" class="reg-added"></li>');
		$itemToAdd = $dataSrc.next('.reg-added');
		loadControl($itemToAdd, href, {}, { filterFn: trimContentPage });
	}
	return false;
}

function trimContentPage(data, key) {
	var $page = $(data),
		$content = $page.filter('#contentList');
	if ($content.length == 1) {
		$content.click(onClickCultivarList);
		if (key)
			$content = $content.wrapAll('<div id="e-' + key + '"/>').parent();
		return $content;
	}
	else
		return $page;
}

$(function() {
	$('#NothogenusMenu').live('click', onGenusMenuClick);
	$('#CultivarList').live('click', onClickCultivarList);
	$('#WhatsNewList').live('click', onClickCultivarList);
});

