/* --------------------------------------------------------------------------------
 *
 *  General utility and header methods
 *
 * -------------------------------------------------------------------------------- */
/* * * *
 *  adjusts the height of the main_body div to the minimumHeight by adding padding.
 *  Padding allows the element to expand vertically, as normal vs setting an absolute height that causes overflow outside the container.
/*/
var setHeight = function( jqObjSelector, ht ) {
        var jqObj = $(jqObjSelector);
        var minimumHeight = ht == undefined ? 500 : ht;
	//alert('jqObj.height = '+jqObj.name + ' ' +jqObj.height());

        if ( jqObj.height() < minimumHeight )
		jqObj.css( { "padding-bottom" : ( minimumHeight - jqObj.height() ) } );
            //jqObj.height(minimumHeight); 
    }

function setupMain() {
    setHeight('div#main_body', 500);
}


/* * * *
 *  currently, each page should set the javascript var crumbs which is a list of strings.
        Example: crumbs = { "Home","Research Genes", "Location eQTL"};

        Explanation:  key = string value that goes between the anchor tags <a>[key]</a>
                      value = string value that will be the href, if empty just the text will be used (represents where you are NOW)
/*/
function prepareCrumbTrail( jsonTrail ) {

	/* * * 
	 * The masterJsonTrail maps the titles that will be shown on the crumb trail to the 
	 * screens that will be accessed 
	/*/
	var masterJsonTrail = {
		"Home" : contextPath + "/web/common/" + "startPage.jsp",
        	"Research Genes" : contextPath + "/web/geneLists/" + "geneListMain.jsp",
        	"Location EQTL" : contextPath + "/web/geneLists/" + "locationEqtl.jsp",
        	"Annotation" : contextPath + "/web/geneLists/" + "annotation.jsp",
        	"Analyze Microarray Data" : contextPath + "/web/experiments/" + "microarrayMain.jsp",
        	"Differential Expression Analysis" : contextPath + "/web/experiments/" + "filters.jsp?analysisType=diffExp",
        	"Cluster Analysis" : contextPath + "/web/experiments/" + "filters.jsp?analysisType=cluster",
        	"Correlation Analysis" : contextPath + "/web/experiments/" + "correlation.jsp",
        	"Investigate QTL Regions" : contextPath + "/web/geneLists/" + "locationEqtl.jsp"
	};

    if ( jsonTrail != undefined ) {
       var theTrail = $("#crumb_trail");
       for ( var i in jsonTrail ) {
		/* 
		alert('jsonTrail[i] = '+jsonTrail[i]);
		alert('masterJsonTrail[i] = '+masterJsonTrail[jsonTrail[i]]);
		*/
            theTrail.append( theTrail.text().length > 0 ? "&nbsp;&nbsp;&raquo;&nbsp;&nbsp;": "" );

		if (i < jsonTrail.length -1) {
            		if (masterJsonTrail[jsonTrail[i]].length > 0 ) {
                		theTrail.append( $("<a href='" + masterJsonTrail[jsonTrail[i]] + "'>" + jsonTrail[i] + "</a>") );
            		} else {
                		theTrail.append( jsonTrail[i] );
        		}
		} else {
                	theTrail.append( jsonTrail[i] );
		}
	}
    }
}


/* * * *
    this method does :
        a) sets the Main Tab Help text
/*/
function selectTab( )
{
    /* var hlpTxt = $("div.selected").text(); */
    var hlpTxt = "";

    $(".main_tab_help").find("a span").html( hlpTxt + " Help" );
}

/* * * *
 *  generic method to create a dialog box, with some basic settings that can be overridden by options.
 *      selector: tells what element to be used as the dialog box
/*/
function createDialog(selector, options) {
    var settings = { draggable: true,
                     modal: true,
                     autoOpen: false,
                     overlay: { opacity: .4, background: "#ccc" }
                    };
    $.extend(settings, options);
    var element = $(selector);

    var dialog = element.dialog( settings );

    if ( settings.draggable ) {
        dialog.parents(".ui-dialog")
            .draggable({
                handle: ".ui-dialog-titlebar",
		/* browser.msie true means the browser is Internet Explorer */
                containment: $.browser.msie ? $(document) : "document" 
            });
    }

    return dialog;
}

function closeWindow() {
	$("div[class='closeWindow']").click(function(){
		window.close();
	});
}

function closeDialog(dialogWindow) {
	dialogWindow.find("div.closeWindow").click(function() {
		dialogWindow.dialog("close");
	});
}

/* * * *
 *  generic method to create a popup browser window, with settings that can be overridden by options.
 *      pageURL: url of the page that will be loaded
 *      options: various attributes of the popup window
/*/
function openPopup( pageURL, options )
{
    var settings = { width      : 700,
                     height     : 650,
                     scrollbars : "no",
                     statusBar  : "no",
                     locBar     : "no",
                     screenX    : 100,
                     screenY    : 100,
                     resize     : "yes",
                     winName    : "popupName",  // names the window so that it can be referenced by this name in javascript
		     asTab      : false
                   };

    $.extend(settings, options);

    // window bars
    var windowAttr = "location=" + settings.locBar + ",status=" + settings.statusBar;
    windowAttr += ",directories=no,menubar=no,titlebar=yes,toolbar=no,dependent=yes";

    // window attributes
    windowAttr += ",width=" + settings.width + ",height=" + settings.height + ",resizable=" + settings.resize;
    windowAttr += ",screenX=" + settings.screenX + ",screenY=" + settings.screenY;

    var newWin = window.open( pageURL, settings.winName,  settings.asTab ? "" : windowAttr );
    newWin.focus();
}

/* * * *
 *  returns the rows currently in the table minus any header rows
/*/
function getRows() {
    return $("table[name='items']").find("tr").not(".title, .col_title");
}

/* * * *
 *  returns the rows currently in the table minus any header rows
/*/
function getRowsFromNamedTable(tableElement) {
    return tableElement.find("tr").not(".title, .col_title");
}


function clickRadioButton() {
	$(':radio, tr').filter(':has(:radio:selected)').end().click(function(event) {
              //if the user didn't click on the radio button itself, check it
                   if (event.target.type !== 'radio') {
                   	$(':radio', this).trigger('click');
                   }
              $(':radio, tr').removeClass('selected');
              $(this).toggleClass('selected');
          });
}

// check the check box if user clicks anywhere on the row
function clickCheckBox() {
    $(":checkbox, tr").find("td").not(".details").click(function(event){
        //if the user didn't click on the checkbox itself, check it
        if (event.target.type !== 'checkbox') {
            $(':checkbox', $(this).parents("tr") ).trigger('click');
        }

        $(':checkbox, tr').removeClass('checked');
        $(this).toggleClass('checked');
    });
}



/* * * *
 *  this function adds the striping and the row hovering for the table
/*/
function stripeAndHoverTable(tableRows) {
	stripeTable(tableRows);
	hoverRows(tableRows);
}


/* * * *
 *  this function adds the striping for the table
/*/
function stripeTable( tableRows ) {
	tableRows.find("td.alt_stripe").removeClass("alt_stripe");
	tableRows.filter(":odd").each(function(){
		$(this).find("td").addClass( "alt_stripe" );
	});
}

/* * * *
 *  this function adds the row hovering for the table
/*/
function hoverRows( tableRows ) {
	tableRows.each(function(){
		//---> hover functionality
        	// columns that get hover EVENT
		// do not hover on description, details, delete, or download, but do get cursorPointer on details
        	var rowCells = $(this).find("td:not('td.details, td.btnsDeleteDownload, td.description')");

        	rowCells.hover(
                	function() { rowCells.addClass("hover"); },
                	function() { rowCells.removeClass("hover"); }
            	)
            	.addClass("cursorPointer");
        	var detailsCells = $(this).find("td.details");
        	detailsCells.addClass("cursorPointer");
	});
}



/* * * *
 *  this function sets up the events for the DELETE button
/*/
function setupDeleteButton(url) {
    var modalOptions = {height: 250, width: 650, position: [250,250], title: "<center>Delete Item</center>"};
    deleteModal = createDialog( ".deleteItem", modalOptions );

    $("table[name='items']").find("td div.delete").click(
        function() {
            var theRow = $(this).parents("tr");
                var dataParams = {itemID: theRow.attr("id") };

            // send to .jsp to handle delete
            $.ajax({
                type: "POST",
                url: url,
                dataType: "html",
                data: dataParams,
                async: false,
                success: function( html ){
                    deleteModal.html( html ).dialog("open");
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert( "there was an error processing this request: " + textStatus + " " + errorThrown );
                }
            });
        });
}

function cancelDelete() {
    deleteModal.dialog( "close" );
}

function confirmDelete() {
	if ( confirm("Please confirm your choice to delete this item") ) {
		return true;
	}
	cancelDelete();
	return false;
}
/* * * *
 *  this function sets up the events for the DOWNLOAD button
/*/
function setupDownloadButton(url) {
    var modalOptions = {height: 550, width: 750, position: [250,150], title: "<center>Download Item</center>"};
    downloadModal = createDialog( ".downloadItem", modalOptions );

    $("table[name='items']").find("td div.download").click(
        function() {
            var theRow = $(this).parents("tr");

                var dataParams = { itemID: theRow.attr("id") };

            // send to .jsp to handle download
            $.ajax({
                type: "POST",
                url: url,
                dataType: "html",
                data: dataParams,
                async: false,
                success: function( html ){
                    downloadModal.html( html ).dialog( "open" );
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert( "there was an error processing this request: " + textStatus + " " + errorThrown );
                }
            });
        });
}

function checkUncheckAll( id, name ) {
   $("INPUT[@name=" + name + "][type='checkbox']").attr('checked', $('#' + id).is(':checked'));
}

function setupExpandCollapse() {
	$("span.trigger").click(function(){
		var baseName = $(this).attr("name");
                var thisHidden = $("div#" + baseName).is(":hidden");
                $(this).toggleClass("less");
                if (thisHidden) {
			$("div#" + baseName).show();
                } else {
			$("div#" + baseName).hide();
                }
	})
}

