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

*

* ADOBE CONFIDENTIAL

* ___________________

*

*  Copyright 2012 Adobe Systems Incorporatedz

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

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

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

var SOURCE_TYPE;
var helpDoc = MM.HELP_objVideo;

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

function canInspectSelection(){
  return true;
}

function inspectSelection(){ 
    
	var theDOM = dw.getDocumentDOM(); 
	if( theDOM )
	{
    	var theObj = theDOM.getSelectedNode(); 
	
		setSourceType();
		setSourceImageAndLabel();	

		// Get the value id.
		if( theObj )
		{ 	
			var sourceID = theObj.getAttribute('id'); 
			// update all the fields
			if( sourceID )
			{
				document.topLayer.document.sourceID.editText = sourceID;
			}
			else
			{
				document.topLayer.document.sourceID.editText = "";		
			}	
		
			populateIdList( sourceID );
		}

		// Now update the sources
		updateSourceField();
	
		// populate classes
		populateClassList();
		
		var classSel = document.getElementById('classList');
		
		if(classSel)
		{
			if( theObj )
			{
				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;
				}
			}
		}
	}
}

function updateSourceField()
{
	var theDOM = dw.getDocumentDOM(); 
    var theObj = theDOM.getSelectedNode();
	var sourceField = document.topLayer.document.source1;
	
	if(theObj && sourceField)
	{
		var src1 = theObj.getAttribute('src');
		if(src1)
		{
			document.topLayer.document.source1.value = src1;
		}
		else
		{
			document.topLayer.document.source1.value = '';
		}
	}
}

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
	return theObj;
}


function setVideoAttr(attrName, checkVal)
{
	var theObj = getSelectedNode();
	if( theObj ){
		if( checkVal )
		{
			theObj.setAttribute(attrName, checkVal );
			modifySourceTag();
		}
		else
			theObj.removeAttribute(attrName);
	}
}

function fillAttributes()
{
	var selectedNode = getSelectedNode();
	if(selectedNode)
	{
		var strout = "";
		
		temp = getSelectedNode().getAttribute('id');
		if( temp && temp!="")
		{
			strout = strout + ' id="' + temp + '" ';
		}
		temp = getSelectedNode().getAttribute('class');
		if( temp && temp!="")
		{
			strout = strout + ' class="' + temp + '" ';
		}
		temp = getSelectedNode().getAttribute('src');
		if( temp && temp!="")
		{
			strout = strout + ' src="' + temp + '" ';
		}
		temp = getSelectedNode().getAttribute('type');
		if( temp && temp!="")
		{
			strout = strout + ' type="' + temp + '" ';
		}			
		return strout;
	}
	return "";
}

function modifySourceTag()
{
	var strout = "<source ";
	strout = strout + fillAttributes();
	strout = strout + ">" ;		
	getSelectedNode().outerHTML = strout;
	
}
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();
	   if (dom)
	   {
			var allClasses = getClasses();
			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;
					}
				}
			}			
		}
}

function populateIdList(id)
{
	   var dom = dw.getDocumentDOM();
	   if (dom)
	   {
			var allIds = getIDs();
			
			var alreadyAddedIDs = new Array();
			var IDOptions = document.topLayer.document.sourceID.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.sourceID.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;
						}
					}
				}
			}
		}
}

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;

}

// pass in the file name
function isKnownFormat(fileName)
{

	var ext = findExtension(fileName);
	if( SOURCE_TYPE == "AUDIO")
	{
		if( ext == "ogg" || ext == "mp3" || ext == "wav" )
			return true;
		return false;	
	}
	if( SOURCE_TYPE == "VIDEO")
	{
		if(ext == "ogg" || ext == "mp4" || ext == "webm" || ext == "ogv"  || ext == "3gp" || ext == "m4v" )
			return true;
		return false;
	}
	return true;
}

function alertUser()
{
	var errStr;
	if(SOURCE_TYPE == "AUDIO")
	{
		errStr = dw.loadString("Inspectors/audio/text/invalid_file_format");
	}
	if(SOURCE_TYPE == "VIDEO")
	{
		errStr = dw.loadString("Inspectors/video/text/invalid_file_format");
	}
	if(errStr)
		alert(errStr);	
}

function setVideoSource( srcField)
{
 	var finalExt = null; 
	if( isKnownFormat( srcField ) )
		finalExt = findExtension(srcField);
				
	var theDOM = dw.getDocumentDOM(); 
    var theObj = theDOM.getSelectedNode();

	if(theObj)
	{			
		var sourceAttr = theObj.getAttribute('src');
		// check if the sourceAttr and srcField are
		// same no need to update the DOM
		if( srcField == sourceAttr )
			return; 

		if( srcField ){
			theObj.setAttribute('src',srcField);
			if( finalExt )			
				theObj.setAttribute('type',  getSourceType(finalExt));
			else
				theObj.removeAttribute('type');	
		}
		else
		{
			if( !theObj.getAttribute('id') && !theObj.getAttribute('class'))
			{
				removeSelectedNodeFromParent();			
				return;	
			}
			else
			{
				theObj.removeAttribute('src');
				var mediaTag = theObj.getAttribute('type');
				if( mediaTag )
					theObj.removeAttribute('type');
			}
			
		}
	}
	updateSourceField();
}

function getSourceType(extension)
{
	 if( !extension || extension == "" )
    {
        return "";
    }
	if( SOURCE_TYPE == "VIDEO")
	{
		if( extension == "mp4" || extension == "m4v")
		{
			return "video/mp4";
		}
		if(extension == "ogg" || extension == "ogv" )
		{
			return "video/ogg";
		}
		if(extension == "3gp" || extension == "3g2" )
		{
			return "video/3gp";
		}
		if(extension == "webm" )
		{
			return "video/webm";
		}
	}
	if( SOURCE_TYPE == "AUDIO")
	{
		if( extension == "mp3" )
		{
			return "audio/mp3";
		}
		if(extension == "ogg"  )
		{
			return "audio/ogg";
		}
		if(extension == "wav" )
		{
			return "audio/wav";
		}
	}
	return "";
}

function setSource1()
{
	setVideoSource( document.topLayer.document.source1.value);
}

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

function setSourceId()
{
	var idSel = document.getElementById('sourceID');
	
	var theObj = getSelectedNode();
    if( theObj )
    {
        if(idSel.editText)
        {		
          var editObject = 
            {
                replaceID: idSel.editText
            };
        
          dw.applyIDToSelection(editObject);
          theObj.setAttribute('id', idSel.editText);
		  modifySourceTag();
        }	
        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('sourceID');
		
		if(idSel)
		{
			var selIndex =  idSel.selectedIndex ;		
			if(selIndex >= 0)
			{
				var idval = idSel.options[selIndex].value;
				theObj.setAttribute('id', idval);
				modifySourceTag();			
			}			
		}
			
	}    
	
}



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


function browseForFile(srcField){

 	var filePath = null;
 	if( srcField && srcField == "one"){
	 	filePath = document.topLayer.document.source1.value;
	 
	 	var supportedMediaTypes;
		var selMediaStr;
		if(SOURCE_TYPE == "AUDIO")
		{
			supportedMediaTypes  = new Array("*.ogg; *.wav; *.mp3");
			selMediaStr = dw.loadString("Inspectors/audio/selectAudio");
		}
		if(SOURCE_TYPE == "VIDEO")
		{
			supportedMediaTypes  = new Array("*.ogg; *.mp4; *.m4v; *.webm; *.ogv;  *.3gp");
			selMediaStr = dw.loadString("Inspectors/video/selectVideo");
		}
		
		var fileName= browseForFileURL("select", selMediaStr, false, true, supportedMediaTypes, "",true, filePath);
		if( fileName ){
			if(!isKnownFormat(fileName)){
				alertUser();
				return;
			}
		}
 
		if (fileName) {
			document.topLayer.document.source1.value = fileName;
			setSource1();
		 } // if( fileName )	
	}
	
}

function setSourceType()
{
	var theObj = getSelectedNode(); 
	if( theObj ){
		var selectedNode = new TagEdit( theObj.parentNode.outerHTML);	
		SOURCE_TYPE = selectedNode.getTagName();
		if(SOURCE_TYPE == "AUDIO")
		{
			helpDoc = MM.HELP_objAudio; 
		}
		if(SOURCE_TYPE == "VIDEO")
		{
			helpDoc = MM.HELP_objVideo; 
		}
	}	
}

function setSourceImageAndLabel()
{
	var label = document.topLayer.document.getElementById('label');
	var sourceImage = document.getElementById('sourceImage');
	if( sourceImage )
	{
		
		if( label && sourceImage && SOURCE_TYPE )
		{
				if(SOURCE_TYPE == "AUDIO")
				{			
					label.innerHTML = dw.loadString("Inspectors/audioSource/label");
					sourceImage.src = "HTML5AudioTag.png";
				}
				else if(SOURCE_TYPE == "VIDEO")
				{
					label.innerHTML = dw.loadString("Inspectors/videoSource/label");
					sourceImage.src = "HTML5VideoTag.png";
				}
				else
				{
					label.innerHTML = dw.loadString("Inspectors/source/label");
					sourceImage.src = "";
				}
		}
	}
	
}