$(document).ready(function(event){
     setupCheckboxTable(); // toggle checkbox on table rows
     setupLinkTable();     // launch links when clicking anywhere on a row
	 registerAjaxLoadingNotification('#loading_window'); // show loading animation during ajax operations
});

// show loading animation during ajax operations
function registerAjaxLoadingNotification(loadingDivID){
   $(loadingDivID)
      .hide()  // hide it initially
      .ajaxStart(function() {
        //$(this).show();
      })
      .ajaxStop(function() {
        //$(this).hide();
      });
}

// find and handle CheckboxTables (tables with checkbox rows)
function setupCheckboxTable(){
    // based on Karl Swedberg's blog
  $('.checkboxTable tr')
    .disableSelection()
    .filter(':has(:checkbox:checked)')
    .addClass('selected')
    .end()
  .click(function(event) {
    $(this).toggleClass('selected');
    if (event.target.type !== 'checkbox') {
      $(':checkbox', this).attr('checked', function() {
        return !this.checked;
      });
    }
  });
}

// find and handle LinkTables (tables with links)
function setupLinkTable(){
  $('.linkTable tr').click(function(event) {
    window.location.href = $('a', this).attr('href');
    //$('a', this).click();
  });
}

/* FORM DIALOG CODE */ 

    var contributionFormLoading;
	var contributionFormRegionID;

    // converts the specified DIV into a dialog for form submissions
	function initializeFormDialog(regionID){
		contributionFormRegionID = regionID;
        contributionFormLoading  = $('#loading_window').clone();
		contributionFormOriginal = null;

		$(contributionFormRegionID)
			.dialog({width: 500, modal: false, autoOpen: false, hide: 'clip', dialogClass: 'drop-shadow' });

		convertDialogFormToAjax(contributionFormRegionID); // not needed since this will always be empty at initialization
	}

    // convert all forms inside dialog to ajax
	function convertDialogFormToAjax(divID){
		$(divID).find("form")
				.ajaxForm({
					target: divID,
					success: formSuccessDelegate,
					error: formErrorDelegate
					})
				.append('<input type="hidden" name="output" value="popup">');
	}
    
    // convert the given form to ajax
	function convertFormToAjax(formID, targetID){
		$(formID)
				.ajaxForm({
					target: targetID,
					success: formSuccessDelegate,
					error: formErrorDelegate
					})
				.append('<input type="hidden" name="output" value="popup">');
	}

    // loads specified file's contents into the dialog, and displays it
	function showContributionFormFromFile(path){
		showLoading();
		$(contributionFormRegionID)
			.load(path, showDialogDelegate);
	}

    // show a "loading..." message on the dialog
	function showLoading(){
		$(contributionFormRegionID)
        .empty()
		.append(contributionFormLoading.html())
		.dialog('open');
	}

    // Pre-processes dialog contents, then displays it
	function showDialogDelegate(){
        var title = preprocessDialogContents(contributionFormRegionID); // pre-process h1 tags, dynamic elements, etc

		$(contributionFormRegionID)
			.dialog('option','title',title)         // set dialog title
			.dialog('option','position','center')   // set dialog position
			.dialog("open");                        // open dialog
	}

    // Async ajax request has completed
    // Runs after success or error delegate call
	function formCompleteDelegate(jqXHR, textStatus) {  
		// this executes regardless of ajax success or error
	}

    // Async ajax request was successful. Show contents.
	function formSuccessDelegate(resultData,textStatus,jqXHR) {  
        var title = preprocessDialogContents(contributionFormRegionID); // pre-process h1 tags, dynamic elements, etc
                
		$(contributionFormRegionID)
			.dialog('option','title',title)         // set dialog title
            .dialog("open");     // display the dialog
	}

    // Async ajax request failed
	function formErrorDelegate(jqXHR, textStatus, errorThrown) {  
		alert('Error: ' + errorThrown); // display error message
	}
    
    // Pre-processes contents that have been injected into a div
    // Returns the title, i.e. <h1> tag
    function preprocessDialogContents(regionID){
        var headingTag = $(regionID).find('title'); // extract title info from the dialog text
		var title = headingTag.text();
		headingTag.fadeOut();
        
		convertDialogFormToAjax(regionID);  // convert all forms inside the dialog to ajax

        preprocessDynamicElements(regionID); // Update Dynamic Elements

        return title;
    }
    
    // Update dynamic elements in all or a portion of the DOM
    // DEBUG: Refactor to global
    function preprocessDynamicElements(subsectionID){
        var prefix = "";
        if (subsectionID) {
            prefix = subsectionID + " ";
        }
        // TODO: add behavior here
    }







/* Tab Control */

	function setFocusAndCursor(oTextbox) {    
		if (oTextbox != null){
			if (oTextbox .createTextRange) {
                    var r = (oTextbox.createTextRange());
                    r.moveStart('character', (oTextbox.value.length));
                    r.collapse();
                    r.select();
            }
			oTextbox.focus();
		}
	}

	function showNav(strObj){
		tner = document.getElementById("topnavEnglishRow");
		tnrr = document.getElementById("topnavRomanRow");
		tnnr = document.getElementById("topnavNaskhRow");
		tnea = document.getElementById("topnavEnglishA");
		tnra = document.getElementById("topnavRomanA");
		tnna = document.getElementById("topnavNaskhA");
		tnet = document.getElementById("GlobalSearchEnglishText");
		tnrt = document.getElementById("GlobalSearchRomanText");
		tnnt = document.getElementById("GlobalSearchNaskhText");
		tnea.className = 'topnavOffL';
		tnra.className = 'topnavOffL';
		tnna.className = 'topnavOffL';	
		//tner.style.display = 'none';
		//tnrr.style.display = 'none';
		//tnnr.style.display = 'none';
		switch (strObj){
		case 'English':
			tner.style.display = '';
			tnrr.style.display = 'none';
			tnnr.style.display = 'none';
			tnea.className                    = 'topnavOnL tabEnglish';
			if (tnet != null)
				setFocusAndCursor(tnet);
			break;
		case 'Roman':
			tner.style.display = 'none';
			tnrr.style.display = '';
			tnnr.style.display = 'none';
			tnra.className                    = 'topnavOnL tabRoman';
			if (tnrt != null)
				setFocusAndCursor(tnrt);
			break;
		case 'Naskh':
			tner.style.display = 'none';
			tnrr.style.display = 'none';
			tnnr.style.display = '';
			tnna.className                    = 'topnavOnL tabNaskh';
			if (tnnt != null)
				setFocusAndCursor(tnnt);
			break;
		case 'Alphabet':
			tnar.style.display              = '';
			tnaa.className                    = 'topnavOnL tabAlphabet';
			break;
		case 'Daily':
			tndr.style.display              = '';
			tnda.className                    = 'topnavOnL tabDaily';
			break;
		default:
			alert ('Invalid navigation selection.');
		} // end switch
	}
