//Copyright 2012-2013 Adobe Systems Incorporated.  All rights reserved.

var helpDoc = MM.HELP_jQueryAccordion;

var ACCORDION_ID;
var PANEL_HEIGHT;
var MESSAGE;
var MESSAGETEXT;
var LIST_PANEL;
var UP_BTN;
var DOWN_BTN;
var ADD_BTN;
var DEL_BTN;
var ACTIVE_INPUT;
var COLLAPSIBLE_CHECK;
var EVENT_LIST;
var HEIGHTSTYLE_LIST;
var DISABLED_CHECK;
var ANIMATE_LIST;
var ANIMATE_INPUT;
var HEADER_LIST;
var ACTIVEHEADER_LIST;



// ********************* API FUNCTIONS ***************************

//--------------------------------------------------------------------
// FUNCTION:
//   canInspectSelection
//
// DESCRIPTION:
//   This is a Property Inspector API function that gets called
//   whenever the selection in the document changes to decide whether
//   or not this property inspector should be displayed.
//
// ARGUMENTS:
//  None
//
// RETURNS:
//   true if the currently selected node is a Accordion element,
//   false if it is not.
//--------------------------------------------------------------------

function canInspectSelection() 
{

  var bCanInspectSelection = false;
  var dom = dw.getDocumentDOM();
  var selectedNode = dom.getSelectedNode();
	
  if ( !selectedNode || !selectedNode.getTranslatedAttribute )
    return false;

  var attr = selectedNode.getTranslatedAttribute('accordion');
  
  if ( attr && attr.length > 0 )
  {

    bCanInspectSelection = true;
    
    // If the widget manager is out of sync, run the translator
    var widgetMgr = JQuery.DesignTime.Widget.Manager.getManagerForDocument(dom); 
	
    if ( !widgetMgr.getWidget('accordion', selectedNode.id ) )
    { 
      dom.runTranslator("jQuery Widget");

      if ( !widgetMgr.getWidget('accordion', selectedNode.id ) )
      { 
        // Running the translator failed to create a design time object
        // for this widget. Either caInspectSelection() was called in the
        // middle of an edit operation, which prevents the translator from
        // running right now, or an error occurred during the translation.

        bCanInspectSelection = false;
      }
    }  
  }

  return bCanInspectSelection;
}

//--------------------------------------------------------------------
// FUNCTION:
//   initializeUI
//
// DESCRIPTION:
//   This is an internal utility function that searches through the
//   Property Inspector document to find all of the UI controls we
//   will programatically manipulate, and stores handles to them in
//   global variables which are used in some of the other functions
//   for this Property Inspector.
//
// ARGUMENTS:
//  None
//
// RETURNS:
//   N/A
//--------------------------------------------------------------------

function initializeUI() 
{
  ACCORDION_ID = document.getElementById("idEditBox");
  ACCORDION_ID.value = "";  
  MESSAGE = document.getElementById("message");
  MESSAGETEXT = document.getElementById("messageText");
  MESSAGETEXT.innerHTML = "";
  LIST_PANEL = new ListControl("panelList");
  ADD_BTN = document.getElementById("elemAdd");
  DEL_BTN = document.getElementById("elemDel");
  UP_BTN = document.getElementById("elemUp");
  DOWN_BTN = document.getElementById("elemDown");
	ACTIVE_INPUT = document.getElementById("activeInput");
  COLLAPSIBLE_CHECK = document.getElementById("collapsibleCheck");
  EVENT_LIST = new ListControl("eventList");
  HEIGHTSTYLE_LIST = new ListControl("heightStyleList");
	DISABLED_CHECK = document.getElementById("disabledCheck");
	ANIMATE_LIST = new ListControl ("animateSelect");
	ANIMATE_INPUT = document.getElementById("animateInput");
	HEADER_LIST = new ListControl ("headerSelect");
	ACTIVEHEADER_LIST = new ListControl ("activeHeaderSelect");

}

//--------------------------------------------------------------------
// FUNCTION:
//   inspectSelection
//
// DESCRIPTION:
//   This is a Property Inspector API function that gets called
//   whenever the selection in the document has changed and it has
//   been decided that this Property Inspector should be displayed.
//   This function syncs up the Property Inspector UI with the
//   widget's design-time object so that it accurately reflects
//   what is in the widget HTML markup and its JS constructor.
//
// ARGUMENTS:
//  None
//
// RETURNS:
//   N/A
//--------------------------------------------------------------------

function inspectSelection() 
{
	dw.logEvent(UT_JQUERY_ACCORDION, UT_JQUERY_ACCORDION_INSPECT);
  // Call initializeUI() here; it's how the global variables get
  // initialized. The onLoad event on the body tag is never triggered
  // in inspectors.
  initializeUI();

  var dom = dw.getDocumentDOM();
  var selectedNode = dom.getSelectedNode();
  if (!canInspectSelection())
    return;
  
  var divId = selectedNode.id;
  // Update the ID field in the PI.
  ACCORDION_ID.value = divId;
  
  var widgetMgr = JQuery.DesignTime.Widget.Manager.getManagerForDocument(dom); 
  
  if (!widgetMgr)
	return;
  
  var acc = widgetMgr.getWidget('accordion', divId );

  if ( !acc )
  {
    displayTopLayerErrorMessage(dw.loadString("jquery/widget/alert/broken structure"));
    return;
  }
  
  clearTopLayerErrorMessage();   

	if (acc && acc.recalculateOpts)
		acc.recalculateOpts();
  
  // Enumerate over the list of panels.

  
  var panelLabelStrings = new Array();
  var accLabels = [];
  if ( acc )
    accLabels = acc.getLabelElements();
  var selIndex = 0;
  var isBroken = false;
	
  for (var i=0; i < accLabels.length; i++)
  {
    var label = "";
    var labelNode = accLabels[i];
	
	if ( labelNode )
	{
		label = dwscripts.collectTextInNode(labelNode);
		label = dwscripts.entityNameDecode(label); 
		label = dwscripts.trim(label);
		
		if (label.length == 0)
			label = dw.loadString("jquery/widget/unlabeled panel");
	}
	else
	{
		label = dw.loadString("jquery/widget/broken panel");
		isBroken = true;
	}
    
   
    
    panelLabelStrings.push( label );
	
    if ( JQuery.DesignTime.Widget.Accordion.areConsecutiveLabelPanel(accLabels[i], acc.currentContent ))
      selIndex = i;
	
  }
  
  if ( isBroken )
  {
    // Show a warning message in the PI.
    MESSAGETEXT.innerHTML = dw.loadString("jquery/widgets/accordion/alert/broken structure");
    MESSAGE.style.display = "";
  }
  else
  {
    MESSAGETEXT.innerHTML = "";
    MESSAGE.style.display = "none";
  }
  
  // Set the list values.
  LIST_PANEL.setAll(panelLabelStrings,panelLabelStrings);
  if ( panelLabelStrings.length )
  {
       LIST_PANEL.setIndex(selIndex);
  }
	
	ACTIVE_INPUT.value = acc.getActivePanel();
	COLLAPSIBLE_CHECK.checked = acc.getCollapsibleValue();
		
	var eventArray = acc.getEventOptions();
	EVENT_LIST.setAll(eventArray, eventArray);
	if (eventArray && eventArray.length)
		EVENT_LIST.setIndex(acc.getEventIndex());
		
	var heightStyleArray = acc.getHeightStyleOptions();
	HEIGHTSTYLE_LIST.setAll(heightStyleArray, heightStyleArray);
	if (heightStyleArray && heightStyleArray.length)
		HEIGHTSTYLE_LIST.setIndex(acc.getHeightStyleIndex());
		
	DISABLED_CHECK.checked = acc.getDisabledValue();
	
	var easingArray = acc.getEasingOptions();
	ANIMATE_LIST.setAll(easingArray, easingArray);
	if (easingArray && easingArray.length)
		ANIMATE_LIST.setIndex(acc.getEasingIndex());
		
	ANIMATE_INPUT.value = acc.getAnimateDurationValue();
	
	var headerArray = acc.getHeaderOptions();
	HEADER_LIST.setAll(headerArray, headerArray);
	if (headerArray && headerArray.length)
		HEADER_LIST.setIndex(acc.getHeaderIndex());
		
	var activeHeaderArray = acc.getActiveHeaderOptions();
	ACTIVEHEADER_LIST.setAll(activeHeaderArray, activeHeaderArray);
	if (activeHeaderArray && activeHeaderArray.length)
		ACTIVEHEADER_LIST.setIndex(acc.getActiveHeaderIndex());				
	
  enableControls(acc, isBroken);
}

//--------------------------------------------------------------------
// FUNCTION:
//   enableControls
//
// DESCRIPTION:
//   This internal utility function enables/disables the controls
//   in the Property Inspector based on the state of the widget
//   design-time object.
//
// ARGUMENTS:
//  acc - object - The widget design-time object.
//  errorOnPage - boolean - true if the widget markup is invalid,
//                          false if the markup is valid.
//
// RETURNS:
//   N/A
//--------------------------------------------------------------------

function enableControls(acc, errorOnPage)
{
  if (LIST_PANEL.getLen() > 0)
       LIST_PANEL.enable();
  else
       LIST_PANEL.disable();

  if (!errorOnPage)
  {
    ADD_BTN.removeAttribute("disabled");
    ADD_BTN.src = "../Shared/MM/Images/btnAddSmall.png";
	DEL_BTN.removeAttribute("disabled");
    DEL_BTN.src = "../Shared/MM/Images/btnDelSmall.png";
	UP_BTN.removeAttribute("disabled");
    UP_BTN.src = "../Shared/MM/Images/btnUpSmall.png";
	DOWN_BTN.removeAttribute("disabled");
    DOWN_BTN.src = "../Shared/MM/Images/btnDownSmall.png";
  }
  else
  {
    ADD_BTN.setAttribute("disabled", true);
    ADD_BTN.src = "../Shared/MM/Images/btnAddSmall_dis.png";
	DEL_BTN.setAttribute("disabled", true);
    DEL_BTN.src = "../Shared/MM/Images/btnDelSmall_dis.png";
	UP_BTN.setAttribute("disabled", true);
    UP_BTN.src = "../Shared/MM/Images/btnUpSmall_dis.png";
	DOWN_BTN.setAttribute("disabled", true);
    DOWN_BTN.src = "../Shared/MM/Images/btnDownSmall_dis.png";
  }
  
  var selIndex = LIST_PANEL.getIndex();
  if (selIndex == 0)
  {
	UP_BTN.setAttribute("disabled", true);
    UP_BTN.src = "../Shared/MM/Images/btnUpSmall_dis.png";
  }
  if (selIndex >= LIST_PANEL.getLen()-1)
  {
	DOWN_BTN.setAttribute("disabled", true);
    DOWN_BTN.src = "../Shared/MM/Images/btnDownSmall_dis.png";
  }
  if (LIST_PANEL.getLen() == 0)
  {
	DEL_BTN.setAttribute("disabled", true);
    DEL_BTN.src = "../Shared/MM/Images/btnDelSmall_dis.png";
  }
	
	EVENT_LIST.enable();
	ANIMATE_LIST.enable();
	HEADER_LIST.enable();
	ACTIVEHEADER_LIST.enable();
	HEIGHTSTYLE_LIST.enable();
}

//--------------------------------------------------------------------
// FUNCTION:
//   updateTag
//
// DESCRIPTION:
//   This function handles all of the user actions triggered by the
//   user from the Propery Inspector controls.
//
// ARGUMENTS:
//  action - string - The name of the action to perform.
//
// RETURNS:
//   N/A
//--------------------------------------------------------------------

function updateTag(action)
{
  var dom = dw.getDocumentDOM();
  var selectedNode = dom.getSelectedNode();
  if (!canInspectSelection())
    return;
  
  var divId = selectedNode.id;
  
  var widgetMgr = JQuery.DesignTime.Widget.Manager.getManagerForDocument(dom); 
  var acc = widgetMgr.getWidget('accordion', divId );
  if ( !acc )
    return;
  
  var contentElements = acc.getContentElements();
  var selIndex = LIST_PANEL.getIndex();
  
  if (action) 
  {
    switch (action)
    {
			case "setActive":
      {
        acc.setActiveValue(ACTIVE_INPUT.value);
      }
      break;
			
			case "setCollapsible":
      {
        acc.setCollapsibleValue(COLLAPSIBLE_CHECK.checked);
      }
      break;
			
			case "setEvent":
      {
        acc.setEvent(EVENT_LIST.getIndex());
      }
      break;
			
			case 'setHeightStyle'	:
			{
				acc.setHeightStyleIndex(HEIGHTSTYLE_LIST.getIndex());
			}
			break;
			
			case 'setDisabled':
			{
				acc.setDisabledValue(DISABLED_CHECK.checked);
			}
			break;
			
			case 'setAnimateCheck':
			{
				acc.setAnimateCheckValue(ANIMATE_CHECK.checked);
			}
			break;
			
			case 'setAnimateSelect':
			{
				acc.setEasingIndex(ANIMATE_LIST.getIndex());
			}
			break;
			
			case 'setAnimateEasingInput':
			{
				acc.setAnimateEasingInput(ANIMATE_LIST.getValue());
			}
			break;
			
			case 'setAnimateInput':
			{
				acc.setAnimateDurationValue(ANIMATE_INPUT.value);
			}
			break;
			
			case 'setHeader':
			{
				acc.setHeaderIndex(HEADER_LIST.getIndex());
			}
			break;
			
			case 'setActiveHeader':
			{
				acc.setActiveHeaderIndex(ACTIVEHEADER_LIST.getIndex());
			}
			break;
			
			
			
      case "addPanel":
      {
        // Add new panel after the current selection.
        acc.addNewPanel();
        
        // Add after current panel.
        selIndex = selIndex+1;
        
        
      }
      break;
      
      case "deletePanel":
      {
        // Verify bounds.
        if (!contentElements || contentElements.length < 0 || selIndex < 0 || selIndex >= contentElements.length )
          return;
          
        // Delete the currently selected panel.
        var selPanel = contentElements[selIndex];
		var labelForPanel = acc.getLabelForContent(selPanel);
		
		acc.canRefresh = false;
        selPanel.outerHTML = "";
		labelForPanel.outerHTML = "";
		acc.canRefresh = true;
        
        var newPanelLength = contentElements.length -1;
        if ( newPanelLength <= selIndex )
          selIndex = newPanelLength -1;
      }
      break;
      
      case "movePanelUp":
      {
        // Verify bounds.
        if (!contentElements || contentElements.length < 0 || (selIndex-1) < 0 || selIndex >= contentElements.length )
          return;
          
        var selPanel = contentElements[selIndex];
				var selLabel = acc.getLabelForContent(selPanel);
				var siblingPanel = contentElements[selIndex-1];
				var siblingLabel = acc.getLabelForContent(siblingPanel);
        
				acc.canRefresh = false;
		
        siblingPanel.outerHTML = selLabel.outerHTML + selPanel.outerHTML + siblingLabel.outerHTML + siblingPanel.outerHTML;
        selPanel.outerHTML = "";
				selLabel.outerHTML = "";
				siblingLabel.outerHTML = "";
        acc.canRefresh = true;
		
        selIndex = selIndex-1;
      }
      break;
      
      case "movePanelDown":
      {
        // Verify bounds.
        if (!contentElements || contentElements.length < 0 || selIndex < 0 || (selIndex+1) >= contentElements.length )
          return;
          
        var selPanel = contentElements[selIndex];
		var selLabel = acc.getLabelForContent(selPanel);
		var siblingPanel = contentElements[selIndex+1];
		var siblingLabel = acc.getLabelForContent(siblingPanel);
		
		acc.canRefresh = false;
        siblingPanel.outerHTML = siblingLabel.outerHTML + siblingPanel.outerHTML + selLabel.outerHTML + selPanel.outerHTML;
        selPanel.outerHTML = "";
		selLabel.outerHTML = "";
		siblingLabel.outerHTML = "";
		acc.canRefresh = true;
        
        selIndex = selIndex+1;
     
      }
      break;
      
      case "panelSelected":
      {
        // Don't need to do anything, the refresh below will set it to the correct index.
      }
      break;
      
      case "id":
      {
        // Validate the new id.
        var newId = ACCORDION_ID.value;
        if ( newId == divId )
          return; // Nothing to change.
        
        if ( newId.length == 0 )
        {
          alert(dw.loadString("jquery/widget/alert/need unique id"));
          return;
        }
        
        if ( dom.getElementById(newId) )
        {
          alert(dw.loadString("jquery/widget/alert/id already exists"));
          return;
        }
        
        if ( !dwscripts.isValidID(newId) )
        {
          alert(dw.loadString("jquery/widget/alert/id is invalid"));
          return;
        }
        
        // Update the constructor.
        acc.updateWidgetId(newId);

        // Update the WidgetManager for the new ID.
        widgetMgr.setWidget('accordion', newId, acc );
      }
      break;
      
      case "guide":
      {
        dwscripts.displayDWHelp(widgetGuide);
      }
      break;    
			
			
    }
   }

  // All these edits modify the accordian. We need to recreate the JS Object to reflect those changes.
  acc.refresh();
  
  contentElements = acc.getContentElements(); // Re-get the panels since they've changed.

  if (contentElements && contentElements.length > 0 && selIndex >= 0 && selIndex < contentElements.length )
  {
      acc.openPanel(contentElements[selIndex]);
  }

  // Make sure selection stays on the div.
  dom.setSelectedNode(selectedNode); 
  inspectSelection();
  LIST_PANEL.setIndex(selIndex);
  //we need to refresh live view after doing this, as partial refresh will not be suffiecient to show the changes!
  dw.reloadLiveView();
}
