/**
 * @author kyle.geske
 */

// Autocomplete match finder, the autocomplete_data array is generated via php.
function autoIt(q, matchCase)
{
	var matches = "";
	
	for (i in autocomplete_data)
	{
		var test = matchCase ?  autocomplete_data[i] : autocomplete_data[i].toLowerCase();
		if (test.indexOf(q) != -1)		
			matches += autocomplete_data[i] + "\n";
	}
	
	return matches;
}

// Toggle the print-mode for calculators
function print_calc()
{
	$("div").not("#page").toggle();
}

//A pre-edit filter for edit-in-place
function cleanEdit(txt)
{
	txt = txt.replace(/^Keywords: /,"");
	txt = txt.replace(/^\d\d?(\.\d\d?)* - /,"");
	txt = txt.replace(/<\/a>/gi,"");
	txt = txt.replace(/<a[^>]*>/gi,"");
	txt = txt.replace(/[,]?\s*$/,"");
	return txt;
}

// Ajax sumbit for the private/public radio buttons.
function ajaxy_radio(page_id) {

	if ($("form.radio").size() > 0)
	{
		$("form.radio").change(function() {
			var p = {};
			p["Value"] = $("input",this).get(1).checked;
			p["Action"] = "ManagePages";
			p["SubAction"] = "EditPage";
			p["Type"] = "Private";
			p["page_id"] = page_id;
			
			$.post("admin.php",p);
		});
	}
}

function isUndefined(a) {
    return typeof a == 'undefined';
} 

$(document).ready(function()
{
   setTimeout(function() { // This anonymous function is called after 50ms. Needed for IE only in the case where a login fails. Strange.

	// Initialize the DomBuilder
	DomBuilder.apply($);

	// Top Menu Rollovers
	$("div#menu li").rollover($("div#chapter p"));

	// Sidebar Menu Folding
	$("div#sidebar ul.sidebar_level").accordian();

	// Autocomplete
	$("input.autocomplete").autocomplete("", { minChars:2, matchSubset:1, matchContains:1, cacheLength:10, fromFnc:autoIt });

	// Edit in Place
	var input = $("input.page_id").get(0);
	var page_id = (!isUndefined(input)) ? $.attr(input,'value') : 0;
	input = $("input.chapnum").get(0);
	var chapnum = (!isUndefined(input)) ? $.attr(input,'value') : 0;
	$(".editable_single").editable("admin.php",{submitButton:1, buttonClass:"btn", describe: 1, preFilter: cleanEdit, postAppend: chapnum, extraParams: {"page_id": page_id}});
	$(".editable_many").editable("admin.php",{type:"textarea", buttonClass:"btn", describe: 1, extraParams: {"page_id": page_id}});
	
	// Stripe Zebra Tables
	$("table.zebra").zebra("tr","zebra_even");

	// Stripe Zebra Definitions
	$("dl.def").zebra("dd","zebra_even_special");
	$("dl.def").zebra("dt","zebra_even");

	// Make our Edit in Place Radio Button work
	ajaxy_radio(page_id);	

	// Add the tooltips
	$("a.def").ToolTip('linksTooltip');

	//$("div#login").sizr();
   },5);
});
