/*
****************************************************************************
* Filename:   ACH Functions
* Function:   ACH RULES Javascript Functions 
*              
* Created by:  Vincent Perlerin for WebFirst, Inc.
* Date:        2007
*
* Modification log:
* Author		Date		Modification
* ------		----		------------
*
****************************************************************************
*/

var t = null;							// Universal Timer
var bookmarkPage = '/MyBookmarks.aspx?1=1'	// BOOKMARK PAGE (to change to booklib.asp)
var searchPage	 = '/MySearch.aspx?1=1'		// SEARCH PAGE 	 (to change to searchlib.asp)
var logoutPage   = '/index.aspx?logout='
var isIE6  = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);


/*****************************************************************************
 * Function: manageDialogBox
 * show/hide dialog boxes ('My Bookmark' and 'My Search')  
 *
 * @attr:	
 *  	currentTrigger	  : dialog box trigger (ex: bookMarkTrigger)
 *  	ajaxTarget		  : URL to page to display inside the dialog box (ex: bookmarkPage)
 *		ajaxTargetContent : element used for displaying ajaxTargets (ex: div#contentBox)
 *  	idBox			  : id of current box  (ex: bookmarkDialog)
 *  	dragEl			  : class of element used for dragging the box (ex: .drag)
 *  	resizeEl		  : class of element used for resizing (SE) the box (ex: .resize) 
 *****************************************************************************/
function manageDialogBox(currentTrigger, ajaxTarget, ajaxTargetContent, idBox, dragEl, resizeEl) {
	
	// Manage dialog box
	$('#'+idBox).jqm({
							trigger: '#'+currentTrigger,	 	// Link to open bookmark boxe
							overlay: 30, 					 // Overlay div transparency 
							overlayClass: 'whiteOverlay',	 // Overlay div class
							ajax: ajaxTarget + '&hash=' + Math.random(),				 // BOOKMARK PAGE **
							target: ajaxTargetContent, 		 // Target content for bookmark page
							modal:true,						 // Modal 
							onShow: function(h) {			 // EFFECT ON SHOW
									h.w.fadeIn(100);
									h.w.blur();
									if(isIE6) $('select').hide();
					      		},
							
							onHide: function(h) {			 // EFFECT ON HIDE
									h.w.fadeOut(100);
									h.o.fadeOut(200);
									g = h.o;
									t = setTimeout('g.remove()', 300);
									if(isIE6) $('select').show();
							}
						 })
	;
	
	//  Manage dialog box (RESIZE and DRAG)
	 $('#'+idBox).Resizable({
		 minWidth:  	200,
		 minHeight: 	255,
		 maxWidth: 		800,
		 maxHeight: 	400,
		 ghosting:		true,
		 dragHandle: 	dragEl,
		 handlers: {
			 se: 		resizeEl
		 },
		 onResize : function(size, position) {
			 $(ajaxTargetContent).css('height', size.height-33 + 'px');
			 var windowContentEl = $(ajaxTargetContent).css('width', size.width - 25 + 'px');
			 if (!$(ajaxTargetContent).isMinimized) {
			 	windowContentEl.css('height', size.height - 48 + 'px');
			 }
 		}
	 })	
}

/*****************************************************************************
 * Function: confirm
 * show/hide confirm dialog box ('Logout')  
 *****************************************************************************/
function confirm(msg,callback) {

  $('#confirm')
    .jqmShow()
    .find('p.jqmConfirmMsg')
      .html(msg)
    .end()
    .find(':button:visible')
      .click(function(){
        if(this.value == 'Yes')
          (typeof callback == 'string') ?
            window.location.href = callback :
            callback();
        $('#confirm').jqmHide();
      });
}


/*****************************************************************************
 * Function: confirmDialog
 * manage logout box 
 *****************************************************************************/
function confirmDialog() {

	
// MANAGE LOGOUT DIALOG BOX
	$('#confirm').jqm({		
			overlay: 30, 					 // Overlay div transparency 
			overlayClass: 'whiteOverlay',	 // Overlay div class
			modal: true,
			trigger: '#logout',
			
			onShow: function(h) {	
  							    h.w.fadeIn(100);
								h.w.blur();
								if(isIE6) $('select').hide();
				},
				onHide: function(h) {			 // EFFECT ON HIDE
								h.w.fadeOut(100);
								h.o.fadeOut(200);
								g = h.o;
								t = setTimeout('g.remove()', 300);
								if(isIE6) $('select').show();
				}
				
	});
	
	 $('#confirm').Resizable({
		 minWidth:  	200,
		 minHeight: 	255,
		 maxWidth: 		800,
		 maxHeight: 	400,
		 ghosting:		true,
		 dragHandle: 	'#dragLogout',
		 handlers: {
			 se: 		'#resizeLogout'
		 }
	 })	
	
 
  // trigger a confirm whenever links of class alert are pressed.
  $('a.confirm').click(function() { 
    confirm('You are about to logout from ACH Rules Online.', logoutPage ); 
    return false;
  });
  
  
  
  
}


/*****************************************************************************
 * Function: title Bookmark
 * manage Bookmark box 
 *****************************************************************************/
function confirmBookmark() {
    
	$('#nameBookmark').jqm({		
			overlay: 30, 					 // Overlay div transparency 
			overlayClass: 'whiteOverlay',	 // Overlay div class
			modal: true,
			trigger: '#bookmark',
			onShow: function(h) {	
  							    h.w.fadeIn(100);
								h.w.blur();
								if(isIE6) $('select').hide();
				},
				onHide: function(h) {			 // EFFECT ON HIDE
								h.w.fadeOut(100);
								h.o.fadeOut(200);
								g = h.o;
								t = setTimeout('g.remove()', 300);
								if(isIE6) $('select').show();
				}
	});
	
	 $('#nameBookmark').Resizable({
		 minWidth:  	200,
		 minHeight: 	255,
		 maxWidth: 		800,
		 maxHeight: 	400,
		 ghosting:		true,
		 dragHandle: 	'#dragBook',
		 handlers: {
			 se: 		'#resizeBook'
		 }
	 })	
	
  $('#nameBookmark')
    .find(':button:visible')
      .click(function(){
		if (this.value == 'Ok'){
			var query = '';
			var name = $('#titleBookmarkField').attr('value');
			var trimmed = name.replace(/^\s+|\s+$/g, '');
			
			if (trimmed == ''){
				alert('Please enter a name of the bookmark');
				return;
			}
			query = 'MyBookmarks.Status=AddBookmark&MyBookmarks.Name=' + escape(trimmed) + '&MyBookmarks.DocumentID=' + $('#SelectedDocumentID').attr('value');
			$.post('MyBookmarks.aspx', query, onSendSaveBookmarkSuccess);
		}
		$('#nameBookmark').jqmHide();
      })
	  ;
}

function onSendSaveBookmarkSuccess(data){
	//alert('Your Bookmark has been saved successfully.');
	$('#nameBookmark').jqmHide();
}

function confirmNotLogged() {
    
	$('#nameNotLogged').jqm({		
			overlay: 30, 					 // Overlay div transparency 
			overlayClass: 'whiteOverlay',	 // Overlay div class
			modal: true,
			trigger: '.OnlyForLogged',
			onShow: function(h) {	
  							    h.w.fadeIn(100);
								h.w.blur();
								if(isIE6) $('select').hide();
				},
				onHide: function(h) {			 // EFFECT ON HIDE
								h.w.fadeOut(100);
								h.o.fadeOut(200);
								g = h.o;
								t = setTimeout('g.remove()', 300);
								if(isIE6) $('select').show();
				}
	});
	
	 $('#nameNotLogged').Resizable({
		 minWidth:  	200,
		 minHeight: 	255,
		 maxWidth: 		800,
		 maxHeight: 	400,
		 ghosting:		true,
		 dragHandle: 	'#dragNotLogged',
		 handlers: {
			 se: 		'#resizeNotLogged'
		 }
	 })	
}

/*****************************************************************************
 * Function: title SaveSearch
 * manage SaveSearch box 
 *****************************************************************************/
function confirmSaveSearch() {
    
	$('#nameSaveSearch').jqm({		
			overlay: 30, 					 // Overlay div transparency 
			overlayClass: 'whiteOverlay',	 // Overlay div class
			modal: true,
			trigger: '#saveSearch',
			onShow: function(h) {	
  							    h.w.fadeIn(100);
								h.w.blur();
								if(isIE6) $('select').hide();
				},
				onHide: function(h) {			 // EFFECT ON HIDE
								h.w.fadeOut(100);
								h.o.fadeOut(200);
								g = h.o;
								t = setTimeout('g.remove()', 300);
								if(isIE6) $('select').show();
				}
	});
	
	 $('#nameSaveSearch').Resizable({
		 minWidth:  	200,
		 minHeight: 	255,
		 maxWidth: 		800,
		 maxHeight: 	400,
		 ghosting:		true,
		 dragHandle: 	'#dragSaveSearch',
		 handlers: {
			 se: 		'#resizeSaveSearch'
		 }
	 })	
	
  $('#nameSaveSearch')
    .find('#yesButSaveSearch')
      .click(function(){
		var query = '';
		var name = $('#titleSaveSearchField').attr('value');
		var trimmed = name.replace(/^\s+|\s+$/g, '');
		
		if (trimmed == ''){
			alert('Please enter a name of the search');
			return;
		}
		query = getSaveSearchQueryString();
		if (query == ''){
			alert('Bad search parameters');
			$('#nameSaveSearch').jqmHide();
			return;
		}
		$.post('Search.aspx', query, onSendSearchParametersSuccess);
      })
	  ;
}

function getSaveSearchQueryString(){
	var str = '';
	str += getSaveSearchValue('AllWords');
	str += getSaveSearchValue('Phrase');
	str += getSaveSearchValue('OneOfWords');
	if (str == '') return str;
	str += getSaveSearchValue('NoneWords');
	str += getSaveSearchValue('SectionTypeID');
	str += 'SearchForm.Name=' + $('#titleSaveSearchField').attr('value') + '&';
	str += 'SearchForm.Status=SaveSearch';
	return str;
}

function getSaveSearchValue(paramId){
	var val = document.getElementById('SaveSearch.'+paramId).value;
	
	if ((val != null) && (val != ''))
		return 'SearchForm.' + paramId + '=' + val + '&';
	else
		return '';
}

function onSendSearchParametersSuccess(data){
	//alert('Your Search has been saved successfully.');
	$('#nameSaveSearch').jqmHide();
}

/*****************************************************************************
 * Function: position
 * Size all elements of ACH Rules pages based on screen size
 *****************************************************************************/
function position(){ 
	$('#page').css("height",$(window).height()-$('#frameTools').height()-$('#titleFrame').height()-30) ;
	$('#treeContainer').css("height",$('#page').height()/2 -40);
	$('#faqContainer').css("height",$('#treeContainer').height());
	$('.Loading').css("height",$('#documentNavigator').height());
}
/*****************************************************************************
 * Function: testHomepage
 * Return true when we are on the homepage
 *****************************************************************************/
function testHomepage() {
	return $('body').attr('id')=='home'
}



/*****************************************************************************
 * Function: positionTagLine
 * When document is resized
 *****************************************************************************/
function positionTagLine() {

	// Tagline positionning 
	if(	$('#wrapper').width()>984	) {
			$('#tagline').css('right','40%');
	} else {
			$('#tagline').css('right','36.5%');
	}
}

/*****************************************************************************
 * Function: resizeAds
 * Resizes homepage ads for small screens
 *****************************************************************************/
function resizeAds() {
	// If content height bigger than ad height ...
	if( $('div#ad2 div.contentAdR div.adContent').height() > $('div#ad2 div.contentAdR').height() )   {
		$('p.date').hide();
	} else {
		$('p.date').show();
	}
}



/*****************************************************************************
 * Function: addBookmark
 * Add bookmark function to an element
 *****************************************************************************/
function getUrl() {
 return location.href.match(/^([^?]*)/)[1];
}

function addBookmark() {
	 var url = getUrl();
	 var title = "ACH RULES";
	 if (window.sidebar) 	   {  window.sidebar.addPanel(title, url,"");
	 } else if( document.all ) {  window.external.AddFavorite( url, title);
	 } else {
	 	alert("Click 'Open this page in a new window' and Ctrl+D");
	 }
}


/*****************************************************************************
 * Function: footerFixing
 * place Footer at  the bottom of the page
 *****************************************************************************/
function footerFixing() {
	

	if ($('#mainContent .rightCol').html() != null){
	    mainCHeight = $('#mainContent').height();
	    rightCHeigh = $('#mainContent .rightCol').height();

	
		if(mainCHeight > rightCHeigh) {
			$('#mainContent .rightCol').css('height',mainCHeight-20)
		}
	}

}


/*****************************************************************************
 * Function: resize
 * When document is resized
 *****************************************************************************/
function content_resize() {
	
	
	// If Homepage
	if(testHomepage()) {
		$(document).pngFix(); // Stupid IE 6
		positionTagLine();	  // Tagline Positionning
		resizeAds();		  // Resize Ads for small screen
	} else {
		if(  $('body').attr('id')!='search' && $('body').attr('id')!='achRules' )  
			footerFixing();		  // Fix Footer everywhere else	
		
	}
}

$( window ).wresize( content_resize ); 





/*****************************************************************************
 * Function: jQuery.ready
 * When document is loaded
 *****************************************************************************/
$().ready(function() {

	
    //$('#mainCol ul').tabs({ fxFade: true, fxSpeed: 'fast' });
    $(document).pngFix(); // Stupid IE 6

	// If Homepage
	if(testHomepage()) {
		positionTagLine();	  // Tagline Positionning
		resizeAds();		  // Resize Ads for small screen
		
	} else {
		if( !$('#search') || !$('#mainTable') )  {
			footerFixing();		  // Fix Footer everywhere else	
			}
	}

	
	
 	// MANAGE BOOKMARK DIALOG BOX
	manageDialogBox('bookMarkTrigger', bookmarkPage, '#contentBookmarkDialog', 'bookmarkDialog', '#dragBoormark', '#resizeBoormark') 
	
	// MANAGE SEARCH DIALOG BOX
	manageDialogBox('searchTrigger', searchPage, '#contentSearchDialog', 'searchDialog', '#dragSearch', '#resizeSearch') 
	
	// MANAGE SAVESEARCH BOX
	confirmSaveSearch() 
	
	// MANAGE LOGOUT BOX 
	confirmDialog();
	
	confirmNotLogged();
	

   // HOVER EFFECT ON CLOSE BUTTONS FOR MODAL DIALOG BOXES
   $('input.jqmdX').hover(
    		function(){ $(this).addClass('jqmdXFocus'); }, 
    		function(){ $(this).removeClass('jqmdXFocus'); })
  				  .focus( 
    		function(){ this.hideFocus=true; $(this).addClass('jqmdXFocus'); })
  				  .blur( 
    		function(){ $(this).removeClass('jqmdXFocus'); }
	);

});