// Copyright (C) 1997-2004 Alias Systems Corp.
// 
// The information in this file is provided for the exclusive use of the
// licensees of Alias.  Such users have the right to use, modify,
// and incorporate this code into other products for purposes authorized
// by the Alias license agreement, without fee.
// 
// ALIAS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
// INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
// EVENT SHALL ALIAS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
// CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
// DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

//
// Script:    texturePanel.mel
//
// SYNOPSIS
//		Creates a panel that contains the texture window
//

// The string prepended to the name of all controls that appear in
// the menubar (as opposed to the pop up menu)
//
global string $gTextureEditorMenubarPrefix = "M";
global int $gTextureEditorPopupType = 0;

global proc texturePanel(string $panelName) 
//
// Description:
//		Create a new scripted panel for the texture window
// Arguments:
//
// Returns:
//
//
{
	global string $gMainPane;

	if (!`scriptedPanelType -exists polyTexturePlacementPanel`) {
		scriptedPanelType
			-unique true
			-createCallback "createTextureWindow" 
			-addCallback "addTextureWindow" 
			-removeCallback "removeTextureWindow" 
			polyTexturePlacementPanel;

		setParent $gMainPane;
		scriptedPanel -unParent -type "polyTexturePlacementPanel" $panelName;
	}
}

global proc createTextureWindow(string $whichPanel)
//
// Description:
//		Create the window in the panel
// Arguments:
//
// Returns:
//
//
{
    textureWindow -unParent $whichPanel;
}

global proc txtWndUpdateEditor(string $editor, string $editorCmd, string $updatFunc, int $reason)
//
// Description:
//		Update menu items based on current state of texture window
//		options. 
//
//		This proc should also be registered as the textureWindow's change
//		command (by calling: "textureWindow -e -cc " with the appropriate
//		parms). It is for this reason that an updateFunc and reason param
//		are included.
//
// 		This proc is explicitly called from all menuItems and
//		buttons that modify the state of another menuItem or button
//		(e.g. the toggleGridButton modifies the state of the Grid menuItem)
//		The default reason 101 is given so as not to conflict with any
//		textureWindow specific reasons (see docs for a brief explanation).
//
// Arguments:
//
// Returns:
//
// Notes:
//		hmmm $updateFunc is never used ?
//
{
	global string $gTextureEditorMenubarPrefix;

	string $popupPrefix = $editor;
	string $menubarPrefix = ($gTextureEditorMenubarPrefix + $editor);

	// update texture items
	//
	if ( $reason == 101 ) {
		// update image display menu item
		//
		int $drawImage = eval ($editorCmd +" -q -imageDisplay "+ $editor) ;
		menuItem -e -cb  $drawImage ($popupPrefix+"ImageDisplay") ;
		menuItem -e -cb  $drawImage ($menubarPrefix+"ImageDisplay") ;
		iconTextCheckBox -e -value $drawImage imageDisplayButton;

		// update image dimming menu item
		//
		float $color[] = eval ($editorCmd +" -q -imageBaseColor "+ $editor) ;
		int $dimmed = ($color[0] < 0.99);
		menuItem -e -cb  $dimmed ($popupPrefix+"DimImage") ;
		menuItem -e -cb  $dimmed ($menubarPrefix+"DimImage") ;
		iconTextCheckBox -e -value $dimmed dimmerButton;

		// update editor image display menu items and icone
		//
		int $drawEditorImage = `optionVar -q displayEditorImage`;
		menuItem -e -cb  $drawEditorImage ($popupPrefix+"DisplayEditorImage") ;
		menuItem -e -cb  $drawEditorImage ($menubarPrefix+"DisplayEditorImage") ;
		iconTextCheckBox -e -value $drawEditorImage editorImageDisplayButton;

		//showUVImageButton -e -value 0; // update toolbar

		int $flag = eval ($editorCmd +" -q -iuf "+ $editor) ;
		menuItem -e -cb  $flag ($popupPrefix+"ImageUnfiltered") ;
		menuItem -e -cb  $flag ($menubarPrefix+"ImageUnfiltered") ;
		iconTextCheckBox -e -value $flag filteredButton;

		$flag = eval ($editorCmd +" -q -imr "+ $editor) ;
		menuItem -e -cb  $flag ($popupPrefix+"ImageRatio") ;
		menuItem -e -cb  $flag ($menubarPrefix+"ImageRatio") ;
		iconTextCheckBox -e -value $flag ratioButton;

		$flag = eval ($editorCmd +" -q -ip "+ $editor) ;
		menuItem -e -cb  $flag ($popupPrefix+"ImageSnap") ;
		menuItem -e -cb  $flag ($menubarPrefix+"ImageSnap") ;
		iconTextCheckBox -e -value $flag pixelSnapButton;

		// update grid settings menu item
		//
		int $drawGrid = eval ($editorCmd +" -q -tgl "+ $editor) ;
		menuItem -e -cb  $drawGrid ($popupPrefix+"toggleGrid") ;
		menuItem -e -cb  $drawGrid ($menubarPrefix+"toggleGrid") ;
		iconTextCheckBox -e -value $drawGrid gridDisplayButton;
		
		// showUVGridButton -e -value 0; // update toolbar
		
		// update Toolbar menuItem
		//
		int $showToolbar = (!`optionVar -q textureEditorToolbarState`);
		menuItem -e -cb $showToolbar ($popupPrefix+"toggleToolbar");
		menuItem -e -cb $showToolbar ($menubarPrefix+"toggleToolbar");

		// update "contained faces" menu item
		//
		int $selectContained = eval($editorCmd + " -q -internalFaces " + $editor);
		menuItem -e -cb $selectContained ($popupPrefix+"containedFacesItem");
		menuItem -e -cb $selectContained ($menubarPrefix+"containedFacesItem");
		if ( $selectContained ) {
			optionVar -iv textureWindowShaderFacesMode 0;
		}			

		// update "connected faces" menu item
		//
		int $selectConnected = eval($editorCmd + " -q -relatedFaces " + $editor);
		menuItem -e -cb $selectConnected ($popupPrefix+"connectedFacesItem");
		menuItem -e -cb $selectConnected ($menubarPrefix+"connectedFacesItem");
		if ($selectConnected) {
			optionVar -iv textureWindowShaderFacesMode 0;
		}			

		// update "shader faces" menu item
		//
		int $useFaceGroup = eval($editorCmd + " -q -useFaceGroup " + $editor);
		int $selectShader = `optionVar -q textureWindowShaderFacesMode`;
		int $shaderFacesVal = 0;
		int $isolateViewVal = 0;

		if (0 == $useFaceGroup && 0 == $selectShader)
		{
			$shaderFacesVal = 0;
			$isolateViewVal = 0;
		}
		else
		{
			if (1 == $useFaceGroup && 0 == $selectShader)
			{
				$shaderFacesVal = 0;
				$isolateViewVal = 0;
			}
			if ( 1 == $useFaceGroup && 1 == $selectShader)
			{
				$shaderFacesVal = 1;
				$isolateViewVal = 0;
				int $shaderIndex = textureWindowFindActiveShader($editor);
				if (0 != $shaderIndex) 
					textureWindowSelectImage($shaderIndex-1, $editor);
			}
			if ( 1 == $useFaceGroup && 2 == $selectShader)
			{
				$shaderFacesVal = 0;
				$isolateViewVal = 1;
			}
		}
		menuItem -edit -checkBox $shaderFacesVal 
			($popupPrefix+"shaderFacesItem");
		menuItem -edit -checkBox $shaderFacesVal 
			($menubarPrefix+"shaderFacesItem");
		menuItem -edit -checkBox $isolateViewVal 
			($popupPrefix+"isolateViewItem");
		menuItem -edit -checkBox $isolateViewVal 
			($menubarPrefix+"isolateViewItem");
		iconTextCheckBox -edit -value $isolateViewVal isolateSelectButton;
	}
}

global proc addTextureWindow(string $whichPanel)
//
// Description:
//		Add the texture window + menus to the panel
// Arguments:
//
// Returns:
//
//
{
	//
	// Build Menubar.
	//
	textureWindowCreateMenubar($whichPanel, "textureWindow");

	string $formName = `formLayout`;

	// Add in toolbar UI
	// Create new frame and form

    if (!`optionVar -exists textureEditorToolbarState`) 
		optionVar -iv "textureEditorToolbarState" 0;
    int $toolBarState = `optionVar -q textureEditorToolbarState`;

    string $toolBar = `frameLayout
        -visible true
        -borderVisible false
        -collapsable true
		-labelVisible false
        -collapse $toolBarState
        textureEditorToolbarFrameLayout`;

		string $toolForm = `formLayout -visible true`;
		textureWindowCreateToolBar ($toolForm, $whichPanel, "textureWindow");
		setParent -m ..;
	setParent -m ..;	

	// Attach the editor to the UI
	textureWindow -e -parent $formName $whichPanel;

	string $textureEditorControl = `textureWindow -query -control $whichPanel`;

	// Add a popup marking menu and a popup version of the menubar
	//
	string $popupPostMenuCmd = "textureWindowUpdatePopup( \"";
	$popupPostMenuCmd += $whichPanel+"popupMenus\", \"";
	$popupPostMenuCmd += $whichPanel+"\", \"";
	$popupPostMenuCmd += "textureWindow\")";
	popupMenu -parent $textureEditorControl -mm true -b 3 -aob true -pmc $popupPostMenuCmd ($whichPanel+"popupMenus");
	textureWindowCreatePopupRadialMenu( $whichPanel, "textureWindow", 0 );
	textureWindowCreatePopupMenubar( $whichPanel, "textureWindow" );
	setParent -m ..;


	// Add a popup marking menu for the (SHIFT) modified click to access
	// quick selection conversion tools
	//
	//popupMenu -parent $textureEditorControl -mm true -sh true -b 3 -aob true ($whichPanel + "popupMenusShift");
	//textureWindowCreatePopupContextMenu($whichPanel, "textureWindow");
	//setParent -m ..;

	string $contextMenuName = ($whichPanel + "popupMenusShift");
	if (!`popupMenu -exists $contextMenuName`) {
		popupMenu -parent $textureEditorControl -aob true $contextMenuName;
		string $buildCommandMM = "textureWindowCreatePopupContextMenu";

		popupMenu -edit
			-markingMenu true 
			-ctrlModifier false
			-shiftModifier true
			-button 3 
			-postMenuCommand ($buildCommandMM + " \"" + $contextMenuName + "\"")
			$contextMenuName;
	}
	setParent -m ..;

	// Add a popup marking menu for the (CTRL) modified click to access
	// quick selection conversion tools
	//
	popupMenu -parent $textureEditorControl -mm true -ctl true -b 3 -aob true ($whichPanel+"popupMenusCtl");
	textureWindowCreatePopupConvertMenu($whichPanel, "textureWindow");
	setParent -m ..;

	//	 Constraints
	formLayout -e 
		-attachForm $toolBar top 0
		-attachForm $toolBar right 0
		-attachForm $toolBar left 0

		-attachControl $whichPanel top 0 $toolBar
		-af $whichPanel "top" 0
		-af $whichPanel "right" 0
		-af $whichPanel "left" 0
		-ap $whichPanel "bottom"  0 100 

		$formName;
	//setParent -m ..;

	//
	// If any changes goto update
	//
	textureWindow -e 
		-cc "txtWndUpdateEditor" $whichPanel
		"textureWindow" "null"
		$whichPanel;

	txtWndUpdateEditor($whichPanel,"textureWindow","null",101);

	//
	// change grid
	//
	if (`exists performTextureViewGridOptions`)
		performTextureViewGridOptions 0;

	// Change image range
	if (`exists performTextureViewImageRangeOptions`)
		performTextureViewImageRangeOptions 0;
		
	// Change texture bake
	if (`exists performTextureViewBakeTextureOptions`)
		performTextureViewBakeTextureOptions 0;
		
	// Change to baked texture mode to user's last pref
	if ( `optionVar -exists displayEditorImage` )
    {
        int $display = `optionVar -q displayEditorImage`;
        if ($display == 1)
            textureWindow -e -vpi 0 $whichPanel;
        else
            textureWindow -e -vpi 1 $whichPanel;
    }
        	
}

global proc removeTextureWindow(string $whichPanel)
//
// Description:
//		Remove window from panel
// Arguments:
//
// Returns:
//
//
{
    textureWindow -e -unParent $whichPanel;
}

global proc updateTextureWindow(int $reason)
//
// Description:
//		Update texture window (unused ?)
// Arguments:
//
// Returns:
//
//
{;}

//////////////////////////////////////////////////////////////////////
// Popup menu and menubar routines
//////////////////////////////////////////////////////////////////////

// Utility method
//
global proc txtWndShapesFromSelList(string $shapes[])
{
	// Counter to maintain current insertion point for new shapes
	//
	int $shapeCount = 0;
	
	// Loop through selection list *and* hilite list for shapes.
	//
	string $selList[] = `ls -l -sl`;
	string $hiliteList[] = `ls -l -hl`;
	$selList = stringArrayCatenate( $selList, $hiliteList );
	$selList = stringArrayRemoveDuplicates( $selList );

	int $i;
	for( $i = 0; $i < size($selList); $i++ )
	{
		// Determine object type
		//
		string $object = $selList[$i];
		string $type = `objectType $object`;

		string $tmpShapes[];
		int $nShapes = 0;
		if( $type == "transform" )
		{
			// Get all children that are shapes of the transform
			//
			$tmpShapes = `listRelatives -f -ad -typ "shape" $object`;
			$nShapes = size($tmpShapes);
		}
		else
		{
			// If it is not a transform, we assume it to be a shape.
			//
			$tmpShapes[0] = $object;
			$nShapes = 1;
		}

		// Append the list of shapes obtained from this object to our return
		// value
		//
		int $j;
		for( $j = 0; $j < $nShapes; $j++ )
		{
			$shapes[$shapeCount] = $tmpShapes[$j];
			$shapeCount++;
		}
	}
}

global proc txtWndSelectedTypes( int $selectedTypes[] )
//
//	Description:
//		Returns (3) booleans of what types have been selected. The integer array
//	parameter serves as the output array of booleans. The meaning of each element
//	is as follows:
//
//	$selectedType[0] == "A Poly is selected"
//	$selectedType[1] == "A NURBS is selected"
//	$selectedType[2] == "A Subdiv is selected"
//
{
	string $shapes[];
	txtWndShapesFromSelList( $shapes );

	int $polySelected = 0;
	int $nurbsSelected = 0;
	int $subdivSelected = 0;
	int $i = 0;
	int $nShapes = size($shapes);
	for( $i = 0; $i < $nShapes; $i++ )
	{
		string $type = `objectType $shapes[$i]`;
		if( $type == "mesh" )
		{
			$polySelected = 1;
		}
		else if( $type == "nurbsSurface" )
		{
			$nurbsSelected = 1;
		}
		else if( $type == "subdiv" )
		{
			$subdivSelected = 1;
		}
	}

	$selectedTypes[0] = $polySelected;
	$selectedTypes[1] = $nurbsSelected;
	$selectedTypes[2] = $subdivSelected;
}

global proc txtWndRelFacesMode(string $editor, string $editorCmd, int $internal)
//
// Description:
//		Set face selection filter modes
// Arguments:
//
// Returns:
//
//
{
	int	$state;
	if ($internal)
	{
		$state = eval( $editorCmd + " -q -internalFaces " + $editor );
		if ($state == 0){
			eval ( $editorCmd + " -e -if 1 "+$editor );
		}
		else
		{
			eval ( $editorCmd + " -e -if 0 "+$editor);
	}
	}
	else
	{
		$state = eval( $editorCmd + " -q -relatedFaces " + $editor );
		if ($state == 0){
			eval ( $editorCmd + " -e -rf 1 "+$editor );
		}
		else
		{
			eval ( $editorCmd + " -e -rf 0 "+$editor);
	}
}
}

global proc textureWindowShaderFacesMode(string $editor, 
										 string $editorCmd, 
										 int $isolate)
//
// Description:
//		Set shaderFacesMode
// Arguments:
//
// Returns:
//
//
{
	int $viewState = `optionVar -q textureWindowShaderFacesMode`;
	//0 off
	//1 view shaders
	//2 view isolate

	if ($isolate){
		if ($viewState != 2){
			optionVar -iv textureWindowShaderFacesMode 2;
			eval ( $editorCmd + " -e -useFaceGroup 1 "+$editor );
		}
		else 
		{
			optionVar -iv textureWindowShaderFacesMode 0;
			eval ( $editorCmd + " -e -useFaceGroup 0 "+$editor);
		}
	}
	else
	{
		if ($viewState != 1){
			optionVar -iv textureWindowShaderFacesMode 1;
		eval ( $editorCmd + " -e -useFaceGroup 1 "+$editor );
		}
	else
		{
			optionVar -iv textureWindowShaderFacesMode 0;
		eval ( $editorCmd + " -e -useFaceGroup 0 "+$editor);
}
	}
	// force texture window update since both modes here use the 
	// useFaceGroup flag
	txtWndUpdateEditor($editor, $editorCmd, "Thanks Jey, for showing me the way!", 101);
}


global proc textureWindowToggleTextureImage(string $editor, string $editorCmd)
//
// Description:
//		Toggle image display for the texture window
// Arguments:
//
// Returns:
//
//
{
	int $draw = eval ( $editorCmd +" -q -imageDisplay "+ $editor ) ;
	if ($draw == 0) {
//		if ( `optionVar -exists displayEditorImage` && `optionVar -q displayEditorImage` ) {
//	        textureWindow -e -vpi 0 $editor;
//		}
		eval( $editorCmd +" -e -imageDisplay 1 " + $editor ) ;
	}
	else {
		eval( $editorCmd +" -e -imageDisplay 0 " + $editor ) ;
	}
}

global proc textureWindowToggleImageDimming(string $editor, string $editorCmd)
//
// Description:
//		Toggle image dimming for the texture window
// Arguments:
//
// Returns:
//
//
{
	float $color[] = eval ( $editorCmd +" -q -imageBaseColor "+ $editor ) ;
	if ($color[0] > 0.99) {
		eval( $editorCmd +" -e -imageBaseColor 0.5 0.5 0.5 " + $editor ) ;
	}
	else {
		eval( $editorCmd +" -e -imageBaseColor 1.0 1.0 1.0 " + $editor ) ;
	}
}

global proc textureWindowToggleUnfiltered(string $editor, string $editorCmd)
{
	int $unfiltered = eval ( $editorCmd +" -q -iuf "+ $editor ) ;
	if ($unfiltered == 0) {
		eval( $editorCmd +" -e -iuf 1 " + $editor ) ;
	}
	else {
		eval( $editorCmd +" -e -iuf 0 " + $editor ) ;
	}
}

global proc textureWindowToggleRatio(string $editor, string $editorCmd)
{
	int $ratio = eval ( $editorCmd +" -q -imr "+ $editor ) ;
	if ($ratio == 0) {
		eval( $editorCmd +" -e -imr 1 " + $editor ) ;
	}
	else {
		eval( $editorCmd +" -e -imr 0 " + $editor ) ;
	}
}

global proc textureWindowToggleSnap(string $editor, string $editorCmd)
{
	int $snap = eval ( $editorCmd +" -q -ip "+ $editor ) ;
	if ($snap == 0) {
		eval( $editorCmd +" -e -ip 1 " + $editor ) ;
	}
	else {
		eval( $editorCmd +" -e -ip 0 " + $editor ) ;
	}
}

global proc textureWindowToggleGrid(string $editor, string $editorCmd)
//
// Description:
//		Toggle grid settings based on current state of grid toggle for
//		window
// Arguments:
//
// Returns:
//
//
{
	// textureView -q -tgl $editor (panelname)
	int $draw = eval ( $editorCmd +" -q -tgl "+ $editor ) ;
	if ($draw == 0) {
		eval( $editorCmd +" -e -tgl 1 " + $editor ) ;
	}
	else {
		eval( $editorCmd +" -e -tgl 0 " + $editor ) ;
	}
}

global proc textureWindowToggleToolbar()
//
// Description:
//		Toggle toolbar based on current state of toolbar toggle for
//		window
//
{
	int $toolBarState = `optionVar -q textureEditorToolbarState`;
	frameLayout -edit -collapse (!$toolBarState)
		textureEditorToolbarFrameLayout;
	optionVar -iv "textureEditorToolbarState" (!$toolBarState);
}


global proc textureWindowBuildViewMenu(string $parent, string $editor, 
									   string $editorCmd, int $menuBar)
//
// Description:
//		View menu
// Arguments:
//
// Returns:
//
//
{
	global string $gTextureEditorMenubarPrefix;

	setParent -m $parent;

	// Add a prefix to have a different name in the menuBar from the popup menu
	string $prefix="";
	if ($menuBar == 1) {
		$prefix = ($gTextureEditorMenubarPrefix + $editor);
	} 
	else {
		$prefix = $editor;
	}

	// Face selection filter
	string	$cmdStr = "txtWndRelFacesMode( \"" + $editor
						+ "\", \"" + $editorCmd + "\", ";

	string $cmdStr2 = ("textureWindowShaderFacesMode( \"" + $editor
						+ "\", \"" + $editorCmd + "\", ");
	

	string $updateEditor = ( "txtWndUpdateEditor(\"" + $editor + "\", \"" +
							 $editorCmd + "\", \"null\", 101);" );

	if (!`optionVar -exists textureWindowShaderFacesMode`)
		optionVar -iv textureWindowShaderFacesMode 0;
		//0 off
		//1 view shaders
		//2 view isolate

	//********************************************
	//*** some of these menuItems need annotations
	//*** should they be runtime commands?
	//********************************************
	menuItem -l "View Contained Faces" -checkBox 0
			 -command ($cmdStr + " 1);" + $updateEditor)
			 ($prefix+"containedFacesItem");

	menuItem -l "View Connected Faces" -checkBox 0
			 -command ($cmdStr + " 0);" + $updateEditor)
			 ($prefix+"connectedFacesItem");

	menuItem -l "View Faces of Selected Images" -checkBox 0
			 -command ($cmdStr2 + " 0);" + $updateEditor)
			 ($prefix+"shaderFacesItem");

	menuItem -l "Isolate Select" 
			 -subMenu true
			 -tearOff true
			 ($prefix+"isolateFacesItem");

		menuItem -label "View Set" -checkBox 0
			-command ($cmdStr2 + " 1);" + $updateEditor)
			-annotation "View Set: Toggle Isolate Select mode"
			($prefix+"isolateViewItem");

		menuItem -label "Add Selected"
			-command ("textureEditorIsolateSelect 1;")
			-annotation "Add Selected: Add selected UVs to the isolate select set."
			($prefix+"isolateAddItem");

		menuItem -label "Remove Selected"
			-command ("textureEditorIsolateSelect 2;")
			-annotation "Remove Selected: Remove selected UVs to the isolate select set."
			($prefix+"isolateRemoveItem");

		menuItem -label "Remove All"
			-command ("textureEditorIsolateSelect 0;")
			-annotation ("Remove All: Remove all UVs of the selected " +
				"object from the isolate select set.")
			($prefix+"isolateResetItem");

		setParent -m $parent;

	menuItem -d 1 ;

	// Grid display menu item + option box
	//
	// textureWindow -e -tgl 1/0 $panelname;
    
	string $gridPath;
	menuItem -l "Grid" 
		-checkBox 0 
		-c ("textureWindowToggleGrid (\"" + 
			$editor+ "\",\""  +
			$editorCmd + "\" );" +
			$updateEditor)
		-annotation "Show grid on/off"
		($prefix+"toggleGrid");

	menuItem -ecr false -optionBox 1 
		-l "Grid Option Box"
		-annotation "Grid option box"
		-c "performTextureViewGridOptions true" textureViewGridSpacingItem;

	string $toolbarPath;
	menuItem -l "Toolbar" 
		-ecr false
		-checkBox (!`optionVar -q textureEditorToolbarState`)
		//note that the optionVar stores the collapse state of the 
		//frameLayout which is opposite to most controls - false 
		//means the frameLayout is not collapsed so the ! operator
		//is used
		-command ("textureWindowToggleToolbar;" + $updateEditor)
		-annotation "Toggle the display of the toolbar"
		($prefix+"toggleToolbar");

	menuItem -d 1 ;

	// Frame options
	menuItem -label "Frame All"
			 -command ("FrameAll")
			 ($prefix+"frameAllItem");
	menuItem -label "Frame Selection"
			 -command ("FrameSelected")
			 ($prefix+"frameSelectedItem");
	//menuItem -l "Real Size"
	//		 -c ($editorCmd+" -e -realSize "+$editor)
	//		 ($prefix+"realSizeItem");
    setParent -m ..;
}

global proc textureWindowBuildEditMenu(string $parent, string $editor, 
										 string $editorCmd, int $menuBar)
//
// Description:
//		Edit menu
// Arguments:
//
// Returns:
//
//
{
	global string $gTextureEditorMenubarPrefix;

	setParent -m $parent;

	// Add a prefix to have a different name in the menuBar from the popup menu
	string $prefix="";
	if ($menuBar == 1) {
		$prefix = ($gTextureEditorMenubarPrefix + $editor);
	} 
	else {
		$prefix = $editor;
	}


	menuItem -l "Copy UVs" -ecr true -i "polyClipboard.xpm"
		-ann "Copy UVs from selected face."
		-c "polyClipboard -cp -uv";

	menuItem -l "Paste UVs" -ecr true -i "polyClipboard.xpm"
		-ann "Paste UVs from selected face(s)."
		-c "polyClipboard -ps -uv";

	int $creator = 0;
	string $selectCmd = "ls -sl";
    string $prefix = ($creator == 0 ? "" : "PolyRequestUVSetName \"Create Empty UV Set\" ");
    string $cmd = $prefix + "performCreateUVSet";
    string $version = "\"1\"";
    string $args0 = ("{\"0\", \"" + $selectCmd + "\", \"" + ($creator == 1 ? "1" : "0") + "\"}");
    string $args1 = ("{\"1\", \"" + $selectCmd + "\", \"" + ($creator == 1 ? "1" : "0") + "\"}");
    string $suffix = ($creator == 0 ? " \"\"" : "");
    string $c = ($cmd + " " + $version + " " + $args0 + $suffix);
    menuItem
        -label ($creator == 1 ? "Empty UV Set" : "Create Empty UV Set")
        -ecr true
        -i "polyCreateUVSet.xpm"
        -ann "Create UV Set: Create a new empty UV set"
        -c $c createUVSetItemTexturePanel;

	if( $creator != 1 ) {
    	string $c = ($cmd + " " + $version + " " + $args1 + $suffix);
    	menuItem -optionBox 1
        	-i "polyCreateUVSet.xpm"
        	-annotation "Create UV Set Option Box"
        	-l "Create UV Set Option Box" -ecr false -c $c
			createUVSetOptionItemTexturePanel;
	}

	{

	// Menu item to Copy UVs to another uvset.  This has a submenu to display 
	// all available uv sets to copy to.
	//
    string $selectUVSetMenuForCopy = 
		`menuItem -l "Copy UVs to UV Set" -ecr true
         -command "SetCurrentUVSet" 
		-subMenu true -allowOptionBoxes true`;

	// This causes submenu to rebuild everytime it shows 
	string $pmc = "string $menuNames[]; buildUVSetMenuNames($menuNames);" +
				  "buildUVSetMenu " + $selectUVSetMenuForCopy + " $menuNames \"" + $prefix + " \" 1;" +
				  "buildUVSetMenuWithCopyUVsCmd " + $selectUVSetMenuForCopy + " $menuNames ;" ;

	menuItem -e -postMenuCommand $pmc $selectUVSetMenuForCopy;

    string $prefix = ($creator == 0 ? "" : "PolyRequestUVSetName \"Copy Current UV Set\" ");
    string $cmd = $prefix + "performCopyCurrentUVSet";
    string $version = "\"1\"";
    string $args0 = ("{\"0\", \"" + $selectCmd + "\", \"" + ($creator == 1 ? "1" : "0") + "\"}");
    string $args1 = ("{\"1\", \"" + $selectCmd + "\", \"" + ($creator == 1 ? "1" : "0") + "\"}");
    string $args2 = ("{\"2\", \"" + $selectCmd + "\", \"" + ($creator == 1 ? "1" : "0") + "\"}");
    string $suffix = ($creator == 0 ? " \"\"" : "");
    string $c = ($cmd + " " + $version + " " + $args0 + $suffix);
    menuItem -l "Copy into New UV Set" -ecr true
        -i "polyCreateUVSet.xpm"
        -annotation "Copy the selected face's UVs from the active UVset to a new UVset."
        -c $c copyCurrentUVSetTexturePanel;

	if( $creator != 1 ) {
     	string $c = ($cmd + " " + $version + " " + $args1 + $suffix);
     	menuItem -optionBox 1
            -i "polyCreateUVSet.xpm"
            -ann "Copy into New UV Set Option Box"
            -l "Copy into New UV Set Option Box" -ecr false
            -c $c copyCurrentUVSetOBTexturePanel;
	}

    setParent -m ..;
	}

    menuItem -l "Set Current UV Set..." -ecr true
         -i "polySetCurrentUVSet.xpm"
         -ann "Set the current UV Set on selected objects."
         -c "SetCurrentUVSet" setCurrentUVSetTexturePanel;

    menuItem -l "Rename Current UV Set..." -ecr true
         -i "polyRenameUVSet.xpm"
         -ann "Rename the current UV Set on selected objects."
         -c "RenameCurrentUVSet" renameCurrentUVSetTexturePanel;

    menuItem -l "Delete Current UV Set" -ecr true
         -i "polyDeleteUVSet.xpm"
         -ann "Delete the current UV Set on selected objects."
         -c "DeleteCurrentUVSet" deleteCurrentUVSetTexturePanel;

	////////////////////////////////////////////////////////////////
	menuItem -divider true;

	menuItem -l "Normalize UVs"  -ecr true -i "polyNormalize.xpm"
		-ann "Normalize UVs: Normalize UVs of the selected faces"
		-c	 "performPolyForceUV normalize 0" normalizeUVItem;
		menuItem -optionBox 1 -i "polyNormalize.xpm" 
			-annotation "Normalize UVs on Polygons Option Box" 
			-l "Normalize UVs on Polygons Option Box" -ecr false 
			-c "performPolyForceUV normalize 1" ($prefix+"normalizeUVOptionItem");

	menuItem -l "Unitize UVs"  -ecr true -i "polyUnitize.xpm"
		-ann "Unitize UVs: Selected face UVs will be moved to fit 0 to 1 texture space"
		-c	 "performPolyForceUV unitize 0" unitizeUVItem;
	   menuItem -optionBox 1
		   -annotation "Unitize UVs Option Box"
		   -l "Unitize UVs Option Box" -ecr false
		   -c "performPolyForceUV unitize 1"  ($prefix+"unitizeUVOptionItem");


	menuItem -l "Flip UVs"  -ecr true -i "polyFlipUV.xpm"
		-ann "Flip UVs: Flip UVs."
		-c	 "performPolyForceUV flip 0" flipUVItem;
		menuItem -optionBox 1 -i "polyFlip.xpm" 
			-annotation "Flip UVs on Polygons Option Box" 
			-l "Flip UVs on Polygons Option Box" -ecr false 
			-c "performPolyForceUV flip 1" ($prefix+"flipUVOptionItem");

	// m2.1 Rotate uvs about vertex
	menuItem -l "Rotate UVs" -ecr true
		-i "polyRotateUvsAboutVertex.xpm"
		-ann "Rotate UVs about Vertex : Rotate selected UVs about vertex."
		-c "performPolyRotateUVs 0"
		rotateUVItem;
	menuItem -optionBox 1
		-ecr false
		-i "polyRotateUvsAboutVertex.xpm"
		-ann "Rotate UVs Option Box"
		-l "Rotate UVs Option Box"
		-c "performPolyRotateUVs 1"
		rotateUVOptionItem;

	menuItem -l "Cycle UVs" -ecr true
		-i "cycleUVs.xpm"
		-ann "Cycle UVs: Cycles the UVs of the selected face counter clockwise."
		-c "polyRotateUVsByVertex"
		cycleUVItem;

	menuItem -l "Best Plane Texturing Tool"  -ecr true -i "polyBestPlaneTexturing.xpm"
        -ann "Best Plane Texturing Tool: Create UVs by computing the best fitting plane"
        -c   "setToolTo polyBestPlaneTexturingContext" polyBestPlaneTexturingItem;

	menuItem -l "Map UV Border"  -ecr true
		-i "polyMapUVBorder.xpm"
		-ann "Map UV Border: Map the texture border indicated by selected UV to specified shape"
		-c	 "performPolyUntangleUV map 0" mapUVBorderItem;
		menuItem -optionBox 1 -i "polyMapUVBorder.xpm" 
			-annotation "Map UV Border Option Box" 
			-l "Map UV Border Option Box" -ecr false 
			-c "performPolyUntangleUV map 1" ($prefix+"mapUVBorderOptionItem");

   menuItem -l "Straighten UV Border"
       -ann "Straighten UV Border: Select 2 consecutive UVs and a third one to define the border to be straightened"
       -c "performPolyStraightenUV 0" -i "polyStraightenUVBorder.xpm"
		straightenUVBorderItem;
   menuItem -optionBox 1 -l "Straighten UV Border Option Box"
       -ann "Straighten UV Border Option Box"
       -c "performPolyStraightenUV 1" -ecr false
       -i "polyStraightenUVBorder.xpm"
		($prefix+"straightenUVOptionItem");


	menuItem -l "Relax UVs"  -ecr true
		-i "polyRelaxUVShell.xpm"
		-ann "Relax UVs: Automatically move UVs for better texture space distribution"
		-c	 "performPolyUntangleUV relax 0" relaxUVShellItem;
	menuItem -optionBox 1 -i "polyRelaxUVShell.xpm" 
		-annotation "Relax UVs Option Box" 
		-l "Relax UVs Option Box" -ecr false 
		-c "performPolyUntangleUV relax 1" ($prefix+"relaxUVShellOptionItem");

	menuItem -l "Unfold UVs"
		-ann "Unfold UVs: Select a poly object or UV's to be unfolded"
		-echoCommand true
		-dragMenuCommand "performUnfold 2"
		-c "performUnfold 0" 
		-i "polyUnfoldUVs.xpm"
		unfoldUVItem;
	menuItem -optionBox true
		-ann "Unfold UVs Option Box"
		-l "Unfold UVs Option Box"
		-c "performUnfold 1"
		-i "polyUnfoldUVs.xpm"
		unfoldUVOptItem;

    menuItem -l "Layout UVs"
         -ann "Layout UVs: Select faces to be moved in UV space"
         -c "performPolyLayoutUV 0" -i "polyLayoutUV.xpm" 
		 layoutUVItem;
    menuItem -optionBox 1
         -l "Layout UVs Option Box" -ann "Layout UVs Option Box"
         -c "performPolyLayoutUV 1" -ecr false -i "polyLayoutUV.xpm"
		($prefix+"layoutUVOptionItem");

	menuItem -label "Grid UVs"
		-image "polyGridUV.xpm"
		-command ("polyGridUV `optionVar -query gridUVValueU` " +
				"`optionVar -query gridUVValueV` " +
				"`optionVar -query gridUVValuePixel`")
		-annotation "Grid UVs: Snap selected UVs to user specified grid"
		gridUVItem;

		menuItem -optionBox 1
			-command "performPolyGridUV 1"
			($prefix+"gridUVOptionItem");

	menuItem -l "Align UVs"
		-c "performTextureViewAlignUVsOptions false"
		-annotation "Align UVs: Align selected UVs"
		($prefix+"AlignUVs");
	menuItem -l "Align UVs Option Box"
		-optionBox true
		-c "performTextureViewAlignUVsOptions true"
		textureViewAlignUVsItem;

	menuItem -l "Warp Image"
		-ann "Warp Image: Warp selected poly object"
		-echoCommand true
		-dragMenuCommand "performPolyWarpImage 2"
		-c "performPolyWarpImage 0" 
		-i "polyWarpImage.xpm"
		layoutWarpImageItem;
	menuItem -optionBox true
		-ann "Warp Image Option Box"
		-l "Warp Image Option Box"
		-c "performPolyWarpImage 1"
		-i "polyWarpImage.xpm"
		layoutWarpImageOptItem;

	////////////////////////////////////////////////////////////////
	menuItem -divider true;

	menuItem -l "Cut UVs"  -ecr true -i "polyMapCut.xpm"
		-ann "Cut UVs: Separate the UVs along the selected edges."
		-c "polyPerformAction polyMapCut e 0" ($prefix+"cutTextureItem");

	menuItem -l "Sew UVs"  -ecr true -i "polyMapSew.xpm"
		-ann "Sew UVs: Sew the UVs together along the selected edges."
		-c "polyPerformAction polyMapSew e 0" ($prefix+"sewTextureItem");

    menuItem -l "Move and Sew UVs"
        -ann "Move and Sew: Select edges to be mapped merged"
        -c "performPolyMapSewMove 0" -i "polyMoveSew.xpm"
		($prefix+"moveSewTextureItem");
    menuItem -optionBox 1
        -l "Move and Sew Option Box" -ann "Move and Sew Option Box"
        -c "performPolyMapSewMove 1" -ecr false -i "polyMoveSew.xpm";

    menuItem -l "Merge UVs"
        -ann "Merge UVs: Select UVs to be merged"
        -c "performPolyMergeUV 0" -i "polyMergeUV.xpm" 
		($prefix+"mergeUVTextureItem");

    menuItem -optionBox 1 -l "Merge UVs Option Box"
        -ann "Merge UVs Option Box"
        -c "performPolyMergeUV 1" -ecr false -i "polyMergeUV.xpm" ;

    menuItem -l "Delete UVs"  -ecr true -i "polyMapDel.xpm"
        -ann "Delete UVs: Deletes the texture coordinates of the selected faces"
        -c "DeleteUVs" 
		($prefix+"delUVsTextureItem");

	////////////////////////////////////////////////////////////////
	menuItem -divider true;

	menuItem -l "UV Snapshot ..."
		-ann "UV Snapshot: Draws the UVs into an image"
		-c "performUVSnapshot" -i "polyUVSnapshot.xpm";

    setParent -m ..;
}

global proc textureWindowBuildEditSubdivMenu(string $parent, string $editor, 
										 string $editorCmd, int $menuBar)
//
// Description:
//		Edit Subdiv menu
// Arguments:
//
// Returns:
//
//
{
	global string $gTextureEditorMenubarPrefix;

	setParent -m $parent;

	// Add a prefix to have a different name in the menuBar from the popup menu
	string $prefix="";
	if ($menuBar == 1) {
		$prefix = ($gTextureEditorMenubarPrefix + $editor);
	} 
	else {
		$prefix = $editor;
	}

        menuItem -l "Cut UVs"  -ecr true -i "polyMapCut.xpm"
            -ann "Cut UVs: Separate the texture coordinates along the selected edges"
            -c "SubdCutUVs"
            subdivCutTextureItem;

        menuItem -l "Layout UVs"
            -ann "Layout UVs: Select faces to be moved in UV space"
            -c "performSubdLayoutUV 0" -i "polyLayoutUV.xpm";
        menuItem -optionBox 1
            -l "Layout UVs Option Box" -ann "Layout UVs Option Box"
            -c "performSubdLayoutUV 1" -ecr false -i "polyLayoutUV.xpm";

        menuItem -l "Move and Sew UVs"
            -ann "Move and Sew: Select edges to be mapped merged"
            -c "performSubdMapSewMove 0" -i "polyMoveSew.xpm";
        menuItem -optionBox 1
            -l "Move and Sew Option Box" -ann "Move and Sew Option Box"
            -c "performSubdMapSewMove 1" -ecr false -i "polyMoveSew.xpm";
 
	////////////////////////////////////////////////////////////////
	menuItem -divider true;

	menuItem -l "UV Snapshot ..."
		-ann "UV Snapshot: Draws the UVs into an image"
		-c "performUVSnapshot" -i "polyUVSnapshot.xpm";

    setParent -m ..;
}

/*
global proc textureWindowBuildEditNurbsMenu(string $parent, string $editor, 
										 string $editorCmd, int $menuBar)
//
// Description:
//		Edit Nurbs menu
// Arguments:
//
// Returns:
//
//
{
	global string $gTextureEditorMenubarPrefix;

	setParent -m $parent;

	// Add a prefix to have a different name in the menuBar from the popup menu
	string $prefix="";
	if ($menuBar == 1) {
		$prefix = ($gTextureEditorMenubarPrefix + $editor);
	} 
	else {
		$prefix = $editor;
	}

        menuItem -l "Edit UV Mode"  -ecr true 
			-checkBox (`queryNurbsEditUVMode`)
            -ann "Edit UV Mode: Toggles the use of implicit and explicit UVs on a NURBS object."
            -c "nurbsToggleEditUVMode"
            ($prefix+"NurbsEditUVModeItem");

    setParent -m ..;
}
*/

global proc int queryNurbsEditUVMode()
{
	int $value = 0;

	string $shapes[];
	txtWndShapesFromSelList( $shapes );
	
	// Go through all shapes. If any one has EditUV mode enabled,
	// return true.
	//
	int $i;
	for( $i = 0; $i < size($shapes); $i++ )
	{
		// Only grab first selected object to reflect state
		//
		string $shape = $shapes[$i];

		if( `objectType $shape` == "nurbsSurface" )
		{
			int $values[] = `nurbsUVSet -q -ue $shape`;
			$value = $values[0];

			if( $value )
			{
				break;
			}
		}
	}
	return $value;
}

global proc updateNurbsEditUVModeMenuItem( string $menuitem )
{
	int $value = queryNurbsEditUVMode();
	menuItem -e -checkBox $value $menuitem;
}

global proc textureWindowBuildSelectMenu(string $parent, string $editor, 
										 string $editorCmd, int $menuBar)
//
// Description:
//		Selection menu
// Arguments:
//
// Returns:
//
//
{
	global string $gTextureEditorMenubarPrefix;

	setParent -m $parent;

	// Add a prefix to have a different name in the menuBar from the popup menu
	string $prefix="";
	string $prefix="";
	if ($menuBar == 1) {
		$prefix = ($gTextureEditorMenubarPrefix + $editor);
	} 
	else {
		$prefix = $editor;
	}

	menuItem -l "Select Contained Faces"
			 -c ($editorCmd+" -e -selectInternalFaces "+$editor)
			 ($prefix+"selContainedFacesItem");

	menuItem -l "Select Connected Faces"
			 -c ($editorCmd+" -e -selectRelatedFaces "+$editor)
			 ($prefix+"selConnectedFacesItem");

	menuItem -l "Select Shell"
		-c ("SelectUVShell")
		-annotation (getRunTimeCommandAnnotation ("SelectUVShell"))
		($prefix+"selShellItem");

	menuItem -l "Select Shell Border"
		-c ("SelectUVBorder")
		-annotation (getRunTimeCommandAnnotation ("SelectUVBorder"))
		($prefix+"selShellBorder");

	menuItem -divider true;

	menuItem -l ("Convert Selection to Faces" )
        -c ("PolySelectConvert 1")
		($prefix+"selConvertToFaces");

	menuItem -l "Convert Selection to Edges"
        -c ("PolySelectConvert 2")
		($prefix+"selConvertToEdges");

	menuItem -l "Convert Selection to Vertices"
        -c ("PolySelectConvert 3")
		($prefix+"selConvertToVertices");

	menuItem -l "Convert Selection to UVs" 
        -c ("PolySelectConvert 4")
		($prefix+"selConvertToUVs");


    setParent -m ..;
}

proc int isMesh(string $thisObject) {
	if ("" == $thisObject) return 0;
	return size(`polyListComponentConversion -tf $thisObject`);
}

global proc int textureWindowFindActiveShader(string $whichPanel)
{
	string $menuNames[] = `textureWindow -q -imageNames $whichPanel`;
	int $i = 0;	
	for ($menuName in $menuNames) {
		$i++;
		string $buffer[];
		tokenize $menuName " " $buffer;
		string $thisObject = $buffer[0];
		string $thisShader = $buffer[2];

		if (!isMesh($thisObject)) {
			continue;
		}
		
		int $activeGid = getAttr ($thisObject+".dfgi");
		string $objGroups[] = `listConnections -p on ($thisShader+".dsm")`; 
		string $shapes[] = `listConnections -sh on ($thisShader+".dsm")`;
		int $j;
		for ($objGroup in $objGroups) {
			int $gid = -99;
			if (`objExists ($objGroup+".gid")`) {
				$gid = `getAttr ($objGroup+".gid")`;
			} else {
				continue;
			}
			if ($gid == $activeGid) {
				return $i;
			}
		}
	}
	return $i;
}

global proc textureWindowBuildToolMenu(string $parent, string $editor, 
										 string $editorCmd, int $menuBar)
//
// Description:
//		Selection menu
// Arguments:
//
// Returns:
//
//
{
	global string $gTextureEditorMenubarPrefix;

	setParent -m $parent;
	
	string $whichCtx = `currentCtx`;

	// Add a prefix to have a different name in the menuBar from the popup menu
	string $prefix="";
	string $prefix="";
	if ($menuBar == 1) {
		$prefix = ($gTextureEditorMenubarPrefix + $editor);
	} 
	else {
		$prefix = $editor;
	}

	// callback for updating the state of all editor controls
	//
	string $updateEditor = ( "txtWndUpdateEditor(\"" + $editor + "\", \"" +
							 $editorCmd + "\", \"null\", 101);" );

	menuItem -l "UV Lattice Tool"
			 -command ( "setToolTo texLatticeDeformSuperContext;" +
						$updateEditor)
			 -annotation "UV Lattice Tool"
			 ($prefix+"LatticeTool");

	menuItem -l "UV Lattice Tool Option Box"
			-optionBox true
			-c "performTextureLatticeOptions true"
			textureViewLatticeOptionItem;

	menuItem -l "UV Smudge Tool"
			 -command ( "setToolTo texSmudgeUVSuperContext;" +
						$updateEditor)
			 -annotation "UV Smudge Tool"
			($prefix+"SmudgeTool");

	menuItem -l "UV Smudge Tool Option Box"
			-optionBox true
			-c "performTextureSmudgeOptions true"
			textureViewSmudgeOptionItem;


    setParent -m ..;
}


global proc textureWindowSelectImage(int $i, string $whichPanel)
{
	string $menuNames[] = `textureWindow -q -imageNames $whichPanel`;
	
	if (size($menuNames) == 0) return;

	string $buffer[];
	tokenize $menuNames[$i] " " $buffer;
	if (size($buffer) == 0) return;

	string $thisShader = $buffer[2];
	//string $thisObject = $buffer[0];
	if ($thisShader == "") return;

	string $objGroups[] = `listConnections -p on ($thisShader+".dsm")`; 
	string $shapes[] = `listConnections -sh on ($thisShader+".dsm")`;
	//string $objects[] = `listConnections ($thisShader+".dsm")`;

	int $j;
	for ($j=0; $j<size($shapes); $j++) {
		string $objGroup = $objGroups[$j];
		int $gid;
		if (`objExists ($objGroup+".gid")`) {
			$gid = `getAttr ($objGroup+".gid")`;
		} else {
			//$gid = `getAttr ($objGroup+".cgid")`;
			continue;
		}
		if (`nodeType $shapes[$j]` != "mesh") {
			continue;
		}
		setAttr ($shapes[$j]+".dfgi") $gid;
	}
	
	textureWindow -e -imageNumber $i $whichPanel;
}

global proc updateSelectedImageMenu( string $menuName, string $prefix,
									string $whichPanel)
{
	// Clear out this menu first
	menu -e -deleteAllItems $menuName;

	setParent -m $menuName;

	// Build 1 menu item for each image
	// currently cached.
	int $numImages 		= `textureWindow -q -numberOfImages $whichPanel`;
	int $selectedImg 	= `textureWindow -q -imageNumber $whichPanel`;
	string $menuNames[] = `textureWindow -q -imageNames $whichPanel`;

	int $markIndex = 0;
	if (`textureWindow -q -useFaceGroup $whichPanel`) {
		$markIndex = textureWindowFindActiveShader($whichPanel);
		$markIndex--;
	} else {
		$markIndex = $selectedImg;
	}

	// If there are no UV sets to display, then put an empty menu item
	if( $numImages == 0 ) {
		menuItem -ecr false -enable false -l "No object selected.";		
	}

	int $i;
	for ($i=0; $i<$numImages; $i++)
	{
		// Mark the proper image on the list as selected.
		int $checkBox = 0;
		if ( $i == $markIndex ) {
			$checkBox = 1;
		} 

		// Command will set the current image number
		menuItem -ecr false -l $menuNames[$i]
			-cb $checkBox 
			-command ("textureWindowSelectImage " + $i + " " + $whichPanel )
			($prefix+$menuName);	
	}
	setParent -m ..;
}

global proc updateUVSetMenu( string $menuName, string $prefix,
							string $whichPanel)
{
	// Clear out this menu first
	menu -e -deleteAllItems $menuName;

	setParent -m $menuName;
	string $menuNames[] = `textureWindow -q -uvs $whichPanel`;
	int $numUVSets = size($menuNames);
	int $i;

	// If there are no UV sets to display, then put an empty menu item
	if( $numUVSets == 0 ) {
		menuItem -ecr false -enable false -l "No object selected.";
		return;
	}

	string $selectObj[] = `ls -o -sl`;
	int $numObjects = size($selectObj);
	
	for ($i=0; $i<$numUVSets; $i++)	
	{
		// $menuNames[$i] comes in the format
		// "|polySurface3|polySurfaceShape3 | map3"
		// So tokenize it on the space to get the map set name
		string $buf[];
		tokenize $menuNames[$i] " " $buf;

		string $fullMenuItemName;
		// Create a menu item for each uv set 
		string $currUVSet[] = `polyUVSet -q -currentUVSet $buf[0]`;
		if ($currUVSet[0] == $buf[size($buf) - 1]) {

			// Put a check mark on the menu item with the current uvset
			$fullMenuItemName = 
				`menuItem -ecr false -l $menuNames[$i]
				-checkBox true
				($prefix+$menuName+$i)`;		

		} else {
			$fullMenuItemName = 
				`menuItem -ecr false -l $menuNames[$i]
				($prefix+$menuName+$i)`;		
		}
	
		// Display a shorter name in the menu item if there's
		// only one object selected
		if( `menuItem -exists $fullMenuItemName` && ($numObjects == 1) ) {
			menuItem -e -l $buf[size($buf)-1] $fullMenuItemName;
		}
	
		// Attach a command to this menu item
		if( size($fullMenuItemName) > 0 ) {
			// This part of the cmd will switch the current uv set
			string $cmd = ("textureWindow -e -suv " + $i + " " 
							+ $whichPanel + ";");
			menuItem -e 
				-command $cmd
				$fullMenuItemName;
		}
	}
}


global proc updateUVSetMenuWithCopyUVsCmd( 
		string $menuName, string $prefix,
		string $whichPanel)
{
	setParent -m $menuName;
	string $menuItems[] = `menu -q -itemArray $menuName`;
	string $menuNames[] = `textureWindow -q -uvs $whichPanel`;
	int $numUVSets = size($menuNames);

	// If there aren't any uv sets to display, then just return now.
	if( $numUVSets == 0 ) {
		return;
	}

	int $i;
	for( $i=0; $i<$numUVSets; $i++ ) 
	{
		string $buf[];
		tokenize $menuNames[$i] " " $buf;
		
		if( size($buf) == 0 ) continue;

		// for each menu item, disable it if it's the active one
		// or add a command to run the polyCopyUVs cmd
		string $currUVSet[] = `polyUVSet -q -currentUVSet $buf[0]`;
		string $destinationUVSet = $buf[size($buf) - 1];

		if ($currUVSet[0] == $destinationUVSet)
		{
			menuItem -e -enable false $menuItems[$i];
		} else {

			//  Overwrite the existing command with a polyCopyUVs cmd
			string $existingCmd = `menuItem -q -command $menuItems[$i]`;
			string $copyCmd = ( "if( `performPolyCopyUVsToUVsetArgList " 
				    + "\"1\" {"
					+ $currUVSet[0] + ",  " 
					+ $destinationUVSet + ", \"1\"}` > 0 ) { " 
					+ $existingCmd + "}");
			menuItem -e -command $copyCmd $menuItems[$i];
		}
	}
}

global proc textureWindowBuildImageMenu(string $parent, string $editor, 
										string $editorCmd, int $menuBar)
//
// Description:
//		Image menu
// Arguments:
//
// Returns:
//
//
{
	global string $gTextureEditorMenubarPrefix;

	setParent -m $parent;

	// Add a prefix to have a different name in the menuBar from the popup menu
	string $prefix="";
	if ($menuBar == 1) {
		$prefix = ($gTextureEditorMenubarPrefix + $editor);
	} 
	else {
		$prefix = $editor;
	}

	// callback for updating the state of all editor controls
	//
	string $updateEditor = ( "txtWndUpdateEditor(\"" + $editor + "\", \"" +
							 $editorCmd + "\", \"null\", 101);" );


	//
	// Make the Image menu
	//
	menuItem -l "Image Range"
		($prefix+"ImageRange");
	menuItem -l "Image Range Option Box"
		-optionBox true
		-c "performTextureViewImageRangeOptions true"
		textureViewImageRangeItem;
	
	menuItem -l "Display Image"
		-cb 1
		-c ("textureWindowToggleTextureImage (\"" + 
			$editor+ "\",\"" + 
			$editorCmd+ "\");" +
			$updateEditor)
		($prefix+"ImageDisplay");

	menuItem -l "Dim Image"
		-cb 1
		-c ("textureWindowToggleImageDimming (\"" + 
			$editor+ "\",\"" + 
			$editorCmd+ "\");" +
			$updateEditor)
		($prefix+"DimImage");

	menuItem -label "UV Texture Editor Baking"
			 -checkBox 1
			 -command ( "textureWindowToggleEditorImage (\"" + 
						$editor+ "\");" +
						$updateEditor)
			 -annotation "UV Texture Editor Baking on/off"
			($prefix+"DisplayEditorImage");
	menuItem -l "UV Texture Editor Baking Option Box"
		-optionBox true
		-c "performTextureViewBakeTextureOptions true"
		textureViewBakeTextureItem;

	menuItem -l "Display Unfiltered"
		-cb 0
		-c ("textureWindowToggleUnfiltered (\"" + 
			$editor + "\",\"" + 
			$editorCmd + "\" );" +
			$updateEditor)
		($prefix+"ImageUnfiltered");

	menuItem -l "Display RGB Channels"
		-c ("textureWindow -e -displayStyle \"color\" " + $editor)
		($prefix+"ImageRGB");

	menuItem -l "Display Alpha Channel"
		-c ("textureWindow -e -displayStyle \"mask\" " + $editor)
		($prefix+"ImageAlpha");

	menuItem -l "Use Image Ratio"
		-cb 0
		-c ("textureWindowToggleRatio (\"" + 
			$editor + "\",\"" 
			+ $editorCmd + "\");" +
			$updateEditor)
		($prefix+"ImageRatio");

	menuItem -l "Pixel Snap"
		-cb 0
		-c ("textureWindowToggleSnap (\"" + 
			$editor + "\",\"" +
			$editorCmd + "\");" +
			$updateEditor)
		($prefix+"ImageSnap");
		
	menuItem -l "Create PSD Network..."
		-c "photoShopPaintTex"
		textureViewCreatePSDTextures ;
		
	menuItem -l "Update PSD Networks"
		-c "psdUpdateTextures"
		textureViewUpdatePSDTextures ;
		

	// List of images
	string $selectImageMenu = `menuItem -l "Selected Images"
		-subMenu true
		//-tearOff true -- Can't allow this due to UI restrictions !
		($prefix+"SelectedImages")`;

	menuItem -e -pmc ("updateSelectedImageMenu " + 
					  $selectImageMenu + " " +
					  $prefix + " " +
					  $editor)
		$selectImageMenu;

	setParent -m ..;

	// List of uvsets
	string $selectUVSetMenu = `menuItem -l "UV Sets" 
		-subMenu true
		($prefix+"UVSets")`;

	string $pmc = "string $menuNames[];buildUVSetMenuNames($menuNames);" +
				  "buildUVSetMenu " + $selectUVSetMenu + " $menuNames \"" + $prefix + " \" 0;" +
				  "buildUVSetMenuWithSetUVSetCmdByIndex " + $selectUVSetMenu + " " + $editor + ";" ;

	menuItem -e -pmc $pmc $selectUVSetMenu;
    setParent -m ..;
}

global proc textureWindowSelectConvert(int $toType)
{
	string $converted[];
	string $convSubd[];
	string $tokens[];
	string $evalStr;
	
	// To Face
	if ($toType == 1)
	{
		$converted = `polyListComponentConversion -in -fv -fe -fuv -fvf -tf`;
		if (`isTrue "SubdivUIExists"`) {
			$convSubd = `subdListComponentConversion -in -fv -fe -fuv -tf`;
		}
	}
	
	// To Edge
	else if ($toType == 2)
	{
		$converted = `polyListComponentConversion -fv -ff -fuv -fvf -te`;
		if (`isTrue "SubdivUIExists"`) {
			$convSubd = `subdListComponentConversion -fv -ff -fuv -te`;
		}
	}
	
	// To Vertex
	else if ($toType == 3)
	{
		$converted = `polyListComponentConversion -ff -fe -fuv -fvf -tv`;
		if (`isTrue "SubdivUIExists"`) {
			$convSubd= `subdListComponentConversion -ff -fe -fuv -tv`;
		}
	}
	
	// To UV
	else if ($toType == 4)
	{
		$converted = `polyListComponentConversion -fv -fe -ff -fvf -tuv`;
		if (`isTrue "SubdivUIExists"`) {
			$convSubd = `subdListComponentConversion -fv -fe -ff -tuv`;
		}
	}
	
	int $numConv = size($converted);
	int $numSubd = size($convSubd);
	if ( ($numConv > 0) || ($numSubd > 0 ) )
	{
		$evalStr = "select -r";
		for ( $i=0; $i<$numConv; $i++ )
		{
			$evalStr += " \"";
			$evalStr += $converted[$i];
			$evalStr += "\"";
		}
		for ( $i=0; $i<$numSubd; $i++ )
		{
			$evalStr += " \"";
			$evalStr += $convSubd[$i];
			$evalStr += "\"";
		}
		eval $evalStr;
	}
}

global proc textureWindowCreatePopupRadialMenu( string $editor, string $editorCmd, int $popupType )
//
// Description:
//		Texture window popup marking menu creation. This part is solely the radial
//	component of the marking menu.
//
// Arguments:
//		$popupType - defines whether to create the Poly/SubD marking menu, the
//					NURBS marking menu, or the combined marking menu.
//
//					case 0: Poly / SubD marking menu
//					case 1: NURBS marking menu
//					case 2: Both
//
// Returns:
//
//
{
	// Record the popup type
	//
	global int $gTextureEditorPopupType;
	$gTextureEditorPopupType = $popupType;

	// Marking menu selection commands
	//
	string $selectCmd[8];
	if (!`isTrue "SubdivUIExists"`)
	{
		if (`selectMode -q -object`)
		{
			$selectCmd[0] = ("changeSelectMode -component; setComponentPickMask \"Facet\" true; " +
							"selectType -ocm -alc false; " +
							"selectType -ocm -facet true; " +
							"selectType -sf false -se false -suv false -cv false; ");
			$selectCmd[1] = ("changeSelectMode -component; setComponentPickMask \"Line\" true; " +
							"selectType -ocm -alc false; " +
							"selectType -ocm -edge true; " +
							"selectType -sf false -se false -suv false -cv false; ");
			$selectCmd[2] = ("changeSelectMode -component; " +
							"selectType -ocm -alc false; selectType -alc false; " +
							"selectType -puv true; " +
							"selectType -suv true; ");
			$selectCmd[3] = ("changeSelectMode -component; setComponentPickMask \"Point\" true; " +
							"selectType -ocm -alc false; " +
							"selectType -ocm -vertex true; " +
							"selectType -sf false -se false -suv false -cv false; ");
		} 
		else
		{
			$selectCmd[0] = ("changeSelectMode -component; setComponentPickMask \"Facet\" true; " +
							"selectType -ocm -alc false; " +
							"selectType -facet true; " +
							"selectType -sf false -se false -suv false -cv false; ");
			$selectCmd[1] = ("changeSelectMode -component; setComponentPickMask \"Line\" true; " + 
							"selectType -ocm -alc false; " +
							"selectType -edge true; " +
							"selectType -sf false -se false -suv false -cv false; ");
			$selectCmd[2] = ("changeSelectMode -component; " +
							"selectType -alc false; " +
							"selectType -puv true; " +
							"selectType -suv true; ");
			$selectCmd[3] = ("changeSelectMode -component; setComponentPickMask \"Point\" true; " +
							"selectType -ocm -alc false; " +
							"selectType -vertex true; " +
							"selectType -sf false -se false -suv false -cv false; ");
		}
	}
	else
	{
		if (`selectMode -q -object`)
		{
			$selectCmd[0] = ("changeSelectMode -component; setComponentPickMask \"Facet\" true; " +
							"selectType -ocm -alc false; " +
							"selectType -ocm -facet true; " +
							"selectType -sme false -smu false -smp false; " +
							"selectType -sf false -se false -suv false -cv false; ");
			$selectCmd[1] = ("changeSelectMode -component; setComponentPickMask \"Line\" true; " +
							"selectType -ocm -alc false; " +
							"selectType -ocm -edge true; " + 
							"selectType -smf false -smu false -smp false; " +
							"selectType -sf false -se false -suv false -cv false; ");
			$selectCmd[2] = ("changeSelectMode -component; " +
							"selectType -ocm -alc false; selectType -alc false; " +
							"selectType -puv true; " +
							"selectType -smu true; " + 
							"selectType -suv true; ");
			$selectCmd[3] = ("changeSelectMode -component; setComponentPickMask \"Point\" true; " +
							"selectType -ocm -alc false; " +
							"selectType -ocm -vertex true; " +
							"selectType -sf false -se false -suv false -cv false; ");
		} 
		else
		{
			$selectCmd[0] = ("changeSelectMode -component; setComponentPickMask \"Facet\" true; " +
							"selectType -ocm -alc false; " +
							"selectType -facet true; " +
							"selectType -sme false -smu false -smp false; " +
							"selectType -sf false -se false -suv false -cv false; ");
			$selectCmd[1] = ("changeSelectMode -component; setComponentPickMask \"Line\" true; " + 
							"selectType -ocm -alc false; " +
							"selectType -edge true; " +
							"selectType -smf false -smu false -smp false; " +
							"selectType -sf false -se false -suv false -cv false; ");
			$selectCmd[2] = ("changeSelectMode -component; " +
							"selectType -alc false; " +
							"selectType -puv true; " +
							"selectType -smu true; " +
							"selectType -suv true; ");
			$selectCmd[3] = ("changeSelectMode -component; setComponentPickMask \"Point\" true; " +
							"selectType -ocm -alc false; " +
							"selectType -vertex true; " +
							"selectType -sf false -se false -suv false -cv false; ");
		}
	}

	// Marking menu directions
	//
	string $directions[8];
	$directions[0] = "S";
	$directions[1] = "N";
	$directions[2] = "E";
	$directions[3] = "W";
	$directions[4] = "NE";
	$directions[5] = "NW";
	$directions[6] = "SE";
	$directions[7] = "SW";

	// If we want to create Poly/SubD marking menu, or the combined Poly/SubD/NURBS
	// marking menu, then execute this code.
	//
	if( $popupType == 0 || $popupType == 2 )
	{

		menuItem -l "Face"
			-rp ($directions[0])
			-c ($selectCmd[0])
			($editor+"Face");
		
		menuItem -l "Edge"
			-rp ($directions[1])
			-c ($selectCmd[1])
			($editor+"Edge");
		
		menuItem -l "UV"
			-rp ($directions[2])
			-c ($selectCmd[2])
			($editor+"UV");
		
		menuItem -l "Vertex"
			-rp ($directions[3])
			-c ($selectCmd[3])
			($editor+"Vertex");

		if( $popupType == 2 )
		{
			menuItem -l "Edit NURBS UV Mode"
				-checkBox (`queryNurbsEditUVMode`)
				-rp ($directions[4])
				-c "nurbsToggleEditUVMode"
				($editor+"EditNURBSUV");
		}
	}
	else if( $popupType == 1 )
	{
		// We want *only* the NURBS marking menu
		//
		menuItem -l "UV"
			-rp ($directions[2])
			-c ($selectCmd[2])
			($editor+"UV");

		menuItem -l "Edit NURBS UV Mode"
			-checkBox (`queryNurbsEditUVMode`)
			-rp ($directions[4])
			-c "nurbsToggleEditUVMode"
			($editor+"EditNURBSUV");
	}
}

global proc textureWindowDeletePopupRadialMenu( string $editor )
{
	if( `menuItem -q -ex ($editor+"Face")` ) deleteUI ($editor+"Face");
	if( `menuItem -q -ex ($editor+"Edge")` ) deleteUI ($editor+"Edge");
	if( `menuItem -q -ex ($editor+"UV")` ) deleteUI ($editor+"UV");
	if( `menuItem -q -ex ($editor+"Vertex")` ) deleteUI ($editor+"Vertex");
	if( `menuItem -q -ex ($editor+"EditNURBSUV")` ) deleteUI ($editor+"EditNURBSUV");
}

global proc textureWindowCreatePopupMenubar( string $editor, string $editorCmd )
//
//	Description:
//		Create the popup version of the menubar. This is the popup menu that
//		appears below the marking menu that is a replica of the UV texture editor
//		menubar, except as a popup menu instead.
//
//		When adding a new menuitem to an existing menu, modify the
//		appropriate textureWindowBuildNAMEMenu. If adding a new menu
//		create a new textureWindowBuildNAMEMenu proc.
//
//		In either case, if the new menuItem is a checkbox, it should
//		call txtWndUpdateEditor when selected. See
//		textureWindowBuildViewMenu for examples.
//		In addition, code should be added to txtWndUpdateEditor to update
//		the state of all controls which provide an interface to the new
//		functionality. This is to ensure that all the controls are in
//		sync.
//
//		Keep in mind that there is also a textureWindowCreateMenubar proc. If
//		you wish your new menuItem to be in the popup, you must modify that
//		proc as well.
//
{
	string	$subName = `menuItem -l "Polygons" -aob true -sm 1 -to 1 ($editor+"EditMenu")`;
	textureWindowBuildEditMenu( $subName, $editor, $editorCmd, 0 );
	
	if (`isTrue "SubdivUIExists"`) {
		string	$subName = `menuItem -l "Subdivs" -aob true -sm 1 -to 1
		($editor+"EditSubdivMenu")`;
		textureWindowBuildEditSubdivMenu( $subName, $editor, $editorCmd, 0 );
	}

	// Disabling NURBS UV Menu - NURBS UVs are only partially implemented.
	// Here we are limiting their exposure. When the remaining features of
	// NURBS UVs are implemented, the following lines can be uncommented.
	// [lli]
	//
	/*
	// Nurbs "Edit UV Mode" update.
	//
	// Note: we must issue a -pmc to update this item since it is based on
	// the object selection rather than the txtWndUpdateEditor method - which
	// only responds to editor changes.
	//
	string $nurbsPostMenuCommand = "updateNurbsEditUVModeMenuItem(\"" +
									$editor +
									"NurbsEditUVModeItem\")";

	string  $subName = `menuItem -l "NURBS"
								-aob true
								-sm 1
								-pmc $nurbsPostMenuCommand
								-to 1
								($editor+"EditNurbsMenu")`;
	textureWindowBuildEditNurbsMenu( $subName, $editor, $editorCmd, 0 );
	*/
	
	string	$subName = `menuItem -l "View" -aob true -sm 1 -to 1 ($editor+"ViewMenu")`;
	textureWindowBuildViewMenu( $subName, $editor, $editorCmd, 0 );
	
	$subName = `menuItem -l "Select" -sm 1 -aob true -to 1 ($editor+"SelectMenu")`;
	textureWindowBuildSelectMenu( $subName, $editor, $editorCmd, 0 );

	$subName = `menuItem -l "Tool" -sm 1 -aob true -to 1 ($editor+"ToolMenu")`;
	textureWindowBuildToolMenu( $subName, $editor, $editorCmd, 0 );

	$subName = `menuItem -l "Image" -sm 1 -aob true -to 1 ($editor+"ImageMenu")`;
	textureWindowBuildImageMenu( $subName, $editor, $editorCmd, 0 );
}

global proc textureWindowCreatePopupConvertMenu( string $editor, string $editorCmd )
//
//	Description:
//		Create popup marking menu for selection conversion. Currently this is
//	the control key modifier popup menu for the UV texture editor.
//
{
	// Marking menu selection commands
	//
	string $selectCmd[8];

	$selectCmd[0] = "textureWindowSelectConvert 1"; // F
	$selectCmd[1] = "textureWindowSelectConvert 2"; // E
	$selectCmd[2] = "textureWindowSelectConvert 4"; // UV 
	$selectCmd[3] = "textureWindowSelectConvert 3"; // V 
	$selectCmd[4] = "polySelectBorderShell 0";        // UV shell
	$selectCmd[5] = "polySelectBorderShell 1";		  // UV border
	$selectCmd[6] = "SelectEdgeLoop";    // Contiguous edges
	$selectCmd[7] = "polySelectBorderShell 1";		  // Shell border

	string $directions[8];
	$directions[0] = "S";
	$directions[1] = "N";
	$directions[2] = "E";
	$directions[3] = "W";
	$directions[4] = "NE";
	$directions[5] = "NW";
	$directions[6] = "SE";
	$directions[7] = "SW";

	menuItem -l "To Face"
		-rp ($directions[0])
		-c ($selectCmd[0])
		($editor+"ToFace");
	
	menuItem -l "To Edge"
		-rp ($directions[1])
		-c ($selectCmd[1])
		($editor+"ToEdge");
	
	menuItem -l "To UV"
		-rp ($directions[2])
		-c ($selectCmd[2])
		($editor+"ToUV");
	
	menuItem -l "To Vertex"
		-rp ($directions[3])
		-c ($selectCmd[3])
		($editor+"ToVertex");

	menuItem -l "To Shell"
		-rp ($directions[4])
		-c ($selectCmd[4])
		($editor+"ToShell");

	menuItem -l "To Border"
		-rp ($directions[5])
		-c ($selectCmd[5])
		($editor+"ToBorder");

	menuItem -l "To Edge Loop"
		-rp ($directions[6])
		-c ($selectCmd[6])
		($editor+"ToEdgeLoop");

	menuItem -l "To Shell Border"
		-rp ($directions[7])
		-c ($selectCmd[7])
		($editor+"SelectShellBorder");
}


global proc textureWindowCreatePopupContextMenu( string $parent )
//
//	Description:
//		Create popup marking menu for context sensitive tools. Currently this is
//	the shift key modifier popup menu for the UV texture editor.
//
{

	string $firstSelected[];
	string $firstSelectedShape[];
	string $firstSelectedShapeNodeType = "unknown";


	//Get last selected component or object with shape
	$firstSelected = `ls -sl -head 1`;

	if (`size $firstSelected` != 0)
		$firstSelectedShape = `listRelatives -shapes $firstSelected[0]`;
	if (`size $firstSelectedShape` != 0)
		$firstSelectedShapeNodeType = `nodeType $firstSelectedShape[0]`;

	//if (`popupMenu -query -exists ($parent + "popupMenusShift")`){
	//	popupMenu -edit -deleteAllItems ($parent + "popupMenusShift");

	//	setParent -menu ($parent + "popupMenusShift");
	if (`popupMenu -query -exists $parent`){
		popupMenu -edit -deleteAllItems $parent;

		setParent -menu $parent;

		
		menuItem
			-label "Toggle Texture Borders"
			-command ("int $borders[] = `polyOptions -q -displayMapBorder`;" +
			"float $borderWidth[] = `optionVar -q displayPolyBorderEdgeSize`;" +
			"polyOptions -displayMapBorder (!$borders[0]) -sizeBorder $borderWidth[1]")
			-annotation "Toggle Texture Borders: Toggle the display of texture borders for the active mesh"
			;

		//Check selection for uv,vertex,face,edge,mesh

		//////////////////////////////////////////////////////////////
		//
		//	UV
		//
		//////////////////////////////////////////////////////////////


		if (`gmatch $firstSelected[0] "*.map*"`)
		{

			menuItem
				-enableCommandRepeat 1
				-radialPosition "SE"
				-annotation "Map UV Border: Map the texture border indicated by selected UV to specified shape" 
				-label "Map UV Border" 
				-command "untangleUV -mb shape_circular" 
				;

			menuItem
				-enableCommandRepeat 1
				-radialPosition "SE"
				-optionBox 1
				-annotation "Map UV Border Option Box" 
				-label "Map UV Border Option Box" 
				-command "performPolyUntangleUV map 1" 
				;

			menuItem
				-enableCommandRepeat 1
				-radialPosition "SW"
				-annotation "Straighten UV Border: Select 2 consecutive UVs and a third one to define the border to be straightened" 
				-label "Straighten UV Border" 
				-command "performPolyStraightenUV 0" 
				;

			menuItem
				-enableCommandRepeat 1
				-radialPosition "SW"
				-optionBox 1
				-annotation "Straighten UV Border Option Box" 
				-label "Straighten UV Border Option Box" 
				-command "performPolyStraightenUV 1" 
				;

			menuItem
				-enableCommandRepeat 1
				-radialPosition "E"
				-annotation "Relax UVs: Automatically move UVs for better texture space distribution" 
				-label "Relax UVs " 
				-command "untangleUV -r harmonic -pb 1 -ps 0 -pu 0 -rt 0 -mri 5" 
				;

			menuItem
				-enableCommandRepeat 1
				-radialPosition "E"
				-optionBox 1
				-annotation "Relax UVs Option Box" 
				-label "Relax UVs Option Box" 
				-command "performPolyUntangleUV relax 1" 
				;

			menuItem
				-enableCommandRepeat 1
				-radialPosition "N"
				-annotation "Unfold UVs: Select a poly object or UV's to be unfolded" 
				-label "Unfold UVs" 
				-command "unfold -i 500 -ss 0.001 -gb 0 -gmb 0.4397 -pub 0 -ps  0 -us off" 
				;

			menuItem
				-enableCommandRepeat 1
				-radialPosition "N"
				-optionBox 1
				-annotation "Unfold UVs Option Box" 
				-label "Unfold UVs Option Box" 
				-command "performUnfold 1" 
				;

			menuItem
				-enableCommandRepeat 1
				-radialPosition "W"
				-annotation "Layout UVs: Select faces to be moved in UV space" 
				-label "Layout UVs" 
				-command "performPolyLayoutUV 0" 
				;

			menuItem
				-enableCommandRepeat 1
				-radialPosition "W"
				-optionBox 1
				-annotation "Layout UVs Option Box" 
				-label "Layout UVs Option Box" 
				-command "performPolyLayoutUV 1" 
				;

			menuItem
				-command  "textureWindowSetContext texLatticeDeformSuperContext;"
				-annotation "UV Lattice Tool: Deforms region of UVs using lattice deformer."
				-label "UV Lattice Tool"
				-radialPosition "NE"
				;

			menuItem
				-label "UV Lattice Tool Options"
				-annotation "UV Lattice Tool Options"
				-radialPosition "NE"
				-optionBox 1
				-command "setToolTo texLatticeDeformSuperContext;toolPropertyWindow;"
				;

			menuItem
				-command  "smudgeSetToTool; textureWindowSetContext texSmudgeUVSuperContext;" 
				-annotation "UV Smudge Tool: Deforms UVs using smudge deformer"
				-label "UV Smudge Tool"
				-radialPosition "NW"
				texSmudgeUVButton;

			menuItem
				-label "UV Smudge Tool Options"
				-annotation "UV Smudge Tool Options"
				-radialPosition "NW"
				-optionBox 1
				-command "setToolTo texSmudgeUVSuperContext;toolPropertyWindow;"
				;

			// allow user to define a proc with additional menu items
			if (`exists contextUVToolsUVUserMM`)
				contextUVToolsUVUserMM $parent;

		}

		//////////////////////////////////////////////////////////////
		//
		//	VERTEX
		//
		//////////////////////////////////////////////////////////////

		if (`gmatch $firstSelected[0] "*.vtx*"`)
		{

			// allow user to define a proc with additional menu items
			if (`exists contextUVToolsVertexUserMM`)
				contextUVToolsVertexUserMM $parent;

		}

		//////////////////////////////////////////////////////////////
		//
		//	FACE
		//
		//////////////////////////////////////////////////////////////

		else if (`gmatch $firstSelected[0] "*.f*"`)	
		{

			menuItem
				-enableCommandRepeat 1
				-radialPosition "W"
				-annotation "Layout UVs: Select faces to be moved in UV space" 
				-label "Layout UVs" 
				-command "performPolyLayoutUV 0" 
				;

			menuItem
				-enableCommandRepeat 1
				-radialPosition "W"
				-optionBox 1
				-annotation "Layout UVs Option Box" 
				-label "Layout UVs Option Box" 
				-command "performPolyLayoutUV 1" 
				;

			menuItem
				-enableCommandRepeat 1
				-radialPosition "NE"
				-annotation "Normalize UVs: Normalize UVs of the selected faces" 
				-label "Normalize UVs" 
				-command "polyNormalizeUV -normalizeType 1 -preserveAspectRatio off " 
				;

			menuItem
				-enableCommandRepeat 1
				-radialPosition "NW"
				-annotation "Unitize UVs: Selected face UVs will be moved to fit 0 to 1 texture space" 
				-label "Unitize UVs" 
				-command "polyForceUV -unitize " 
				;

			menuItem
				-enableCommandRepeat 1
				-radialPosition "N"
				-label "Planar Map" 
				-command "polyProjection -ch 1 -type Planar -ibd on -icx 0.5 -icy 0.5 -ra 0 -isu 1 -isv 1 -md bestPlane ;setToolTo ShowManips;" 
				;



			// allow user to define a proc with additional menu items
			if (`exists contextUVToolsFaceUserMM`)
				contextUVToolsFaceUserMM $parent;

		}

		//////////////////////////////////////////////////////////////
		//
		//	EDGE
		//
		//////////////////////////////////////////////////////////////

		else if (`gmatch $firstSelected[0] "*.e*"`)	
		{

			menuItem
				-enableCommandRepeat 1
				-radialPosition "W"
				-annotation "Cut UVs: Separate the texture coordinates along the selected edges" 
				-label "Cut UVs" 
				-command "polyPerformAction polyMapCut e 0" 
				;

			menuItem
				-enableCommandRepeat 1
				-radialPosition "E"
				-annotation "Sew UVs: Sew the textures together along the selected edges" 
				-label "Sew UVs" 
				-command "polyPerformAction polyMapSew e 0" 
				;

			menuItem
				-enableCommandRepeat 1
				-radialPosition "N"
				-annotation "Move and Sew: Select edges to be mapped merged" 
				-label "Move and Sew UVs" 
				-command "performPolyMapSewMove 0" 
				;

			menuItem
				-enableCommandRepeat 1
				-radialPosition "N"
				-optionBox 1
				-annotation "Move and Sew Option Box" 
				-label "Move and Sew Option Box" 
				-command "performPolyMapSewMove 1" 
				;

			// allow user to define a proc with additional menu items
			if (`exists contextUVToolsEdgeUserMM`)
				contextUVToolsEdgeUserMM $parent;

		}	

		//////////////////////////////////////////////////////////////
		//
		//	POLY OBJECT
		//
		//////////////////////////////////////////////////////////////

		else if ($firstSelectedShapeNodeType == "mesh")
		{

			// allow user to define a proc with additional menu items
			if (`exists contextUVToolsObjectUserMM`)
				contextUVToolsObjectUserMM $parent;

		}	


		//////////////////////////////////////////////////////////////
		//
		//	DEFAULT
		//
		//////////////////////////////////////////////////////////////

		else		{

			// allow user to define a proc with additional menu items
			if (`exists contextUVToolsDefaultUserMM`)
				contextUVToolsDefaultUserMM $parent;

		}		

	}
}



global proc textureWindowUpdatePopup( string $popupMenu, string $editor, string $editorCmd )
//
//	Description:
//		This procedure will update the popup menu on the fly based on the current
//	selection. ie. If polys are selected, this will make sure that the marking menu
//	is the poly/subd menu set. If NURBS are selected, the NURBS menu set will be
//	created. If both are present, the combined menu set will be created. This is executed
//	each time the popup menu is requested.
//
//		Use this method if you would like the ability to update the popup menu prior
//	to being shown. This includes: rebuilding the menu, updating checkboxes, etc.
//
{
	global int $gTextureEditorPopupType;

	// Determine type based on the selection/hilite list.
	//
	int $selectedTypes[];
	txtWndSelectedTypes( $selectedTypes );
	int $polySelected = $selectedTypes[0];
	int $nurbsSelected = $selectedTypes[1];
	int $subdivSelected = $selectedTypes[2];

	// Popup types:
	//
	// 0 == "Poly/SubD marking menu"
	// 1 == "NURBS marking menu"
	// 2 == "Combined Poly/SubD/NURBS marking menu"
	//
	int $popupType = 0;
	if( $polySelected || $subdivSelected )
	{
		if( $nurbsSelected )
		{
			$popupType = 2;
		}
		else
		{
			$popupType = 0;
		}
	}
	else if( $nurbsSelected )
	{
		$popupType = 1;
	}

	// If the popupTypes do not match, then switch the menuset.
	//
	if( $popupType != $gTextureEditorPopupType )
	{
		string $oldParent = `setParent -q -m`;

		// Clear the existing radial menu and rebuild it
		//
		textureWindowDeletePopupRadialMenu( $editor );
		setParent -m $popupMenu;
		textureWindowCreatePopupRadialMenu( $editor, $editorCmd, $popupType );
		setParent -m $oldParent;
	}

	// Now perform any updating necessary specific to the marking menus
	//
	if( $gTextureEditorPopupType == 1	||
		$gTextureEditorPopupType == 2	)
	{
		updateNurbsEditUVModeMenuItem( $editor+"EditNURBSUV" );
	}
}

global proc buildTextureViewContextHelpItems(string $nameRoot, string $menuParent)
//
//  Description:
//		Build context sensitive menu items
//		
//  Input Arguments:
//		$nameRoot - name to use as the root of all item names
//		$menuParent - the name of the parent of this menu
//
//  Return Value:
//      None
//
{
	menuItem -label "Help on UV Texture Editor..."
		-enableCommandRepeat false
		-command "showHelp TextureView";
}

global proc textureWindowCreateMenubar(string $editor, string $editorCmd)
//
// Description:
//		Texture window menu bar creation.
//
//		When adding a new menuitem to an existing menu, modify the
//		appropriate textureWindowBuildNAMEMenu. If adding a new menu
//		create a new textureWindowBuildNAMEMenu proc.
//
//		In either case, if the new menuItem is a checkbox, it should
//		call txtWndUpdateEditor when selected. See
//		textureWindowBuildViewMenu for examles.
//		In addition, code should be added to txtWndUpdateEditor to update
//		the state of all controls which provide an interface to the new
//		functionality. This is to ensure that all the controls are in
//		sync.
//
//		Keep in mind that there is also a textureWindoCreatePopup proc. If
//		you wish your new menuItem to be in the popup, you must modify that
//		proc as well.
// Arguments:
//
// Returns:
//
//
{
	global string $gTextureEditorMenubarPrefix;

	//
	//	Make the Edit sub menu.
	//
	string	$subName = `menu -l "Polygons" 
		-to 1 
		-aob true
		-familyImage "menuIconEdit.xpm"
		($editor+"EditPolyMenu")`;
	textureWindowBuildEditMenu( $subName, $editor, $editorCmd, 1 );


	//
	//	Make the Edit Subdiv sub menu.
	//
	if (`isTrue "SubdivUIExists"`) {
		string	$subName = `menu -l "Subdivs" 
			-to 1 
			-aob true
			-familyImage "menuIconEdit.xpm"
			($editor+"EditSubdivMenu")`;
		textureWindowBuildEditSubdivMenu( $subName, $editor, $editorCmd, 1 );
	}

	// Disabling NURBS UV Menu - NURBS UVs are only partially implemented.
	// Here we are limiting their exposure. When the remaining features of
	// NURBS UVs are implemented, the following lines can be uncommented.
	// [lli]
	//
	/*
	//
	//	Make the Edit NURBS sub menu.
	//
	// Note: we must issue a -pmc to update this item since it is based on
	// the object selection rather than the txtWndUpdateEditor method - which
	// only responds to editor changes.
	//
	string $nurbsPostMenuCommand = "updateNurbsEditUVModeMenuItem(\"" +
									$gTextureEditorMenubarPrefix +
									$editor +
									"NurbsEditUVModeItem\")";
	string $subName = `menu -l "NURBS"
		-to 1
		-aob true
		-pmc $nurbsPostMenuCommand
		-familyImage "menuIconEdit.xpm"
		($editor+"EditNurbsMenu")`;
	textureWindowBuildEditNurbsMenu( $subName, $editor, $editorCmd, 1 );
	*/

	//
	//	Make the View sub menu.
	//
	string	$subName = `menu -l "View" 
		-to 1 
		-aob true
		-familyImage "menuIconView.xpm"
		($editor+"ViewMenu")`;
	textureWindowBuildViewMenu( $subName, $editor, $editorCmd, 1 );

	//
	// Make the select sub menu
	//
	$subName = `menu -l "Select"
		-to 1
		-aob true
		-familyImage "menuIconSelect.xpm"
		($editor+"SelectMenu")`;
	textureWindowBuildSelectMenu( $subName, $editor, $editorCmd, 1 );


	//
	// Make the tool sub menu
	//
	$subName = `menu -l "Tool"
		-to 1
		-aob true
//		-familyImage "menuIconTool.xpm" // TO DO
		($editor+"ToolMenu")`;
	textureWindowBuildToolMenu( $subName, $editor, $editorCmd, 1 );

	//
	// Make the image sub menu
	//
	$subName = `menu -l "Image"
		-to 1
		-aob true
		-familyImage "menuIconImages.xpm"
		($editor+"ImageMenu")`;
	textureWindowBuildImageMenu( $subName, $editor, $editorCmd, 1 );

	//
	//	Create the common tools of the menuBar.
	//
	//iiWindowEditorMenuBar( $editor, $editorCmd );

	//	Add support for the Context Sensitive Help Menu.
	//
	addContextHelpProc $editor "buildTextureViewContextHelpItems";
}


