/*************************************************************************
*
* ADOBE CONFIDENTIAL
* ___________________
*
*  Copyright 2012 Adobe Systems Incorporated
*  All Rights Reserved.
*
* NOTICE:  All information contained herein is, and remains
* the property of Adobe Systems Incorporated and its suppliers,
* if any.  The intellectual and technical concepts contained
* herein are proprietary to Adobe Systems Incorporated and its
* suppliers and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Adobe Systems Incorporated.
**************************************************************************/

//--------------------------------------------------------------------
// CLASS:
//   JQuery.DesignTime.Editing.Utils
//
// DESCRIPTION:
//	A collection of general functions to help with jQuery idget editing in Dreamweaver

if( typeof JQuery == 'undefined' ) JQuery = {};
if( typeof JQuery.DesignTime == 'undefined' ) JQuery.DesignTime = {};
if( typeof JQuery.DesignTime.Editing == 'undefined' ) JQuery.DesignTime.Editing = {};

// FUNCTIONS:
//  JQuery.DesignTime.Editing.Utils - Constructor method. No instructions right now

JQuery.DesignTime.Editing.Utils = function()
{
};

// FUNCTIONS:
//  JQuery.DesignTime.Editing.Utils.canInsertWidget - reports conditions that prevent widget insertion

JQuery.DesignTime.Editing.Utils.canInsertWidget = function(dom, widgetType)
{
	var sel = dom.getSelection(true);
	var selNode = dom.getSelectedNode();

	if( selectionIsContainedInTagOfType(sel, "MMTEMPLATE:EDITABLE", dom, false) )
	{
		alert(dw.loadString('jquery/widget/alert/cant insert into editable region'));
		return false;
	}
	
	if( !dom.isHeadEditable() )
	{
		alert( dwscripts.sprintf(dw.loadString('jquery/alert/lockedHeadRegion'), dom.getAttachedTemplate()) );
		return false;
	}  
	
	if( dom.URL == '' )
	{
		if(confirm(dw.loadString('jquery/widget/please save file')))
		{
			if (dw.canSaveDocument(dw.getDocumentDOM()))
			{
				dw.saveDocument(dw.getDocumentDOM());
				var saved = (dom.URL != '');
				return saved;
			}
		}
		return false;
	}

	return true;
};

// FUNCTIONS:
//  JQuery.DesignTime.Editing.Utils.getNewJSObjectName - Fetches a new JQuery 
//	Widget name for the widget type provided

JQuery.DesignTime.Editing.Utils.getNewJSObjectName = function(baseName)
{ 
	return dwscripts.getUniqueId(baseName, 1);
};

//When undo an insertion of a widget the widget object is not removed from the widget manager
//This function will remove any cached object that does not exists in page
JQuery.DesignTime.Editing.Utils.removeCachedObjects = function(dom, widgetType)
{
  var widgetMgr;
	if( typeof (dom.JQuery) == 'undefined' || 
      typeof (dom.JQuery.Widgets) == 'undefined' || 
      typeof (dom.JQuery.Widgets.Manager) == 'undefined' )
	{
		return;
	}

	widgetMgr = dom.JQuery.Widgets.Manager;
  if( widgetMgr.widgets && widgetType )
  {
    for (var id in widgetMgr.widgets[widgetType])
    { 
      if( !dw.nodeExists(widgetMgr.widgets[widgetType][id].element) )
      {
        widgetMgr.deleteWidget(widgetType, id);
      }
    }
  }
};
/*
JQuery.DesignTime.Editing.Utils.parseForJsOptions

We use this method to create and return an options object that we can use. This object should contain all javascript options for a widget. For an input (widgetStr) like following:
$(function() {
		$( "#Accordion1" ).accordion({
			active:2,
			collapsible:true
		}); 
	});
	
	the output would be and object "obj = {active:2,collapsible:true}";
	*/
JQuery.DesignTime.Editing.Utils.parseForJsOptions = function(widgetStr, widgetType)
{
	var returnObject = null;
	var parseString = "";
	var parseArray = widgetStr.split(widgetType);
	if (parseArray.length > 1)
	{
		for( var i = 1; i < parseArray.length; i++ )
		{
			parseString += widgetType;
			parseString += parseArray[i];
		}
		
		if (parseString)
		{
			parseArray = JQuery.DesignTime.Editing.Utils.getContainedString(parseString, '{', '}', true);
			if (parseArray)
			{
				parseString = parseArray[0];
				if (parseString)
				{
					parseString = parseString.replace(/\n+/g,'');
					
					try
					{
						 eval('returnObject = ' + parseString);
					}
					catch(e)
					{
						returnObject = null;
					}
				}
			}
		}
	}
	return returnObject;
}
JQuery.DesignTime.Editing.Utils.getContainedString = function (str, char1, char2, useStack)
{
	if( typeof useStack == 'undefined' )
		useStack = false;
	
	var returnArray = [];
	
	if (!str || !char1 || !char2)
		return;
	
	var i = str.indexOf(char1);
	
	if( i < 0 )
		return null;
	
	if( useStack == false )
	{
		var j = str.indexOf(char2);
		
		returnArray[0] = str.slice(i, j+1);
		returnArray[1] = i;
		returnArray[2] = j+1;
		return returnArray;
	}
	
	var stack = [];	
	
	for( j = i ; j < str.length; j++ )
	{
		//ignore any characters inside quotes 
		if (str.charAt(j) == "\"" || str.charAt(j) == "'")
		{
			j += str.slice(j+1).indexOf(str.charAt(j)) + 1;
			continue;
		}
		
		switch (str.charAt(j))
		{
			case '(': 
				stack.push('(');
				break;
			case '[':
				stack.push('[');
				break;
			case '{':
				stack.push('{');
				break;
			case ')':
				var topStack = stack.pop();
				if( topStack != '(' )
				{
					stack.push(topStack);							//push it back in
					stack.push(')');
				}
				break;
			case ']':
				var topStack = stack.pop();
				if( topStack != '[' )
				{
					stack.push(topStack);							//push it back in
					stack.push(']');
				}
				break;
			case '}':
				var topStack = stack.pop();
				if( topStack != '{' )
				{
					stack.push(topStack);							//push it back in
					stack.push('}');
				}
				break;						
		}
	
		if (!stack.length)
		{
			if( str.charAt(j) == char2 )
			{
				returnArray[0] = str.slice(i, j+1);
				returnArray[1] = i;
				returnArray[2] = j+1;
				return returnArray;
			}
		}
	}
	return returnArray;
}


