var mySimpleDialog;
var mySimpleVerify;
var myOnlineDetailsDialog;
var confirmVal;
var confirmed;
var aLink;
var wait;
var defaultButtons;
window.realAlert = window.alert;
if(document.getElementById) {
		window.alert = function(title,txt){
              createCustomAlert(title,txt);
        }
}
function verify(title,txt,aref){
		aLink = aref;
       createCustomVerify(title,txt);
}
function doNothing(){}
function createCustomAlert(title,txt) {
    if (!txt) {
        // this check has to be here 'cause it is pretty much a bad idea to override
        // a language level api and change the signature, so when apis (like a4j) call
        // alert('somethig bad happened'), they don't break
        realAlert(title);
        return;
    }

	mySimpleDialog.setHeader(title);
	mySimpleDialog.setBody(txt);
	mySimpleDialog.show();

}

function createCustomVerify(title,txt) {
	confirmVal = false;
	mySimpleVerify.setHeader(title);
	mySimpleVerify.setBody(txt);
	mySimpleVerify.configButtons("buttons", [defaultButtons], mySimpleVerify);
	mySimpleVerify.show();

}

var handleVerify = function(){
   this.hide();
   confirmed = true;
   confirmVal = true;
   var linkList = getElementsByClass('control-link',null,'a');
   for(var i = 0; i < linkList.length; i++){
      var linkId = '' + linkList[i].onclick;
      if(linkId.indexOf(aLink) > -1){
          linkList[i].onclick();
          break;
      }
   }
}
var handleDecline = function(){
   this.hide();
   confirmed = true;
}
var handleOk = function() {   
   this.hide();   
 }
 
 function initVerify(){
	 defaultButtons = [ {text:"I Understand", handler:handleVerify},{text:"Decline", handler:handleDecline} ];
	 confirmed = false;
		mySimpleVerify = new YAHOO.widget.SimpleDialog("vfy", {
		 fixedcenter:true,
		 modal:true,
		 visible:false,
		 draggable:false,
		 close:false,
		 width:"300px",
		 buttons: defaultButtons
	});
	mySimpleVerify.setHeader("Oops!!");
	mySimpleVerify.setBody('Alert body passed to window.alert');
	mySimpleVerify.render(document.body);
}
function initPopup(){
		mySimpleDialog = new YAHOO.widget.SimpleDialog("dlg", {
			fixedcenter:true,
			modal:true,
			visible:false,
			draggable:false,
			close:false,
			width:"400px",
			buttons: [ {text:"Ok", handler:handleOk} ]
	});

	mySimpleDialog.setHeader("Oops!!");
	mySimpleDialog.setBody('Alert body passed to window.alert');
	mySimpleDialog.render(document.body);
}
function createLoadingPopup(){
	wait = new YAHOO.widget.Panel("wait",
				{width:"240px",
				  fixedcenter:true,
				  close:false,
				  draggable:false,
				  zindex:4,
				  modal:true,
				  visible:false
				}
			);

	wait.setHeader('Searching Database.....');
	wait.setBody('<img src="/express/images/ajax-loader.gif" />');
	wait.render(document.body);
}
function createOnlineDetailsDialog() {
	myOnlineDetailsDialog = new YAHOO.widget.SimpleDialog("onlineDetails",
				{
					fixedcenter:true,
					close:true,
					draggable:false,
					zindex:4,
					modal:true,
					visible:false
				}
			);

	myOnlineDetailsDialog.setHeader('Details');
	myOnlineDetailsDialog.render(document.body);
}


/**
    cal search js functions
*/

var com = com || {};
com.resmark = com.resmark || {};
com.resmark.searchResultMessages = {};
com.resmark.waitDisabled = false;

com.resmark.showActivityDetails = function (detailsUrl) {
	var bd = '<iframe width="800px" height="650px" src="http://' + detailsUrl + '"/>';
	myOnlineDetailsDialog.setBody(bd);
	myOnlineDetailsDialog.show();
}

com.resmark.disableWaitDialog = function ()
{
	com.resmark.waitDisabled = true;
	wait.hide();
};

com.resmark.enableWaitDialog = function ()
{
	com.resmark.waitDisabled = false;
};

/**
    Alias for $(elementId) that is provided so that jsf's don't flip out
    when you call $(someElementId) 'cause it is trying to do macro replacement.
*/
com.resmark.byId = function (elementId)
{
    return $(elementId);
};

/**
    void showActivity()
    Hides the leftPanelContainer and the searchGroupContainer
    and shows the requestedResultContainer.
*/
com.resmark.showActivity = function ()
{
    //var inputContainer     = $('calendarSearchInput');
    var inputContainer     = $('leftPanelContainer');
    var searchContainer    = $('searchGroupContainer');
    var requestedResult    = $('requestedResultContainer');
	var continueContainer  = $('bottomContinueContainer');
    
    if (searchContainer && requestedResult)
    {
        inputContainer.hide();
        searchContainer.hide();
		continueContainer.hide();
        requestedResult.show();
    }
};

/**
    void hideActivity()
    Shows the leftPanelContainer and the searchGroupContainer
    and hides the requestedResultContainer.
*/
com.resmark.hideActivity = function ()
{
    //var inputContainer     = $('calendarSearchInput');
    var inputContainer     = $('leftPanelContainer');
    var searchContainer    = $('searchGroupContainer');
    var requestedResult    = $('requestedResultContainer');
	var continueContainer  = $('bottomContinueContainer');
    
    if (searchContainer && requestedResult)
    {
        inputContainer.show();
        searchContainer.show();
		continueContainer.show();
        requestedResult.hide();
    }
};


/**
    void showReservationStatus(String searchBracketId, String searchResultId [, String searchResultMessage])
*/
com.resmark.showReservationStatus = function (searchBracketId, searchGroupId, searchResultId, searchResultMessage) {
    
    var messageElement = document.getElementById('reservation_messages');
    if (messageElement)
    {
        searchResultMessage = messageElement.innerHTML;
    }
        
    searchResultMessage = searchResultMessage || '';
    //realAlert('showReservationStatus ' + searchResultId);
    //realAlert('showReservationStatus resultMessage: "' + searchResultMessage + '"');

    if (searchResultMessage.length > 0)
    {
        var elementId = searchBracketId + '_' + searchGroupId + '_' + searchResultId + '_messages';
        var messagePanel = $(elementId);
        if (messagePanel)
        {
            messagePanel.style.display = '';
            messagePanel.innerHTML = searchResultMessage;
            com.resmark.showActivity();
        }
    }
    else
    {
        com.resmark.hideActivity();
    }
};

/**
    void showConfirmDialog(HTMLCheckboxElement checkboxElement, String titleText, String confirmMessage )
    Shows a modal confirmation dialog for the specified activity/launch.
    This dialog is presented to the user, if the user selects a "cancel" type
    option, then the supplied checkbox is un-checked, otherwise it is left alone.
*/
com.resmark.showConfirmDialog = function (checkboxElement, titleText, confirmMessage)
{
     var newButtons = [
         {text:"I Understand", handler:function(){mySimpleVerify.hide();}}, 
         {text:"Decline", handler:function() {checkboxElement.checked = false;mySimpleVerify.hide();}}
     ];

     mySimpleVerify.configButtons("buttons", [newButtons], mySimpleVerify);
     mySimpleVerify.setHeader(titleText);
     mySimpleVerify.setBody(confirmMessage);
     mySimpleVerify.show();
};

com.resmark.hideConfirmDialog = function () {
    mySimpleVerify.hide();
};

/**
    void showWaitMessage(String messageTitle)
    Displays the pleaseWaitMessage for the current page
    with the supplied message title.
*/
com.resmark.showWaitMessage = function (messageTitle)
{
    com.resmark.pleaseWaitMessage.setHeader(messageTitle || 'Please Wait...');
    com.resmark.pleaseWaitMessage.show();
    
};

com.resmark.hideWaitMessage = function ()
{
    com.resmark.pleaseWaitMessage.hide();
}

/**
    void initActivityDialog()
    creates the com.resmark.activityDialog
    and renders the dialog in the document (initially hidden)
*/
com.resmark.initActivityDialog = function () {
    
   com.resmark.pleaseWaitMessage =  
	        new YAHOO.widget.Panel("pleaseWaitMessage",
	            {width:"240px",  
	              fixedcenter:true,  
	              close:false,  
	              draggable:false,  
	              zindex:4, 
	              modal:true, 
	              visible:false 
	            }
	        );
	
	com.resmark.pleaseWaitMessage.setHeader('Expanding Date Range.....');
	com.resmark.pleaseWaitMessage.setBody('<center><img src="/express/images/ajax-loader.gif" /></center>');
    com.resmark.pleaseWaitMessage.render(document.body);

    com.resmark.activityDialog = new YAHOO.widget.SimpleDialog("activityDialog", {
        width:"0px",
        fixedcenter:true,
        modal:true,
        visible:false,
        draggable:false,
        close:false
    });
    
    // listen for the close event so we can restore our "borrowed" element:
    com.resmark.activityDialog.setBody('');
    com.resmark.activityDialog.render(document.body);
    
};

/**
    void scrollDays(String tableId, int delta)
    toggles the visibility of the columns in the first row of the table with the supplied tableId
    to the right/left depending on the value of the supplied parameter delta.
*/
com.resmark.scrollDays = function (tableIdSuffix, params)
{
    var bracketIds = params.bracketIds;
    var paramClone = {};
    Object.extend(paramClone, params);
    $A(bracketIds).each(function (bracketId) {com.resmark.scrollDaysForTable(bracketId + tableIdSuffix, bracketId, params);});
    
    var firstTableId = bracketIds[0] + tableIdSuffix;
    var startDate = com.resmark.getDisplayWindowStart(firstTableId);
    var endDate   = com.resmark.getDisplayWindowEnd(firstTableId);
    // now tell the server we changed the date window:
    new Ajax.Request("scrollOneDay.html", {
        method: 'get',
        parameters: {
                        'delta': params.delta || 0,
                        'startDate': startDate,
                        'endDate' : endDate
                    },
        onSuccess: function(transport) {}
    });
};

com.resmark.scrollDaysForTable = function (tableId, bracketId, params)
{
    params = params || {};
    var delta       = params.delta || 0;
    var myTable     = $(tableId);
    var cellCount   = params.cellCount || 3; // for right now just assume a 3 column table...
    
    var idSuffix = 'Forward';
    var otherIdSuffix = 'Back';
    if (params.delta < 0)
    {
        idSuffix = 'Back';
        otherIdSuffix = 'Forward';
    }
    
    var containerPrefix = bracketId + params.containerName;
    
    var linkContainerId = containerPrefix + idSuffix;
    var htmlLinks = $(linkContainerId).select('a.jsLink');
    var htmlLink = htmlLinks[0];
    
    // here we need to get a hold of the links for the "other" scroll direction.
    // this ensures that if the user clicks all the way to the end of one scroll
    // direction (without clicking the command link), then starts clicking back in
    // the other direction, that the command link is hidden and the html link is shown.
    var otherLinkContainerId = containerPrefix + otherIdSuffix;
    
    //var otherCommandLink = $(otherCommandLinkId) || $(otherCommandLinkId + 'Disabled');
    var otherLinks = $(otherLinkContainerId).select('a.calendarScrollBtn, div.calendarScrollBtn');
    var otherHtmlLink    = $(otherLinkContainerId).select('a.jsLink')[0];
    
    otherHtmlLink.show();
    if (otherLinks)
    {
        otherLinks = otherLinks.without(otherHtmlLink);
        otherLinks.each(function (myLink) {$(myLink).hide();});
    }
    
    if (myTable)
    {
        var myRow = myTable.rows[0];
        var myCells = com.resmark.toTdArray(myRow.cells);
        var firstIndex = com.resmark.getFirstVisibleCell(myCells);
        var startIndex = Math.min(firstIndex + delta, myCells.length - 1);
        startIndex = Math.max(startIndex, 0);
        var endIndex = Math.min(startIndex + cellCount - 1, myCells.length - 1);
        
        //com.resmark.logMessage("startIndex: " + startIndex + ", endIndex: " + endIndex);
        
        // check to see if we need to show the commandLink:
        if (startIndex < 1 || endIndex >= myCells.length - 1)
        {
            var commandLinks = $(linkContainerId).select('a.cmdLink, div.cmdLink');
            if (commandLinks && commandLinks.length > 0) {
                commandLinks[0].show();
            }
            
            htmlLink.hide();
        }
        
        // don't check the first, or last column, they are the ones that have our navigation arrows:'
        for (var i = 0; i < myCells.length; i++)
        {
            var myCell = myCells[i];
            myCell.style.display = (i < startIndex || i > endIndex) ? 'none' : '';
        }
    }

};

/**
    HTMLTDElement[] toTdArray(HTMLTDElement[] targetCells)
    Returns an array just like the supplied targetCells,
    but without the first or last elements in it.
*/
com.resmark.toTdArray = function (targetCells)
{
    var result = [];
    
    var resultIndex = 0;
    for (var i = 1; i < targetCells.length - 1; i++)
    {
        result[resultIndex++] = targetCells[i];
    }
    
    return result;
};

/**

*/
com.resmark.logMessage = function (/* var args signature */)
{
    if (console)
    {
        console.log(arguments);
    }
};

/**
    void getDisplayWindowStart(String tableId)
    Locates the first visible cell inside the specified table,
    and extracts the value of the property "searchdate" from that
    cell.
*/
com.resmark.getDisplayWindowStart = function (tableId) 
{
    var myTable = $(tableId);
    var myRow = myTable.rows[0];
    var myCells = com.resmark.toTdArray(myRow.cells);
    var firstIndex = com.resmark.getFirstVisibleCell(myCells);
    return myCells[firstIndex].getAttribute('searchdate');
};

/**
    void getDisplayWindowEnd(String tableId)
    Locates the last visible cell inside the specified table,
    and extracts the value of the property "searchdate" from that
    cell.
*/
com.resmark.getDisplayWindowEnd = function (tableId) 
{
    var myTable = $(tableId);
    var myRow = myTable.rows[0];
    var myCells = com.resmark.toTdArray(myRow.cells);
    var lastIndex = com.resmark.getLastVisibleCell(myCells);
    return myCells[lastIndex].getAttribute('searchdate');
};


/**
    int getFirstVisibleCell(HTMLTDElement[] myCells)
    returns the first element inside the supplied myCells array that is visible
*/
com.resmark.getFirstVisibleCell = function (myCells)
{
    var myIndex = 0;
    
    for (var i = 0; i < myCells.length; i++)
    {
        var myCell = $(myCells[i]);
        
        if (myCell.visible())
        {
            myIndex = i;
            break;
        }
    }

    return myIndex;
}

com.resmark.getLastVisibleCell = function (myCells)
{
    var myIndex = 0;
    
    for (var i = myCells.length - 1; i >= 0; i--)
    {
        var myCell = $(myCells[i]);
        
        if (myCell.visible())
        {
            myIndex = i;
            break;
        }
    }

    return myIndex;
}


/**
	void updateCheckboxForSelection(HTMLSelectElement selectBox, String activityId, String pleaseNote, String preReservationComments)
	Looks for a checkbox that has a css style activityId-checkbox
	and checks/unchecks it as appropriate.  The checkbox is checked
	if any of the select inputs for the given activityId have a value
	other than 0, it is unchecked if all selects for the given activityId
	have a value of zero.
*/
com.resmark.updateCheckboxForSelection = function (selectBox, activityId, pleaseNote, preReservationComments)
{
	var tableRow = $(selectBox).up('tr');
	var selectBoxes = $(tableRow).select('select.' + activityId + '-select') || [];
	var checkBoxes  = $(tableRow).select('input.' + activityId + '-checkbox') || [];
	var somethingSelected = false;
	
	if (checkBoxes.length > 0)
	{
		for (var i = 0; i < selectBoxes.length; i++)
		{
			var mySelect = selectBoxes[i];
			somethingSelected |= mySelect.value != '0'; 
		}
		
		var wasChecked = false;
		// there should really only be a single checkbox, so, we'll just grab the first one:
		var myCheckbox = checkBoxes[0];
		wasChecked |= myCheckbox.checked;
		myCheckbox.checked = somethingSelected;
		
		if (!wasChecked && somethingSelected && preReservationComments && preReservationComments.length > 0)
		{
			// if we weren't selected and now we are...
			com.resmark.showConfirmDialog(myCheckbox, pleaseNote, preReservationComments);
		}
	}
	
};


YAHOO.util.Event.addListener(window, 'load', com.resmark.initActivityDialog);
 

 YAHOO.util.Event.addListener(window, 'load', initPopup);
 YAHOO.util.Event.addListener(window, 'load', initVerify);
 YAHOO.util.Event.addListener(window, 'load', createLoadingPopup);
 YAHOO.util.Event.addListener(window, 'load', createOnlineDetailsDialog);
 
 
 