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

var helpDoc = MM.HELP_jQueryDatepicker;			//need new help ids

var DATEPICKER_ID;
var DATEFORMAT_LIST;
var LOCALE_LIST; 
var SHOWBUTTONIMAGE_CHECK; 
var BUTTONIMAGE_INPUT ;
var CHANGEMONTH_CHECK; 
var CHANGEYEAR_CHECK; 
var INLINE_CHECK; 
var SHOWBUTTONPANEL_CHECK ;
var MINDATE_INPUT; 
var	MINDATE_INPUT; 
var	MONTHS_INPUT; 
var TAGNAME;
var BROWSE_BTN;

if (!String.prototype.beginsWith) {
  String.prototype.beginsWith = function (str){
    return this.indexOf(str) == 0;
  };
}



// ********************* 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 Datepicker element,
//   false if it is not.
//--------------------------------------------------------------------

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

	bCanInspectSelection = true;
	var widgetMgr = JQuery.DesignTime.Widget.Manager.getManagerForDocument(dom); 
	
	if (!widgetMgr)
		return false;

	if ( !widgetMgr.getWidget('datepicker', selectedNode.id ) )
		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() 
{
	DATEPICKER_ID = document.getElementById("idInput");
  DATEFORMAT_LIST = new ListControl("dateFormatSelect");
  LOCALE_LIST = new ListControl("localeSelect");
  SHOWBUTTONIMAGE_CHECK = document.getElementById("showButtonImageCheck");
  BUTTONIMAGE_INPUT = document.getElementById("buttonImageInput");
	BUTTONIMAGE_INPUT.value = "";
  CHANGEMONTH_CHECK = document.getElementById("changeMonthCheck");
  CHANGEYEAR_CHECK = document.getElementById("changeYearCheck");
  INLINE_CHECK = document.getElementById("inlineCheck");
  SHOWBUTTONPANEL_CHECK = document.getElementById("showButtonPanelCheck");
	MINDATE_INPUT = document.getElementById("minDateInput");
	MAXDATE_INPUT = document.getElementById("maxDateInput");
	MONTHS_INPUT = document.getElementById("monthsInput");
	BROWSE_BTN = document.getElementById('browseImage');
	TAGNAME = "";
}

//--------------------------------------------------------------------
// 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_DATEPICKER, UT_JQUERY_DATEPICKER_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();
	
	var attr = selectedNode.getTranslatedAttribute('datepicker');
  
  if ( !attr || attr.length <= 0 )
  {
		dom.runTranslator("jQuery Widget");
	}
	
	var tagString = selectedNode.outerHTML.toString();
	TAGNAME = tagString.beginsWith('<input')? 'Input' : 'Div';
	
  if (!canInspectSelection())
    return;
		
	var inputId = selectedNode.id;
  // Update the ID field in the PI.
  DATEPICKER_ID.value = inputId;	
	
	var widgetMgr = JQuery.DesignTime.Widget.Manager.getManagerForDocument(dom); 
  
  if (!widgetMgr)
	return;
	
	var dp = widgetMgr.getWidget('datepicker', inputId);
	
	if (!dp)
	{
		return;
	}
	
	if (dp && dp.recalculateOpts)
		dp.recalculateOpts();
	
	var dateFormatArray = dp.getDateFormatArray();
	DATEFORMAT_LIST.setAll(dateFormatArray,dateFormatArray);
	if( dateFormatArray.length )
		DATEFORMAT_LIST.setIndex(dp.getDateFormatIndex());
		
	var localeArray = dp.getLocaleArray();
	LOCALE_LIST.setAll(localeArray,localeArray);
	var localeIndex = dp.getLocaleIndex();
	if( localeArray.length )
		LOCALE_LIST.setIndex(localeIndex);
		
	SHOWBUTTONIMAGE_CHECK.checked = dp.getShowButtonImageValue();
	
	if( SHOWBUTTONIMAGE_CHECK.checked )
	{
		BUTTONIMAGE_INPUT.value = dp.getButtonImagePathValue();
	}
	
	CHANGEMONTH_CHECK.checked = dp.getChangeMonthValue();
	CHANGEYEAR_CHECK.checked = dp.getChangeYearValue();
	INLINE_CHECK.checked = TAGNAME == 'Div';
	SHOWBUTTONPANEL_CHECK.checked = dp.getShowButtonPanelValue();
	MINDATE_INPUT.value = dp.getMinDateValue();
	MAXDATE_INPUT.value = dp.getMaxDateValue();
	MONTHS_INPUT.value = dp.getMonthValue().toString();
	
	if( MONTHS_INPUT.value = "" )
		MONTHS_INPUT.value = "1";
		
	enableControls(dp);
}

//--------------------------------------------------------------------
// 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(dp)
{
	if( LOCALE_LIST.getLen() > 0 )
		LOCALE_LIST.enable();
	else
		LOCALE_LIST.disable();
		
	if( DATEFORMAT_LIST.getLen() > 0 )	
		DATEFORMAT_LIST.enable();
	else
		DATEFORMAT_LIST.disable();
		
	if (!SHOWBUTTONIMAGE_CHECK.checked)
	{
		BUTTONIMAGE_INPUT.disabled=true;
		BROWSE_BTN.setAttribute("disabled", true);
	}
	else
	{
		BUTTONIMAGE_INPUT.disabled=false;
		BROWSE_BTN.removeAttribute("disabled");
	}
}

//--------------------------------------------------------------------
// 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 inputId = selectedNode.id;
  
	if (!inputId)
		return;
  
	var widgetMgr = JQuery.DesignTime.Widget.Manager.getManagerForDocument(dom); 
	var dp = widgetMgr.getWidget('datepicker', inputId );
	if ( !dp )
		return;
		
	if (action)
	{
		switch (action)
		{
			case "id":
			{
			// Validate the new id.
        var newId = DATEPICKER_ID.value;
        if ( newId == inputId )
          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.
        dp.updateWidgetId(newId);
				inputId = newId;
				
        // Update the WidgetManager for the new ID.
        widgetMgr.setWidget('datepicker', newId, dp );
			}
			break;
			case "setDateFormat":
			{
				dp.setDateFormatIndex(DATEFORMAT_LIST.getIndex());
			}
			break;
			case "setLocale":
			{
				dp.setLocaleValue(LOCALE_LIST.getIndex());
			}
			break;
			case "setShowButtonImage":
			{
				dp.setShowButtonImageValue(SHOWBUTTONIMAGE_CHECK.checked);
			}
			break;
			case "setButtonImagePath":
			{
				dp.setButtonImagePathValue(BUTTONIMAGE_INPUT.value);
			}
			break;
			case "setChangeMonth":
			{
				dp.setChangeMonthValue(CHANGEMONTH_CHECK.checked);
			}
			break;
			case "setInline":
			{
				if (INLINE_CHECK.checked)
				{
					selectedNode.outerHTML = '<div id="' + inputId + '"></div>';
					
				}
				else
				{
					selectedNode.outerHTML = '<input type="text" id="' + inputId + '"/>';
				}
			}
			break;
			case "setChangeYear":
			{
				dp.setChangeYearValue(CHANGEYEAR_CHECK.checked);
			}
			break;
			case "setShowButtonPanel":
			{
				dp.setShowButtonPanelValue(SHOWBUTTONPANEL_CHECK.checked);
			}
			break;
			case "setMinDate":
			{
				dp.setMinDateValue(MINDATE_INPUT.value);
			}
			break;
			case "setMaxDate":
			{
				dp.setMaxDateValue(MAXDATE_INPUT.value);
			}
			break;
			case "setNumberOfMonths":
			{
				dp.setMonthValue(MONTHS_INPUT.value);
			}
			break;
		}
	}
	dp.refresh();
	var newNode = dom.getElementById(inputId);
	dom.setSelectedNode(newNode);
	
	inspectSelection();
    //we need to refresh live view after doing this, as partial refresh will not be suffiecient to show the changes!
	dw.reloadLiveView();
}

function browseForSource()
{
	var browseTitle = dw.loadString("Inspectors/jquery_datepicker/browseTitle");
	
	var filename = 	dw.browseForFileURL("select", browseTitle, true);
	BUTTONIMAGE_INPUT.value = filename;
	updateTag('setButtonImagePath');
}