/* ------------------------------------------------------------------------ *
 * SAS Institute, Inc.                                                      *
 *                                                                          *
 * Copyright (c) 2003-2007 SAS Institute, Inc.  All rights reserved.             *
 *                                                                          *
 * Contains javascript functions used by com.sas.apps.citation.view.tbeans. *
 * html.CitationButton.java                                                 *
 *                                                                          *
 * Dependencies: citation_events.js                                         *
 * ------------------------------------------------------------------------ */
wrsProvide("citation_button");
wrsRequire("citation",  SCRIPT_DIR, "citation_button");

// use single global since only one button can have mouse in it at one time
var g_overExistingButton = false;

// Constants used to indicate a buttons state
setButtonState.DISABLED = 0;
setButtonState.ROLLOVER = 1;
setButtonState.ROLLOUT  = 2;
setButtonState.ENABLED  = 3;

// cache all button images
var buttonImages = new Array(9);
buttonImages[0] = new Image();
buttonImages[1] = new Image();
buttonImages[2] = new Image();
buttonImages[3] = new Image();
buttonImages[4] = new Image();
buttonImages[5] = new Image();
buttonImages[6] = new Image();
buttonImages[7] = new Image();
buttonImages[8] = new Image();

// This function takes the id for a given button and changes the
//  style features of the button's components based on the value
//  of the 'state' parameter
//
// @parm event - event that caused button change,
//               can be null if state is DISABLED or ENABLED
// @parm buttonId - id of the button object
// @parm state - one of the above button state constants
// @parm styleClassRoot - the root name of the button's style classes;
//                        defaults to 'button' if not specified.
// @parm bStyleChangeOnly - true: that only a style change will be done;
//                          false: button will also be enabled/disabled based on
//                              the state parameter.
//                          The default is false.
// @parm imageRootName - root name of button's center cell image.
//                       Passing 'null' results in default where
//                       button displays no image in its center cell.
function setButtonState(event, buttonId, state, styleClassRoot, bStyleChangeOnly, imageRootName) {
    // local function returns target -- generating element
    function _getEventSource(event) {
        var eventSource = null;
        if (event) {
            if (event.target) { // Standard property
                event.stopPropagation();
                eventSource = event.currentTarget;
            } else if (event.srcElement) { // IE property
                event.cancelBubble = true;
                eventSource = event.srcElement;
            }
        }
        return eventSource;
    }    
    var button = document.getElementById(buttonId);
    if (button == null) {
        return;
    // Button.type only works on IE.
    // Button instanceof HTMLElement) is DOM standard but generates error on IE.
    } else if (button.type && button.type == 'button') {
        if (state == setButtonState.DISABLED) {
            imageType = 'inactive';
            button.disabled = true;
            cursorUpdate = setAutoCursor;
            // remove hover color if on
           	button.className = button.className.replace(/ buttonHover/, "");
            if (button.className.indexOf('Disabled') == -1) {
	            button.className = button.className + "Disabled";
	        }
        } else {
            imageType = 'default';
            button.disabled = false;
            cursorUpdate = setSelectionCursor;
            // remove Disabled part of className to make it enabled
           	button.className = button.className.replace(/Disabled/, "");
        }

        if (imageRootName != null) {
            var imageDoc = document.getElementById('img_' + button.id + '_c' );
            if (imageDoc != null) {
                imageDoc.src = IMAGE_DIR + imageRootName  + '_' + imageType + '.gif';
            }
        }
        cursorUpdate(button);
        return;
    } else if( button.cweb_state == null || button.cweb_state != state ) {
        button.cweb_state = state;
    } else if (bStyleChangeOnly) { 
        return;
    }
    if (state == setButtonState.DISABLED || state == setButtonState.ENABLED) {
        g_overExistingButton = false;
    }
    if (g_overExistingButton) {
        if (state == setButtonState.ROLLOVER) {
            return;
        } else if (state == setButtonState.ROLLOUT) {
            // check to make sure we are not still inside button for IE
            if (event != null && event.toElement) {
                if (! button.contains(event.toElement)
                    && event.toElement.id != _getEventSource(event)) {
                    g_overExistingButton = false;
                } else {
                    return;
                }
            }
        }
    } else {
        if (state == setButtonState.ROLLOVER) {
            g_overExistingButton = true;
        }
    }
    var classNameRoot = ( styleClassRoot != null ) ? styleClassRoot : 'button';

    var cursorUpdate = setSelectionCursor;
    var imageType = 'default';

    if( state == setButtonState.ROLLOVER ) {
        imageType = 'rollover';
    }
    else if( state == setButtonState.DISABLED ) {
        imageType = 'inactive';
        cursorUpdate = setAutoCursor;
    }

    var buttonText = document.getElementById(button.id + '_textObj');
    if( buttonText != null && buttonText.className != null )
    {
        buttonText.className = classNameRoot + '_text_' + imageType; //Update style of span el that wraps the button's text
    }

    var ctrCell = document.getElementById(button.id + '_c');
    if( ctrCell != null ) {

        ctrCell.className= classNameRoot + '_center_cell_' + imageType;

        if( imageRootName != null )
        {
            var ctrCellImg = document.getElementById('img_' + button.id + '_c' );
            ctrCellImg.src = IMAGE_DIR + imageRootName  + '_' + imageType + '.gif';
        }

    }

    cursorUpdate(button);
    cursorUpdate( document.getElementById( button.id + '_coreButton') );

    var westCell = document.getElementById(button.id + '_w');
    if( westCell != null && westCell.className != null) {
        westCell.className = classNameRoot + '_left_cell_' + imageType ;
    }

    var westCellImg = document.getElementById('img_' + button.id + '_w');
    if( westCellImg != null ) {
        westCellImg.src = IMAGE_DIR + classNameRoot + '_left_' + imageType + '.gif';
    }

    var eastCell = document.getElementById(button.id + '_e');
    if( eastCell != null && eastCell.className != null) {
        eastCell.className = classNameRoot + '_right_cell_' + imageType ;
    }

    var eastCellImg = document.getElementById('img_' + button.id + '_e');
    if( eastCellImg != null ) {
        eastCellImg.src = IMAGE_DIR + classNameRoot + '_right_' + imageType + '.gif';
    }
    if( !bStyleChangeOnly ) {
        // enable/disable the button based on state
        if (button.setEnabled) {
            button.setEnabled( (state != setButtonState.DISABLED) );
        } else {
            button.disabled = (state == setButtonState.DISABLED);
        }
    }
}
// -----------------------------------------------------------
// Preloading images for buttons.
// Helper function to generate names and pre-load images for
// typical button cells that contain images for rollover effects.
// 
var g_preloadedButtomImages = new Object();
//
// Name formed is imageDirectory_imageRootName_variants_imageType.gif
//
// loadWhich: 0 = only the "main" image; 
//            1 = only the center, left, right
//            2 = include all four
function preloadButtonImages(imageRootName, imageType, loadWhich) 
{
    if (null == imageType)
    {
        imageType = "default";
    }
    if (null == loadWhich)
    {
        loadWhich = 2;
    }
    var cell = String(imageRootName + imageType).replace("/","_");
    if (loadWhich == 0 || loadWhich == 2)
    {
        g_preloadedButtomImages[cell] = new Image();
        g_preloadedButtomImages[cell].src = IMAGE_DIR + imageRootName  +  '_'  + imageType + '.gif';
        // showDebugMsgs("preloadImages", cell + " = " + g_preloadedButtomImages[cell].src);
    }        
    if (loadWhich == 1 || loadWhich == 2)
    {            
	    var ctrCell = String(imageRootName + imageType + '_c').replace("/","_");
	    g_preloadedButtomImages[ctrCell] = new Image();
	    g_preloadedButtomImages[ctrCell].src = IMAGE_DIR + imageRootName  +  '_center_'  + imageType + '.gif';
	    // showDebugMsgs("preloadImages", ctrCell + " = " + g_preloadedButtomImages[ctrCell].src);
	    
	    var westCellImg = String(imageRootName + imageType + '_w').replace("/","_");
	    g_preloadedButtomImages[westCellImg] = new Image();    
	    g_preloadedButtomImages[westCellImg].src = IMAGE_DIR + imageRootName + '_left_' + imageType + '.gif';
	    // showDebugMsgs("preloadImages", westCellImg + " = " + g_preloadedButtomImages[westCellImg].src);
	
	    var eastCellImg = String(imageRootName + imageType + '_e').replace("/","_");
	    g_preloadedButtomImages[eastCellImg] = new Image();    
	    g_preloadedButtomImages[eastCellImg].src = IMAGE_DIR + imageRootName + '_right_' + imageType + '.gif';
	    // showDebugMsgs("preloadImages", eastCellImg + " = " + g_preloadedButtomImages[eastCellImg].src);
    }    
}

// -----------------------------------------------------------------------------
// Class used to enable/disable a button based on the presence of text in a
// textEntry or textArea. Currently used for the search button in Choose Report
// and the save button in the save dialog.
// -----------------------------------------------------------------------------
EnableButtonBasedOnTextFieldListener.prototype.textField = null;
EnableButtonBasedOnTextFieldListener.prototype.button = null;
EnableButtonBasedOnTextFieldListener.prototype._isWhitespaceStringAllowed = true;

EnableButtonBasedOnTextFieldListener.prototype.isWhitespaceStringAllowed = function()
{
    return this._isWhitespaceStringAllowed;
}

EnableButtonBasedOnTextFieldListener.prototype.setWhitespaceStringAllowed = function(isWhitespaceStringAllowed)
{
    this._isWhitespaceStringAllowed = isWhitespaceStringAllowed;
}

EnableButtonBasedOnTextFieldListener.prototype.getBaseImage = function()
{
	return this.baseImage;
}

EnableButtonBasedOnTextFieldListener.prototype.setBaseImage = function(baseImage)
{
	this.baseImage = baseImage;
}

EnableButtonBasedOnTextFieldListener.prototype.isEmptyText = function(testText)
{
    var retval = (testText == null
                    || testText.length < 1
                    || (!this.isWhitespaceStringAllowed() && testText.match(/^\s*$/)) );
    return retval;
}

// -----------------------------------------------------------------------------
// Return true if the text field value has or will become empty in response
// to the event.
// @param event - optional event parameter; if null the return value will be
//                based on the text field's current value.
EnableButtonBasedOnTextFieldListener.prototype.isTextFieldEmptyBasedOnEvent = function(event)
{
    var retval = false;
    if( event != null )
    {
        if( isPasteEvent != null && isPasteEvent(event) ) {
            //alert('handling paste');
            if(window.clipboardData)	{ 	// Is IE?
            	var strPasteData = window.clipboardData.getData('Text');
            	retval = !this.isEmptyText(strPasteData);
			}
			// TODO: handle in Firefox - see ProhibitedCharacterListener in citation_event.js for possible way
        }
        else if( isCutEvent != null && isCutEvent(event)) {
            //alert('handling cut');
            if (document.selection && document.selection.createRange) {
            	var selectedText = document.selection.createRange()
            	retval = (selectedText.text != this.textField.value);
			}
			//TODO: handle for Firefox
        }
        else {
          retval = !this.isEmptyText(this.textField.value);
        }
    }
    else
    {
        retval = !this.isEmptyText(this.textField.value);
    }
    return retval;
}

EnableButtonBasedOnTextFieldListener.prototype.handleEvent = function(event)
{
    var bEnable = this.isTextFieldEmptyBasedOnEvent(event)
    var buttonState = (bEnable ? setButtonState.ENABLED : setButtonState.DISABLED);
    if (this.baseImage == null) {
	    setButtonState(event,this.button.id, buttonState );
	}
	else { // button has an image - switch gifs as well as state
		setButtonState(event,this.button.id, buttonState, 'button', false, this.baseImage);
	}
}
EnableButtonBasedOnTextFieldListener.prototype.initialize = function ()
{
    registerEventHandler( this.textField, 'keyup', this, false );
    registerEventHandler( this.textField, 'change', this, false );
    registerEventHandler( this.textField, 'blur', this, false );
    registerEventHandler( this.textField, 'paste', this, false );
    registerEventHandler( this.textField, 'cut', this, false );
    this.handleEvent(); //set initial state of button
}
function EnableButtonBasedOnTextFieldListener(textField, button)
{
    this.textField = textField;
    this.button = button;
    this.setWhitespaceStringAllowed(true);
    this.baseImage = null;
}

// -------------------------------------------------------------------------
// Expand/Collapse button hides or shows an area based on toggled state
//
function ExpandCollapseToggle(buttonId, areaId, expandedImage, collapsedImage, expandedText, collapsedText)
{
    this.buttonId = buttonId;
    this.areaId = areaId;
    this.expandedImage = expandedImage;
    this.collapsedImage = collapsedImage;
    this.expandedText = expandedText;
    this.collapsedText = collapsedText;
    this.hideOnlyNoCollapse = false;
    var button = findDOM(this.buttonId);
    var area = findDOM(this.areaId);
    if (area && button) {	// set initial tooltips
	    var viz = area.style.visibility;
    	if (viz == "hidden") {
    		area.style.display = "none";	// needed for IE
        	button.alt = this.collapsedText;           
	        button.title = this.collapsedText;
            if (this.collapsedImage != '')
      	       button.src = this.collapsedImage;
    	}
    	else {	// assume visible (expanded)
    		area.style.display = "block";
	        button.alt = this.expandedText;
    	    button.title = this.expandedText;
            if (this.expandedImage != '')
          	   button.src = this.expandedImage; 
    	}
    }
}
ExpandCollapseToggle.prototype.setHideOnly = function (hideOnly)
{
   this.hideOnlyNoCollapse = hideOnly;
}
ExpandCollapseToggle.prototype.getHideOnly = function ()
{
   return(this.hideOnlyNoCollapse);
}
ExpandCollapseToggle.prototype.toggle = function(event, button, notifyUrl)
{
    showDebugMsgs("toggle", this.buttonId + " " + this.areaId + " " + notifyUrl + " " + button.id);
    if (!button || button.id != this.buttonId){
        showDebugMsgs("toggle", "button in error");
        return;
    }

    if (notifyUrl) 
    {
      // for design mode layout mouse event calculations
      // only ExpandCollapses with a notifyUrl seem to use this
       dojo.io.bind({
         method: "POST",
         transport: "XMLHTTPTransport",
         url: notifyUrl + "?session=required",
         preventCache: true,
         error: function (type, data, evt) {
                     showDebugMsgs("ERROR: toggleSidePane", 
                        "ERROR Returned from expand/collapse call." + data);
                },
         load: function (type, data, evt) { 
                     showDebugMsgs("toggleSidePane", "Successful return from expand/collapse call.");
                 }         
         });          
    }

    var area = findDOM(this.areaId);
    var viz = area.style.visibility;
    if (viz == "hidden") {
        area.style.visibility = "visible";
        area.style.display = "block";
        button.alt = this.expandedText;
        button.title = this.expandedText;
        if (this.expandedImage != '')
           button.src = this.expandedImage; 
    } else if (viz == "visible" || viz == "") {
        area.style.visibility = "hidden";
        area.style.display = this.hideOnlyNoCollapse ? "block" : "none";
        button.alt = this.collapsedText;           
        button.title = this.collapsedText;
        if (this.collapsedImage != '')
           button.src = this.collapsedImage;
    } else {
        alert("Internal error: invalid style on toggled area.");
    }
	if (notifyUrl) {
	   // for design mode layout mouse event calculations
	   // only ExpandCollapses with a notifyUrl seem to use this
	   if (window.WrsEdit.layout.generateGridDropZones) {
	      WrsEdit.layout.generateGridDropZones(event, "paneClick", false);
	   }
   	}
};
