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

*

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

// ---- Object API ---

function isDOMRequired() { 
	return true;
}

function objectTag()
{
    dw.logEvent(UT_EDGE, UT_EDGE_INSERT);
    var binsert = CanInsertEdge();
	if(!binsert)
	    return "";
		
    var fileTypeDescription = dw.loadString("Objects/Edge/InsertEdgeAnimation");
	var supportedMediaTypes = new Array("*.oam");
	var filePath = null;
	
	filePath =  dw.doURLEncoding(dw.browseForFileURL("select",  fileTypeDescription, false, true, supportedMediaTypes));
	
	if(filePath == "null" || filePath == "")
	  return "";
	  
 	var fulloampath = dw.unzipOamFile(filePath);
	if(fulloampath == "null")
	  return "";
	  
	var oampathname = dw.getDocumentDomPath(fulloampath);
		
	//Form config xml path
	var configEdgePath = oampathname + "config.xml";
	var xmlDoc = dw.getDocumentDOM(configEdgePath);
	if(!xmlDoc)
	    return "";

    try{
	    var oamTag = xmlDoc.getElementsByTagName("oamfile")[0];
	} catch (e) {
	    alert(e);
	    return "";
	}
	
	if(!oamTag)
		return "";
	var oamSrc = oamTag.getAttribute("src");
	if(!oamSrc)
		return "";

	//Form Asset xml path
	var oamxmlPath = oampathname + oamSrc;
	var oamxmlDoc = dw.getDocumentDOM(oamxmlPath);
	if(!oamxmlDoc)
		return "";
	
	var index = 0;
	var oamhtmlSrc = "";
     
    try{
	    var oamrequireTag = oamxmlDoc.getElementsByTagName("require")[index];	
	    while(oamrequireTag)
	    {
		
		    oamhtmlSrc = oamrequireTag.getAttribute("src");
		    if(oamhtmlSrc)
		    {	
			    if(oamhtmlSrc.indexOf(".html") != -1)
			     break;
		    }	
		    index = index + 1;
		    oamrequireTag = oamxmlDoc.getElementsByTagName("require")[index];
	    }
    } catch (e) {
        alert(e);
        return "";
    }
	if(oamhtmlSrc = "")
		return "";
	
	var oampropertyName = "";
	var oamResizeVal = "";
	var isEA5 = "false";
	var headTagContents = "";
	var shouldFallback = "true";
	var toInsert = "";
	var bodyTagContents = "";
	var object_string = '';
	
	try{
		if(oamxmlDoc.getElementsByTagName("description").length < 1)
			return "";
		var oamDescriptionTag = oamxmlDoc.getElementsByTagName("description")[0];
		var descriptionTagContents = oamDescriptionTag.innerHTML;
		if (descriptionTagContents.indexOf("V1.DW.Edge") > -1)
		{	 
			isEA5 = "true";
			var indexes = 0;
			if(oamxmlDoc.getElementsByTagName("property").length < 1)
				return "";
			var oampropertyTag = oamxmlDoc.getElementsByTagName("property")[indexes];
			while(oampropertyTag)
			{
				oampropertyName = oampropertyTag.getAttribute("name");
				if(oampropertyName)
				{	
					if(oampropertyName.indexOf("resizable") != -1)
					{
						oamResizeVal = oampropertyTag.getAttribute("defaultValue");
						break;
					}
				}	
				indexes = indexes + 1;
				oampropertyTag = oamxmlDoc.getElementsByTagName("property")[indexes];
			}
			
			var asset_path = dw.getAssetPath(fulloampath);
			var htmlDoc = dw.getDocumentDOM(oampathname+"Assets/"+oamhtmlSrc);
			if(!htmlDoc)
				return "";
			headTagContents = htmlDoc.getElementsByTagName("head")[0].innerHTML;
			if(headTagContents.split("<!--Adobe Edge Runtime-->").length < 2)
				return "";
			var tempStr = headTagContents.split("<!--Adobe Edge Runtime-->")[1];
			if(tempStr.indexOf("var custHtmlRoot=\"\";") > -1)
			{
					shouldFallback = "false";	
					toInsert = tempStr.replace('var custHtmlRoot=\"\"','var custHtmlRoot=\"'+ asset_path +'\"');
					bodyTagContents = htmlDoc.getElementsByTagName("body")[0].innerHTML;
					
			}
		}	
    } catch (e) {
        return "";
    }

	if(isEA5 == "true" && oamResizeVal == "true" && shouldFallback == "false")
	{
		//Take out the tags.
		var cssCodeAnimate = '<!--Adobe Edge Runtime-->\n'+ toInsert +'\n';
		if(dw.getDocumentDOM().getElementsByTagName("head").length < 1)
			return "";
		var headTag = dw.getDocumentDOM().getElementsByTagName("head")[0].innerHTML;	
		var newCSS = headTag + cssCodeAnimate;
		dw.getDocumentDOM().getElementsByTagName('head')[0].innerHTML = newCSS;	
		
		object_string = object_string + bodyTagContents;
		
	}
	
	else
	{
	 var height = 20;
	 var width = 20;

     try{
         var oamiconTag = oamxmlDoc.getElementsByTagName("icon")[0];

         if (!oamiconTag)
             alert("oamiconTag is null");
         else {
             height = height + parseInt(oamiconTag.getAttribute("height"));
             if (!height)
                 alert("height is null");

             width = width + parseInt(oamiconTag.getAttribute("width"));
             if (!width)
                 alert("width is null");
         }

     } catch (e) {
         alert(e);
  
     }
	
	//Take out the tags.
	var edgeid = dwscripts.getUniqueId("EdgeID");
	var asset_path = dw.getAssetPath(fulloampath);
	var edgebasefile = asset_path + oamhtmlSrc;

	if (edgebasefile == "")
	    return "";

	object_string = object_string + '<object id="' + edgeid + '" ';
	
	object_string = object_string + 'type="text/html"'+ " " + 'width="'+ width + '" height="' +
						height +'" data-dw-widget="Edge" data="'+ edgebasefile +'"> </object>';
	}
	
	var dom = dw.getDocumentDOM('document');
    if( dom && dw.getActiveTarget() == "live")
    {
        dom.insertHTML(object_string, false);
        //we need to refresh live view after doing this, as partial refresh will not be suffiecient to show the changes!
        var liveViewBrowser = dw.getBrowser();
        if(liveViewBrowser) {
            liveViewBrowser.refreshPage();
        }
    }
    else
    {
        return object_string; 
    }	
}


function CanInsertEdge()
{
	var bCanInsert = false;
	var aDOM = dw.getDocumentDOM();
	if (aDOM)
	{
		if(aDOM.URL == '' )
		{
			bCanInsert = false; //cannot insert since document is not saved.
			if(confirm(MM.MSG_saveDocument))
			{
				if (dw.canSaveDocument(aDOM))
				{
					//check if document is saved
					dw.saveDocument(aDOM);
					bCanInsert = (aDOM.URL != '');
				}
			}					
		}
		else
		{
			bCanInsert = true;
		}
	}
	return bCanInsert;
}
