/* 
Description: BroadVision CHRM javascript.
Version: 1.0
Released: 10/23/08
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -   */
// A function for deactivating tabs on profile template pages. Is run on page load when user enters "edit mode".
jQuery(document).ready(function() {

    // Create unordered list in div.pageButtonWrap to allow for styling of buttons.
    jQuery('.pageButtonWrap').wrapInner('<ul class="controls_list"></ul>').find('input').wrap('<li></li>');

    // Add disabled class to input buttons and their parent li's if the button has disabled=disabled.
    jQuery('input[disabled]').addClass('disabled').parent().addClass('disabled');
    jQuery('.controls_list input.disabled').parent().addClass('disabled');

	// Call scrollingTable function which adds a scrolling div around any wide tables.
	scrollingTable();

    // Add class of dropdown to parent LI of any third-level UL in the top nav.
    jQuery('#navigation li li ul').parent().addClass('dropdown');

    // Add 'selected' class to top-level LI when it is clicked. This will make the 2nd & 3rd level menus for
    // that item appear and will make the tab appear selected.
    jQuery('#navigation > li > a').click(function() {
        jQuery('#navigation li').removeClass('selected');
        jQuery(this).parent().addClass('selected');
		return false;
    });

    // Creates tabs from .panel divs wrapped in div.in_page_tabs.
    /*	jQuery('.in_page_tabs').semantictabs({
	  container:'in_page_tabs',    //-- Selector of element containing all panels
	  panel:'panel',            //-- Selector of individual panel body
	  head:'h4',             //-- Selector of element containing panel header
	  active:':first'                        //-- Which panel to activate by default
	});
*/
    // Wraps buttons in a self-clearing div in profile pages to avoid having tables float up next to buttons.
    jQuery('.panel .controls_list').not('.drag_column .controls_list').wrap('<div class="controls_list_not"></div>');
    jQuery('.records_search + .controls_list').wrap('<div class="controls_list_wrapper"></div>');

    // The following is used activate tabs programatically. It will need to be used when user returns to profile 
    // page template after trip to server.
    /*	var selectedPanel = jQuery.getURLParam('selectedPanel');
		if (jQuery.getURLParam('selectedPanel')) {
			jQuery('.in_page_tabs').semantictabs({activate:selectedPanel});
		}
	*/

    // Add updown function to headers in department tree.
    jQuery('#dept_tree_container h5').toggle(function() {
        jQuery(this).next().slideUp('slow');
    },
    function() {
        jQuery(this).next().slideDown('slow');
    });

    // This code will have to run upon page refresh when user enters "edit mode".
    var editMode = jQuery.getURLParam('editMode');
    if (editMode == 'true') {
        deactivateTabs();
    }

    // Replace first and last links in pagination table with brackets.
    jQuery('.first').html('&lt;&lt;');
    jQuery('.last').html('&gt;&gt;');

    // Run the altshade function on tables.
    altShade();

    // Set heights of .search_section divs to match to keep things from floating up next to them.	
    maxDivHeight = 0;
    jQuery('.records_search .search_section').each(function() {
        if (jQuery(this).height() > maxDivHeight) {
            maxDivHeight = jQuery(this).height();
        }

        /*	maxLabelWidth=0;
		jQuery(this).children('p').children('label:first-child').each(function() {
			if (jQuery(this).width() > maxLabelWidth) {
				maxLabelWidth = jQuery(this).width();
			}
		});
		jQuery(this).children('p').children('label:first-child').each(function() {
			jQuery(this).width(maxLabelWidth);
			jQuery(this).height(jQuery(this).parent().height());
		});
*/
        /*		jQuery(this).children('p').children('label:has(input[type=checkbox])').each(function() {
			jQuery(this).css({'margin-left':maxWidth+8,'font-weight':'normal'});											  
		});
*/
    });
    jQuery('.records_search .search_section').each(function() {
        jQuery(this).height(maxDivHeight);
    });

    // Add textfield class to textfields to allow them to be styled uniquely.
    jQuery('.records_search input[type=text]').addClass('textfield');

    // remove right padding from the last div.search_section.
    jQuery('.search_section:last').css({
        'padding-right': 0,
        'clear': 'right'
    });

    /*	jQuery('.records_search label:has(input[type=checkbox])').css({'font-weight':'normal','font-size':'11px'});
*/


var numberProfileColumns = jQuery('.columns td table').length;

if (numberProfileColumns == 2) {
	jQuery('.columns td:has(table)').css('width','50%');
}
if (numberProfileColumns == 3) {
	jQuery('.columns td:has(table)').css('width','33%');	
}
	
connectColumns();
bindDeleteColumn();
bindResetColumn();
setColumnWidth();
var dragColumnsHaveButtons = jQuery('.drag_column .pageButtonWrap').length;
if (dragColumnsHaveButtons > 0) {
	jQuery('.drag_column').not('.drag_column:has(div[class=pageButtonWrap])').css('margin-top','26px');
}

jQuery('input#add_column').click(function() {

		// Figure out how many columns there are and put it in a variable.
		var howManyColumns = jQuery('.drag_column').length;
		if (howManyColumns == 4) {
			alert('Maximum number of columns reached.');
			return false;
		} else {
		jQuery('div.dragndrop').append('<div class="drag_column"><div class="pageButtonWrap"><input type="button" class="inputButton controls-delete delete_column" value="Delete" /><input type="button" class="inputButton controls-reset reset_column" value="Reset" /></div><ul id="drag_column_' + (howManyColumns + 1) + '"></ul></div>');


jQuery('#drag_column_' + (howManyColumns + 1) ).siblings('.pageButtonWrap').wrapInner('<ul class="controls_list"></ul>').find('input').wrap('<li></li>');
bindDeleteColumn();
bindResetColumn();
setColumnWidth();
connectColumns();
}
	 });

    // If there are more than a certain number of tabs in a profile tab layout,
    // create a "more" tab with a dropdown for picking the other tabs.
    jQuery('.semtabs').each(function() {

        var howManyTabs = jQuery(this).find('li').length
        if (howManyTabs > 6) {
            var extraTabs = jQuery(this).find('li');
            extraTabs = extraTabs.slice(6, extraTabs.length);
            jQuery(this).append('<li class="show_more_tabs"><ul class="more_tabs"></ul><a href="javascript:void(0);"><span>More Tabs</span></a></li>');
            jQuery(this).find('.more_tabs').append(extraTabs);
            var moreTabsMaxWidth = 0;
            jQuery(this).find('.more_tabs li').each(function() {
                if (jQuery(this).width() > moreTabsMaxWidth) {
                    moreTabsMaxWidth = jQuery(this).width();
                }
            });
            jQuery(this).find('.more_tabs li a').each(function() {
                jQuery(this).width(moreTabsMaxWidth);
            });
        }
    });

    // Alter the source of the search button depending upon the product edition.
	if (jQuery('#search_button').length > 0) {
		var searchButtonSrc = jQuery('#search_button').attr('src');
		searchButtonSrc = searchButtonSrc.replace(/.gif/, '');
		jQuery('.product_60 #search_button').attr('src', searchButtonSrc + '-60.gif');
		jQuery('.product_120 #search_button').attr('src', searchButtonSrc + '-120.gif');
		jQuery('.product_240 #search_button').attr('src', searchButtonSrc + '-240.gif');
		jQuery('.product_360 #search_button').attr('src', searchButtonSrc + '-360.gif');
	}

 
 jQuery('.in_page_tabs').each(function() {
        jQuery(this).find('div.panel').hide();
        jQuery(this).find('div.panel:eq(0)').show();
        jQuery(this).find('ul.tabs li:eq(0)').addClass('selected');
        var currentGroup = jQuery(this);
        jQuery(this).find('ul.tabs li').click(function() {
            // jQuery(this) is li now
            currentGroup.find('.panel').hide();
            currentGroup.find('ul.tabs li').removeClass('selected');
            jQuery('div[title=' + jQuery(this).text() + ']').show();
            jQuery(this).addClass('selected');
        });
    });

	// If a button row appears right after a data table, give it a top margin to create some breathing room.
	// Doing this via js since IE doesn't support adjacent selectors.
	jQuery('.data_table + .pageButtonWrap .controls_list').css('margin-top','20px');

	// Add a negative margin to the top of captions which follow button rows so they will align horizontally.
	// If the caption is blank, don't add the negative margin. Does not work in IE.
	jQuery('.pageButtonWrap + .data_table caption').each(function() {
	 	var hasCaption = false;
		if (jQuery(this).text() == ' ') {
			hasCaption = false;
		} else {
			hasCaption = true;	
		}
		if (hasCaption) {
			jQuery(this).css('margin-top','-30px');
		}
    });
	
	// Add class="actions" to all td with headers="Actions"
	jQuery('td[headers=Actions]').addClass('actions');
	
	// Set the width of the actions column in table.data_table so the action links will not wrap.
	jQuery('.data_table').each(function () {
		var actionLinks = jQuery(this).find('.actions:first a').length;
		var actionColumnWidth = actionLinks * 23;
		jQuery(this).find('.actions').css('width',actionColumnWidth + 'px');
	});
	
	// Add a class to the settings tables in the jpivot reports so I can style them more easily. 
	// Had to do this because the origin IDs have periods in them.
	jQuery('table[id*="printform"]').addClass('jpivot_settings_table');
	jQuery('table[id*="chartform"]').addClass('jpivot_settings_table');
	
	
	// The following script is not used for now. It was going to set the width of TH in table.detailed_info
	// when there was a long non-breaking item in the TD.
/*	jQuery('.detailed_info').each(function() {
		var tableWidth = jQuery(this).width();
		var tdWidth = jQuery(this).find('td').width();
		var thWidth = 382 - tdWidth;
		if (tableWidth > 382) {
			jQuery(this).find('th').each(function() {
				 jQuery(this).css('width',thWidth + 'px');
			 });
		}
    });
*/


});

// Deactivates all tabs except for the selected one.
function deactivateTabs() {
    jQuery('.semtabs li[class!="selected"] a').css('cursor', 'default').css('color', '#999').click(function() {
        return false;
    });
    return false;
}

// Alternating shading for tables.
function altShade() {
    jQuery('.detailed_info').not('.data_table').each(function() {
        jQuery(this).find('tr:nth-child(odd)').addClass('shaded')
    });
    jQuery('.data_table').each(function() {
        jQuery(this).find('td').removeClass('shaded')
    });
    jQuery('.data_table').each(function() {
        jQuery(this).find('tr:nth-child(even) td').addClass('shaded')
    });
    jQuery('.data_table').each(function() {
        jQuery(this).find('tr:nth-child(even) th').addClass('shaded')
    });
}

    // This function adds a scrolling div around any wide tables.
function scrollingTable() {
    jQuery('#content_main table').not('table.columns').each(function() {
        tableWidth = jQuery(this).width();
        parentWidth = jQuery(this).parent().width();
        if (tableWidth > 848 && jQuery(this).parents('.overflow_table').length == 0) {
            jQuery(this).wrap('<div class="overflow_table"></div>').css('margin-bottom', '0');
        }
    });
}


function alphaColumn1 () {
var items = $('#drag_column_1 li').get();
items.sort(function(a,b){ 
  var keyA = $(a).text();
  var keyB = $(b).text();

  if (keyA < keyB) return -1;
  if (keyA > keyB) return 1;
  return 0;
});
var ul = $('#drag_column_1');
$.each(items, function(i, li){
  ul.append(li);
});
	
}

function bindDeleteColumn() {
	jQuery('.delete_column').click(function () {
		if (jQuery('.drag_column').length == 2) {
			alert('Your form must contain at least one column.');	
			return false;
		} else {
		jQuery(this).parents('.drag_column').find('ul.ui-sortable li').appendTo('#drag_column_1');
		alphaColumn1();
		var thisID = jQuery(this).attr('id');
		var numberOfColumns = jQuery('.drag_column').length;
		if (thisID = 'drag_column2') {
			if (numberOfColumns == 3) {
				jQuery('#drag_column_3').attr('id','drag_column_2');	
			}
			if (numberOfColumns == 4) {
				jQuery('#drag_column_3').attr('id','drag_column_2');	
				jQuery('#drag_column_4').attr('id','drag_column_3');	
			}
		}
		if (thisID = 'drag_column_3') {
			if (numberOfColumns == 4) {
				jQuery('#drag_column_4').attr('id','drag_column_3');	
			}
		}
		jQuery(this).parents('.drag_column').remove();
connectColumns();

	setColumnWidth();
		}
});
}

function bindResetColumn() {
	jQuery('.reset_column').click(function () {
		jQuery(this).parents('.drag_column').find('ul.ui-sortable li').appendTo('#drag_column_1');
		alphaColumn1();
});
}

function connectColumns() {
    // enable sortable on all columns
    // this will add drag-and-drop functionality as well
    jQuery("#drag_column_1").sortable('destroy');
    jQuery("#drag_column_2").sortable('destroy');
    jQuery("#drag_column_3").sortable('destroy');
    jQuery("#drag_column_4").sortable('destroy');
   jQuery("#drag_column_1").sortable({
        connectWith: ["#drag_column_2","#drag_column_3","#drag_column_4"],
		appendTo: "body",
		update: function() { alphaColumn1(); }
    });
    jQuery("#drag_column_2").sortable({
        connectWith: ["#drag_column_1","#drag_column_3","#drag_column_4"],
		appendTo: "body"
    });
    jQuery("#drag_column_3").sortable({
        connectWith: ["#drag_column_1","#drag_column_2","#drag_column_4"],
		appendTo: "body"
    });
    jQuery("#drag_column_4").sortable({
        connectWith: ["#drag_column_1","#drag_column_2","#drag_column_3"],
		appendTo: "body"
    });
	
}

function setColumnWidth(upDown) {
/*		var currentMarginRight = jQuery('.drag_column').css('margin-right');
		currentMarginRight = currentMarginRight.replace('px','');
		currentMarginRight  = parseInt(currentMarginRight);
		if (upDown == 'add') {
			var marginAdjustment = -10;
		} else {
			var marginAdjustment = 10;
		}
		alert(marginAdjustment);
*/		jQuery('.drag_column').css({'width':88/jQuery('.drag_column').length + '%'});
jQuery('#drag_column_2').parent().css('margin-right','30px');
jQuery('#drag_column_3').parent().css('margin-right','30px');
jQuery('#drag_column_4').parent().css('margin-right','0px');
}