/*************************************************************************

*

* 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.

**************************************************************************/





//form field names (all text fields):

//Href

//ID

//Title

//Rel

//Rev



// *********** GLOBAL VARS *****************************

var helpDoc = MM.HELP_objVideo;

var VIDEO_SRC1;
var VIDEO_SRC2;
var VIDEO_SRC3;
var VIDEO_SRC4;

var gVideoTag;
var gVideoHTMLTag;

// ******************** API ****************************

function canInspectSelection(){
  return true;
}

function inspectSelection() {
    

	gVideoTag = null;
	var theDOM = dw.getDocumentDOM(); 
    var theObj = getSelectedNode(); 
	
    // Get the value id. 	
    var vID = theObj.getAttribute('id'); 
	// update all the fields
	if( vID )
		document.topLayer.document.videoID.editText = vID;
	else
		document.topLayer.document.videoID.editText = "";
    populateIdList( vID );
	 
   	var width = theObj.getAttribute('width');
	if( width )
	{
	    document.topLayer.document.widthAttr.value = width;		
	}
	else
		document.topLayer.document.widthAttr.value = ""; 

	var height = theObj.getAttribute('height');
	if( height )
	{
	    document.topLayer.document.heightAttr.value = height;		
	}
	else
		document.topLayer.document.heightAttr.value = "";

	// Update the poster image path
	var poster = theObj.getAttribute('poster');
	if( poster )
		document.topLayer.document.poster.value = poster;
	else
		document.topLayer.document.poster.value = "";

	// Update the title	
	var title = theObj.getAttribute('title');
	if( title )
		document.topLayer.document.title.value = title;
	else
		document.topLayer.document.title.value = "";	

	var controls = theObj.getAttribute('controls');

	var muted = theObj.getAttribute('muted');

	var autoplay = theObj.getAttribute('autoplay');

	var loop = theObj.getAttribute('loop');

	if( controls )
		document.bottomLayer.document.controls.checked = true;
	else
		document.bottomLayer.document.controls.checked = false;

	if( muted )
		document.bottomLayer.document.muted.checked = true;
	else
		document.bottomLayer.document.muted.checked = false;	

	if( autoplay )
		document.bottomLayer.document.autoplay.checked = true;
	else
		document.bottomLayer.document.autoplay.checked = false;	

	if( loop )
		document.bottomLayer.document.loopVideo.checked = true;
	else
		document.bottomLayer.document.loopVideo.checked = false;

	// Update the preload tag
	var preloadval = theObj.getAttribute('preload');
	var selIdx = 0;
	if( preloadval ){
		if( preloadval == "none" )
			selIdx = 0;
		else if( preloadval == "auto" )
			selIdx = 1;
		else
			selIdx = 2;
	}
	document.bottomLayer.document.preload.selectedIndex = selIdx; 

	// Now update the sources
	updateSourceFields();

	// populate classes
	populateClassList();


	var classSel = document.getElementById('classList');
	if(classSel)
	{
		var cl = theObj.getAttribute('class');
		if(cl)
		{
			var allclasses = getClasses();
			if(allclasses)
			{
				classSel.selectedIndex = allclasses.indexOf(cl) + 1;				
			}
			else{
				classSel.selectedIndex = 0;
			}
		}
		else{
			classSel.selectedIndex = 0;
		}
	}
	//set the source
	if(isOnlyInlineSourcePresent())
	{	setInlineSourceAsPrimarySource();
	}
	
}

// ******************** LOCAL FUNCTIONS ****************************

function _updateSourceTags()
{

	VIDEO_SRC1 = null;
	VIDEO_SRC2 = null;
	VIDEO_SRC3 = null;
	VIDEO_SRC4 = null;
	
	var theObj = getSelectedNode(); 
	if( theObj ){

		var selectedNode = new TagEdit( theObj.outerHTML);
		gVideoTag     = theObj;
		gVideoHTMLTag = selectedNode;
		var childNodes = selectedNode.getChildNodes();
		var isPtagFound = false;

		if( childNodes ){

			var numChild = childNodes.length;
			if( numChild > 0 ){

				var i = 0;
				for( var j = 0; j < numChild ; j++ ){
					var tagName = childNodes[j].getTagName();
					if( tagName && tagName == "SOURCE" && i<3 ){
						
						if( i == 0  ){
							VIDEO_SRC1 = childNodes[j];
							i++;
						}
						else if( i == 1 ){
							VIDEO_SRC2 = childNodes[j];
							i++;
						}
						else if( i == 2 ){
							VIDEO_SRC3 = childNodes[j];
							i++;
						}
						
					}
					else if(tagName == "EMBED")
					{
						VIDEO_SRC4 = childNodes[j];
					}
					else if(tagName == "P")
					{
						isPtagFound = true;
						var defaulttext = childNodes[j].getInnerHTML();
						if(defaulttext)
						{						
							if(defaulttext != document.topLayer.document.defaulttext.value)
							{
								document.topLayer.document.defaulttext.value = defaulttext;
							}							
						}
						else
						{
							document.topLayer.document.defaulttext.value = '';
						}
					}// childNodes[i].getTagName() == "SOURCE"
				} // for loop
			} // numChild
		}// childNodes
		if( !isPtagFound )
		{
			document.topLayer.document.defaulttext.value = '';
		}
	} // theObj;
	
}
 
function onClickBrowsePosterImage()
{
	browseForFile('poster');
	detectWidthHeightFromImage();
}
 
function setDefaultText()
{
	
	var defText = document.topLayer.document.defaulttext.value ;
	var theObj = getSelectedNode(); 
	
	if( theObj  ){
		var selectedNode = new TagEdit( theObj.outerHTML);
		var childNodes = selectedNode.getChildNodes();
		if(defText && defText != "")
		{
			if( childNodes ){
				var i=0 ;
				var numChild = childNodes.length;
				if( numChild > 0 ){
					for( var j = 0; j < numChild ; j++ ){							
						if( childNodes[j].getTagName() == "P" ){
							i++;
							childNodes[j].setInnerHTML(defText);							
							break;
						}
					}
				}
				if(i==0)
				{
					defaulttextTag = new TagEdit("<p>"+ defText + "</p>");
					childNodes.push(defaulttextTag);
				}
			}
			gVideoHTMLTag.setChildNodes(childNodes);
		}
		else
		{
			if( childNodes ){
				var numChild = childNodes.length;
				if( numChild > 0 ){
					var newChildNodes = Array();
					for( var j = 0; j < numChild ; j++ ){
						if( childNodes[j].getTagName() != "P" ){
							newChildNodes.push(childNodes[j])
						}
					}
				}				
			}
			gVideoHTMLTag.setChildNodes(newChildNodes);
		}
		var updateText = gVideoHTMLTag .getOuterHTML();
		updateObjOuterHTML(updateText);		
	}
}

function updateSourceField(sourceField, sourceFieldValue)
{

	var someStr = '';
	if( sourceField ){

		var src1 = null;
		src1 = sourceField.getAttribute('src');
		if( src1 ){
			sourceFieldValue.value = src1;
		}
		else
			sourceFieldValue.value = someStr;
	}
	else
		sourceFieldValue.value = someStr;
}

// Call this function after every source tag insert or
// source tag attribute change.

function updateSourceFields()
{	
	// Update our source tags
	_updateSourceTags();
	// Now call each source field
	updateSourceField(VIDEO_SRC1, document.topLayer.document.source1);
	updateSourceField(VIDEO_SRC2, document.bottomLayer.document.source2);
	updateSourceField(VIDEO_SRC3, document.bottomLayer.document.source3);
	updateSourceField(VIDEO_SRC4, document.bottomLayer.document.flashVideo);	
}

function getSelectedNode()
{
	// Get the DOM of the current document. 
    var theDOM = dw.getDocumentDOM(); 
	// Get the selected node. 
    var theObj;
	if( theDOM )
		theObj  = theDOM.getSelectedNode(); 
	// return the selected node
	
	if( theObj != null && theObj.tagName.toUpperCase() != "VIDEO")
	{	
		//in cases where the selection spans outside video tag, video tag's parent is the selected node
		//here we locate the video tag amongst the children
		if(theObj.childNodes)
		{
			for(var i=0; i<theObj.childNodes.length; i++)
			{
				var tagName = theObj.childNodes[i].tagName;
				if( tagName && tagName.toUpperCase() == "VIDEO")
				{
					theObj = theObj.childNodes[i];
					break;
				}
			}
		}
	}
	return theObj;
}

// passing null to this will remove the attribute
// from the video tag.
function setOrRemoveAttribute(attrName, attrValue)
{
	// set the attribute name. if the attrValue
	// is null then remove that attribute from the video tag.
	if( attrName ){
		var theNode = getSelectedNode();
		if( theNode ){
			// Set the attribute value if present or
			// remove the attribute if not present.
			if( attrValue )
			{
				theNode.setAttribute(attrName,attrValue);
				modifyVideoTag();
			}
			else
				theNode.removeAttribute(attrName);
		}
	}
}

function removeAttr(attrName)
{   
	var theObj = getSelectedNode();
	if( theObj ){
		theObj.removeAttribute(attrName);
	}
}

function isIDInUse(idStr)
{
	var dom = dw.getDocumentDOM();
	if (dom && idStr)
	{	
		var nodeList = dom.getElementsByAttributeName('id');
		if (nodeList)
		{
			for (var i = 0; i < nodeList.length; i++)
			{
			  var nodeId = nodeList[i].getAttribute('id');
				if (nodeId && (nodeId.toLowerCase() == idStr.toLowerCase()))
					return true;
			}
		}
	}
	return false;
}

function getClasses()
{
	var dom = dw.getDocumentDOM();
	if (dom)
	{
		allClasses = dom.getSelectorsDefinedInStylesheet('class');
			
		for (i = 0; i < allClasses.length; i++)
		{
			if (allClasses[i][0] == '.')
			allClasses[i] = allClasses[i].slice(1);
		}
		return allClasses;
	}
	return null;
}
function isSame(array1, array2)
{
	if(array1 && array2 )
	{
		if(array1.length != array2.length)
			return false;
		for(var i=0 ; i<array1.length ; i++ )	
		{
			if(array1[i]!=array2[i])
			{
				return false;
			}
		}
		return true;
	}
	if(!array1 && !array2)
	{
		return true;
	}
	return false;
}
function populateClassList()
{
	   var dom = dw.getDocumentDOM();
	   var none = dw.loadString("Inspectors/text/classoption/none");
	   if (dom)
	   {
			var allClasses = getClasses();
			if( allClasses && allClasses.length > 0)
			{
				var alreadyAddedClasses = new Array();
				var classOptions = document.topLayer.document.classList.options;
				if(classOptions && alreadyAddedClasses)
				{
					for(var i=1 ; i<classOptions.length ; i++)
					{
						alreadyAddedClasses.push(classOptions[i].text);
					}
					if( !isSame(allClasses, alreadyAddedClasses) )
					{
						classOptions.disableUpdates();
						for(var i=classOptions.length-1 ; i>0 ; i--)
						{
							classOptions[i] = null;							
						}
						if(allClasses)
						{
							for( var i = 0; i < allClasses.length ; i++) {
								var theOption = new Option;
								if(theOption)
								{		
									theOption.text = allClasses[i];
									theOption.value = allClasses[i];	
									classOptions[i+1] = theOption;
								}
							}
						}
						classOptions.enableUpdates();
						var theOption = new Option;	
						if(theOption)
						{	
							theOption.text =  none;
							theOption.value =  "none";	
							classOptions[0] = theOption;
						}
					}
				}
			}
			else
			{
				var classOptions = document.topLayer.document.classList.options;
				if(classOptions && classOptions.length>1)
				{
					classOptions.disableUpdates();
					for(var i=classOptions.length-1 ; i>0 ; i--)
					{						
						classOptions[i] = null;						
					}
					classOptions.enableUpdates();
					var theOption = new Option;	
					if(theOption)
					{	
						theOption.text =  none;
						theOption.value = "none";	
						classOptions[0] = theOption;
						classOptions.length=1;
					}					
				}
				
			}
		}
}

function populateIdList(id)
{
	   var dom = dw.getDocumentDOM();
	   if (dom)
	   {
			var allIds = getIDs();
			if( allIds && allIds.length > 0)
			{
				var alreadyAddedIDs = new Array();
				var IDOptions = document.topLayer.document.videoID.options;
				if(IDOptions && alreadyAddedIDs)
				{
					var i=0;
					if(id)
						i++;
					for( ; i<IDOptions.length ; i++)
					{
						alreadyAddedIDs.push(IDOptions[i].text);
					}
					if( !isSame(allIds, alreadyAddedIDs) )
					{
						IDOptions.disableUpdates();
						for(var i=IDOptions.length-1 ; i>=0 ; i--)
						{						
							IDOptions[i] = null;						
						}
						var curIndex =0;
						if(id)
						{	
							theOption = new Option;
							if(theOption)
							{	
								theOption.text = id;
								theOption.value = id;
								IDOptions[curIndex++] = theOption;
							}
						}
						if(allIds)
						{ 
							for( var i = 0; i < allIds.length ; i++) {
								var theOption = new Option;
								if(theOption)
								{		
									theOption.text = allIds[i];
									theOption.value = allIds[i];		
									IDOptions[curIndex++] = theOption;
								}
							}
						}
						IDOptions.enableUpdates();
						if(id)
						{
							IDOptions.selectedIndex = 0;
							IDOptions[0].selected=true;
							document.topLayer.document.videoID.editText = id;
						}
						if( id || (allIds && allIds.length >0 ) ) 
						{
							theOption = new Option;
							if(theOption)	
							{
								if(id)
								{				
									theOption.text = id;
									theOption.value = id;
								}
								else
								{
									theOption.text = allIds[0];
									theOption.value = allIds[0];
								}			
								IDOptions[0] = theOption;
							}
						}
					}
				}
			}
			else
			{
				var IDOptions = document.topLayer.document.videoID.options;
				if( IDOptions && IDOptions.length > 0)
				{
					IDOptions.disableUpdates();
					for(var i=IDOptions.length-1 ; i>0 ; i--)
					{						
						IDOptions[i] = null;						
					}
					IDOptions.enableUpdates();
					IDOptions[0] = null;
					IDOptions.length=0;
					
				}
			}
		}
}

function getIDs()
{
     var dom = dw.getDocumentDOM();
     if (dom)
     {
     	var ids = dom.getSelectorsDefinedInStylesheet('id');
	
		if(ids)
		{
			allUnusedIDs = new Array();
			for (i = 0; i < ids.length; i++)
			{
				if (ids[i][0] == '#')
					ids[i] = ids[i].slice(1);
				if (!isIDInUse(ids[i]))
					allUnusedIDs.push(ids[i]);
			}
			return allUnusedIDs;
		}
		
	 }
	 return null;
}

function findExtension(fileName)
{
	if( fileName ){
		var ext = /^.+\.([^.]+)$/.exec(fileName);
		var finalExt = ext == null ? "" : ext[1];
		return finalExt;
	}
	else
		return null;
}

function getVideoType(extension)
{
    if( !extension || extension == "" )
    {
        return "";
    }
	
	if( extension == "mp4" || extension == "m4v")
	{
		return "mp4";
	}
	if(extension == "ogg" || extension == "ogv" )
	{
		return "ogg";
	}
	if(extension == "3gp" || extension == "3g2" )
	{
		return "3gp";
	}
	if(extension == "webm" )
    {
        return "webm";
    }
	return "";
}

// pass in the file name
function isKnownVideoFormat(fileName)
{
	var ext = findExtension(fileName);
	if( ext == "ogg" || ext == "mp4" || ext == "webm" || ext == "ogv"  || ext == "3gp" || ext == "m4v")
		return true;
	else
		return false;
}
// pass in the file name
function isKnownPosterFormat(fileName)
{
	var ext = findExtension(fileName);
	if( ext == "gif" || ext == "jpg" || ext == "jpeg" || ext == "png"  || ext == "psd")
		return true;
	else
		return false;
}

function alertUser(srcfield)
{
	var errStr ;
	if(srcfield == "poster")
		errStr = dw.loadString("Inspectors/video/text/invalid_poster_format");
	else
		errStr = dw.loadString("Inspectors/video/text/invalid_file_format");
		
	alert(errStr);	
}

function setVideoSource( srcTag, srcField)
{	
 	var finalExt = null; 
	if( isKnownVideoFormat( srcField ) )
		finalExt = findExtension(srcField);
	if( srcTag  ){
		var sourceAttr = srcTag.getAttribute('src');
		// check if the sourceAttr and srcField are
		// same no need to update the DOM
		if( srcField == sourceAttr )
			return; 
		if( srcField )
		{   
			srcTag.setAttribute('src',srcField);
			if(finalExt )
				srcTag.setAttribute('type', "video/" + getVideoType(finalExt));
			else
				srcTag.removeAttribute('type');
		}
		else
		{   
			if( !srcTag.getAttribute('id') && !srcTag.getAttribute('class'))
			{
				if(gVideoHTMLTag)
					gVideoHTMLTag.setChildNodes(removeChildTagEdit(srcTag,gVideoHTMLTag));			
			}
			else
			{
				srcTag.removeAttribute('src');
				var mediaTag = srcTag.getAttribute('type');
				if( mediaTag )
					srcTag.removeAttribute('type');
			}
		}
	}
	else{
		if( srcField && srcField != "" ){
			srcTag = new TagEdit("<source>");
			var childNodes = gVideoHTMLTag.getChildNodes();
			srcTag.setAttribute('src', srcField );
			
			if( VIDEO_SRC1 !=null && VIDEO_SRC2 !=null && getSelectedNode())
			{		
				updateUsageTrackingForAllSourcesUsed();	
			}
	
			// find the position and set the new child
			var newChildNodes = new Array();
			var i=0;
			if(childNodes)
			{
				for( ; i<childNodes.length; i++)
				{
					if( childNodes[i].getTagName() == "SOURCE" )
					{
						newChildNodes.push(childNodes[i]);				
					}
					else
					{
						break;
					}
				}
			}
			newChildNodes.push(srcTag);
			if(childNodes)
			{
				for( i=0 ; i<childNodes.length; i++)
				{
					var tagName = childNodes[i].getTagName() ;
					if( tagName && tagName != "SOURCE" )
						newChildNodes.push(childNodes[i]);
				}			
			}			
			if( finalExt )
				srcTag.setAttribute('type', "video/" + getVideoType(finalExt));
			gVideoHTMLTag.setChildNodes(newChildNodes);
		}
		else
			return;			
	}
	var updateText = gVideoHTMLTag .getOuterHTML();
	updateObjOuterHTML(updateText);	
}
function updateObjOuterHTML(updateText)
{   
	var theObj = getSelectedNode();
	if( theObj )
    {		
		theObj.outerHTML = updateText;
		return true;		
	}
	return false;
}
function updateUsageTrackingForAllSourcesUsed()
{	
	// log the event for head light tracking
   	dw.logEvent(UT_HTML5_VIDEO, UT_HTML5_VIDEO_ALL_SOURCES_INSERTED);	
}
function setSource1()
{
	if(document.topLayer.document.source1.value && isAutoFillPossible("one") )
		autoFill(document.topLayer.document.source1.value);
	else
		setVideoSource( VIDEO_SRC1, document.topLayer.document.source1.value);
	if(document.topLayer.document.source1.value)
	{
		removeInlineSource();
	}
	else if(isOnlyInlineSourcePresent())
	{
		setInlineSourceAsPrimarySource();
	}	
}

function setSource2()
{
	var flagInlineSrcRemoval = false;
	if(isInlineSourcePresent())
	{
		flagInlineSrcRemoval = true;		
		setVideoSource( VIDEO_SRC1, getInlineSource());
	}
	if(document.bottomLayer.document.source2.value && isAutoFillPossible("two"))
		autoFill(document.bottomLayer.document.source2.value);
	else
		setVideoSource( VIDEO_SRC2, document.bottomLayer.document.source2.value);
		
	if(flagInlineSrcRemoval)	
	{
		removeInlineSource();
	}
}

function setSource3()
{   
	var flagInlineSrcRemoval = false;
	if(isInlineSourcePresent())
	{
		flagInlineSrcRemoval = true;		
		setVideoSource( VIDEO_SRC1, getInlineSource());
	}
	if(document.bottomLayer.document.source3.value && isAutoFillPossible("three"))
		autoFill(document.bottomLayer.document.source3.value);
	else	
		setVideoSource( VIDEO_SRC3, document.bottomLayer.document.source3.value);
	if(flagInlineSrcRemoval)	
	{
		removeInlineSource();
	}		
}

function setFlashVideo()
{
	var srcTag = VIDEO_SRC4;
	var srcField = document.bottomLayer.document.flashVideo.value;
	if( srcTag  ){
		var sourceAttr = srcTag.getAttribute('src');
		// check if the sourceAttr and srcField are
		// same no need to update the DOM
		if( srcField == sourceAttr )
			return; 
		if( srcField ){
			srcTag.setAttribute('src',srcField);			
			srcTag.setAttribute('type', "application/x-shockwave-flash");
		}
		else
		{		
			if( !srcTag.getAttribute('class'))
			{
				if(gVideoHTMLTag)
					gVideoHTMLTag.setChildNodes(removeChildTagEdit(srcTag,gVideoHTMLTag));			
			}
			else
			{
				srcTag.removeAttribute('src');
				var mediaTag = srcTag.getAttribute('type');
				if( mediaTag )
					srcTag.removeAttribute('type');
			}
		}
	}
	else{
		if( srcField && srcField != "" ){
			srcTag = new TagEdit("<embed />");
			if(srcTag)
			{
				srcTag.setAttribute('src', srcField );				
				srcTag.setAttribute('type', "application/x-shockwave-flash" );
				
				//Inherit the width and height from Video
				var width = document.topLayer.document.widthAttr.value;
				var height = document.topLayer.document.heightAttr.value;
				if(width.length > 0 )
					srcTag.setAttribute('width', width);				
				if( height.length > 0)
					srcTag.setAttribute('height', height);
				
			}
			var childNodes = gVideoHTMLTag.getChildNodes();
			// find the position and set the new child
			var newChildNodes = new Array();
			var i=0;
			if(newChildNodes)
			{
				if(childNodes)
				{
					for( ; i<childNodes.length; i++)
					{
						if( childNodes[i].getTagName() == "SOURCE" )
						{
							newChildNodes.push(childNodes[i]);				
						}
						else
						{
							break;
						}
					}
				}
				if(srcTag)
				{
					newChildNodes.push(srcTag);
				}
				if(childNodes)
				{
					for( i=0 ; i<childNodes.length; i++)
					{
						var tagName = childNodes[i].getTagName();
						if( tagName && tagName != "SOURCE" )
							newChildNodes.push(childNodes[i]);
					}				
				}
				gVideoHTMLTag.setChildNodes(newChildNodes);			
			}
		}
		else
			return;
	}
	var updateText = gVideoHTMLTag .getOuterHTML();
	updateObjOuterHTML(updateText);
}

function setFlashDimensions(width,height)
{	
	var srcTag = VIDEO_SRC4;
	if( srcTag  ){
		var widthAttr = srcTag.getAttribute('width');
		var heightAttr = srcTag.getAttribute('height');
		if( (!widthAttr || widthAttr=="") && (!heightAttr || heightAttr==""))
		{
			srcTag.setAttribute('width', width);
			srcTag.setAttribute('height', height);
			if( gVideoHTMLTag )
				updateObjOuterHTML(gVideoHTMLTag.getOuterHTML());
		}
	}
	
}
function setVideoID()
{
    var vID = document.topLayer.document.videoID.value;
    // Set the value of the direction attribute to theDirection. 
	setOrRemoveAttribute('id', vID); 
}

function setWidth(){
	var theObj = getSelectedNode();
	var oldWidth ;

	if(theObj)
		oldWidth = theObj.getAttribute('width');
	var width = document.topLayer.document.widthAttr.value;

    if(!isValidValue(width))
	{
		var errStr = dw.loadString("Inspectors/video/invalidValue");
		if(oldWidth)
			document.topLayer.document.widthAttr.value = oldWidth;
		else
			document.topLayer.document.widthAttr.value = "";
		alert("'" + width + "' " + errStr);				
		return;						
	}
    // Set the value of the direction attribute to theDirection
	setOrRemoveAttribute('width',width);
	modifyVideoTag();
}

function isValidValue(sText)
{
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;
   var length = sText.length;

   for (i = 0; i < length && IsNumber == true; i++) 
   { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
   }
   return IsNumber;
}

function setHeight()
{
	var theObj = getSelectedNode();
	var oldHeight ;

	if(theObj)
		oldHeight = theObj.getAttribute('height');
	var height = document.topLayer.document.heightAttr.value;
	
 	if(!isValidValue(height))
	{
		var errStr = dw.loadString("Inspectors/video/invalidValue");
		alert("'" + height + "' " +  errStr);
		if(oldHeight)
			document.topLayer.document.heightAttr.value = oldHeight;
		else
			document.topLayer.document.heightAttr.value = "";
		return;
	}
	// Set the value of the direction attribute to theDirection. 
	setOrRemoveAttribute('height',height);
	modifyVideoTag();
}

function setPoster()
{
	var poster = document.topLayer.document.poster.value;
    // Set the value of the direction attribute to theDirection. 
	setOrRemoveAttribute('poster', poster);
}

function setTitle()
{
	var title= document.topLayer.document.title.value;
    // Set the value of the direction attribute to theDirection. 
	setOrRemoveAttribute('title', title);
}

function setControl()
{
	if(document.bottomLayer.document.controls.checked)
		modifyVideoTag();
	else
		removeAttr('controls');

}

function fillAttributes()
{
	var selectedNode = getSelectedNode();
	if(selectedNode)
	{
		var strout = "";
		var temp = selectedNode.getAttribute('width');
		if(temp && temp!="")
		{
			strout = strout + 'width="' + temp + '" ';
		}
		temp = selectedNode.getAttribute('height');
		if( temp && temp!="")
		{
			strout = strout + 'height="' + temp + '" ';
		}
		temp = selectedNode.getAttribute('id');
		if( temp && temp!="")
		{
			strout = strout + 'id="' + temp + '" ';
		}
		temp = selectedNode.getAttribute('class');
		if( temp && temp!="")
		{
			strout = strout + 'class="' + temp + '" ';
		}
		temp = selectedNode.getAttribute('src');
		if( temp && temp!="")
		{
			strout = strout + 'src="' + temp + '" ';
		}
		temp = selectedNode.getAttribute('title'); 
		if( temp && temp!="")
		{
			strout = strout + 'title="' + temp + '" ';
		}
		temp = selectedNode.getAttribute('poster');
		if( temp && temp!="")
		{
			strout = strout + 'poster="' + temp + '" ';
		}
		temp = selectedNode.getAttribute('preload');
		if( temp && temp!="")
		{
			strout = strout + 'preload="' + temp + '" ';
		}
		if(document.bottomLayer.document.controls.checked)
		{
			strout = strout + 'controls="controls" ';
		}
		if(document.bottomLayer.document.muted.checked)
		{ 
			strout = strout + 'muted="muted" ';
		}
		if(document.bottomLayer.document.autoplay.checked)
		{ 
			strout = strout + 'autoplay="autoplay" ';
		}
		if(document.bottomLayer.document.loopVideo.checked)
		{ 
			strout = strout + 'loop="loop" ';
		}
		return strout;
	}
	return "";
}

function modifyVideoTag()
{   
	var strout = "<video ";
	strout = strout + fillAttributes();
	strout = strout + ">" ;
	var selectedNode = getSelectedNode();
	
	if( selectedNode && selectedNode.childNodes)
	{	
		var selNode = new TagEdit(selectedNode.outerHTML);
		var childNodes = selNode.getChildNodes();			
		for(var i=0 ; i< childNodes.length ; i++ )
		{
			strout = strout + childNodes[i].getOuterHTML();
		}
	}
	strout = strout + "</video>";
	if( selectedNode)	
		selectedNode.outerHTML = strout;
	
}
function setMuted()
{
	if(document.bottomLayer.document.muted.checked)
		modifyVideoTag();
	else
		removeAttr('muted');
}

function setAutoplay()
{
	if(document.bottomLayer.document.autoplay.checked)
		modifyVideoTag();
	else
		removeAttr('autoplay');
}

function setLoopVideo()
{
	if(document.bottomLayer.document.loopVideo.checked)
		modifyVideoTag();
	else
		removeAttr('loop');
}

function onPreLoadChange()
{
	// Get the index of the selected option in the pop-up menu 
    // in the interface. 
    var selIndex = document.bottomLayer.document.preload.selectedIndex; 
	// Update the tag
    var preloadval = document.bottomLayer.document.preload.options[selIndex].value;

	if( preloadval ){
		var theObj = getSelectedNode();
		if( theObj ){
			theObj.setAttribute('preload', preloadval);
			modifyVideoTag();
		}
	}
}

function onClassChange()
{
	// Get the index of the selected option in the pop-up menu 
	var theObj = getSelectedNode();
	if( theObj )
	{
		var classSel = document.getElementById('classList');
		
		var selIndex =  classSel.selectedIndex ;
		var classval = classSel.options[selIndex].value;
		if(classval && selIndex > 0)
		{
			theObj.setAttribute('class', classval);
			modifyVideoTag();
		}
		else
		{
			theObj.removeAttribute('class');
		}
	}    
}

function setvId()
{
	var idSel = document.getElementById('videoID');
    var theObj = getSelectedNode();
    if( theObj )
    {
        if(idSel.editText)
        {		
          var editObject = 
            {
                replaceID: idSel.editText
            };
        
          dw.applyIDToSelection(editObject);
          theObj.setAttribute('id', idSel.editText);
		  modifyVideoTag();
        }	
        else
        {
            theObj.removeAttribute('id');
        }
    }
}

function onIdChange()

{
	// Get the index of the selected option in the pop-up menu 
	var theObj = getSelectedNode();
	if( theObj )
	{
		var idSel = document.getElementById('videoID');
		var selIndex =  idSel.selectedIndex ;		
		if(selIndex >= 0)
		{
			var idval = idSel.options[selIndex].value;
			theObj.setAttribute('id', idval);			
			modifyVideoTag();
		}
	}
}

function toggleCssFloater()
{
	dw.toggleFloater("CSS styles");
}

function detectWidthHeightFromImage()
{
	var fileURL = document.topLayer.document.poster.value;
	var width = document.topLayer.document.widthAttr.value;
	var height = document.topLayer.document.heightAttr.value;
	
	//Starting the auto detection only if width and height are empty
	if(fileURL.length > 0 && width.length == 0 && height.length == 0)
	{
		//Case of non-absolute URL
		if(fileURL.toLowerCase().substring(0,7) != "file://")
		{
			//case where url is relative to doc
			if(fileURL.substring(0,1) != '/')
			{
				var docPath = dw.getDocumentPath('document');
				fileURL = dw.relativeToAbsoluteURL(docPath, "", fileURL);
			}
			//case where url is relative to site
			else
			{
				var siteRoot = dw.getSiteRoot();
				fileURL = dw.relativeToAbsoluteURL("", siteRoot, fileURL);
			}
		}
		
		if(DWfile.exists(fileURL))
		{
			height = dw.getImageHeight(fileURL);
			width  = dw.getImageWidth(fileURL);
			
			if(height > 0 && width > 0)
			{
				setFlashDimensions(width,height);
				setPoster();
				document.topLayer.document.widthAttr.value = width;
				setWidth();
				document.topLayer.document.heightAttr.value = height;
				setHeight();				
			}
		}
	}
}

function browseForFile(srcField){

 var filePath = null;
 if( srcField ){
	 switch( srcField ){
		 case "one":
		 	filePath = document.topLayer.document.source1.value;
		 	break;
		 case "two":
		 	filePath =  document.bottomLayer.document.source2.value;
		 	break;
		 case "three":
		 	filePath = document.bottomLayer.document.source3.value;
			break;
		 case "poster":
		 	filePath = document.topLayer.document.poster.value;
			break;
		case "flash":
		 	filePath = document.bottomLayer.document.flashVideo.value;
			break;
		 default:
		 	break;
	 }
     var supportedMediaTypes;
     var selVideoStr;
	 if( srcField == "poster" )
	 {
	     supportedMediaTypes = new Array("*.gif; *.jpg; *.jpeg; *.png; *.psd");
	     selVideoStr = dw.loadString("Inspectors/video/selectImage");
	 }
	 else if( srcField == "flash" )
	 {
	     supportedMediaTypes = "";
	     selVideoStr = dw.loadString("Inspectors/video/selectVideo");
	 }
	 else
	 {
      	supportedMediaTypes  = new Array("*.ogg; *.mp4; *.m4v; *.webm; *.ogv; *.3gp" );
        selVideoStr = dw.loadString("Inspectors/video/selectVideo");
	 }
	 var  fileName= dw.browseForFileURL("select", selVideoStr, false, false, supportedMediaTypes, "",true, filePath);

	if( fileName)
	{
		if(srcField == "poster")
		{
			if(!isKnownPosterFormat(fileName)){
				alertUser(srcField);
				return;
			}
		}
		else if(srcField != "flash")
		{
		 	if(!isKnownVideoFormat(fileName)){
				alertUser(srcField);
				return;
			}
		}
	}

	if (fileName) {
		  var fileURL = new File(fileName);
		  if(fileURL && fileURL.exists())
		  { 
			  switch( srcField ){
	
				 case "one":				
					document.topLayer.document.source1.value = fileName;
					setSource1();
					break;
	
				 case "two":
				    document.bottomLayer.document.source2.value = fileName;
					setSource2();
					break;
	
				 case "three":
					document.bottomLayer.document.source3.value = fileName;
					setSource3();
					break;
	
				 case "poster":
					document.topLayer.document.poster.value = fileName;
					setPoster();
					break;
				case "flash":
					document.bottomLayer.document.flashVideo.value = fileName;
					setFlashVideo();
					break;
					
				 default:
					break;
			 } // switch
			 
		  }
	 } // if( fileName ) 		 
 }// if srcField 
 
}
function isAutoFillPossible(srcField)
{
	switch( srcField ){
	
		case "one":
				if(!document.bottomLayer.document.source2.value && !document.bottomLayer.document.source3.value)	
					return true;
				
		case "two":
				if(!document.topLayer.document.source1.value && !document.bottomLayer.document.source3.value)	
					return true;
				
		case "three":
				if(!document.topLayer.document.source1.value && !document.bottomLayer.document.source2.value)	
					return true;
									
	    default:
			return false;
			
	} // switch
	return false;
}
function autoFill(fileName)
{	
	var extArray = new Array(".mp4", ".ogg", ".webm",".m4v", ".ogv", ".3gp");
	if(fileName && fileName.lastIndexOf(".")>=0)
	{
		var head = fileName.substring(0,fileName.lastIndexOf("."));
		var ext = fileName.substring(fileName.lastIndexOf("."), fileName.length);
		var fileList = new Array();
		fileList.push(fileName);
				
		for(var i=0, count=1 ; i< extArray.length && count<3 ; i++)	
		{
			if(ext != extArray[i])
			{
				var tempFileName = head + extArray[i];
				var tempFile = new File(tempFileName);
				var encodedFileName = dw.doURLEncoding(tempFileName)
				if( tempFile.exists() && !isDuplicateVideo(encodedFileName) )
				{
					fileList.push(encodedFileName);				
					count++;
				}
			}
		}
		
		var childNodes = gVideoHTMLTag.getChildNodes();
		var newChildNodes = new Array();
		var i=0;
				
		for(var i=0 ; i<fileList.length ; i++ )
		{
				srcTag = new TagEdit("<source>");
				if(srcTag)
				{
					srcTag.setAttribute('src', fileList[i]);
					var extn = findExtension(fileList[i]);
					if( extn )
						srcTag.setAttribute('type', "video/" + getVideoType(extn));			
					// find the position and set the new child			
					newChildNodes.push(srcTag);
				}
		}
		if(childNodes)
		{
			//push all the sources first
			for( i=0; i<childNodes.length; i++)
			{   
				var tagName = childNodes[i].getTagName();
				if( tagName && tagName != "SOURCE" )
					newChildNodes.push(childNodes[i]);
			}			
		}			
		gVideoHTMLTag.setChildNodes(newChildNodes)
		var updateText = gVideoHTMLTag .getOuterHTML();
		if( updateObjOuterHTML(updateText) )
		{
			if(fileList && fileList.length == 3)	
			{   
				updateUsageTrackingForAllSourcesUsed();
			}
		}
	}
}

function isDuplicateVideo(fileName)
{
	if( fileName == document.topLayer.document.source1.value || 
		fileName == document.bottomLayer.document.source2.value || 
		fileName == document.bottomLayer.document.source3.value   )
			return true; 
	
	return false;
}

function isOnlyInlineSourcePresent()
{
	var theObj = getSelectedNode();
	if(document.topLayer.document.source1.value || document.bottomLayer.document.source2.value || document.bottomLayer.document.source3.value)
	{
		return false;
	}
	if(theObj && theObj.getAttribute('src'))
	{
		return true;
	}
	return false;	
}
function setInlineSourceAsPrimarySource()
{   
	var theObj = getSelectedNode();
	if(theObj)
		document.topLayer.document.source1.value = theObj.getAttribute('src');
}
function removeInlineSource()
{
	var theObj = getSelectedNode();
	if(theObj)
	{   
		theObj.removeAttribute('src');
	}
}

function isInlineSourcePresent()
{
	var theObj = getSelectedNode();	
	if(theObj && theObj.getAttribute('src'))
	{
		return true;
	}
	return false;	
}

function getInlineSource()
{
	var theObj = getSelectedNode();	
	if(theObj )
		return theObj.getAttribute('src') ;
}