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

//--------------------------------------------------------------------
// CLASS:
//   JQuery.DesignTime.Widget.Progressbar
//
// DESCRIPTION:
//   This class is used by the Progressbar property inspector to manage
//   and manipulate the design-time state of the widget's markup in the
//   design view.
//--------------------------------------------------------------------

//--------------------------------------------------------------------
// FUNCTION:
//   Progressbar
//
// DESCRIPTION:
//	 This is the constructor method for this design time Progressbar object.
//	 It calls the base widget constructor which helps us inherit all base methods
//	 like addClass, removeClass, ensureValidElements etc
//	 
//   It also manages the Progressbar's widget markup in the design view. This constructor
//   is registered in the JQuery Widget translator found at:
//
//       Configuration/Translators/jQueryWidget.htm
//	 
//
// ARGUMENTS:
//   dom - object - The DOM used by the document in design view.
//   element - object - The top-level DOM element for our widget markup.
// RETURNS:
//   N/A
//--------------------------------------------------------------------

JQuery.DesignTime.Widget.Progressbar = function(dom, element, consArgs)
{
  JQuery.DesignTime.Widget.Base.call(this, dom, element);

	this.opts = {};
	this.opts = consArgs;
	this.init(element);
};

// JQuery.DesignTime.Widget.Progressbar derives from our JQuery.DesignTime.Widget.Base
// class, so create a Base object and use it as our prototype so we inherit all of its
// methods.
JQuery.DesignTime.Widget.Progressbar.prototype = new JQuery.DesignTime.Widget.Base();

// Reset the constructor property back to Progressbar for our newly created prototype
// object so callers know that our object was created with the Progressbar constructor.
JQuery.DesignTime.Widget.Progressbar.prototype.constructor = JQuery.DesignTime.Widget.Progressbar;

//--------------------------------------------------------------------
// FUNCTION:
//   init
//
// DESCRIPTION:
//   Initializes the design-time object's properties. This  method is
//   called from the constructor and refresh() methods.
//
// ARGUMENTS:
//   element - object - The widget's top-level DOM element.
//
// RETURNS:
//   N/A
//--------------------------------------------------------------------
JQuery.DesignTime.Widget.Progressbar.prototype.init = function(element)
{
	this.element = this.getElement(element);

	this.canRefresh = true;
};

//--------------------------------------------------------------------
// FUNCTION:
//  	getValue
//
// DESCRIPTION:
//  	This method returns the value of the Value attribute in the widget constructor.
//		If user changes the 'Value' value in the code. This is where we 'read' that updated 
//		Value from the object
//
// ARGUMENTS:
//  	None
//
// RETURNS:
//  	String: The value of the Value attribute as string
//--------------------------------------------------------------------

JQuery.DesignTime.Widget.Progressbar.prototype.getValue = function()
{
	if( this.opts && this.opts.value != null && typeof this.opts.value != 'undefined' )
	{
		return this.opts.value;
	}
	return 0;
}

//--------------------------------------------------------------------
// FUNCTION:
//  	setValue
//
// DESCRIPTION:
//  	When a new value for Value is attained for the Value attribute from the PI
//		we have to update our opts object with this new 'Value' value and initiate an update cycle
//		for this change to be reflected in code.
//
// ARGUMENTS:
//  	value: The value of the Value attribute that needs to be set
//
// RETURNS:
//  	None
//--------------------------------------------------------------------

JQuery.DesignTime.Widget.Progressbar.prototype.setValue = function(value)
{
	if( value == null || typeof value == "undefined" )
		return;
	
	if (!this.opts)
		this.opts = {};
	
	var oldValue = this.opts.value;
	if( value == "" || parseInt(value).toString() == 'NaN' || parseInt(value) == 0 )
	{
		this.opts.value = null;
	}	
	else
	{
		this.opts.value = parseInt(value);
	}
	
	if (oldValue != this.opts.value)
		this.updateOptions(this.widgetType, this.opts);
}

//--------------------------------------------------------------------
// FUNCTION:
//  	getDisabledValue
//
// DESCRIPTION:
//  	This method returns the value of the disabled attribute in the widget constructor.
//		If user changes the disabled value in the code. This is where we 'read' that updated 
//		value from the object
//
// ARGUMENTS:
//  	None
//
// RETURNS:
//  	Boolean: The value of the disabled attribute as boolean
//--------------------------------------------------------------------

JQuery.DesignTime.Widget.Progressbar.prototype.getDisabledValue = function()
{	
	if( this.opts && this.opts.disabled != null && typeof this.opts.disabled != 'undefined' )
	{
		return (this.opts.disabled == true);
	}
	return false;
}

//--------------------------------------------------------------------
// FUNCTION:
//  	setDisabledValue
//
// DESCRIPTION:
//  	When a new value for disabled is attained for the disabled attribute from the PI
//		we have to update our opts object with this new disabled value and initiate an update cycle
//		for this change to be reflected in code.
//
// ARGUMENTS:
//  	None
//
// RETURNS:
//  	None
//--------------------------------------------------------------------

JQuery.DesignTime.Widget.Progressbar.prototype.setDisabledValue = function(disabledValue)
{	
	if( disabledValue == null || typeof disabledValue == "undefined" )
		return;

	if (!this.opts)
		this.opts = {};
		
	if( disabledValue == true )
	{
		this.opts.disabled = true;
	}	
	else
	{
		this.opts.disabled = null;
	}
	
	this.updateOptions(this.widgetType, this.opts);
}
JQuery.DesignTime.Widget.Progressbar.prototype.getAnimatedNode = function()
{
	if (!this.dom)
		return;
		
	var styleNodes = this.dom.getElementsByTagName('style');
	
	for (var i = styleNodes.length-1; i >= 0; i--)
	{
		var styleContent = styleNodes[i].innerHTML;
		animatedClass = styleContent.match(/\.ui-progressbar \.ui-progressbar-value /g);
		
		if (animatedClass)
		{
			return styleNodes[i];
		}			
	}
	return null;
}
JQuery.DesignTime.Widget.Progressbar.prototype.getAnimatedValue = function()
{
	return (this.getAnimatedNode() != null);
}
JQuery.DesignTime.Widget.Progressbar.prototype.setAnimatedValue = function(animatedValue)
{
	if (!this.dom)
		return;
		
	var animatedNode = this.getAnimatedNode();
	var animatedStyleExists = false;
	
	if (animatedNode)
		animatedStyleExists = true;	
	
	if (animatedStyleExists == animatedValue)
		return;
		
	if (animatedValue)
	{		
		var fileName = this.dom.copyAssetWithoutReference("Shared/jQueryWidgets/Widgets/Progressbar/pbar-ani.gif", "images/pbar-ani.gif");
		var fileName = fileName.replace(/\\/g,"/")
		var headNode = this.dom.getElementsByTagName('head')[0];
		headNode.innerHTML = headNode.innerHTML + "<style>\n.ui-progressbar .ui-progressbar-value { \nbackground-image: url(" + fileName + ");  \nbackground-size: contain\n}\n</style>";
	}
	else if (animatedNode)
	{
		animatedNode.outerHTML = "";
	}

}


//--------------------------------------------------------------------
// FUNCTION:
//   getAssets
//
// DESCRIPTION:
//   Static function that returns the assets to be applied to page
//
// ARGUMENTS:
//   None
//
// RETURNS:
//   (array of objects)
//--------------------------------------------------------------------

JQuery.DesignTime.Widget.Progressbar.getAssets = function()
{
	var assets = new Array();
	
	assetObject = new Object();
	assetObject.fullPath = jQProgressbarImagesPath;
	assetObject.file = jQProgressbarImagesFile;
	assetObject.type = "";
	assets.push(assetObject);
	
	assetObject = new Object();
	assetObject.fullPath = jQCoreCssPath;
	assetObject.file = jQCoreCssFile;
	assetObject.type = "link";
	assets.push(assetObject);

	assetObject = new Object();
	assetObject.fullPath = jQCssThemePath;
	assetObject.file = jQCssThemeFile;
	assetObject.type = "link";
	assets.push(assetObject);
	
	assetObject = new Object();
	assetObject.fullPath = jQProgressbarCssWidgetPath;
	assetObject.file = jQProgressbarCssWidgetFile;
	assetObject.type = "link";
	assets.push(assetObject);
	
	assetObject = new Object();
	assetObject.fullPath = jQMainPath;
	assetObject.file = jQMainFile;
	assetObject.type = "javascript";
	assets.push(assetObject);
	
	assetObject = new Object();
	assetObject.fullPath = jQProgressbarJsPath;
	assetObject.file = jQProgressbarJsFile;
	assetObject.type = "javascript";
	assets.push(assetObject);
	
	return (assets);
	
};

//--------------------------------------------------------------------
// FUNCTION:
//   refresh
//
// DESCRIPTION:
//   None
//
// ARGUMENTS:
//   Syncs up the internal state of the design-time widget object
//   with the markup that currently exists in the design view.
//
//   This method gets called from the translator if a design-time
//   object already exists for a specific widget ID, and from various
//   methods in the Progressbar property inspector.
//
// RETURNS:
//   N/A
//--------------------------------------------------------------------

JQuery.DesignTime.Widget.Progressbar.prototype.refresh = function()
{
  if (!this.canRefresh)
	return;
	
	if (!this.opts)
		this.opts = {};
	var consArgs = this.getConstructorArgs(this.widgetType);
	
	this.opts = consArgs; 
  this.init(this.element_id);  
};

//--------------------------------------------------------------------
// FUNCTION:
//   JQuery.DesignTime.Widget.Progressbar.getNewProgressbarSnippet
//
// DESCRIPTION:
//   Static utility function that returns a string containing the
//   markup for a complete Progressbar.
//
// ARGUMENTS:
//  id - string - The string to use as the widget's id attribute.
//
// RETURNS:
//   String that is the HTML markup fragment for the panel.
//--------------------------------------------------------------------

JQuery.DesignTime.Widget.Progressbar.getNewProgressbarSnippet = function(id)
{
  var dpSnippet = '<div id="' + id + '">\n</div>';
  return dpSnippet;
};

//--------------------------------------------------------------------
// FUNCTION:
//   JQuery.DesignTime.Widget.Progressbar.getNewProgressbarConstructorSnippet
//
// DESCRIPTION:
//   Static utility function that returns a string that contains the
//   constructor snippet for creating a JQuery widget with the specified id.
//
// ARGUMENTS:
//  id - string - The id of the widget markup to insert into the
//                constructor snippet.
//
// RETURNS:
//   String containing JS that is the constructor call to create the
//   widget.
//--------------------------------------------------------------------

JQuery.DesignTime.Widget.Progressbar.getNewProgressbarConstructorSnippet = function(id)
{
  return ' $(function() {\n\t$( "#' + id + '" ).progressbar(); \n});';
 /* $(function() {
		$( "#Progressbar1" ).Progressbar();
	});*/
};

JQuery.DesignTime.Widget.Progressbar.getDeleteWidgetCallback = function(removeString, widgetId)
{
	var deleteFunction = function(e)
	{
		var targetDom = e.target.ownerDocument;					
		
		if (!targetDom)
			return;
		
		var scriptTags = targetDom.getElementsByTagName("script");
		for( var i = 0; i < scriptTags.length; i++ )
		{
			var str = scriptTags[i].innerHTML;
			var index = str.indexOf(removeString);
			if( index >= 0 )
			{
				var strBefore = str.substr(0, index);
				var strAfter = str.substr(index+removeString.length);
				while( strBefore.length > 0 && ( strBefore.charAt(strBefore.length-1) == ' ' ||
												strBefore.charAt(strBefore.length-1) == '\t' ||
												strBefore.charAt(strBefore.length-1) == '\n' ||
												strBefore.charAt(strBefore.length-1) == '\r' ) )
				{
					strBefore = strBefore.substr(0, strBefore.length-1);
				}
				// We'll store the new InnerHTML to newInnerHTML and we'll decide later whether we'll replace the inner value with this
				// one or we'll simply remove the SCRIPT tag.
				var newInnerHTML = strBefore + strAfter;

				// Look if there is any valid JS code remining in the SCRIPT tag; of empty (or only comments were found) => go and remove it
				var tempInnerHTML = newInnerHTML;
				if (tempInnerHTML && tempInnerHTML.replace)
				{
					tempInnerHTML = tempInnerHTML.replace(/[\r\n]*(?:\<\!\-\-|\/\/\-\-\>)[\r\n]*/gi, "");
					tempInnerHTML = tempInnerHTML.replace(/[\r\n\s\t]*/gi, "")
				}

				// If the InnerHTML is empty, we'll remove the entire SCRIPT tag.
				if (tempInnerHTML === "")
				{
					scriptTags[i].outerHTML = "";
				}
				else
				{
					scriptTags[i].innerHTML = newInnerHTML;
				}
				
				//Clear style tag if it was added for the progress bar animated property
				var styleNodes = targetDom.getElementsByTagName('style');
	
				for (var k = styleNodes.length-1; k >= 0; k--)
				{
					var styleContent = styleNodes[k].innerHTML;
					animatedClass = styleContent.match(/\.ui-progressbar \.ui-progressbar-value /g);
		
					if (animatedClass)
					{
						styleNodes[k].outerHTML = "";
						break;
					}			
				}
				
				// Get WidgetManager instance
				var widgetMgr = JQuery.DesignTime.Widget.Manager.getManagerForDocument(targetDom);
				
				if (!widgetMgr)
					return;
			
				// Search for widgets of the same type in the page, but different from the current one (compared by ID)
				var count = 0;
				var allWidgets = widgetMgr.getAllWidgets('progressbar');
				for (var widget in allWidgets) {
					if (widget != widgetId)
					{
						count++;
						break;
					}
				}
				
				if (count == 0)
				{
					// There are no more widgets remaining in the page of the current type, we'll remove the assets as well
					if (!JQuery.DesignTime.Widget.Progressbar)
					  return;
					  
					var assets = JQuery.DesignTime.Widget.Progressbar.getAssets();
					var tags = new Array();
					tags = tags.concat(targetDom.getElementsByTagName("script"));
					tags = tags.concat(targetDom.getElementsByTagName("link"));
					
					for (var j=0; j<tags.length; j++)
					{
					
						var tag = tags[j];
						if (tag && tag.getAttribute)
						{
							// Get the value to search; the attribute is different according to tag name: script or link
							var valueToSearch = tag.getAttribute("src");
							if (!valueToSearch)
							{
								valueToSearch = tag.getAttribute("href");
							}

							// Once we have a value, we test it against all assets
							if( valueToSearch && valueToSearch.match(/ui/) )
							{
								//Adding a special case for jquery.ui.theme.css and jquery.ui.core.css which should not be removed on removal of a widget as these files are commonly shared amongst widgets
								if (!valueToSearch.match(/jquery\.ui\.theme\.min\.css/) && !valueToSearch.match(/jquery\.ui\.core\.min\.css/))
								{	
									for (var k=0; k<assets.length; k++)
									{
										if (assets[k].type)
										{
											// If the current tag's value matches an asset we'll remove the tag from page
											if (valueToSearch.match && valueToSearch.match(new RegExp("(?:^|[\\/\\\\])" + dwscripts.escRegExpChars(assets[k].file) + "$", "gi")))
											{
												tag.outerHTML = "";
												break;
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
	};
	return deleteFunction;
}

//--------------------------------------------------------------------
// FUNCTION:
//  	getMaxValue
//
// DESCRIPTION:
//  	This method returns the value of the Max attribute in the widget constructor.
//		If user changes the 'Max' value in the code. This is where we 'read' that updated 
//		Value from the object
//
// ARGUMENTS:
//  	None
//
// RETURNS:
//  	String: The value of the Max attribute as string
//--------------------------------------------------------------------

JQuery.DesignTime.Widget.Progressbar.prototype.getMaxValue = function()
{
	if( this.opts && this.opts.max != null && typeof this.opts.max != 'undefined' )
	{
		return this.opts.max;
	}
	return 100;
}

//--------------------------------------------------------------------
// FUNCTION:
//  	setMaxValue
//
// DESCRIPTION:
//  	When a new value for Max is attained from the PI
//		we have to update our opts object with this new 'Max' value and initiate an update cycle
//		for this change to be reflected in code.
//
// ARGUMENTS:
//  	value: The value of the Max attribute that needs to be set
//
// RETURNS:
//  	None
//--------------------------------------------------------------------

JQuery.DesignTime.Widget.Progressbar.prototype.setMaxValue = function(maxValue)
{
	if( maxValue == null || typeof maxValue == "undefined" )
		return;
	
	if (!this.opts)
		this.opts = {};
	
	var oldMaxValue = this.opts.max;
	if( maxValue == "" || parseInt(maxValue).toString() == 'NaN' || parseInt(maxValue) == 0 )
	{
		this.opts.max = null;
	}	
	else
	{
		this.opts.max = parseInt(maxValue);
	}
	
	if (oldMaxValue != this.opts.max)
		this.updateOptions(this.widgetType, this.opts);
}


